问:
Java: getting strings from enum without having to call .toString()?
Say I have this enum:

```<code>public class MyErrors {
    public enum Errors {
        BAD_FILE_PATH("Please point to a valid file");

        private final String message;

        Errors(final String message) {
            this.message = message;
        }

        @Override
        public String toString() {
            return message;
        }
    }
</code>```

And this call:

```<code>Logging.log(Level.INFO, MyErrors.Errors.BAD_FILE_PATH.toString());
</code>```

It seems so verbose to me to have to call .toString(). Isn't there a way to just call the enum itself and have it return its string by default?

Ideally I'd like something like MyErrors.BAD_FILE_PATH --> which returns a string so it's not so verbose. Does that make any sense?

答:
Both of these work for me in Eclipse:

```

    LOG.info(Errors.BAD_FILE_PATH);   // Using Log4j
    System.out.println(Errors.BAD_FILE_PATH);

```

These two methods take an Object parameter.  And since are not receiving Strings, the logic in those methods must call the toString() method on the passed in object to obtain a string.

The log() method of java.util.logging.Logger does not support an Object parameter.  Instead, it is expecting a String parameter; thus, the logic in this method has no need to call toString().

What you are looking for is a new signature for the Logger that supports an Object parameter.  However, I don't know that extending the Logger is a straight forward process or advisable; see here.

Another option would be to use Log4j.

Body:
Say I have this enum:

public class MyErrors {
    public enum Errors {
        BAD_FILE_PATH("Please point to a valid file");

        private final String message;

        Errors(final String message) {
            this.message = message;
        }

        @Override
        public String toString() {
            return message;
        }
    }

And this call:

Logging.log(Level.INFO, MyErrors.Errors.BAD_FILE_PATH.toString());

It seems so verbose to me to have to call .toString(). Isn't there a way to just call the enum itself and have it return its string by default?

Ideally I'd like something like MyErrors.BAD_FILE_PATH --> which returns a string so it's not so verbose. Does that make any sense?

Body:
Both of these work for me in Eclipse:

    LOG.info(Errors.BAD_FILE_PATH);   // Using Log4j
    System.out.println(Errors.BAD_FILE_PATH);

These two methods take an Object parameter.  And since are not receiving Strings, the logic in those methods must call the toString() method on the passed in object to obtain a string.

The log() method of java.util.logging.Logger does not support an Object parameter.  Instead, it is expecting a String parameter; thus, the logic in this method has no need to call toString().

What you are looking for is a new signature for the Logger that supports an Object parameter.  However, I don't know that extending the Logger is a straight forward process or advisable; see here.

Another option would be to use Log4j.


来源: stackexchange

问:
Click on a button in a MatFormFieldControl trigger the Submit action on Form in Angular 4
I have developed a custom Component (app-mat-avatar) to use as an avatar choose (See picture). It consists of one big div with a picture and 2 buttons. One to edit, the other to erase.
I built it following Angular guide at Creating a custom form field control

This is the form where I use it:

```<code><form name="detailsForm" [formGroup]="detailsForm" (submit)="submitDetails($event)">
    <app-mat-avatar [size]="150" formControlName="photoURL"></app-mat-avatar>
    <input matInput type="email" placeholder="Email" formControlNamesss="email" disabled value="{{detailsForm.get('email').value}}">
.....

    <div flex layout="row" layout-align="end center" class="fullWidth pad-right-sm">
        <button mat-button mat-raised (click)="resetDetails()" class="push-right-xs" [disabled]="busy">Reset</button>
        <button type="submit" mat-button mat-raised-button color="primary" [disabled]="detailsForm.invalid || busy">Save</button>
    </div>
</form>
</code>```

And this is the code supporting the page Component where the form is located:

```<code>@Component({
  selector: 'app-my-info',
  templateUrl: './my-info.component.html',
  styleUrls: ['./my-info.component.sass']
})
export class MyInfoComponent implements OnInit, OnDestroy {

  detailsForm = new FormGroup({
    uid: new FormControl(''),
    photoURL: new FormControl(''),
    firstName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    lastName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    sex: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email]),
    licenseLocal: new FormControl(''),
    licenseNational: new FormControl(''),
    cellPhone: new FormControl(''),
  });

........

  ngOnInit() {
    fetchUserFromDatabase.subscribe( me => {
      if (!me) {return; }
      this._currentUser = me;
      this.resetDetails();

    }));
  }

  resetDetails() {
    const user = {
      email : this.currentUserCopy.email,
      photoURL: this.currentUserCopy.photoURL,
      firstName: this.currentUserCopy.firstName,
      lastName: this.currentUserCopy.lastName,
      licenseLocal: this.currentUserCopy.licenseLocal || '',
      licenseNational: this.currentUserCopy.licenseNational || '',
      sex: this.currentUserCopy.sex,
      cellPhone: this.currentUserCopy.cellPhone || ''
    };
    this.detailsForm.patchValue( user );
  }

  submitDetails(event) {
    // console.log(event);
    this._currentUser.createFromFirebaseData(this.detailsForm.value);
    this._db.UpdateUser(this._currentUser)
    .then( result => {
      this.busy = false;
      this._popUp.showInfo('Perfil guardado');
    })
    .catch( error => {
      this.busy = false;
      this._popUp.showError(error);
    });
  }
}
</code>```

Everything works well except that when I click on one of the button of the app-mat-avatar component, the submitDetails method is triggered.

I tried to add event.stopPropagation(); as the first line of the method the button click calls, but it has no effect.

Any idea why this could be happening?

答: Add type="button" to the reset button in your template to prevent the submission

ContentLicense: CC BY-SA 3.0

Body:
I have developed a custom Component (app-mat-avatar) to use as an avatar choose (See picture). It consists of one big div with a picture and 2 buttons. One to edit, the other to erase.
I built it following Angular guide at Creating a custom form field control

This is the form where I use it:

<form name="detailsForm" [formGroup]="detailsForm" (submit)="submitDetails($event)">
    <app-mat-avatar [size]="150" formControlName="photoURL"></app-mat-avatar>
    <input matInput type="email" placeholder="Email" formControlNamesss="email" disabled value="{{detailsForm.get('email').value}}">
.....

        <button mat-button mat-raised (click)="resetDetails()" class="push-right-xs" [disabled]="busy">Reset</button>
        <button type="submit" mat-button mat-raised-button color="primary" [disabled]="detailsForm.invalid || busy">Save</button>

</form>

And this is the code supporting the page Component where the form is located:

@Component({
  selector: 'app-my-info',
  templateUrl: './my-info.component.html',
  styleUrls: ['./my-info.component.sass']
})
export class MyInfoComponent implements OnInit, OnDestroy {

  detailsForm = new FormGroup({
    uid: new FormControl(''),
    photoURL: new FormControl(''),
    firstName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    lastName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    sex: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email]),
    licenseLocal: new FormControl(''),
    licenseNational: new FormControl(''),
    cellPhone: new FormControl(''),
  });

........

  ngOnInit() {
    fetchUserFromDatabase.subscribe( me => {
      if (!me) {return; }
      this._currentUser = me;
      this.resetDetails();

    }));
  }

  resetDetails() {
    const user = {
      email : this.currentUserCopy.email,
      photoURL: this.currentUserCopy.photoURL,
      firstName: this.currentUserCopy.firstName,
      lastName: this.currentUserCopy.lastName,
      licenseLocal: this.currentUserCopy.licenseLocal || '',
      licenseNational: this.currentUserCopy.licenseNational || '',
      sex: this.currentUserCopy.sex,
      cellPhone: this.currentUserCopy.cellPhone || ''
    };
    this.detailsForm.patchValue( user );
  }

  submitDetails(event) {
    // console.log(event);
    this._currentUser.createFromFirebaseData(this.detailsForm.value);
    this._db.UpdateUser(this._currentUser)
    .then( result => {
      this.busy = false;
      this._popUp.showInfo('Perfil guardado');
    })
    .catch( error => {
      this.busy = false;
      this._popUp.showError(error);
    });
  }
}

Everything works well except that when I click on one of the button of the app-mat-avatar component, the submitDetails method is triggered.

I tried to add event.stopPropagation(); as the first line of the method the button click calls, but it has no effect.

Any idea why this could be happening?


问:
how to start celery flower as as daemon in RHEL?
Im trying to run flower as daemon. My flower.service file read as follows:

```<code>[Unit]

    Description=Flower Service
    After=network.target

[Service]

    Type=forking
    User=maas
    Group=maas
    PermissionsStartOnly=true
    ExecStart=/bin/flower --broker=amqp://oser000300//

[Install]

    WantedBy=multi-user.target
</code>```

But when i start the service, it is giving error.

```<code>//systemctl status flower.service

* flower.service - Flower Service
   Loaded: loaded (/etc/systemd/system/flower.service; enabled; vendor preset: disabled)
   Active: failed (Result: timeout) since Mon 2017-07-10 20:25:59 UTC; 4min 38s ago
  Process: 49255 ExecStart=/bin/flower --broker=amqp://oser000300//  (code=exited, status=0/SUCCESS)

Connected to amqp://guest:**@oser000300:5672//
flower.service start operation timed out. Terminating.
SIGTERM detected, shutting down
Failed to start Flower Service.
Unit flower.service entered failed state.
flower.service failed.
</code>```

答:
I had the same timeout problem when starting the service.

Those parameters has done the trick (i had already celery service running with forking type):

```<code>Type=simple
Restart=on-failure
</code>```

Body:
Im trying to run flower as daemon. My flower.service file read as follows:

[Unit]

    Description=Flower Service
    After=network.target

[Service]

    Type=forking
    User=maas
    Group=maas
    PermissionsStartOnly=true
    ExecStart=/bin/flower --broker=amqp://oser000300//

[Install]

    WantedBy=multi-user.target

But when i start the service, it is giving error.

//systemctl status flower.service

* flower.service - Flower Service
   Loaded: loaded (/etc/systemd/system/flower.service; enabled; vendor preset: disabled)
   Active: failed (Result: timeout) since Mon 2017-07-10 20:25:59 UTC; 4min 38s ago
  Process: 49255 ExecStart=/bin/flower --broker=amqp://oser000300//  (code=exited, status=0/SUCCESS)

Connected to amqp://guest:**@oser000300:5672//
flower.service start operation timed out. Terminating.
SIGTERM detected, shutting down
Failed to start Flower Service.
Unit flower.service entered failed state.
flower.service failed.

Body:
I had the same timeout problem when starting the service.

Those parameters has done the trick (i had already celery service running with forking type):

Type=simple
Restart=on-failure


问:
Run a list of String through a list of filters
I have List<String> and List<Filter>.

```<code>public interface Filter{
     List<String> filter(List<String> strToFilter);
}
</code>```

How can I pass the List<String> through the list of filters and use the output of one filter as an input to the other filter? I can do this using for-loop. I wanted to know how to achieve this using java 8 stream and lambda

答:
Say you have lists like these:

```<code>List<String> myStrings;
List<Filter> myFilters;
</code>```

So now you do:

```<code>List<String> myFilteredStrings = myFilters
    .stream()
    .reduce(new ArrayList<String>(myStrings), (strings, filter) -> filter.filter(strings), (l1, l2) -> {
        List<String> combined = new ArrayList(l1);
        combined.addAll(l2);
        return combined;
});
</code>```

If you have access to guava library, you can use Iterables.concat and Lists.newArrayList to make it cleaner

```<code>List<String> myFilteredStrings = myFilters
        .stream()
        .reduce(Lists.newArrayList(myStrings), (strings, filter) -> filter.filter(strings), (l1, l2) -> Lists.newArrayList(Iterables.concat(l1, l2));
</code>```

Body:
I have List<String> and List<Filter>.

public interface Filter{
     List<String> filter(List<String> strToFilter);
}

How can I pass the List<String> through the list of filters and use the output of one filter as an input to the other filter? I can do this using for-loop. I wanted to know how to achieve this using java 8 stream and lambda

Body:
Say you have lists like these:

List<String> myStrings;
List<Filter> myFilters;

So now you do:

List<String> myFilteredStrings = myFilters
    .stream()
    .reduce(new ArrayList<String>(myStrings), (strings, filter) -> filter.filter(strings), (l1, l2) -> {
        List<String> combined = new ArrayList(l1);
        combined.addAll(l2);
        return combined;
});

If you have access to guava library, you can use Iterables.concat and Lists.newArrayList to make it cleaner

List<String> myFilteredStrings = myFilters
        .stream()
        .reduce(Lists.newArrayList(myStrings), (strings, filter) -> filter.filter(strings), (l1, l2) -> Lists.newArrayList(Iterables.concat(l1, l2));


问:
Are two classes in same namespace & project also in the same executing assembly?
I am asking the question in the title because this works:

```<code>FooBar fooBar = new FooBar();
</code>```

It hits the constructor in FooBar, etc.  But this returns null:

```<code>Type type = Type.GetType("FooBar");
</code>```

Both FooBar and the class from which I am trying to do this are in the same namespace, the same project, etc.

I've looked over this thread:

Type.GetType("namespace.a.b.ClassName") returns null

According to that accepted answer (and some others), this "only works when the type is found in either mscorlib.dll or the currently executing assembly."

If the two classes are in the same namespace and the same project (ie: same .dll) would that not make the same executing assembly?

What am I doing wrong?

答:
Even though it's in the same assembly and namespace, you still need to provide the namespace. It's just the assembly qualified name you can skip.</p>

```<code>Type type = Type.GetType("YourNamespace.FooBar");
</code>```

Body:
I am asking the question in the title because this works:

FooBar fooBar = new FooBar();

It hits the constructor in FooBar, etc.  But this returns null:

Type type = Type.GetType("FooBar");

Both FooBar and the class from which I am trying to do this are in the same namespace, the same project, etc.

I've looked over this thread:

Type.GetType("namespace.a.b.ClassName") returns null

According to that accepted answer (and some others), this "only works when the type is found in either mscorlib.dll or the currently executing assembly."

If the two classes are in the same namespace and the same project (ie: same .dll) would that not make the same executing assembly?

What am I doing wrong?

Body:
Even though it's in the same assembly and namespace, you still need to provide the namespace. It's just the assembly qualified name you can skip.

Type type = Type.GetType("YourNamespace.FooBar");


问:
Is there "pass by reference"(C++) in go?
I am defined a function using pointer, like the following

```<code>func concat(head1, head2 *Node) Node {
}
</code>```

and pass in pointer. but I am wondering if Go supports pass by reference like C++ which I could use like the following

```<code>func concat(head1, head2 &Node) Node
</code>```

答:
The Go Programming Language Specification

Calls

In a function call, the function value and arguments are evaluated in
  the usual order. After they are evaluated, the parameters of the call
  are passed by value to the function and the called function begins
  execution. The return parameters of the function are passed by value
  back to the calling function when the function returns.

No. Parameters are passed by value.

Body:
I am defined a function using pointer, like the following

func concat(head1, head2 *Node) Node {
}

and pass in pointer. but I am wondering if Go supports pass by reference like C++ which I could use like the following

func concat(head1, head2 &Node) Node


问:
Selecting Postgres UUID's on Laravel
I have a table on Postgres that auto generates UUIDs, when I dd Customer::all(); on Laravel I get an array with "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" which is fine. When I loop or select one record with the only the cs_id the data it retuns 0,2,5 for the three records currently on the table which is incorrect data.

EDIT:

```<code>CREATE TABLE customers
(
  cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}
</code>```

On laravel

```<code>$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();

dd($customerData['cs_id']);
</code>```

答:
To use uuids auto-generated by the database, define your model as follows:

```<code>class Customer extends Model
{
    // rename the id column (optional)
    protected $primaryKey = 'cs_id';

    // tell Eloquent that your id is not an integer
    protected $keyType = 'string';

    // do NOT set $incrementing to false
}
</code>```

Then you can use all Eloquent's methods as you would with classic ids:

```<code>$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');
</code>```

Title: Selecting Postgres UUID's on Laravel

Body:
I have a table on Postgres that auto generates UUIDs, when I dd Customer::all(); on Laravel I get an array with "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" which is fine. When I loop or select one record with the only the cs_id the data it retuns 0,2,5 for the three records currently on the table which is incorrect data.

EDIT:

CREATE TABLE customers
(
  cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}

On laravel

$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();

dd($customerData['cs_id']);

Body:
To use uuids auto-generated by the database, define your model as follows:

class Customer extends Model
{
    // rename the id column (optional)
    protected $primaryKey = 'cs_id';

    // tell Eloquent that your id is not an integer
    protected $keyType = 'string';

    // do NOT set $incrementing to false
}

Then you can use all Eloquent's methods as you would with classic ids:

$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');


问:
AccessViolationException when accessing variable solution value
We've been utilizing the OR tools to solve linear optimizations in a real-time, .NET application. That is, solving linear optimizations regularly using different inputs as time progresses.

Recently we ran into an issue that we haven't seen before while running our application on a server for extended periods of time, in which seemingly random attempts to solve the optimizations were causing AccessViolationExceptions. Specifically,

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
   at Google.OrTools.LinearSolver.operations_research_linear_solverPINVOKE.Variable_SolutionValue(System.Runtime.InteropServices.HandleRef)
...

I'm trying to find out more specifically where this is happening in the pipeline, but given the output there I believe it is a section in which we are trying to retrieve the individual variable solution values out of the solver after solving the optimization.

We are using a wide variety of constraints over a decent sized number of variables.

Has anyone seen this before?

答:
Reference github issue link

After some testing we found that what appears to have been happening is that the garbage collector was collecting some of the Variables we were using during the P/Invoke, as per this.

Unfortunately, this seems to be a side effect of the way that SWIG creates its .NET wrappers and their IDisposable implementations, using HandleRefs instead of something like SafeHandles, which 'handle' this as per the documentation:

Platform invoke operations automatically increment the reference count of handles encapsulated by a SafeHandle and decrement them upon completion. This ensures that the handle will not be recycled or closed unexpectedly.

More information here.

Without wanting to get into the business of creating our own SWIG typemap or compiling a new version of SWIG, .NET provides a way of keeping objects 'alive' with regard to the Garbage Collector. That is, calling GC.KeepAlive on all of the objects which we will be accessing values from via P/Invoke (in our case the Solver and our Variables) at the end of the optimization procedure, prevents the garbage collector from thinking that they are collectible until the end of the scope of the KeepAlive method without side effects (as per their documentation).

Preliminary testing has shown this to work, though given that it was already intermittently occurring before, we'll be watching for this happening going forward.

Going forward, I think either making a request of SWIG to use SafeHandles is probably the best idea (it has been discussed before and is still an open issue) or changing the typemap to use SafeHandles directly, is likely the best option. I may try investigating the later option myself, but because this fix ended up only adding 3 lines of code (plus a host of comments) to our code base for what seems like a full fix, it's going to be low priority for me. That said, a fix for this would be nice for an upcoming version.


问:
Class constructor without a body or member initialization?
Reading through The C++ Programming Language, 4th Edition, there's a class Circle inheriting from Shape like so

```<code>class Circle : public Shape {
public:
    Circle(Point p, int rr); // constructor
    Point center() const { return x; }

    void move(Point to) { x=to; }
    void draw() const;
    void rotate(int) {} // nice simple algorithm
private:
    Point x; // center
    int r; // radius
};
</code>```

and the Shape class

```<code>class Shape {
public:
    virtual Point center() const =0; // pure virtual
    virtual void move(Point to) =0;

    virtual void draw() const = 0; // draw on current "Canvas"
    virtual void rotate(int angle) = 0;

    virtual ˜Shape() {} // destructor
// ...
};
</code>```

The part confusing me is Circle's constructor:

Circle(Point p, int rr);

Where is the return type? In all previous constructors the return type was specified void. I couldn't find a C++ implicit return type (like C's implicit-int rule)

Where is the body/initialization? All previous constructors either initialized via member-list initialization (:) or in the function body {}. I see neither here and so am wondering how the values are initialized at all.

答:
Constructors don't specify a return type, and don't return anything.

And it doesn't have a body because it's only the declaration - the definition will be somewhere else, and will look like

```<code>Circle::Circle (Point p, int rr)
{
 ...
}
</code>```

Body:
Reading through The C++ Programming Language, 4th Edition, there's a class Circle inheriting from Shape like so

class Circle : public Shape {
public:
    Circle(Point p, int rr); // constructor
    Point center() const { return x; }

    void move(Point to) { x=to; }
    void draw() const;
    void rotate(int) {} // nice simple algorithm
private:
    Point x; // center
    int r; // radius
};

and the Shape class

class Shape {
public:
    virtual Point center() const =0; // pure virtual
    virtual void move(Point to) =0;

    virtual void draw() const = 0; // draw on current "Canvas"
    virtual void rotate(int angle) = 0;

    virtual ˜Shape() {} // destructor
// ...
};

The part confusing me is Circle's constructor:

Circle(Point p, int rr);

Where is the return type? In all previous constructors the return type was specified void. I couldn't find a C++ implicit return type (like C's implicit-int rule)

Where is the body/initialization? All previous constructors either initialized via member-list initialization (:) or in the function body {}. I see neither here and so am wondering how the values are initialized at all.

Body:
Constructors don't specify a return type, and don't return anything.

And it doesn't have a body because it's only the declaration - the definition will be somewhere else, and will look like

Circle::Circle (Point p, int rr)
{
 ...
}


问:
how to allow a plugin to store data
I plan to propose an application which allow developers to provide plugins for it.

In my scenario, plugins access the application data and methods through a web-services layer, and as a consequence, the developer can expect to store his plugin-data using this layer. We do not want to allow database modification for each plugin which would need it or even provide a direct access to the database.

The question is, do you know, or can you imagine, a system that would suit the need of allowing any kind of data to be store in our database in this context ?

The application is an ASP.NET application, database is SQL Server.

答: Is the data common for all the plugins? if so, why would a plugin need to modify the schema? if not, why not have each plugin host their own database a-la SQLite ? then they would be independent of eachother and you wouldn't even need to provide services for storage as the plugins would manage themselves.</p>

ContentLicense: CC BY-SA 2.5

Title: how to allow a plugin to store data


问:
read and write same file bash/unix
I have a list of keys which are listed in a txt file

sample.txt
    address
    contact_id
    created_at
    creator_id
    custom_fields
    address
    contact_id
    phone
    name
    email
    name

I have the following recursive script which can remove duplicates

```<code>#!/bin/bash
function keyChecker(){
    if grep -q $i uniqueKeys.txt; then
        echo "Duplicate Key: ${i}"
    else
        echo $i >> uniqueKeys.txt
         echo "New key: ${i}"
    fi
}

function recursiveDoer(){
    for i in $(cat keys.txt); do
        keyChecker $i
    done
recursiveDoer
}
touch uniqueKeys.txt
counter=0
recursiveDoer
</code>```

This code will return a unique list of keys to uniqueKeys.txt

These methods will send into an infinite loop once there are no more duplicates. Every recursive method I have wrote runs into this problem. I usually cheat by adding a counter that forces an exit 1 after an arbitrarily large number like 10,000.

What is the proper way to write this method using recursion and no infinite loop?

Can this be simplified and written as a non-recursive method in a single loop?

答:
If you do not care about the order of the keys you can simply use

sort -u keys.txt > uniqueKeys.txt

Title: read and write same file bash/unix

Body:
I have a list of keys which are listed in a txt file

sample.txt
    address
    contact_id
    created_at
    creator_id
    custom_fields
    address
    contact_id
    phone
    name
    email
    name

I have the following recursive script which can remove duplicates

#!/bin/bash
function keyChecker(){
    if grep -q $i uniqueKeys.txt; then
        echo "Duplicate Key: ${i}"
    else
        echo $i >> uniqueKeys.txt
         echo "New key: ${i}"
    fi
}

function recursiveDoer(){
    for i in $(cat keys.txt); do
        keyChecker $i
    done
recursiveDoer
}
touch uniqueKeys.txt
counter=0
recursiveDoer

This code will return a unique list of keys to uniqueKeys.txt

These methods will send into an infinite loop once there are no more duplicates. Every recursive method I have wrote runs into this problem. I usually cheat by adding a counter that forces an exit 1 after an arbitrarily large number like 10,000.

What is the proper way to write this method using recursion and no infinite loop?

Can this be simplified and written as a non-recursive method in a single loop?


问:
GRAILS 3.1.0 not showing Bootstrap glyphicons
I am using bootstrap on a GRAILS 3.1.0 application with

```<code>compile 'org.webjars:bootstrap:3.3.6'
</code>```

When I run the app both dev and prod from grails ...

```<code>grails prod run-app
grails dev run-app
</code>```

... all work propertly, both bootstap components and glyphicons, but when I put the war on a Tomcat, the glyphicons are not shown, but the bootstrap components works propertly.

I have seen some errors on traces with the form

```<code>No mapping found for HTTP request with URI [/helloworldapplication/fonts/glyphicons-halflings-regular.ttf] in DispatcherServlet with name 'grailsDispatcherServlet'
</code>```

The files could be found on Tomcat in the folder

```<code>webapps\helloworldapplication\assets\webjars\bootstrap\3.3.6\fonts
</code>```

This happends in Grails 3.1.0 and 3.1.1

答:
I put my glyphicon font files inside /grails-app/assets/fonts/. Then, from here, I did this:

Put the fonts directory parallel to stylesheets, images and javascript
  into the grails-app/assets/ folder. For the asset pipeline to know the
  new directory, specify it in the build.gradle file:

```<code>assets {
    minifyJs = true
    minifyCss = true
    includes = ["fonts/*"]
}
</code>```

Then, it seems I also had to do a grails clean before the glyph icons showed up.

Body:
I am using bootstrap on a GRAILS 3.1.0 application with

compile 'org.webjars:bootstrap:3.3.6'

When I run the app both dev and prod from grails ...

grails prod run-app
grails dev run-app

... all work propertly, both bootstap components and glyphicons, but when I put the war on a Tomcat, the glyphicons are not shown, but the bootstrap components works propertly.

I have seen some errors on traces with the form

No mapping found for HTTP request with URI [/helloworldapplication/fonts/glyphicons-halflings-regular.ttf] in DispatcherServlet with name 'grailsDispatcherServlet'

The files could be found on Tomcat in the folder

webapps\helloworldapplication\assets\webjars\bootstrap\3.3.6\fonts

This happends in Grails 3.1.0 and 3.1.1

Body:
I put my glyphicon font files inside /grails-app/assets/fonts/. Then, from here, I did this:

Put the fonts directory parallel to stylesheets, images and javascript
  into the grails-app/assets/ folder. For the asset pipeline to know the
  new directory, specify it in the build.gradle file:

assets {
    minifyJs = true
    minifyCss = true
    includes = ["fonts/*"]
}

Then, it seems I also had to do a grails clean before the glyph icons showed up.


问:
grunt task undefined not found
I'm fairly new to Grunt and trying to run a custom task using grunt-protractor-coverage plugin but I get the error

Warning: Task "undefined" not found. Use --force to continue.

My script is as follows.

```<code>module.exports = function(grunt) {

  grunt.registerTask('test', 'Log some stuff.', function() {
    console.log('Logging some stuff...');
  });

  grunt.initConfig({
        instrument: {
              files: 'server/**/*.js',
              options: {
                lazy: true,
                basePath: "instrumented"
             }
        }
  });

  grunt.loadNpmTasks('grunt-protractor-coverage');

  grunt.registerTask('instrument');

  // Default task(s)
  grunt.registerTask('default', ['instrument']);
};
</code>```

答:
I had this issue before, and solved it by updating grunt. Would be a good first step to try:

npm --global update grunt-cli

Title: grunt task undefined not found

Body:
I'm fairly new to Grunt and trying to run a custom task using grunt-protractor-coverage plugin but I get the error

Warning: Task "undefined" not found. Use --force to continue.

My script is as follows.

module.exports = function(grunt) {

  grunt.registerTask('test', 'Log some stuff.', function() {
    console.log('Logging some stuff...');
  });

  grunt.initConfig({
        instrument: {
              files: 'server/**/*.js',
              options: {
                lazy: true,
                basePath: "instrumented"
             }
        }
  });

  grunt.loadNpmTasks('grunt-protractor-coverage');

  grunt.registerTask('instrument');

  // Default task(s)
  grunt.registerTask('default', ['instrument']);
};


问:
Getting the error 2869 while adding custom actions to a C# setup project
I have created a C# setup project to deploy a C# windows application. I want to add custom prompt screens to my installation. So I have added a new "Installer" Class to my windows application and then overidden the "Install" method in it.

On right clicking SetUp project, in the "Custom Actions" window I added "primary output of the windows application", (where I have overridden "Install" method).

Later I set the "CustomActionData" property like this:

```<code>/txtBox1=[EDITA1]
</code>```

And the argument property to EDITA1, where EDITA1 is the identifier value for the text box that I have added to my custom prompt screen.

Inside the overridden Install method I am accessing this textBox value like this:

```<code> Context.Parameter["txtBox"]
</code>```

But when I try to install this package I am getting a pop up screen throwing error code 2869

The error popup messgae reads:

The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2869.

Kindly let me know how shall I pass values from custom screen to the overridden install method.

THANKS IN ADVANCE

答:
The format should be

/name="value" /name2="value". To pass installer properties the format is
  /name="[SourceDir]"

This link has more details

Body:
I have created a C# setup project to deploy a C# windows application. I want to add custom prompt screens to my installation. So I have added a new "Installer" Class to my windows application and then overidden the "Install" method in it.

On right clicking SetUp project, in the "Custom Actions" window I added "primary output of the windows application", (where I have overridden "Install" method).

Later I set the "CustomActionData" property like this:

/txtBox1=[EDITA1]

And the argument property to EDITA1, where EDITA1 is the identifier value for the text box that I have added to my custom prompt screen.

Inside the overridden Install method I am accessing this textBox value like this:

 Context.Parameter["txtBox"]

But when I try to install this package I am getting a pop up screen throwing error code 2869

The error popup messgae reads:

The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2869.

Kindly let me know how shall I pass values from custom screen to the overridden install method.

THANKS IN ADVANCE


问:
$watch binded variable in parent and nested controller
I have a question about $watch and the scope in nested controller.

I have an input binded with a ng-model.  For example, in my html

```<code>    <input ng-model='searchString' />
</code>```

This is within the child(nested) controller, but I defined ng-model in parent controller.  So I tried to $watch in parent controller.  It doesn't work.

```<code>    app.controller('mainCtrl', ['$scope', function($scope){
        $scope.searchString = '';
        $scope.$watch('searchString', function(){
            console.log("changed in parent");
        })
    }]);
    app.controller("nestedCtrl", ["$scope", function($scope){
    }])
</code>```

However, if I put $watch in child controller it would work.

```<code>    app.controller("nestedCtrl", ["$scope", function($scope){
        $scope.$watch('searchString', function(){
            console.log("changed in child");
        })
    }])
</code>```

Why I defined the scope in parent controller but can only watch in child controller?
Any ways could let parent controller detect the changes? Because I need to do something out of child controller but based on this scope variable, but I couldn't.

答:
That is because AngularJS child scopes copy the elements that are primitives from the parents, and reference the ones that are inherited from Objects. So, the child scope has a copy of searchString defined in the beginning.

Here's an example: https://jsfiddle.net/NitroInside/p85he1du

The detailed explanation is here: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Body:
I have a question about $watch and the scope in nested controller.

I have an input binded with a ng-model.  For example, in my html

    <input ng-model='searchString' />

This is within the child(nested) controller, but I defined ng-model in parent controller.  So I tried to $watch in parent controller.  It doesn't work.

    app.controller('mainCtrl', ['$scope', function($scope){
        $scope.searchString = '';
        $scope.$watch('searchString', function(){
            console.log("changed in parent");
        })
    }]);
    app.controller("nestedCtrl", ["$scope", function($scope){
    }])

However, if I put $watch in child controller it would work.

    app.controller("nestedCtrl", ["$scope", function($scope){
        $scope.$watch('searchString', function(){
            console.log("changed in child");
        })
    }])

Why I defined the scope in parent controller but can only watch in child controller?
Any ways could let parent controller detect the changes? Because I need to do something out of child controller but based on this scope variable, but I couldn't.


问:
How can I transfer ArrayLists between classes?
I am a rather large-scale noob. I have come across the answer a multitude of times, but, it was just not in a format I could understand. Right now, I am attempting to send a List full of values, to a separate class. I tried each of the resources but to no avail. Apologies if this is an inappropriate question here, a simple ask-with-no-code.</p>

答:
```<code>class list_receiver{ //class in which you want to send your list

  public void print_array_list(ArrayList<String> l ){
     System.out.println(l);
    }
 }

 class list_sender{//class from where you are sending your list
    public static void main(String args[]){
   list_receiver r = new list_receiver();
   ArrayList<String> list=new ArrayList<String>();
   list.add("A");
   list.add("B");
   r.print_array_list(list);
   }
}
</code>```


问:
Bootstrap navbar - removing space between buttons
I have a problem. I have a navbar with links represented by images like in the image below (please ignore the Home link as of now):

I would like to remove the grey space between each image horizontally. I have tried to set margin: 0% and padding: 0% on all the images and list items, but to no avail. Looking into Bootstraps source code I suspect it has something to do with the navbar-nav and nav classes being flex containers, but what flex property I should give what value to resolve the issue is unclear to me.

Here is the HTML for the navigation bar:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar_content">

            </button>

                Survey webapp

                    Home

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

<p>And here is the relevant (?) CSS:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav {
    padding: 0%;
    margin: 0%;
}

.navbar-nav {
    padding: 0%;
    margin: 0%;
}

.navitem {
    padding: 0%;
    margin: 0%;
}</code>```

Thanks in advance, I really appreciate the help!

Best regards,
Joshua

答:
It looks as if Bootstrap (version 3) applies padding to  elements inside .nav:

```<code>.nav>li>a {
    position: relative;
    display: block;
    padding: 10px 15px;
}
</code>```

I don't know if Bootstrap has a native method for removing that padding, but you can always override it yourself:

```<code>.nav>li>a {
    padding: 0;
}
</code>```

Body:
I have a problem. I have a navbar with links represented by images like in the image below (please ignore the Home link as of now):

I would like to remove the grey space between each image horizontally. I have tried to set margin: 0% and padding: 0% on all the images and list items, but to no avail. Looking into Bootstraps source code I suspect it has something to do with the navbar-nav and nav classes being flex containers, but what flex property I should give what value to resolve the issue is unclear to me.

Here is the HTML for the navigation bar:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar_content">

            </button>

                Survey webapp

                    Home

And here is the relevant (?) CSS:

.nav {
    padding: 0%;
    margin: 0%;
}

.navbar-nav {
    padding: 0%;
    margin: 0%;
}

.navitem {
    padding: 0%;
    margin: 0%;
}

Thanks in advance, I really appreciate the help!

Best regards,
Joshua

Body:
It looks as if Bootstrap (version 3) applies padding to <a> elements inside .nav:

.nav>li>a {
    position: relative;
    display: block;
    padding: 10px 15px;
}

I don't know if Bootstrap has a native method for removing that padding, but you can always override it yourself:

.nav>li>a {
    padding: 0;
}


问:
Creating loading display in PySide with threading
I am trying to display a loading graphic(for now just a label) at the beginning of my pyside program while another function is running. After it's done it should continue and load the main GUI. I have this so far

```<code>from PySide import QtCore
from PySide import QtGui

class DoStuff:
    def __init__(self):
        pass

    def ReturnInformation(self):
        time.sleep(20)                              #Sleep to simulate processing time
        return "information"

class Main(QtGui.QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.initQ = queue.Queue()
        self.initthread = threading.Thread(target=self.InitThread)
        self.initthread.daemon = True
        self.initthread.start()

        self.setStyleSheet("background-color: black;")
        self.setCursor(QtCore.Qt.BlankCursor)

        self.loaddisplay = QtGui.QLabel(self)
        self.loaddisplay.move(20, 20)
        self.loaddisplay.setText("Loading...")
        self.show()

        self.initthread.join()
        self.MainDisplay()
        self.show()

    def InitThread(self):
        self.dostuff = DoStuff()

    def MainDisplay(self):
        self.display = QtGui.QLabel(self)
        self.display.setStyleSheet("font: 70pt Helvetica; color: white;")
        self.display.move(20, 20)
        self.display.setText(self.dostuff.ReturnInformation())

        self.manager = QtCore.QTimer(self)
        self.manager.timeout.connect(self.Update)
        self.manager.start(100000)

    def Update(self):                                                  #Update the information once in a while
        self.timedisplay.setText(self.dostuff.ReturnInformation())

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    GUI = Main()
    sys.exit(app.exec_())
</code>```

The problem is that only the load graphic is displayed and the GUI from MainDisplay() is never displayed. I'm pretty sure this has something to do with how I'm calling the show()function. Is that the problem, and how do I fix it?

Also, how would I delete the loading label once it has finished loading?

P.S. (I asked this question before, but it got no answers or comments and low views so I deleted it and am asking the question again)

答:
Although python provides several ways to execute task through threads these do not necessarily conform to the rules of Qt, it is appropriate to use the tools of the framework such as QThread:</p>

```<code>class DoStuffThread(QtCore.QThread):
    displaySignal = QtCore.Signal(str)
    timeSignal = QtCore.Signal(str)

    def __init__(self, *args, **kwargs):
        QtCore.QThread.__init__(self, *args, **kwargs)

        self.timer = QtCore.QTimer()
        self.timer.moveToThread(self)
        self.timer.timeout.connect(self.onTimeout)
        self.stuff = DoStuff()

    def onTimeout(self):
        data = self.stuff.ReturnInformation()
        self.timeSignal.emit(data)

    def run(self):
        data = self.stuff.ReturnInformation()
        self.displaySignal.emit(data)
        self.timer.start(20000)
        loop = QtCore.QEventLoop()
        loop.exec_()

class DoStuff:
    def ReturnInformation(self):
        time.sleep(2)  # Sleep to simulate processing time
        return "information-{}".format(QtCore.QTime.currentTime().toString("hh:mm:ss"))

class Main(QtGui.QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.setStyleSheet("background-color: black;")
        self.setCursor(QtCore.Qt.BlankCursor)
        self.setLayout(QtGui.QVBoxLayout())

        self.loaddisplay = QtGui.QLabel(self)
        self.display = QtGui.QLabel(self)
        self.timedisplay = QtGui.QLabel(self)

        self.layout().addWidget(self.loaddisplay)
        self.layout().addWidget(self.display)
        self.layout().addWidget(self.timedisplay)

        self.thread = DoStuffThread(self)
        self.thread.displaySignal.connect(self.display.setText, QtCore.Qt.QueuedConnection)
        self.thread.timeSignal.connect(self.timedisplay.setText, QtCore.Qt.QueuedConnection)
        self.thread.start()

        self.loaddisplay.move(20, 20)
        self.loaddisplay.setText("Loading...")
        self.display.setStyleSheet("font: 70pt Helvetica; color: white;")
        self.display.move(20, 20)

    def closeEvent(self, event):
        self.thread.quit()
        QtGui.QWidget.closeEvent(self, event)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    GUI = Main()
    GUI.show()
    sys.exit(app.exec_())
</code>```

Body:
I am trying to display a loading graphic(for now just a label) at the beginning of my pyside program while another function is running. After it's done it should continue and load the main GUI. I have this so far

from PySide import QtCore
from PySide import QtGui

class DoStuff:
    def __init__(self):
        pass

    def ReturnInformation(self):
        time.sleep(20)                              #Sleep to simulate processing time
        return "information"

class Main(QtGui.QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.initQ = queue.Queue()
        self.initthread = threading.Thread(target=self.InitThread)
        self.initthread.daemon = True
        self.initthread.start()

        self.setStyleSheet("background-color: black;")
        self.setCursor(QtCore.Qt.BlankCursor)

        self.loaddisplay = QtGui.QLabel(self)
        self.loaddisplay.move(20, 20)
        self.loaddisplay.setText("Loading...")
        self.show()

        self.initthread.join()
        self.MainDisplay()
        self.show()

    def InitThread(self):
        self.dostuff = DoStuff()

    def MainDisplay(self):
        self.display = QtGui.QLabel(self)
        self.display.setStyleSheet("font: 70pt Helvetica; color: white;")
        self.display.move(20, 20)
        self.display.setText(self.dostuff.ReturnInformation())

        self.manager = QtCore.QTimer(self)
        self.manager.timeout.connect(self.Update)
        self.manager.start(100000)

    def Update(self):                                                  #Update the information once in a while
        self.timedisplay.setText(self.dostuff.ReturnInformation())

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    GUI = Main()
    sys.exit(app.exec_())

The problem is that only the load graphic is displayed and the GUI from MainDisplay() is never displayed. I'm pretty sure this has something to do with how I'm calling the show()function. Is that the problem, and how do I fix it?

Also, how would I delete the loading label once it has finished loading?

P.S. (I asked this question before, but it got no answers or comments and low views so I deleted it and am asking the question again)

Body:
Although python provides several ways to execute task through threads these do not necessarily conform to the rules of Qt, it is appropriate to use the tools of the framework such as QThread:

class DoStuffThread(QtCore.QThread):
    displaySignal = QtCore.Signal(str)
    timeSignal = QtCore.Signal(str)

    def __init__(self, *args, **kwargs):
        QtCore.QThread.__init__(self, *args, **kwargs)

        self.timer = QtCore.QTimer()
        self.timer.moveToThread(self)
        self.timer.timeout.connect(self.onTimeout)
        self.stuff = DoStuff()

    def onTimeout(self):
        data = self.stuff.ReturnInformation()
        self.timeSignal.emit(data)

    def run(self):
        data = self.stuff.ReturnInformation()
        self.displaySignal.emit(data)
        self.timer.start(20000)
        loop = QtCore.QEventLoop()
        loop.exec_()

class DoStuff:
    def ReturnInformation(self):
        time.sleep(2)  # Sleep to simulate processing time
        return "information-{}".format(QtCore.QTime.currentTime().toString("hh:mm:ss"))

class Main(QtGui.QWidget):
    def __init__(self):
        super(Main, self).__init__()
        self.setStyleSheet("background-color: black;")
        self.setCursor(QtCore.Qt.BlankCursor)
        self.setLayout(QtGui.QVBoxLayout())

        self.loaddisplay = QtGui.QLabel(self)
        self.display = QtGui.QLabel(self)
        self.timedisplay = QtGui.QLabel(self)

        self.layout().addWidget(self.loaddisplay)
        self.layout().addWidget(self.display)
        self.layout().addWidget(self.timedisplay)

        self.thread = DoStuffThread(self)
        self.thread.displaySignal.connect(self.display.setText, QtCore.Qt.QueuedConnection)
        self.thread.timeSignal.connect(self.timedisplay.setText, QtCore.Qt.QueuedConnection)
        self.thread.start()

        self.loaddisplay.move(20, 20)
        self.loaddisplay.setText("Loading...")
        self.display.setStyleSheet("font: 70pt Helvetica; color: white;")
        self.display.move(20, 20)

    def closeEvent(self, event):
        self.thread.quit()
        QtGui.QWidget.closeEvent(self, event)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    GUI = Main()
    GUI.show()
    sys.exit(app.exec_())


问:
Dynamically generate query with diff number of "where"?
How can I dynamically generate query to the db if I don't know how much filter and update -  values will be in the $filters and $updates arrays?
Template of the query is below:

```<code>$model::where($key_1, '=', $filter1)
    ->where($key_2, '=', $filter_2)
    ->where($key_n, '=', $filter_n)
    ->update([$key_1 => $update_1,
        $key_2 => $update_2,
        $key_n => $update_n
    ]);
</code>```

答:
I use and recommend query scopes.
It keeps your code clean and readable while you can reuse code also.

In my model User I would create a function called scopeFilter

```<code>public function scopeFilter($query, $params)
{
    if(isset($params['status']) && trim($params['status']) !== '')
    {
        $query->where('status', '=', trim($params['status']));
    }

    if(isset($params['is_admin']) && is_bool($params['is_admin']))
    {
        $query->where('is_admin', '=', $params['is_admin'] ? '1' : '0');
    }
    return $query;
}
</code>```

In my ApiUsersController I would just use this call, note that word scope is omitted when making the call.

```<code>public function index(Request $request)
{
    $users = User::filter($request->all())->get();

    return Response::make([
        'success' => true,
        'data'    => $users
        ]);
}
</code>```

Now in your case, you can have a loop in scopeFilter something like following

```<code>foreach ($params as $key->$param) {
    $query->where($key, '=', $param);
}
</code>```

This is to give you an idea how I do it and it keeps the code clean.

Also please read Local Scopes in Laravel documentation here. IMHO it is cleanest way to achieve filtering.

Body:
How can I dynamically generate query to the db if I don't know how much filter and update -  values will be in the $filters and $updates arrays?
Template of the query is below:

$model::where($key_1, '=', $filter1)
    ->where($key_2, '=', $filter_2)
    ->where($key_n, '=', $filter_n)
    ->update([$key_1 => $update_1,
        $key_2 => $update_2,
        $key_n => $update_n
    ]);

Body:
I use and recommend query scopes.
It keeps your code clean and readable while you can reuse code also.

In my model User I would create a function called scopeFilter

public function scopeFilter($query, $params)
{
    if(isset($params['status']) && trim($params['status']) !== '')
    {
        $query->where('status', '=', trim($params['status']));
    }

    if(isset($params['is_admin']) && is_bool($params['is_admin']))
    {
        $query->where('is_admin', '=', $params['is_admin'] ? '1' : '0');
    }
    return $query;
}

In my ApiUsersController I would just use this call, note that word scope is omitted when making the call.

public function index(Request $request)
{
    $users = User::filter($request->all())->get();

    return Response::make([
        'success' => true,
        'data'    => $users
        ]);
}

Now in your case, you can have a loop in scopeFilter something like following

foreach ($params as $key->$param) {
    $query->where($key, '=', $param);
}

This is to give you an idea how I do it and it keeps the code clean.

Also please read Local Scopes in Laravel documentation here. IMHO it is cleanest way to achieve filtering.


问:
Replace Console.WriteLine in NUnit
I haven't done much with NUnit before, but I just wanted to dump some text to a window in a console type fashion. For example:

Console.WriteLine("... some information...");
```

That won't work of course because NUnit is driving things.

I'm in the middle of building some unit tests and want to dump a list of variable values for inspection during debug. It isn't strictly a unit test if I need to do this, I admit that, but it would be convenient.

答: In Visual Studio 2017, in the Test Explorer window, there is a link, Output, in the lower Test pane. This brings up anything written to the console during that unit test.

ContentLicense: CC BY-SA 4.0

Title: Replace Console.WriteLine in NUnit

Body:
I haven't done much with NUnit before, but I just wanted to dump some text to a window in a console type fashion. For example:

Console.WriteLine("... some information...");

That won't work of course because NUnit is driving things.

I'm in the middle of building some unit tests and want to dump a list of variable values for inspection during debug. It isn't strictly a unit test if I need to do this, I admit that, but it would be convenient.


问:
Calculating modulus by recursion without using modulo division
I'm doing a problem with recursive functions for a class project.  I'm trying to write a program that uses a recursive function that calculates a modulus without actually using the modulus operator.  I'm trying to use a reference parameter because I think that's the easiest way to do this, however my program is not functioning as intended.  </p>

```<code>//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}
</code>```

答:
Try this:</p>

```<code>int recursiveMod(int num, int den)
{
    if (num < 0) return recursiveMod(num + den, den);

    // Don't forget the case of num = 2 and den = 7
    if (num < den) return num;

    return recursiveMod(num - den, den);
}
</code>```

Body:
I'm doing a problem with recursive functions for a class project.  I'm trying to write a program that uses a recursive function that calculates a modulus without actually using the modulus operator.  I'm trying to use a reference parameter because I think that's the easiest way to do this, however my program is not functioning as intended.

//Michael Hery
//COP 2001
//11/15/2017
//Recursive Modulus

#include <iostream>
#include <iomanip>

using namespace std;

int recursiveMod(int &, int);

int main()
{
    int num;
    int den;
    int displayNum;
    int total;

    cout << "Please input the numerator (an integer) >> ";
    cin >> num;
    while (num < 0)
    {
        cout << "Integer must be greater than or equal to zero. >> ";
        cin >> num;
    }
    displayNum = num;
    cout << "Please input the denominator (an integer) >> ";
    cin >> den;
    while (den <= 0)
    {
        cout << "Integer must be greater than zero. >> ";
        cin >> den;
    }
    cout << "You have entered " << num << " % " << den << endl;

    total = recursiveMod(num, den);

    cout << "Modulus result: " << displayNum << " % " << den << " = " << total << endl;

    system("PAUSE");
    return 0;
}

int recursiveMod(int &num, int den)
{
    if (num == 0)
        return 0;

    num = num - den;

    if ((num - den) > den)
    {
        recursiveMod(num, den);
    }
    return num;
}

Body:
Try this:

int recursiveMod(int num, int den)
{
    if (num < 0) return recursiveMod(num + den, den);

    // Don't forget the case of num = 2 and den = 7
    if (num < den) return num;

    return recursiveMod(num - den, den);
}


问:
How to type a React.ComponentType with a static property?
I'm writing a HOC component for next.js pages, and this HOC needs to accept a component with a specific getInitialProps static function.

I can't get figure out the right typing for this with flow:

```<code>const wrapComponent = (Component: React.ComponentType<*>) => {
    const original: Function = Component.getInitialProps;

    return class extends React.Component<*> {
        static async getInitialProps(ctx) {
            const props = await original(ctx);
            return {
                ...props,
                custom: 'a',
            };
        }

        render() {
            return <Component {...this.props} />;
        }
    }
}
</code>```

I get this error:

```<code>5:     const original: Function = Component.getInitialProps;
                                            ^ property `getInitialProps`. Property not found in
5:     const original: Function = Component.getInitialProps;
                                  ^ statics of React$Component
</code>```

Demo

答:
Is this what you're looking for?

```<code>// @flow

import React from 'react';
import type {ComponentType} from 'react';

interface StaticInterface {
  fn(): void;
}

class NoStatic extends React.Component<{}> {
}

class WithStatic extends React.Component<{}> {
  static fn() {}
}

const c1: ComponentType<{}> = NoStatic;
const c2: ComponentType<{}> = WithStatic;
const c3: ComponentType<{}> & StaticInterface = WithStatic;
// const c4: ComponentType<{}> & StaticInterface = NoStatic;     // NOT OK
</code>```

(demo)

I find this pretty confusing myself. I adapted it from this:

https://blog.bluematador.com/posts/enforcing-method-presence-in-react-components-with-flow

Related:

https://github.com/facebook/flow/issues/2048

https://github.com/facebook/flow/pull/3994

Body:
I'm writing a HOC component for next.js pages, and this HOC needs to accept a component with a specific getInitialProps static function.

I can't get figure out the right typing for this with flow:

const wrapComponent = (Component: React.ComponentType<*>) => {
    const original: Function = Component.getInitialProps;

    return class extends React.Component<*> {
        static async getInitialProps(ctx) {
            const props = await original(ctx);
            return {
                ...props,
                custom: 'a',
            };
        }

        render() {
            return <Component {...this.props} />;
        }
    }
}

I get this error:

5:     const original: Function = Component.getInitialProps;
                                            ^ property `getInitialProps`. Property not found in
5:     const original: Function = Component.getInitialProps;
                                  ^ statics of React$Component

Demo

Body:
Is this what you're looking for?

// @flow

import React from 'react';
import type {ComponentType} from 'react';

interface StaticInterface {
  fn(): void;
}

class NoStatic extends React.Component<{}> {
}

class WithStatic extends React.Component<{}> {
  static fn() {}
}

const c1: ComponentType<{}> = NoStatic;
const c2: ComponentType<{}> = WithStatic;
const c3: ComponentType<{}> & StaticInterface = WithStatic;
// const c4: ComponentType<{}> & StaticInterface = NoStatic;     // NOT OK

(demo)

I find this pretty confusing myself. I adapted it from this:

https://blog.bluematador.com/posts/enforcing-method-presence-in-react-components-with-flow

Related:

https://github.com/facebook/flow/issues/2048

https://github.com/facebook/flow/pull/3994


问:
Java UDP server only receives the first int from array
I'm trying to send an array of int from client to server using java UDP socket. I hardcoded an array of 4 numbers in the client, I send the number 4 (length of the array), the server receives it and then from the client I send the array. But in the server, when I print the array, the first number gets printed followed by 3 zeros.

client.java

```<code>import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class clien {
    public static void main(String args[]) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket();
        InetAddress ip = InetAddress.getByName("localhost");

        byte[] sendData;
        int number = 4;
        sendData = ByteBuffer.allocate(4).putInt(number).array();
        DatagramPacket sendPacket = new DatagramPacket(sendData, 4, ip, 1234);
        datagramSocket.send(sendPacket);

        int[] n = new int[4];
        n[0] = 23;
        n[1] = 44;
        n[2] = 9;
        n[3] = 12;

        ByteBuffer byteBuffer = ByteBuffer.allocate(n.length * 4);
        IntBuffer intBuffer = byteBuffer.asIntBuffer();
        intBuffer.put(n);
        sendData = byteBuffer.array();
        sendPacket = new DatagramPacket(sendData, number, ip, 1234);
        datagramSocket.send(sendPacket);
    }
}
</code>```

server.java

```<code>import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class server {
    public static void main(String args[]) throws Exception{
        byte[] receivedData = new byte[1024];
        DatagramSocket datagramSocket = new DatagramSocket(1234);

        while (true) {
            DatagramPacket datagramPacket = new DatagramPacket(receivedData, receivedData.length);
            datagramSocket.receive(datagramPacket);
            int numbers = ByteBuffer.wrap(receivedData).getInt();

            datagramPacket = new DatagramPacket(receivedData, receivedData.length);
            datagramSocket.receive(datagramPacket);

            IntBuffer intBuffer = ByteBuffer.wrap(receivedData).asIntBuffer();
            int[] n = new int[numbers];
            intBuffer.get(n);

            for (int i = 0; i < numbers; i++) {
                System.out.println(n[i]);
            }

        }
    }
}
</code>```

In this case what is gonna be printed by the server is:
23
0
0
0

.. and I can't figure out what's wrong.

答:
You are only sending the first 4 bytes of the buffer..

```<code>int number = 4;

sendPacket = new DatagramPacket(sendData, number, ip, 1234);
</code>```

number is 4, but needs to be multiplied by the length of an int (4 bytes)

```<code>sendPacket = new DatagramPacket(sendData, number*4, ip, 1234);
</code>```

or as sendData was constructed with the correct length initially..

```<code>sendPacket = new DatagramPacket(sendData, sendData.length, ip, 1234);
</code>```

Also, don't forget that UDP packets can arrive in any order, or not at all. So even though you send the length packet then the data packet, they might not arrive in that order or even go missing. Data in UDP packets should be independent of the others, because of these reasons.

In your case, you don't need to send a packet to specify how many ints will be in the second packet. Simply divide the received packet length by 4.

Body:
I'm trying to send an array of int from client to server using java UDP socket. I hardcoded an array of 4 numbers in the client, I send the number 4 (length of the array), the server receives it and then from the client I send the array. But in the server, when I print the array, the first number gets printed followed by 3 zeros.

client.java

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class clien {
    public static void main(String args[]) throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket();
        InetAddress ip = InetAddress.getByName("localhost");

        byte[] sendData;
        int number = 4;
        sendData = ByteBuffer.allocate(4).putInt(number).array();
        DatagramPacket sendPacket = new DatagramPacket(sendData, 4, ip, 1234);
        datagramSocket.send(sendPacket);

        int[] n = new int[4];
        n[0] = 23;
        n[1] = 44;
        n[2] = 9;
        n[3] = 12;

        ByteBuffer byteBuffer = ByteBuffer.allocate(n.length * 4);
        IntBuffer intBuffer = byteBuffer.asIntBuffer();
        intBuffer.put(n);
        sendData = byteBuffer.array();
        sendPacket = new DatagramPacket(sendData, number, ip, 1234);
        datagramSocket.send(sendPacket);
    }
}

server.java

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class server {
    public static void main(String args[]) throws Exception{
        byte[] receivedData = new byte[1024];
        DatagramSocket datagramSocket = new DatagramSocket(1234);

        while (true) {
            DatagramPacket datagramPacket = new DatagramPacket(receivedData, receivedData.length);
            datagramSocket.receive(datagramPacket);
            int numbers = ByteBuffer.wrap(receivedData).getInt();

            datagramPacket = new DatagramPacket(receivedData, receivedData.length);
            datagramSocket.receive(datagramPacket);

            IntBuffer intBuffer = ByteBuffer.wrap(receivedData).asIntBuffer();
            int[] n = new int[numbers];
            intBuffer.get(n);

            for (int i = 0; i < numbers; i++) {
                System.out.println(n[i]);
            }

        }
    }
}

In this case what is gonna be printed by the server is:
23
0
0
0

.. and I can't figure out what's wrong.

Body:
You are only sending the first 4 bytes of the buffer..

int number = 4;

sendPacket = new DatagramPacket(sendData, number, ip, 1234);

number is 4, but needs to be multiplied by the length of an int (4 bytes)

sendPacket = new DatagramPacket(sendData, number*4, ip, 1234);

or as sendData was constructed with the correct length initially..

sendPacket = new DatagramPacket(sendData, sendData.length, ip, 1234);

Also, don't forget that UDP packets can arrive in any order, or not at all. So even though you send the length packet then the data packet, they might not arrive in that order or even go missing. Data in UDP packets should be independent of the others, because of these reasons.

In your case, you don't need to send a packet to specify how many ints will be in the second packet. Simply divide the received packet length by 4.


问:
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?

Please explain the rationale, if possible.

I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the intermediate value.

Is there any better form of for loop than these two?

p.s: I use the former one as suggested by one of the sources, which i don't remember now.

答:
You should use whichever of <, <=, != etc. best expresses your application logic, but if there's no reason to prefer any particular style, then be consistent.  In informing that decision, the < and != operators have the advantage of allowing comparisons between 0-based indices and sizeof or STL-style size / length values, as in:

```<code>for (size_t i = 0; i < my_vector.size(); ++i)
    ...
</code>```

The < and <= operators sometimes guard against incrementing past the terminating value (if you've got another condition inside the loop under which you increment/add-to i, or there's some floating point rounding/representation disparity).  Not often actually significant, but saving an occasional bug is better than nothing.

Given '<' is the intersection of these two sets, it's a popular choice.  To my mind, < also communicates the states under which the loop runs... a more positive assertion rather than the != style.  In general, negative assertions are discouraged in programming (e.g. bool invalid is more complicated to get your head around reliably than bool valid, especially in complex boolean expression and when double-negatives are introduced).

This is of course for numeric types.  Other types may imply other styles... for example, use of != sentinel.  I prefer to have the choice of operator help document these usage implications of the type, though that's a personal choice and arguably redundant.

Otherwise, preincrement can be more efficient for complicated types than post- as it avoids a temporary.

Body:
You should use whichever of <, <=, != etc. best expresses your application logic, but if there's no reason to prefer any particular style, then be consistent.  In informing that decision, the < and != operators have the advantage of allowing comparisons between 0-based indices and sizeof or STL-style size / length values, as in:

for (size_t i = 0; i < my_vector.size(); ++i)
    ...

The < and <= operators sometimes guard against incrementing past the terminating value (if you've got another condition inside the loop under which you increment/add-to i, or there's some floating point rounding/representation disparity).  Not often actually significant, but saving an occasional bug is better than nothing.

Given '<' is the intersection of these two sets, it's a popular choice.  To my mind, < also communicates the states under which the loop runs... a more positive assertion rather than the != style.  In general, negative assertions are discouraged in programming (e.g. bool invalid is more complicated to get your head around reliably than bool valid, especially in complex boolean expression and when double-negatives are introduced).

This is of course for numeric types.  Other types may imply other styles... for example, use of != sentinel.  I prefer to have the choice of operator help document these usage implications of the type, though that's a personal choice and arguably redundant.

Otherwise, preincrement can be more efficient for complicated types than post- as it avoids a temporary.


问:
C# Execute function at specific time
I made a little Windows Forms program to do some auto backup of some files on my disk. Right now I need to push a button before it is executed, but I want to make the program running and at 3am run the function that does the backup.

I've researched a bit and found out i need a timer for this, but I've failed to use it so it executes at a specific time.

I hope you can help me out. :-)

Thanks!

答:
```<code>    //Perhaps the following is a more suitable solution consume the following

    public class DailyTrigger
    {
        readonly TimeSpan triggerHour;

        public DailyTrigger(int hour, int minute = 0, int second = 0)
        {
          triggerHour = new TimeSpan(hour, minute, second);
          InitiateAsync();
        }

        async void InitiateAsync()
        {
          while (true)
          {
            var triggerTime = DateTime.Today + triggerHour - DateTime.Now;
            if (triggerTime < TimeSpan.Zero)
              triggerTime = triggerTime.Add(new TimeSpan(24, 0, 0));
            await Task.Delay(triggerTime);
            OnTimeTriggered?.Invoke();
          }
        }

        public event Action OnTimeTriggered;
      }

   // as Follows

     var trigger = new DailyTrigger(17); // every day at 5:00pm

          trigger.OnTimeTriggered += () =>
          {
            //Do Logic
          };
</code>```

Title: C# Execute function at specific time


问:
How to make migrations only one app inside project using django?
I have the follow project structure:

```<code>MyProject
|--myBaseApp
|  |--migrations
|  |--__init__.py
|  |--models.py
|  |...
|--myClientApp
|  |--migrations
|  |--__init__.py
|  |--models.py
|  |...
|--myProject
|  |--__init__.py
|  |--settings.py
|  |--urls.py
|  |...
|--manage.py
|...
</code>```

I can import to myClientApp/models.py the models.py from myBaseApp, but when I use the commands on terminal mode:

python manage.py makemigrations
python manage.py migrate myClienteApp
```

The Django creates, on data base, all tables from models.py, both myClienApp/models.py and myBaseApp/models.py. I'd like to make migrate only the models.py from myClienApp/models.py. It's possible? Or do I need to create other project?

答:
It sounds like this is the first migration -- Django will migrate the stuff from the myBaseApp if so

You can try to run a specific migration instead i.e.:

./manage.py migrate myapp 0005_migration_to_run

Body:
I have the follow project structure:

MyProject
|--myBaseApp
|  |--migrations
|  |--__init__.py
|  |--models.py
|  |...
|--myClientApp
|  |--migrations
|  |--__init__.py
|  |--models.py
|  |...
|--myProject
|  |--__init__.py
|  |--settings.py
|  |--urls.py
|  |...
|--manage.py
|...

I can import to myClientApp/models.py the models.py from myBaseApp, but when I use the commands on terminal mode:

python manage.py makemigrations
python manage.py migrate myClienteApp

The Django creates, on data base, all tables from models.py, both myClienApp/models.py and myBaseApp/models.py. I'd like to make migrate only the models.py from myClienApp/models.py. It's possible? Or do I need to create other project?


问:
What is the sequence of calls of copy constructor in a multi-level inheritance?
I have been trying to figure this out rigorously. Given three classes inheriting from each other, how does the sequence work?
For eg: Classes Vehicle->Car->Mercedes</p>

答:
What is the sequence of calls of copy constructor

The order is same as for other constructors.

virtual bases

non virtual bases

members

constructor body

If there are multiple direct bases or members, they are constructed in order of declaration.

In between each sub-object construction, an initializer list expression may be executed for the next sub-object.

For eg: Classes Vehicle->Car->Mercedes

If Car is a base of Mercedes, then the Car base-sub-object is constructed before the contructor body of Mercedes is executed. If Vehicle is base of Car, then the Vehicle base-sub-object is constructed before the constructor body of Car is executed.


问:
Getting values of multiple checkboxes(Javascript), then assigning different values based on selection
So I have a bit of a tricky situation here.

I have a series of forms that have selections that are being stored as arrays. I am checking selections against the correct answer at the index, so index and amount of elements are very important.

My issue arises why trying to concatenate these 2 arrays that hold checked and unchecked values for html checkboxes.

i.e:     let comb = checked.concat(unchecked)

```<code>let checked = $('input:checkbox:checked').map(function() {
return this.value;}).get();

let unchecked = $('input:checkbox:not(:checked)').map(function() {
return "100"; }).get();
</code>```

The problem with that code is it messes up the order of selections, which breaks the code that is checking at specific indexes against the correct answer.

What I need is to get all the checkbox values, and assign the html value only if it is checked, otherwise insert some arbitrary value(as you can see return "100")

Something like this(not syntatically correct or runnable):

```<code>let checked = $('input:checkbox').map(function() {
if ('input:checkbox:checked'){ .  //if checked
return this.value;}).get();}else if ('input:checkbox:not(:checked)'){ //if unchecked
return "100"; }).get();
}
</code>```

答:
You need the whole conditional inside the map() callback

```<code>let checked = $('input:checkbox').map(function() {
  // if checked return the value , if not return "100"
  return this.checked ? this.value : '100';
}).get();
</code>```

Or in long-hand using is() as you were trying to do

```<code>let checked = $('input:checkbox').map(function() {
  if($(this).is(':checked')){
     return this.value;
  }else{
     return '100';
  }
}).get();
</code>```

Body:
So I have a bit of a tricky situation here.

I have a series of forms that have selections that are being stored as arrays. I am checking selections against the correct answer at the index, so index and amount of elements are very important.

My issue arises why trying to concatenate these 2 arrays that hold checked and unchecked values for html checkboxes.

i.e:     let comb = checked.concat(unchecked)

let checked = $('input:checkbox:checked').map(function() {
return this.value;}).get();

let unchecked = $('input:checkbox:not(:checked)').map(function() {
return "100"; }).get();

The problem with that code is it messes up the order of selections, which breaks the code that is checking at specific indexes against the correct answer.

What I need is to get all the checkbox values, and assign the html value only if it is checked, otherwise insert some arbitrary value(as you can see return "100")

Something like this(not syntatically correct or runnable):

let checked = $('input:checkbox').map(function() {
if ('input:checkbox:checked'){ .  //if checked
return this.value;}).get();}else if ('input:checkbox:not(:checked)'){ //if unchecked
return "100"; }).get();
}

Body:
You need the whole conditional inside the map() callback

let checked = $('input:checkbox').map(function() {
  // if checked return the value , if not return "100"
  return this.checked ? this.value : '100';
}).get();

Or in long-hand using is() as you were trying to do

let checked = $('input:checkbox').map(function() {
  if($(this).is(':checked')){
     return this.value;
  }else{
     return '100';
  }
}).get();


答:
Constructors are always executed from bottom to top, so first Vehicle, next Car and finally Mercedes.
The reason for this behavior is that the child classes may use variables of the base class so those have to be initialized first.

Destructors go the same way back: first Mercedes then Car and finally Vehicle, for much the same reasons.

Title: What is the sequence of calls of copy constructor in a multi-level inheritance?

Body:
I have been trying to figure this out rigorously. Given three classes inheriting from each other, how does the sequence work?
For eg: Classes Vehicle->Car->Mercedes


问:
How can I add a list of Matrices in Python 3?
I have already built a function that adds two matrices, now I'm trying to reuse the same function and make up for a function that sums up a LIST of matrices.

I keep getting errors and out of range indexes..

Can anyone shed any light?

Thanks a lot!

This is what I have done:

```<code>def add_matrices(a, b):
answer = []
for i in range(len(a)):
    row = []
    for j in range(len(a[0])):
        row.append(a[i][j]+b[i][j])
    answer[i].append(row)
return answer

print(add_matrices([[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]]))
print(add_matrices([[1,-2],[-4,5]],[[3,2],[5,-4]]))

def sum_matrices(mat_lst):
answer = []
for i in range(1, len(mat_lst)):
    row = []
    for j in range(1, len(a[0][0])):
        row.append(a[i][j]+b[i][j])
    answer.append(row)
return answer

print(sum_matrices([[[1,-2],[-4,5]],[[3,2],[5,-4]]]))
print(sum_matrices([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]],[[31,32,13],[34,35,36]]]))
</code>```

答:
numpy has implemented much of what you are already trying to do. And it will scale much better.

Matrix Addition Example:

```<code>>>> import numpy as np
>>> x1 = np.array([[1,2,3],[4,5,6]])
>>> x2 = np.array([[11,12,13],[14,15,16]])
>>> result = x1 + x2
>>> result
array([[12, 14, 16],
       [18, 20, 22]])
</code>```

If you want to sum up a list of matrices it is as simple as:

```<code>>>> x = [x1, x2]
>>> sum(x)
array([[12, 14, 16],
       [18, 20, 22]])
</code>```

And if you want it specifically as a python nested list:

```<code>>>> sum(x).tolist()
[[12, 14, 16], [18, 20, 22]]
</code>```

Hope this helps!

Body:
I have already built a function that adds two matrices, now I'm trying to reuse the same function and make up for a function that sums up a LIST of matrices.

I keep getting errors and out of range indexes..

Can anyone shed any light?

Thanks a lot!

This is what I have done:

def add_matrices(a, b):
answer = []
for i in range(len(a)):
    row = []
    for j in range(len(a[0])):
        row.append(a[i][j]+b[i][j])
    answer[i].append(row)
return answer

print(add_matrices([[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]]))
print(add_matrices([[1,-2],[-4,5]],[[3,2],[5,-4]]))

def sum_matrices(mat_lst):
answer = []
for i in range(1, len(mat_lst)):
    row = []
    for j in range(1, len(a[0][0])):
        row.append(a[i][j]+b[i][j])
    answer.append(row)
return answer

print(sum_matrices([[[1,-2],[-4,5]],[[3,2],[5,-4]]]))
print(sum_matrices([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]],[[21,22,23],[24,25,26]],[[31,32,13],[34,35,36]]]))

Body:
numpy has implemented much of what you are already trying to do. And it will scale much better.

Matrix Addition Example:

>>> import numpy as np
>>> x1 = np.array([[1,2,3],[4,5,6]])
>>> x2 = np.array([[11,12,13],[14,15,16]])
>>> result = x1 + x2
>>> result
array([[12, 14, 16],
       [18, 20, 22]])

If you want to sum up a list of matrices it is as simple as:

>>> x = [x1, x2]
>>> sum(x)
array([[12, 14, 16],
       [18, 20, 22]])

And if you want it specifically as a python nested list:

>>> sum(x).tolist()
[[12, 14, 16], [18, 20, 22]]

Hope this helps!


问:
Fixed size div which sits to the right of a main div that fills up remainder of screen
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

```<code>+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+
</code>```

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

```<code>#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}
</code>```

答:
look on my site : http://www.mcohenlawyer.com/

is it what you want ?

if yes, this is the CSS code :

(supported in all major browsers)

```<code>div.menubar {
    position: fixed; /*can be absolute too*/
    width: 158px;
    /*what comes latter is not relevant for your question*/
    /*......*/
}
.body { /*the main body*/
    position: absolute;
    right: 180px;/*can be 159px, if you don't want space between divs*/
    min-height: 870px;
    /*what comes latter is not relevant for your question*/
    /*......*/
}
</code>```

Body:
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}

Body:
look on my site : http://www.mcohenlawyer.com/

is it what you want ?

if yes, this is the CSS code :

(supported in all major browsers)

div.menubar {
    position: fixed; /*can be absolute too*/
    width: 158px;
    /*what comes latter is not relevant for your question*/
    /*......*/
}
.body { /*the main body*/
    position: absolute;
    right: 180px;/*can be 159px, if you don't want space between divs*/
    min-height: 870px;
    /*what comes latter is not relevant for your question*/
    /*......*/
}


问:
jekyll liquid, contains inside if loop
Just wondering why the liquid contain statement doesn't seem to see that there's a link in the url?

YAML Front matter

```<code>javascript:
  - https://external.js
  - local-script.js
</code>```

Footer file:

```<code> {% if page.javascript %}
      {% for script in page.javascript %}
        {% if page.javascript contains "://" %}
        <script src="{{ script }}"></script>
          {% else %}
        <script src="{{ script | prepend: '/assets/js/' | relative_url }}"></script> cat
        {% endif %}
      {% endfor %}
    {% endif %}
</code>```

the output is

```<code><script src="/assets/js/https://external.js"></script> "cat"
<script src="/assets/js/local-script.js"></script> "cat"
</code>```

答:
The YAML front matter thinks you have created a variable called https with the value of //external.js. You can test that by calling {{ page.javascript.https }} and see if it returns //external. The solution would be to write your YAML front matter strings like this:

```<code>javascript:
  - 'https://external.js'
  - 'local-script.js'
</code>```

Title: jekyll liquid, contains inside if loop

Body:
Just wondering why the liquid contain statement doesn't seem to see that there's a link in the url?

YAML Front matter

javascript:
  - https://external.js
  - local-script.js

Footer file:

 {% if page.javascript %}
      {% for script in page.javascript %}
        {% if page.javascript contains "://" %}

          {% else %}
         cat
        {% endif %}
      {% endfor %}
    {% endif %}

the output is

 "cat"
 "cat"

Body:
The YAML front matter thinks you have created a variable called https with the value of //external.js. You can test that by calling {{ page.javascript.https }} and see if it returns //external. The solution would be to write your YAML front matter strings like this:

javascript:
  - 'https://external.js'
  - 'local-script.js'


问:
Angular directive @hostbinding argument
Having trouble understanding something regarding the @Hostbinding argument:

Code:

```<code>import { Directive, HostBinding } from "@angular/core";

@Directive({
    selector: '[appDropdown]'
})
export class DropdownDirective {
    @HostBinding('class.open') isOpen = false;

}
</code>```

Why is the argument in the @Hostbinding() passed in as class.open? It looks like the class is an object or something.

答:
Grab an element and log it to the console like so:

```<code>console.log($('div'));
</code>```

In the console you'll see that that element is like an object, it has fields and methods. You could even go further and log the following to the console:

```<code>console.log($("div").attributes.class.value);
</code>```

and you will see the class displayed in the console.

In your case "class.open" means that that element must likely has more than one class.

You can also see it like this:

```<code>Element: {
     attributes : {
                  class : {
                        "open", etc...
                  }
               }
}
</code>```

I hope it helps you see what's happening there.

Title: Angular directive @hostbinding argument

Body:
Having trouble understanding something regarding the @Hostbinding argument:

Code:

import { Directive, HostBinding } from "@angular/core";

@Directive({
    selector: '[appDropdown]'
})
export class DropdownDirective {
    @HostBinding('class.open') isOpen = false;

}

Why is the argument in the @Hostbinding() passed in as class.open? It looks like the class is an object or something.

Body:
Grab an element and log it to the console like so:

console.log($('div'));

In the console you'll see that that element is like an object, it has fields and methods. You could even go further and log the following to the console:

console.log($("div").attributes.class.value);

and you will see the class displayed in the console.

In your case "class.open" means that that element must likely has more than one class.

You can also see it like this:

Element: {
     attributes : {
                  class : {
                        "open", etc...
                  }
               }
}

I hope it helps you see what's happening there.


问:
Google Maps API V3: limit map bounds
I'm trying to set bounds where you can drag the map using Google Maps API V3
Here is the solution for V2 http://econym.org.uk/gmap/example_range.htm that works pretty well.

However with API V3 it isn't so good: when you use the same checkbounds() function, the map is twitching when you reach the bound while map.setCenter() changes the center of the map.

How to fix it? What is the solution for API V3?

答:
This script gets the initial bounds (allowedBounds) and limit the bounds on drag and zoom_changed. Also the zoom is limited on < 7.

```<code>var allowedBounds = false;

google.maps.event.addListener(map, 'idle', function() {
 if (!allowedBounds) {
  allowedBounds = map.getBounds();
 }
});

google.maps.event.addListener(map, 'drag', checkBounds);
google.maps.event.addListener(map, 'zoom_changed', checkBounds);

function checkBounds() {

 if (map.getZoom() < 7) map.setZoom(7);

 if (allowedBounds) {

  var allowed_ne_lng = allowedBounds.getNorthEast().lng();
  var allowed_ne_lat = allowedBounds.getNorthEast().lat();
  var allowed_sw_lng = allowedBounds.getSouthWest().lng();
  var allowed_sw_lat = allowedBounds.getSouthWest().lat();

  var currentBounds = map.getBounds();
  var current_ne_lng = currentBounds.getNorthEast().lng();
  var current_ne_lat = currentBounds.getNorthEast().lat();
  var current_sw_lng = currentBounds.getSouthWest().lng();
  var current_sw_lat = currentBounds.getSouthWest().lat();

  var currentCenter = map.getCenter();
  var centerX = currentCenter.lng();
  var centerY = currentCenter.lat();

  if (current_ne_lng > allowed_ne_lng) centerX = centerX-(current_ne_lng-allowed_ne_lng);
  if (current_ne_lat > allowed_ne_lat) centerY = centerY-(current_ne_lat-allowed_ne_lat);
  if (current_sw_lng < allowed_sw_lng) centerX = centerX+(allowed_sw_lng-current_sw_lng);
  if (current_sw_lat < allowed_sw_lat) centerY = centerY+(allowed_sw_lat-current_sw_lat);

  map.setCenter(new google.maps.LatLng(centerY,centerX));
 }
}
</code>```

Title: Google Maps API V3: limit map bounds

Body:
This script gets the initial bounds (allowedBounds) and limit the bounds on drag and zoom_changed. Also the zoom is limited on < 7.

var allowedBounds = false;

google.maps.event.addListener(map, 'idle', function() {
 if (!allowedBounds) {
  allowedBounds = map.getBounds();
 }
});

google.maps.event.addListener(map, 'drag', checkBounds);
google.maps.event.addListener(map, 'zoom_changed', checkBounds);

function checkBounds() {

 if (map.getZoom() < 7) map.setZoom(7);

 if (allowedBounds) {

  var allowed_ne_lng = allowedBounds.getNorthEast().lng();
  var allowed_ne_lat = allowedBounds.getNorthEast().lat();
  var allowed_sw_lng = allowedBounds.getSouthWest().lng();
  var allowed_sw_lat = allowedBounds.getSouthWest().lat();

  var currentBounds = map.getBounds();
  var current_ne_lng = currentBounds.getNorthEast().lng();
  var current_ne_lat = currentBounds.getNorthEast().lat();
  var current_sw_lng = currentBounds.getSouthWest().lng();
  var current_sw_lat = currentBounds.getSouthWest().lat();

  var currentCenter = map.getCenter();
  var centerX = currentCenter.lng();
  var centerY = currentCenter.lat();

  if (current_ne_lng > allowed_ne_lng) centerX = centerX-(current_ne_lng-allowed_ne_lng);
  if (current_ne_lat > allowed_ne_lat) centerY = centerY-(current_ne_lat-allowed_ne_lat);
  if (current_sw_lng < allowed_sw_lng) centerX = centerX+(allowed_sw_lng-current_sw_lng);
  if (current_sw_lat < allowed_sw_lat) centerY = centerY+(allowed_sw_lat-current_sw_lat);

  map.setCenter(new google.maps.LatLng(centerY,centerX));
 }
}


问:
webkit-filter changing z-index stacking order
Why does applying a webkit filter changes the layers order?

See this minimal example:

setInterval(function(){

 t.classList.toggle('grayed');

}, 1000)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.floater {
    position: fixed;
    top: 5vh;
    left: 5vw;
    width: 90vw;
    height: 90vh;
    z-index: 99;
    background: yellow;
    display: none;
}
td:hover .floater{
    display: initial;
}

.grayed td{
    -webkit-filter: grayscale(0.5);
}

td{
    padding: 1em;
    text-align: center;
    background: blue;
}</code>```

        1
        2
        3

        4
        5

            (Mouse over this)

HELLO

        6

        7
        8
        9

```

答:
The order changes because when the effect is rendered it gets moved to a different stacking contexts (or "layer"). The solution I found was to place whatever should show in front after the element with this effect.

Hover over the buttons on the left and right corners.
http://aminhafamilia.com.br/layout-options/4.html
http://aminhafamilia.com.br/layout-options/4a.html

Page 4.html displays correctly and page 4a.html does not. the only difference is that the text that I want to show on top is actually after the header (which has the filter). Note that no z-index can fix it because they are not in the same stacking context. Moving it down changes the stacking context.

Body:
Why does applying a webkit filter changes the layers order?

See this minimal example:

setInterval(function(){

 t.classList.toggle('grayed');

}, 1000)

.floater {
    position: fixed;
    top: 5vh;
    left: 5vw;
    width: 90vw;
    height: 90vh;
    z-index: 99;
    background: yellow;
    display: none;
}
td:hover .floater{
    display: initial;
}

.grayed td{
    -webkit-filter: grayscale(0.5);
}

td{
    padding: 1em;
    text-align: center;
    background: blue;
}

        1
        2
        3

        4
        5

            (Mouse over this)

HELLO

        6

        7
        8
        9


问:
Make multiple public files back to private on Amazon S3
Currently I have a lot of files on Amazon S3 which are public.

I want to make all files in this bucket no longer public.

How do I do this?

On the UI, when you select multiple folders and click "More", there is an option to make them public, but none to make them un-public.

The only method I found is by manually going on to each file and changing each individual permission.

答:
I would recommend a third party software product for this. CloudBerry supports this ability. Otherwise you can write a script to process each file one by one. In Python this is easy.

CloudBerry Explorer for S3

AWS SDK for Python (Boto3)


问:
What is the main difference between a Compiler and a Transpiler?
What are the main differences between a Compiler and a Transpiler? Please could you provide some examples of both?

答:
Compiler - compiles code to a lower level code.

Example:

"Developer code" -> "Machine code"

PHP -> C

Java -> bytecode

Transpiler - compiles code to same level of code/abstraction.

Example:

"Developer code" -> "Another developer code or version"

JavaScript ES2015+ -> JavaScript ES5