问:
How does the return of control flow work in a chain of Express middleware functions?
I actually have a couple of questions about Express middleware chaining and thought I'd group them in this single post since they're closely related.

Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get executed?

```<code>router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
});

router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
});

router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
});
</code>```

Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an argument to create a certain middleware, and that argument is dependent on which Express app object is the owner of the Request. So I need to access a property of the Request before it is passed to the middleware that needs to be created using that property. Would this work: ?

```<code>router.get('/d', (req, res, next) => {
    var middlewareFunction = createDynamicMiddleware();
    middlewareFunction(req, res, next); // Will this still work as expected?
});
</code>```

Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?

答:
Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get
  executed?

```<code>router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error

});

router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error

});

router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
    //    The request get stuck and after a while it will fail due 'timeout'
});
</code>```

Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an
  argument to create a certain middleware, and that argument is
  dependent on which Express app object is the owner of the Request. So
  I need to access a property of the Request before it is passed to the
  middleware that needs to be created using that property.

Your factory of dynamic middleware should return a new function

Functions that returns new functions, are also knows as curried functions, here is a practical example:

```<code>// based on 'someId' we will return a specific middleware

req.get('/user/:someId',
 createDynamicMiddleware,
 (req,res) => {
  res.send('ok')
 })

function createDynamicMiddleware(req,res,next){
  if(req.params.someId === 'me') {
    return function(req, res, next){
     // do some stuff if someId is me
     return next();
    }
  } else {
    return function(req, res, next){
     // do some other stuff otherwise
     return next();
    }
  }
}
</code>```

Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?

Express handle this for you!

Also, if you add a property to req or res objects, it will be present in the next middlewares

For example:

```<code>router.get('/', (req,res,next) => {
  req.customProperty = 'hello!';
  return next();
}, (req, res) => {
  console.log(req.myCustomProperty)
  // hello!
})
</code>```

Body:
I actually have a couple of questions about Express middleware chaining and thought I'd group them in this single post since they're closely related.

Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get executed?

router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
});

router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
});

router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
});

Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an argument to create a certain middleware, and that argument is dependent on which Express app object is the owner of the Request. So I need to access a property of the Request before it is passed to the middleware that needs to be created using that property. Would this work: ?

router.get('/d', (req, res, next) => {
    var middlewareFunction = createDynamicMiddleware();
    middlewareFunction(req, res, next); // Will this still work as expected?
});

Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?

Body:
Q1: In a middleware function, if I send() the Response, pass to the next function, or just return, does any of the remaining code get
  executed?

router.get('/a', (req, res, next) => {
    res.sendStatus(200);
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error

});

router.get('/b', (req, res, next) => {
    next();
    // Does this ever get executed?
    //    Yes, but don't call next() or res.send() or it will throw an error

});

router.get('/c', (req, res, next) => {
    return;
    // Does this stop the middleware chain? What happens to the request/response?
    //    The request get stuck and after a while it will fail due 'timeout'
});

Q2: Can you pass on to another middleware function from inside of the preceding one? My reason for this is that I have to supply an
  argument to create a certain middleware, and that argument is
  dependent on which Express app object is the owner of the Request. So
  I need to access a property of the Request before it is passed to the
  middleware that needs to be created using that property.

Your factory of dynamic middleware should return a new function

Functions that returns new functions, are also knows as curried functions, here is a practical example:

// based on 'someId' we will return a specific middleware

req.get('/user/:someId',
 createDynamicMiddleware,
 (req,res) => {
  res.send('ok')
 })

function createDynamicMiddleware(req,res,next){
  if(req.params.someId === 'me') {
    return function(req, res, next){
     // do some stuff if someId is me
     return next();
    }
  } else {
    return function(req, res, next){
     // do some other stuff otherwise
     return next();
    }
  }
}

Q3: How are the Request/Response arguments passed to the next middleware when you call next() without any arguments?

Express handle this for you!

Also, if you add a property to req or res objects, it will be present in the next middlewares

For example:

router.get('/', (req,res,next) => {
  req.customProperty = 'hello!';
  return next();
}, (req, res) => {
  console.log(req.myCustomProperty)
  // hello!
})


来源: stackexchange

问:
SMTP connect() failed. While Sending Authentication Email it showing coonect() faild
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.</p>

```<code>$mail = new PHPMailer;
$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.pk';          // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.pk', 'domain');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '<h1>Your Registration Completed. </h1>'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {
    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
     echo $data->msg="Please Verify Your Email Address";
}
</code>```

答:
Don't use random settings and hope it works. SMTPSecure = 'tls' will not work with Port = 465. Set Port = 587 for explicit TLS.

In general, use the latest version, base your code on the examples provided with PHPMailer, and read the troubleshooting guide that the error messages point you to.

ContentLicense: CC BY-SA 3.0

Body:
I'm Trying to send email via php by using php mailer, but it's showing SMTP connect() failed. here is my code. can't find out what is problem in that. if somebody help to track error it will be very helpful for me.

$mail = new PHPMailer;
$mail->isSMTP();                                   // Set mailer to use SMTP
$mail->Host = 'dds.uemtv.com';                    // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                            // Enable SMTP authentication
$mail->Username = 'no-reply@domain.pk';          // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls';                         // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                 // TCP port to connect to

$mail->setFrom('no-reply@domain.pk', 'domain');
$mail->addReplyTo($email, '$name');
$mail->addAddress($email);   // Add a recipient
//$mail->addCC('cc@example.com');
//$mail->addBCC('bcc@example.com');

$mail->isHTML(true);  // Set email format to HTML

$bodyContent = '
Your Registration Completed.
'
$mail->Subject = 'Verify Account- Rozgar';
$mail->Body    = $bodyContent;
if(!$mail->send()) {
    echo $data->msg = $mail->ErrorInfo;
} else {
    // echo 'Message has been sent';
     echo $data->msg="Please Verify Your Email Address";
}


问:
Preserving the 'this' context when using JS Proxy objects
I'm trying to create a proxy to the global browser window object. The idea is simple - if the caller uses an existing method or property just return that, otherwise use the fake object. Here's the code:

```<code>var handler = {
  get: function(target, name) {
    return name in window ?
      window[name] :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};

var fakeWindow = new Proxy(function() {}, handler);
fakeWindow.foo = 'bar';
console.log(fakeWindow.foo); // outputs 'bar'
fakeWindow.alert('hello'); // error - the alert method is called without the correct this value
</code>```

Problem is, when invoking a method on the proxy object (such as alert in example above), the 'this' value is that of the proxy, not the window.
Is there any way to get this to work?

答:
You may bind the context in your getter:</p>
```<code>get: function (target, name) {
  if (name in window) {
    if (typeof window[name] === "function") return window[name].bind(window);
    return window[name];
  }
  return target[name];
}
</code>```

Body:
I'm trying to create a proxy to the global browser window object. The idea is simple - if the caller uses an existing method or property just return that, otherwise use the fake object. Here's the code:

var handler = {
  get: function(target, name) {
    return name in window ?
      window[name] :
      target[name];
  },
  set: function(obj, prop, value) {
    if (prop in window) {
      window[prop] = value
    } else {
      obj[prop] = value
    };
  },
};

var fakeWindow = new Proxy(function() {}, handler);
fakeWindow.foo = 'bar';
console.log(fakeWindow.foo); // outputs 'bar'
fakeWindow.alert('hello'); // error - the alert method is called without the correct this value

Problem is, when invoking a method on the proxy object (such as alert in example above), the 'this' value is that of the proxy, not the window.
Is there any way to get this to work?

Body:
You may bind the context in your getter:

get: function (target, name) {
  if (name in window) {
    if (typeof window[name] === "function") return window[name].bind(window);
    return window[name];
  }
  return target[name];
}

ContentLicense: CC BY-SA 4.0


问:
1292: Incorrect datetime value: '' for column at row 1
I am trying to load data from excel sheet to the below table on MYSQL 5.6 on windows 8.1 and I am getting 'Incorrect datetime value:' error.

Term date column is of DATETIME data type and the data has null values in the excel sheet which I am trying to insert into the table.

I did some research and found that the problem is with the SQL strict mode. But I am not able to figure out how to disable or modify the SQL strict mode.

I in fact tried this SET SESSION sql_mode='ALLOW_INVALID_DATES' but no luck.

Some said editing my.ini file in installation directory will help but I am not able to find it in the installation directory.

can any one please help me resolve this issue.

```<code>create table EMPLOYEE(EMP_ID integer(10),
EMP_NAME char(25),
SALARY integer(25),
START_DATE datetime,
TERM_DATE datetime DEFAULT '1900-01-01',
PRIMARY KEY (EMP_ID));
</code>```

Error Message:

```<code>15:23:08    INSERT INTO `mith`.`EMPLOYEE` (`EMP_ID`, `EMP_NAME`, `SALARY`, `START_DATE`, `TERM_DATE`) VALUES ('26', 'Will Banker', '90000', '00:00.0', '')  1292: Incorrect datetime value: '' for column 'TERM_DATE' at row 1
</code>```

答:
I managed to solve a similar problem using the commands:

```<code>mysql> set session sql_mode='';
</code>```

and

```<code>mysql> set global sql_mode='';
</code>```

in mysql prompt.

Body:
I am trying to load data from excel sheet to the below table on MYSQL 5.6 on windows 8.1 and I am getting 'Incorrect datetime value:' error.

Term date column is of DATETIME data type and the data has null values in the excel sheet which I am trying to insert into the table.

I did some research and found that the problem is with the SQL strict mode. But I am not able to figure out how to disable or modify the SQL strict mode.

I in fact tried this SET SESSION sql_mode='ALLOW_INVALID_DATES' but no luck.

Some said editing my.ini file in installation directory will help but I am not able to find it in the installation directory.

can any one please help me resolve this issue.

create table EMPLOYEE(EMP_ID integer(10),
EMP_NAME char(25),
SALARY integer(25),
START_DATE datetime,
TERM_DATE datetime DEFAULT '1900-01-01',
PRIMARY KEY (EMP_ID));

Error Message:

15:23:08    INSERT INTO `mith`.`EMPLOYEE` (`EMP_ID`, `EMP_NAME`, `SALARY`, `START_DATE`, `TERM_DATE`) VALUES ('26', 'Will Banker', '90000', '00:00.0', '')  1292: Incorrect datetime value: '' for column 'TERM_DATE' at row 1

Body:
I managed to solve a similar problem using the commands:

mysql> set session sql_mode='';

and

mysql> set global sql_mode='';

in mysql prompt.


问:
Using logical operators with %in% and subset
I have a test dataset that I have split up by quarter:

```<code>> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4

subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}
</code>```

Now my objective is to find out all of the unique ids in Q3 that are not in Q1 or in Q2.  Using the %in% operator I try:

```<code>Q1_ids <- unique(Q1$id)
Q2_ids <- unique(Q2$id)

Q3_ids <- subset(unique(Q3$id), !(unique(Q3$id) %in% Q1_ids | Q2_ids))
</code>```

but then I receive an error that operations are possible only for numeric, logical or complex types.   I can subset by one vector, for example if I only use Q1_ids, but I cannot use a logical operator.  What is the solution to this using the subset() function or another way to approach the problem?

```<code>> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame", index = structure(integer(0), "`__quarter`" = integer(0)))
</code>```

答:
```<code>Q3_ids <- unique(setdiff(Q3$id , union(Q2$id, Q1$id)))
</code>```

Body:
I have a test dataset that I have split up by quarter:

> test
   id quarter
1   7      Q1
2   7      Q1
3   5      Q1
4   8      Q1
5   3      Q1
6   6      Q1
7  10      Q1
8   3      Q2
9  10      Q2
10  8      Q2
11  2      Q2
12  7      Q2
13  6      Q2
14  6      Q3
15  9      Q3
16  6      Q3
17  4      Q3
18  9      Q3
19  2      Q3
20  5      Q4
21  8      Q4
22 10      Q4
23  7      Q4
24  1      Q4
25  8      Q4

subsets <-split(test, test$quarter, drop=TRUE)

for (i in 1:length(subsets)) {
  assign(paste0("Q", i), as.data.frame(subsets[[i]]))
}

Now my objective is to find out all of the unique ids in Q3 that are not in Q1 or in Q2.  Using the %in% operator I try:

Q1_ids <- unique(Q1$id)
Q2_ids <- unique(Q2$id)

Q3_ids <- subset(unique(Q3$id), !(unique(Q3$id) %in% Q1_ids | Q2_ids))

but then I receive an error that operations are possible only for numeric, logical or complex types.   I can subset by one vector, for example if I only use Q1_ids, but I cannot use a logical operator.  What is the solution to this using the subset() function or another way to approach the problem?

> dput(test)
structure(list(id = c(7, 7, 5, 8, 3, 6, 10, 3, 10, 8, 2, 7, 6,
6, 9, 6, 4, 9, 2, 5, 8, 10, 7, 1, 8), quarter = c("Q1", "Q1",
"Q1", "Q1", "Q1", "Q1", "Q1", "Q2", "Q2", "Q2", "Q2", "Q2", "Q2",
"Q3", "Q3", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4", "Q4",
"Q4")), .Names = c("id", "quarter"), row.names = c(NA, -25L), class = "data.frame", index = structure(integer(0), "`__quarter`" = integer(0)))


问:
Find a string between 2 known values
I need to be able to extract a string between 2 tags for example: "00002" from "morenonxmldata<tag1>0002</tag1>morenonxmldata"

I am using C# and .NET 3.5.

答:
```<code>string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, @"FirstString (.+?) SecondString ").Groups[1].Value;
</code>```

Title: Find a string between 2 known values


问:
Why don't Django admin "Today" and "Now" buttons show up in Safari?
I'm developing a Django application that contains a model with a date/time field. On my local copy of the application, the admin page for that particular model shows this for the date/time field:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-local.png

This is as expected. However, when I deploy to my webserver and use the application from there, I get this:

alt text http://www.cs.wm.edu/~mpd/images/bugs/django-date-server.png

The application on the server is exactly the same as my local copy, except that I have debugging disabled on the server (but I don't think that should matter...should it?). Why does the admin app on the server differ from the local admin app?

Update

The issue seems localized to Safari. The "Today" and "Now" buttons appear when the admin site is accessed via Firefox. It looks like Safari can't download some of the JavaScript files necessary to show these widgets (strange that Firefox can, though).

I noticed that Safari is receiving a "304 Not Modified" code for the following files, but I'm not sure what that means, or how to fix it. Obviously, these are the JavaScript files and images that control the date/time widget:

RelatedObjectLookup.js

DateTimeShortcuts.js

icon_calendar.gif

icon_clock.gif

答:
Check the media location, permissions and setup on your deployment server.

http://www.djangobook.com/en/1.0/chapter20/

OwnerDisplayName: mipadi

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mipadi

OwnerDisplayName: Jeff Bauer


问:
I need mentoring while developing web based micro finance application
I have been tasked to develop a web based micro finance (small loans for small groups) application. I will need someone to mentor me while I do this as this is the biggest application I have ever been asked to come up with. I am mostly self taught and have always worked alone however i feel this may be a good chance to step up my game so to speak.

I have below the highest level Actors and their Goals that I can think of at the moment and am aming to use agile development methodology hence I will be starting coding, and refining the use cases as I go along.

```<code>***Actor    Goal***
**Borrower** Request registration
            Request to borrow
            Check Loan Account balance
            Check repayment history
            Make early repayment
            Request to Switch groups

**Loan Officer** Pre-register group
             Record daily borrower repayments /collections
             Generate expected daily collection

**Saver**  Request registration
             Check Account balance
             Check deposit history

**Loan Administrator** Assess borrower
             Register borrower
             Approve pending borrower registration
             Get following weeks budget
             Generate default list
             Manage borrowers
             Manage borrower details
             Manage staff
             Generate new loan projection
             Manage loans
             Manage savings accounts

  **System Administrator** Modify system settings
             Manage system parameters
             Approve exception loan amount request

 **Amortization System** Calculate loan repayment schedule
 **Borrower Assessment System** Determine maximum loan amount for borrower
 **Savings System** Credit savings account
                    Debit savings account
                    Create savings account
</code>```

I have decided to have 5 modules in the system ie Loan Module, Savings Module, Loan Administrator Module, Defaul Module and System Administrator Module this is to help me apart from segregating the application also it will help me control access to functionalily better i think.

I am now going to do the use case for what i call the base goals like the various registrations and logins.

cheers

答: Sounds like you are on the right path. Far better direction than I had on my first big project. Extend the same organized process to the code and you should be fine.</p>

Body:
I have been tasked to develop a web based micro finance (small loans for small groups) application. I will need someone to mentor me while I do this as this is the biggest application I have ever been asked to come up with. I am mostly self taught and have always worked alone however i feel this may be a good chance to step up my game so to speak.

I have below the highest level Actors and their Goals that I can think of at the moment and am aming to use agile development methodology hence I will be starting coding, and refining the use cases as I go along.

***Actor    Goal***
**Borrower** Request registration
            Request to borrow
            Check Loan Account balance
            Check repayment history
            Make early repayment
            Request to Switch groups

**Loan Officer** Pre-register group
             Record daily borrower repayments /collections
             Generate expected daily collection

**Saver**  Request registration
             Check Account balance
             Check deposit history

**Loan Administrator** Assess borrower
             Register borrower
             Approve pending borrower registration
             Get following weeks budget
             Generate default list
             Manage borrowers
             Manage borrower details
             Manage staff
             Generate new loan projection
             Manage loans
             Manage savings accounts

  **System Administrator** Modify system settings
             Manage system parameters
             Approve exception loan amount request

 **Amortization System** Calculate loan repayment schedule
 **Borrower Assessment System** Determine maximum loan amount for borrower
 **Savings System** Credit savings account
                    Debit savings account
                    Create savings account

I have decided to have 5 modules in the system ie Loan Module, Savings Module, Loan Administrator Module, Defaul Module and System Administrator Module this is to help me apart from segregating the application also it will help me control access to functionalily better i think.

I am now going to do the use case for what i call the base goals like the various registrations and logins.

cheers


问:
How would I get all errors from a form group in angular 2?
If I build a form group like this:

```<code>    this.passWordForm = this._formBuilder.group({
        "previous_password": [this.changePassword.previous_password, Validators.compose([Validators.required])],
        "new_password": [this.changePassword.new_password, Validators.compose([Validators.required,PasswordValidator.validate])],
    });
</code>```

How would I get all errors from the form group? What I've been doing is this:

```<code><form role="form" [formGroup]="passWordForm" novalidate (ngSubmit)="submitChangePassword()">
<input [(ngModel)]="changePassword.previous_password" formControlName="previous_password" name="previous_password" type="password" placeholder="Previous Password" class="form-control" required>
<input formControlName="new_password" [(ngModel)]="changePassword.new_password" name="new_password" type="password" placeholder="New Password" class="form-control" required>
<div *ngIf="passWordForm.invalid === true && passWordForm.controls['new_password'].errors">
    <div *ngFor="let line of passWordForm.controls['new_password'].errors.message" class="alert alert-danger">{{line}}</div>
</div>
<div *ngIf="passWordForm.invalid === true && passWordForm.controls['previous_password'].errors">
    <div class="alert alert-danger">{{passWordForm.controls['previous_password'].errors.message}}</div>
</div>
</form>
</code>```

I was hoping that passWordForm.errors would return a concatenated list but it's always null, even when passWordForm.invalid === true

答: The only way that I think is to know if the form is valid or not by doing passwordForm.valid and then iterate over the Controls object and find the errors of individual form element.</p>

Body:
If I build a form group like this:

    this.passWordForm = this._formBuilder.group({
        "previous_password": [this.changePassword.previous_password, Validators.compose([Validators.required])],
        "new_password": [this.changePassword.new_password, Validators.compose([Validators.required,PasswordValidator.validate])],
    });

How would I get all errors from the form group? What I've been doing is this:

<form role="form" [formGroup]="passWordForm" novalidate (ngSubmit)="submitChangePassword()">
<input [(ngModel)]="changePassword.previous_password" formControlName="previous_password" name="previous_password" type="password" placeholder="Previous Password" class="form-control" required>
<input formControlName="new_password" [(ngModel)]="changePassword.new_password" name="new_password" type="password" placeholder="New Password" class="form-control" required>

{{line}}

{{passWordForm.controls['previous_password'].errors.message}}

</form>

I was hoping that passWordForm.errors would return a concatenated list but it's always null, even when passWordForm.invalid === true


问:
SQL Query that needs a little bit modification
```<code>select
    IF(posty.id IS NULL, 0, 1) as posty,
    IF(strony.id IS NULL, 0, 1) as strony,
    posty.*, strony.*,
    `master`.url
from
(select 'fajne-to-jest' as url)  `master`
left join posty on posty.url = `master`.url
left join strony on strony.url = `master`.url
;
</code>```

Above queries generate the below result:

And it doesn't work exactly 100% as I'd like it to. Because I want results like

this:
The actual and desired results are different, because in the desired result it eliminates columns with NULL values, and the one url column which apears twice is reduced to one. Below is further visual clarification:

And the question is: is it possible to make this query?
What should the query look like? How to structure it?

答:
Regarding the NULL value showing up, you can use the following construct:

```<code>if (isnull(mycolumn) ,'',mycolumn) as mycolumn
</code>```

Regarding duplicated columns:

As a general rule, in a prod environment, you should always list the columns you want to appear in the result, instead of using the * wildcard.  Replace the wildcard with the column listing and you are set.

Body:
select
    IF(posty.id IS NULL, 0, 1) as posty,
    IF(strony.id IS NULL, 0, 1) as strony,
    posty.*, strony.*,
    `master`.url
from
(select 'fajne-to-jest' as url)  `master`
left join posty on posty.url = `master`.url
left join strony on strony.url = `master`.url
;

Above queries generate the below result:

And it doesn't work exactly 100% as I'd like it to. Because I want results like

this:
The actual and desired results are different, because in the desired result it eliminates columns with NULL values, and the one url column which apears twice is reduced to one. Below is further visual clarification:

And the question is: is it possible to make this query?
What should the query look like? How to structure it?

Body:
Regarding the NULL value showing up, you can use the following construct:

if (isnull(mycolumn) ,'',mycolumn) as mycolumn

Regarding duplicated columns:

As a general rule, in a prod environment, you should always list the columns you want to appear in the result, instead of using the * wildcard.  Replace the wildcard with the column listing and you are set.


问:
The syntax of the command is incorrect - IF Statement Batch
I am trying to execute below function in batch but I am receiving an error in the IF statement, I've been trying to fix this but no luck.

```<code>:Method2
set File=%1
set Filename=%2
echo %Filename%
pause
IF NOT x%Filename:Test=% == x%Filename%
(
    File >> File_List.txt
)

exit /b 2

:End
</code>```

I know the issue is in the IF statement, been debugging the issue but can't find the correct syntax for the code. After this I want to replace that "Test" to be a input parameter from the user so it can be any specific word, I want to make it look something like this...

```<code>IF NOT x%Filename:%Input%=% == x%Filename%
</code>```

Could you please help?

答:
I've found a solution for my problem, yes, basically the "(" needed to be on the end of the IF and it solved that issue, for the parameter issue, I found below solution which works perfectly fine.

```<code>:Method2
set File=%1
set Filename=%2
set param=%3
IF NOT "!Filename:%param%=!"=="%Filename%" (
    echo %File% >> File_List.txt
    echo %File% moved
)
</code>```

Body:
I am trying to execute below function in batch but I am receiving an error in the IF statement, I've been trying to fix this but no luck.

:Method2
set File=%1
set Filename=%2
echo %Filename%
pause
IF NOT x%Filename:Test=% == x%Filename%
(
    File >> File_List.txt
)

exit /b 2

:End

I know the issue is in the IF statement, been debugging the issue but can't find the correct syntax for the code. After this I want to replace that "Test" to be a input parameter from the user so it can be any specific word, I want to make it look something like this...

IF NOT x%Filename:%Input%=% == x%Filename%

Could you please help?

Body:
I've found a solution for my problem, yes, basically the "(" needed to be on the end of the IF and it solved that issue, for the parameter issue, I found below solution which works perfectly fine.

:Method2
set File=%1
set Filename=%2
set param=%3
IF NOT "!Filename:%param%=!"=="%Filename%" (
    echo %File% >> File_List.txt
    echo %File% moved
)


问:
UIView transition animation not executing
I'm trying to use an animation transition for when a UIView appears on screen.  The UIView appears correctly but the animation doesn't occur when it appears.</p>

```<code>  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let coreView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    coreView.backgroundColor = UIColor.cyan
    coreView.layer.borderColor = UIColor.darkGray.cgColor
    coreView.layer.borderWidth = 8
    coreView.layer.cornerRadius = 15
    coreView.isHidden = true
    self.view.addSubview(coreView)

    //The transition occurs here
    UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {

      coreView.isHidden = false
    }, completion: {_ in})

    }
</code>```

答:
This isn't working because coreView is not properly setup until after the viewWillAppear method completes so you can't use the transition animation (you can animate other properties like the alpha).

What you can do is this:

```<code>DispatchQueue.main.async {
    coreView.isHidden = false

     UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {
    }, completion: {_ in})

}
</code>```

This dispatches the transition back onto the main queue and it fires after the viewWillAppear method have completed and the coreView is properly setup.

By the way remember that viewWillAppear is called whenever the view controller is comes into view so if it hides and returns you will add another coreView.

Body:
I'm trying to use an animation transition for when a UIView appears on screen.  The UIView appears correctly but the animation doesn't occur when it appears.

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let coreView = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    coreView.backgroundColor = UIColor.cyan
    coreView.layer.borderColor = UIColor.darkGray.cgColor
    coreView.layer.borderWidth = 8
    coreView.layer.cornerRadius = 15
    coreView.isHidden = true
    self.view.addSubview(coreView)

    //The transition occurs here
    UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {

      coreView.isHidden = false
    }, completion: {_ in})

    }

Body:
This isn't working because coreView is not properly setup until after the viewWillAppear method completes so you can't use the transition animation (you can animate other properties like the alpha).

What you can do is this:

DispatchQueue.main.async {
    coreView.isHidden = false

     UIView.transition(with: coreView, duration: 2, options: [.curveEaseInOut, .transitionCurlDown], animations: {
    }, completion: {_ in})

}

This dispatches the transition back onto the main queue and it fires after the viewWillAppear method have completed and the coreView is properly setup.

By the way remember that viewWillAppear is called whenever the view controller is comes into view so if it hides and returns you will add another coreView.


问:
rewarded video ad example in libGDX
I've been looking for an example, but didn't found it.

I found one without libgdx and some why it didn't work, but app also didn't crash.

```<code>public class AndroidLauncher extends AndroidApplication implements AdHandler, RewardedVideoAdListener{

    ...

    RewardedVideoAd rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    rewardedVideoAd.setRewardedVideoAdListener(this);

    rewardedSetup();

    private void rewardedSetup(){
        if (!rewardedVideoAd.isLoaded()){
            rewardedVideoAd.loadAd("ca-app-pub-683510441556959xxxxxxxxx", new AdRequest.Builder().build());
        }

        @Override
        public void onRewardedVideoAdLoaded() {
            if(rewardedVideoAd.isLoaded()){
                rewardedVideoAd.show();
            }
        }

        @Override
        public void onRewarded(RewardItem rewardItem) {
            rewarded(true);
        }
    }
}
</code>```

And it simply don't shows, maybe it happened to anyone ? (My true code is full of handlers and stuff, thus I didn't put it all, I guess other code has 0 effect on this problem)

答:
```<code>private static final String APP_ID="ca-app-pub-XXXXXX~XXXXX";
private static final String AD_UNIT_ID="ca-app-pub-XXXXX/XXXXXXX";
private RewardedVideoAd mAd;
private boolean isRewardLoaded;

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    MobileAds.initialize(this, APP_ID);

    mAd = MobileAds.getRewardedVideoAdInstance(this);
    mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
        @Override
        public void onRewardedVideoAdLoaded() {
            isRewardLoaded =true;
        }

        @Override
        public void onRewardedVideoAdOpened() {

        }

        @Override
        public void onRewardedVideoStarted() {

        }

        @Override
        public void onRewardedVideoAdClosed() {
            loadRewardedVideoAd();
        }

        @Override
        public void onRewarded(RewardItem rewardItem) {

            // call rewards method from here.
            loadRewardedVideoAd();  // Load for next Reward Point

        }

        @Override
        public void onRewardedVideoAdLeftApplication() {

        }

        @Override
        public void onRewardedVideoAdFailedToLoad(int i) {

        }

        @Override
        public void onRewardedVideoCompleted() {

        }
    });
    loadRewardedVideoAd();
}

private void loadRewardedVideoAd() {
    isRewardLoaded=false;
    mAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
}

@Override
protected void onResume() {
    super.onResume();
    mAd.resume(this);
}

@Override
protected void onPause() {
    super.onPause();
    mAd.pause(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mAd.destroy(this);
}
</code>```

set-up done, need two methods that is implementation of AdHandler, these two methods will call from core module.

```<code>public void showVideoAd(){
        runOnUiThread(new Runnable() {
            public void run() {

                if (mAd.isLoaded()) {
                   mAd.show();
                } else {
                    loadRewardedVideoAd();
                }
            }
        });
}

public boolean hasVideoReward(){

    return isRewardLoaded;
    //return mAd.isLoaded();    // -> must be called on the main UI thread.
}
</code>```

Call hasVideoReward(), that tell you to show reward panel or not and showVideoAd() method show Reward Video.

Hopefully you've these entries in your AndroidManifest.xml file

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

<activity android:name="com.google.android.gms.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
          android:theme="@android:style/Theme.Translucent" />
</code>```

Title: rewarded video ad example in libGDX

Body:
I've been looking for an example, but didn't found it.

I found one without libgdx and some why it didn't work, but app also didn't crash.

public class AndroidLauncher extends AndroidApplication implements AdHandler, RewardedVideoAdListener{

    ...

    RewardedVideoAd rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
    rewardedVideoAd.setRewardedVideoAdListener(this);

    rewardedSetup();

    private void rewardedSetup(){
        if (!rewardedVideoAd.isLoaded()){
            rewardedVideoAd.loadAd("ca-app-pub-683510441556959xxxxxxxxx", new AdRequest.Builder().build());
        }

        @Override
        public void onRewardedVideoAdLoaded() {
            if(rewardedVideoAd.isLoaded()){
                rewardedVideoAd.show();
            }
        }

        @Override
        public void onRewarded(RewardItem rewardItem) {
            rewarded(true);
        }
    }
}

And it simply don't shows, maybe it happened to anyone ? (My true code is full of handlers and stuff, thus I didn't put it all, I guess other code has 0 effect on this problem)

Body:
private static final String APP_ID="ca-app-pub-XXXXXX~XXXXX";
private static final String AD_UNIT_ID="ca-app-pub-XXXXX/XXXXXXX";
private RewardedVideoAd mAd;
private boolean isRewardLoaded;

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    MobileAds.initialize(this, APP_ID);

    mAd = MobileAds.getRewardedVideoAdInstance(this);
    mAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
        @Override
        public void onRewardedVideoAdLoaded() {
            isRewardLoaded =true;
        }

        @Override
        public void onRewardedVideoAdOpened() {

        }

        @Override
        public void onRewardedVideoStarted() {

        }

        @Override
        public void onRewardedVideoAdClosed() {
            loadRewardedVideoAd();
        }

        @Override
        public void onRewarded(RewardItem rewardItem) {

            // call rewards method from here.
            loadRewardedVideoAd();  // Load for next Reward Point

        }

        @Override
        public void onRewardedVideoAdLeftApplication() {

        }

        @Override
        public void onRewardedVideoAdFailedToLoad(int i) {

        }

        @Override
        public void onRewardedVideoCompleted() {

        }
    });
    loadRewardedVideoAd();
}

private void loadRewardedVideoAd() {
    isRewardLoaded=false;
    mAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
}

@Override
protected void onResume() {
    super.onResume();
    mAd.resume(this);
}

@Override
protected void onPause() {
    super.onPause();
    mAd.pause(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mAd.destroy(this);
}

set-up done, need two methods that is implementation of AdHandler, these two methods will call from core module.

public void showVideoAd(){
        runOnUiThread(new Runnable() {
            public void run() {

                if (mAd.isLoaded()) {
                   mAd.show();
                } else {
                    loadRewardedVideoAd();
                }
            }
        });
}

public boolean hasVideoReward(){

    return isRewardLoaded;
    //return mAd.isLoaded();    // -> must be called on the main UI thread.
}

Call hasVideoReward(), that tell you to show reward panel or not and showVideoAd() method show Reward Video.

Hopefully you've these entries in your AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

<activity android:name="com.google.android.gms.ads.AdActivity"
          android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
          android:theme="@android:style/Theme.Translucent" />


问:
How can I dynamically generate parameters for a create method?
I have a model "Item", and I want to generate a bunch of Items with data taken from a CSV file. But I want to allow the user to select which data columns are used.

So my model "User" has a json attribute called Columns, telling which columns should be used from that user's CSV file. For example, if user.columns == {"title"=>"true","category"=>"false"}, then the Title column should be used but the Category column shouldn't.
(Alternatively, I could only list the columns I want to include, like this: {"title"=>"included"}, and later do something like user.columns.each {|c| c[0]} to get an array of all the included columns.)

I have a method for generating Items based on the CSV data:

```<code>def create
  #...
  SmarterCSV.process(file).each do |row| #this line returns an array of all the rows in the CSV file
    Item.create(title: row[:title], category: row[:category])
  end
end
</code>```

but how can I modify the method's parameters based on the contents of user.columns? For the {"title"=>"true","category"=>"false"} example, the method would just be Item.create(name: row[:title]). Is it possible to dynamically generate a method like that?

I'm planning to have quite a lot of possible columns, so doing an if conditional for every possibility is unfeasible.

答:
Item.create(name: row[:name]) also takes a hash, and can be written equivalently as Item.create({ name: row[:name] })

As such - you can build up the entire object in a hash each time; then slice off any attributes that you don't want, and then pass to create. So assuming you have:

```<code>user.columns
#=> {"name"=>"true","category"=>"false"}
</code>```

Then you could write:

```<code>user_object = { "name" => row[:name], "category" => row[:category] }
#=> include all the possible attributes here

included_attributes = user.columns.select { |k, v| v == "true" }
#=> {"name"=>"true"}

Item.create( user_object.slice(*included_attributes.keys) )
#=> `Item` is created with only `name` attribute
</code>```

Edit: as engineersmnky points out in the comments, row is already a hash. This simplifies it further, and you could instead just write:

```<code>SmarterCSV.process(file).each do |row|
  included_attributes = user.columns.select { |k, v| v == "true" }
  Item.create( row.slice(*included_attributes.keys) )
end
</code>```

Body:
I have a model "Item", and I want to generate a bunch of Items with data taken from a CSV file. But I want to allow the user to select which data columns are used.

So my model "User" has a json attribute called Columns, telling which columns should be used from that user's CSV file. For example, if user.columns == {"title"=>"true","category"=>"false"}, then the Title column should be used but the Category column shouldn't.
(Alternatively, I could only list the columns I want to include, like this: {"title"=>"included"}, and later do something like user.columns.each {|c| c[0]} to get an array of all the included columns.)

I have a method for generating Items based on the CSV data:

def create
  #...
  SmarterCSV.process(file).each do |row| #this line returns an array of all the rows in the CSV file
    Item.create(title: row[:title], category: row[:category])
  end
end

but how can I modify the method's parameters based on the contents of user.columns? For the {"title"=>"true","category"=>"false"} example, the method would just be Item.create(name: row[:title]). Is it possible to dynamically generate a method like that?

I'm planning to have quite a lot of possible columns, so doing an if conditional for every possibility is unfeasible.

Body:
Item.create(name: row[:name]) also takes a hash, and can be written equivalently as Item.create({ name: row[:name] })

As such - you can build up the entire object in a hash each time; then slice off any attributes that you don't want, and then pass to create. So assuming you have:

user.columns
#=> {"name"=>"true","category"=>"false"}

Then you could write:

user_object = { "name" => row[:name], "category" => row[:category] }
#=> include all the possible attributes here

included_attributes = user.columns.select { |k, v| v == "true" }
#=> {"name"=>"true"}

Item.create( user_object.slice(*included_attributes.keys) )
#=> `Item` is created with only `name` attribute

Edit: as engineersmnky points out in the comments, row is already a hash. This simplifies it further, and you could instead just write:

SmarterCSV.process(file).each do |row|
  included_attributes = user.columns.select { |k, v| v == "true" }
  Item.create( row.slice(*included_attributes.keys) )
end


问:
Is it possible to develop QT application inside Symbian phone (e.g. E90)?
Actually question is on subject and I think very clear. Just wondering is it possible to develop symbian application on phone?</p>

答:
You mean, like, can you develop an application for your phone using just your phone and not  a desktop/laptop?

No, not really, but you could install PyS60 and use a text editor in your phone to write python programs, though that might be a very broad interpretation of an "application" :).


问:
Appcelerator resolve uri
I'm working on a procedure to import a file within the application, in this case I am taking a google drive file.

When the user selects a file startActivityForResult returns a url like this:

content: //com.google.android.apps.docs.storage/document/acc%%3D1%%3Bdoc%%3D1214

I can not resolve this url to access the content of the file. Does anyone have experience on this?

On google I found some old module, but, I do not think solves my problem.

Thank you.

答:
Finally I've found the solution.
you need to copy the file to the applicationDataDirectory before trying to get the content.

Copying the file will automatically resolve the content uri.

```<code>var intent = Ti.Android.createIntent({
    action: Ti.Android.ACTION_GET_CONTENT,
    type: '*/*'
});

$.win.activity.startActivityForResult(intent, function(e) {

    if (e.intent) {

        var filePath = e.intent.data;
        var file = Ti.Filesystem.getFile(filePath);
        var copiedFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, file.name);
        file.copy(copiedFile.nativePath);

        if (!copiedFile.exists()) {
            // show your error message
            return;
        }

        // file content
        console.log(copiedFile.read().text);

    }
});
</code>```

Title: Appcelerator resolve uri

Body:
Finally I've found the solution.
you need to copy the file to the applicationDataDirectory before trying to get the content.

Copying the file will automatically resolve the content uri.

var intent = Ti.Android.createIntent({
    action: Ti.Android.ACTION_GET_CONTENT,
    type: '*/*'
});

$.win.activity.startActivityForResult(intent, function(e) {

    if (e.intent) {

        var filePath = e.intent.data;
        var file = Ti.Filesystem.getFile(filePath);
        var copiedFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, file.name);
        file.copy(copiedFile.nativePath);

        if (!copiedFile.exists()) {
            // show your error message
            return;
        }

        // file content
        console.log(copiedFile.read().text);

    }
});


问:
Making my first angular directive. 'vm' is undefined
```<code>(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());
</code>```

This is the code that I think is not working...

```<code>HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {
</code>```

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

```<code>function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];
</code>```

答:
You define a controller and a controllerAs equals to vm. Then you want to define a bindToController = true it means the directive bindings will be associated to the controller.

So if inside your controller you do:

```<code>this.myVar = 'test';
</code>```

Then inside your directive's template you can simply do:

```<code><div>{{vm.myVar}}</div>
</code>```

Body:
(function () {
  'use strict';

  angular
    .module('contacts.directives')
    .directive('hotkeys', HotkeysDirective);

  HotkeysDirective.$inject = ['$resource', '$document'];

  function HotkeysDirective($resource, $document) {
    var directive = {
      templateUrl: '/my-app/contacts/client/views/ui/hotkeys.ui.html',
      link: link,
      controller: 'AddManagerController',
      controllerAs: 'vm',
      scope: {},
      bindToController: {
        },
    };

    return directive;

    function link(scope, element, attrs, modelCtrl) {

      $document.bind('keypress', function (e) {
        var key = String.fromCharCode(e.which);
        if (key == 1 || key == 2 || key == 3 || key == 4 || key == 5 || key == 6) {
          scope.$broadcast('keypress', e, e.which);
        }
      });

      scope.$on('keypress', function (event, key) {
        // do stuff
        scope.$apply();
      });
    }
  }
}());

This is the code that I think is not working...

HotkeysDirective.$inject = ['$resource', '$document'];

function HotkeysDirective($resource, $document) {
  var directive = {
    templateUrl: '/request-off-work/contacts/client/views/ui/hotkeys.ui.html',
    link: link,
    controller: 'AddManagerController',
    controllerAs: 'vm',
    scope: {},
    bindToController: {
      },
  };

  return directive;

  function link(scope, element, attrs, modelCtrl) {

It's saying vm is undefined when I'm using controllerAs: 'vm', In the AddManagerController, it says 'var vm = this;'. Also not sure why scope: {} needs to be there, and I'll figure out bindToController eventually... I think I need to bind vm.credentials.groups to it.

Update: here's the controller

function AddManagerController($scope, $document, $rootScope, $state, $window, Authentication, ContactsService, Notification) {
  var vm = this;
  vm.authentication = Authentication;
  vm.credentials = {};
  vm.showGroups = [null, false, false, false, false, false, false];

Body:
You define a controller and a controllerAs equals to vm. Then you want to define a bindToController = true it means the directive bindings will be associated to the controller.

So if inside your controller you do:

this.myVar = 'test';

Then inside your directive's template you can simply do:

<div>{{vm.myVar}}</div>


问:
Android SDK MonkeyRunner 25.3.2 Won't Run
So I upgraded Android SDK tools today and now I'm having a problem getting monkeyrunner to run.  I did the standard which is (from the command prompt)

```<code>D:\Android\SDK\tools\bin\monkeyrunner.bat D:\ScriptName.py
</code>```

Note 1: The directory of monkeyrunner.bat changed in this release, so I had to update my command line accordingly.

That fails with the message:

```<code>SWT Folder '..\framework\x86_64' does not exist.
</code>```

I can fix that by editing monkeyrunner.bat and instead of having frameworkdir be set to 'lib' it gets set to '..\lib', the actual location of the monkey runner jar file.

However, when I implement this fix it then gives the error:

```<code>Cannot run program "..\framework\adb.exe" cannot find the file specified.
</code>```

I'm kind of stuck here because no matter what I change in monkeyrunner.bat I get the same message, which indicates to me that the jar file has this directory hardcoded in it or something.  It should probably be "....\platform-tools\adb.exe"

Any help would be appreciated.

答:
-open monkeyrunner.bat in notepad

change set frameworkdir=. to set frameworkdir=..\lib everywhere

find the line call "%java_exe%" -Xmx512m "-Djava.ext.dirs=%frameworkdir%;%swt_path%" -Dcom.android.monkeyrunner.bindir= -jar %jarpath% %*

change the value of Dcom.android.monkeyrunner.bindir to the path of the folder containing adb.exe. Mine was under platform-tools

Body:
So I upgraded Android SDK tools today and now I'm having a problem getting monkeyrunner to run.  I did the standard which is (from the command prompt)

D:\Android\SDK\tools\bin\monkeyrunner.bat D:\ScriptName.py

Note 1: The directory of monkeyrunner.bat changed in this release, so I had to update my command line accordingly.

That fails with the message:

SWT Folder '..\framework\x86_64' does not exist.

I can fix that by editing monkeyrunner.bat and instead of having frameworkdir be set to 'lib' it gets set to '..\lib', the actual location of the monkey runner jar file.

However, when I implement this fix it then gives the error:

Cannot run program "..\framework\adb.exe" cannot find the file specified.

I'm kind of stuck here because no matter what I change in monkeyrunner.bat I get the same message, which indicates to me that the jar file has this directory hardcoded in it or something.  It should probably be "....\platform-tools\adb.exe"

Any help would be appreciated.


问:
Extract string between by [" "]
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

```<code>String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
</code>```

I can get x using the above code but my string is enclosed between [" "]

答:
This regexp seems to work:

```<code>final String regexpStr = "\\[\"(.*?)\"\\]";
</code>```

JUnit test for it:

```<code>@Test
public void regexp() {
    final String[] noMatch = { "", "[", "[\"", "]", "\"]", "\"[", "]\"", "asdf",
            "[\"asdfasdf\"", "asdf[sadf\"asdf\"]" };
    final String[] match = { "[\"one\"]", "asdf[\"one\"]", "[\"one\"]asdf", "asdf[\"one\"]asdf",
            "asdf[\"one\"]asdf[\"two\"]asdf" };
    final String regexpStr = "\\[\"(.*?)\"\\]";

    final Pattern pattern = Pattern.compile(regexpStr);
    for (final String s : noMatch) {
        final Matcher m = pattern.matcher(s);
        Assert.assertFalse(m.matches());
    }

    for (final String s : match) {
        final Matcher m = pattern.matcher(s);
        Assert.assertTrue(m.find());
        Assert.assertEquals(m.group(1), "one");
        if (m.find()) {
            Assert.assertEquals(m.group(1), "two");
        }
    }
}
</code>```

Title: Extract string between by [" "]

Body:
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

I can get x using the above code but my string is enclosed between [" "]

Body:
This regexp seems to work:

final String regexpStr = "\\[\"(.*?)\"\\]";

JUnit test for it:

@Test
public void regexp() {
    final String[] noMatch = { "", "[", "[\"", "]", "\"]", "\"[", "]\"", "asdf",
            "[\"asdfasdf\"", "asdf[sadf\"asdf\"]" };
    final String[] match = { "[\"one\"]", "asdf[\"one\"]", "[\"one\"]asdf", "asdf[\"one\"]asdf",
            "asdf[\"one\"]asdf[\"two\"]asdf" };
    final String regexpStr = "\\[\"(.*?)\"\\]";

    final Pattern pattern = Pattern.compile(regexpStr);
    for (final String s : noMatch) {
        final Matcher m = pattern.matcher(s);
        Assert.assertFalse(m.matches());
    }

    for (final String s : match) {
        final Matcher m = pattern.matcher(s);
        Assert.assertTrue(m.find());
        Assert.assertEquals(m.group(1), "one");
        if (m.find()) {
            Assert.assertEquals(m.group(1), "two");
        }
    }
}


问:
How to create an array from calculations of another array excel vba
I am new to coding and trying to learn through VBA. What I am trying to do is calculate outliers in a data set following a procedure. My trouble is trying to identify the elements in the Data Set that are furthest from the mean (the outlier) and looping that k times. Most of the code is very messy as I have been trying to find out what is wrong so ignore the MsgBox's and ugly formatting. In the last part of my code I tried taking the elements from DataSet and subtracting them from the mean and storing those values in a new array. After that I would take absolute value of the elements in the Diff array and store them in a new array (Diff2). I know I could bypass Diff2 by just taking the absolute value of the calculation of Diff. When I run the code I get the type mismatch error and after some investigation i realized that Diff (and Diff2) are not arrays. If anyone knows of how I can make Diff an array or of a better workaround for this that would be much appreciated!</p>

```<code>Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff As Variant

    For Each element In DataSet
        Diff = element - mean
        MsgBox Diff & " Difference"
    Next element

    Dim P As Integer
    Dim Outlier As Integer
    Dim Diff2 As Variant

    Diff2 = Abs(Diff)

    For P = 1 To k
        Outlier = UBound(Diff, 1)
        MsgBox Outlier
   Next P
End Sub
</code>```

答:
Here how you create the Diff Array with size n

```<code>ReDim Diff(1 To n) As Double
Dim i As Long
For Each element In DataSet
    i = i + 1
    Diff(i) = element - mean
Next element
</code>```

However, I don't think that this is the correct way to go. There's no need for a Diff array. What you should do is, once you have calculated the mean and SD, iterate on the DataSet array itself, check for each element its absolute difference with mean, divide by stdev, and compare this ratio to some threshold (say 2 or 3) to decide whether this element is an outlier, in which case you print it out as an outlier. Something like this:

```<code>For Each element In DataSet
   If abs(element - mean) / SD > 3 Then Debug.Print "outlier: " & element
Next element
</code>```

Body:
I am new to coding and trying to learn through VBA. What I am trying to do is calculate outliers in a data set following a procedure. My trouble is trying to identify the elements in the Data Set that are furthest from the mean (the outlier) and looping that k times. Most of the code is very messy as I have been trying to find out what is wrong so ignore the MsgBox's and ugly formatting. In the last part of my code I tried taking the elements from DataSet and subtracting them from the mean and storing those values in a new array. After that I would take absolute value of the elements in the Diff array and store them in a new array (Diff2). I know I could bypass Diff2 by just taking the absolute value of the calculation of Diff. When I run the code I get the type mismatch error and after some investigation i realized that Diff (and Diff2) are not arrays. If anyone knows of how I can make Diff an array or of a better workaround for this that would be much appreciated!

Sub CalculateOutliers()
    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim X As Integer
    Dim k As Integer
    Dim DataSet As Variant
    Dim ESDPrin As Double

    DataSet = Selection.Value
    'Copies highlighted data into DataSet variable
    'Cell A1 is (1,1) Because it starts at 0 which is out of range

    n = Selection.CountLarge
    'Counts number of entries
    'If n < 20 Then
        'MsgBox "Data set too small"
        'Exit Sub
    'End If
    'Ends Subroutine if data set is too small for this analysis

    If n < 50 Then
        k = Int(n / 10)
    Else
        k = 5
    End If
    'determines k = number of possible outliers

    mean = Application.WorksheetFunction.Average(DataSet)
    'Calculates mean of Data Set
    MsgBox mean & "Average"

    SD = Application.WorksheetFunction.StDev(DataSet)
    'Calculates Standard Deviation of Data Set

    Dim element As Variant
    Dim Diff As Variant

    For Each element In DataSet
        Diff = element - mean
        MsgBox Diff & " Difference"
    Next element

    Dim P As Integer
    Dim Outlier As Integer
    Dim Diff2 As Variant

    Diff2 = Abs(Diff)

    For P = 1 To k
        Outlier = UBound(Diff, 1)
        MsgBox Outlier
   Next P
End Sub

Body:
Here how you create the Diff Array with size n

ReDim Diff(1 To n) As Double
Dim i As Long
For Each element In DataSet
    i = i + 1
    Diff(i) = element - mean
Next element

However, I don't think that this is the correct way to go. There's no need for a Diff array. What you should do is, once you have calculated the mean and SD, iterate on the DataSet array itself, check for each element its absolute difference with mean, divide by stdev, and compare this ratio to some threshold (say 2 or 3) to decide whether this element is an outlier, in which case you print it out as an outlier. Something like this:

For Each element In DataSet
   If abs(element - mean) / SD > 3 Then Debug.Print "outlier: " & element
Next element


问:
Running Javascript from AJAX file
I've been trying to get this to work for ages now, tried loads of SO question/answers but not geting very far.

I think I originally had 2 issues, one which hopefully I've resolved.

I've been using JotForm (the easy form creator that uses prototype). What I have is a facebook style menu (AjaxFlagMenu) which creates a verticle ajax style menu that pulls in html snippets from external files (which in my case all have a Jotform form in there).

At the moment at the top of the 'main' page that contains the menu, I have:

```<code><script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript" src="/js/jquery.corner.js"></script>
<script type="text/javascript" src="/js/jquery.flagmenu.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($){
    var Menu = $("#_Menu").AjaxFlagMenu({
    Caption:'Manage Profile',
    CaptionClass:'CaptionClass',
    onOutClass:'onOutClass',
    onOverClass:'onOverClass',
    onClickClass:'onClickClass',
    hscOutClass:'hscOutClass',
    hscClickClass:'hscClickClass',
    Loading_gif:'/images/loading.gif',
    ajaxContent:'ajaxContent'
    });
    //Basic
    Menu.add({
        Title:'Basic Info',
        onOutIcon:'/images/icon-vcard-c.png',
        onClickIcon:'/images/icon-vcard-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-basic.php',
        data:''
    });
    //Profile Picture
    Menu.add({
        Title:'Profile Picture',
        onOutIcon:'/images/icon-camera-c.png',
        onClickIcon:'/images/icon-camera-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-photo.php',
        data:''
    });
    //Pricing and Offers
    Menu.add({
        Title:'Pricing and Offers',
        onOutIcon:'/images/icon-pound-c.png',
        onClickIcon:'/images/icon-pound-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-pricing.php',
        data:''
    });
    //Services
    Menu.add({
        Title:'Services',
        onOutIcon:'/images/icon-services-c.png',
        onClickIcon:'/images/icon-services-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-services.php',
        data:''
    });
    //Bio and Additional
    Menu.add({
        Title:'Bio and Additional',
        onOutIcon:'/images/icon-bio-c.png',
        onClickIcon:'/images/icon-bio-d.png',
        HtmlSatusContent:'',
        url:'/instructor/pages/mp-bio.php',
        data:''
    });
    $("#_td").corner("4px");
});
</script>
<script src="/js/jotform/prototype.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/protoplus.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/protoplus-ui.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/jotform.js?v=3.1.92" type="text/javascript"></script>
<script src="/js/jotform/calendarview.js?v=3.1.92" type="text/javascript"></script>
</code>```

What I then need to do, is when the menu item is clicked and loads the HTML from the other page, I need to run JotForm.init(); to enable the JotForm validation functions. However, I don't even seem to be able to alert("Hello World"); to work on the page that is called in.

Any help would be great! Thank you!

答:
Use the JotForm Iframe Code instead. Here is how you can get it. Open your form on the JotForm Form Builder:

Open "Setup & Share" tab on toolbar,

Click on "Share Form"

Click on "Advanced Options"

Click on "iFrame Code"and copy the form code to your site.

Title: Running Javascript from AJAX file

Body:
I've been trying to get this to work for ages now, tried loads of SO question/answers but not geting very far.

I think I originally had 2 issues, one which hopefully I've resolved.

I've been using JotForm (the easy form creator that uses prototype). What I have is a facebook style menu (AjaxFlagMenu) which creates a verticle ajax style menu that pulls in html snippets from external files (which in my case all have a Jotform form in there).

At the moment at the top of the 'main' page that contains the menu, I have:

What I then need to do, is when the menu item is clicked and loads the HTML from the other page, I need to run JotForm.init(); to enable the JotForm validation functions. However, I don't even seem to be able to alert("Hello World"); to work on the page that is called in.

Any help would be great! Thank you!


问:
How to resolve integer overflow errors in R estimation
I'm trying to estimate a model using speedglm in R. The dataset is large (~69.88 million rows and 38 columns). Multiplying the number of rows and columns results in ~2.7 billion which is outside the integer limit. I can't provide the data, but the following examples recreate the issue.

```<code>library(speedglm)

# large example that works
require(biglm)
n <- 500000
k <- 500
y <- rgamma(n, 1.5, 1)
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
working.example <- speedglm(fo, data = da, family = Gamma(log))

# repeat with large enough size to break
k <- 5000       # 10 times larger than above
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
failed.example <- speedglm(fo, data = da, family = Gamma(log))

# attempting to resolve error with chunksize
attempted.fixed.example <- speedglm(fo, data = da, family = Gamma(log), chunksize = 10^6)
</code>```

This causes an error and integer overflow warning.

```<code>Error in if (!replace && is.null(prob) && n > 1e+07 && size <= n/2) .Internal(sample2(n,  :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In nrow(X) * ncol(X) : NAs produced by integer overflow
</code>```

I understand the warning, but I do not understand the error. They seem to be related in this case as they appear together after each attempt.

Removing columns allows the estimation to complete. It does not seem to matter which columns are removed; removing interacted or non-interacted variables will both result in a completed estimation. The chunksize option was added after receiving the error initially, but has not helped.

My questions are: (1) what causes the first error? (2) is there a way to estimate models using data such that the number of rows by the number of columns is larger than the integer limit? (3) is there a better na.action to use in this case?

Thanks,

JP.

Running: R version 3.3.3 (2017-03-06)

Actual code below:

```<code>dft_var <- c("cltvV0", "cltvV60", "cltvV120", "VCFLBRQ", "ageV0",
             "ageV1", "ageV8", "ageV80", "FICOV300", "FICOV650",
             "FICOV900", "SingleHouse", "Apt", "Mobile", "Duplex",
             "Row", "Modular", "Rural", "FirstTimeBuyer",
             "FirstTimeBuyerMissing", "brwtotinMissing", "IncomeRatio",
             "VintageBefore2001", "NFLD", "yoy.fcpwti:province_n")
logit1 <- speedglm(formula = paste("DefaultFlag ~ ",
                                   paste(dft_var, collapse = "+"),
                                   sep = ""),
                   family = binomial(logit),
                   na.action = na.exclude,
                   data = default.data,
                   chunksize = 1*10^7)
</code>```

答:
Update:

Based on my investigation below, @James figured out that the problem can be avoided by providing non-NULL value for the parameter sparse in the call of the speedglm function, as it prevents the internal call of the is.sparse function.

Using the example above, the following should now work:

```<code>speedglm(fo, data = da, family = Gamma(log), sparse = FALSE)
</code>```

My original answer:

Both the warning and the error come from the same line in the function is.sparse in the package speedglm.

The line is:

```<code>sample(X,round((nrow(X)*ncol(X)*camp),digits=0),replace=FALSE)
</code>```

The warning happens because of the use of nrow(X)*ncol(X) for a large matrix. The nrow and ncol functions return integer values, which can overflow. here is an illustration.

```<code>nr = 1000000L
nc = 1000000L
nr*nc
# [1] NA
# Warning message:
# In nr * nc : NAs produced by integer overflow
</code>```

The error happens because the sample function is confused when X is a large matrix and size = NA. Here is an illustration:

```<code>sample(matrix(1,3000,1000000), NA, replace=FALSE)
# Error in if (useHash) .Internal(sample2(n, size)) else .Internal(sample(n,  :
# missing value where TRUE/FALSE needed
</code>```

Body:
I'm trying to estimate a model using speedglm in R. The dataset is large (~69.88 million rows and 38 columns). Multiplying the number of rows and columns results in ~2.7 billion which is outside the integer limit. I can't provide the data, but the following examples recreate the issue.

library(speedglm)

# large example that works
require(biglm)
n <- 500000
k <- 500
y <- rgamma(n, 1.5, 1)
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
working.example <- speedglm(fo, data = da, family = Gamma(log))

# repeat with large enough size to break
k <- 5000       # 10 times larger than above
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
failed.example <- speedglm(fo, data = da, family = Gamma(log))

# attempting to resolve error with chunksize
attempted.fixed.example <- speedglm(fo, data = da, family = Gamma(log), chunksize = 10^6)

This causes an error and integer overflow warning.

Error in if (!replace && is.null(prob) && n > 1e+07 && size <= n/2) .Internal(sample2(n,  :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In nrow(X) * ncol(X) : NAs produced by integer overflow

I understand the warning, but I do not understand the error. They seem to be related in this case as they appear together after each attempt.

Removing columns allows the estimation to complete. It does not seem to matter which columns are removed; removing interacted or non-interacted variables will both result in a completed estimation. The chunksize option was added after receiving the error initially, but has not helped.

My questions are: (1) what causes the first error? (2) is there a way to estimate models using data such that the number of rows by the number of columns is larger than the integer limit? (3) is there a better na.action to use in this case?

Thanks,

JP.

Running: R version 3.3.3 (2017-03-06)

Actual code below:

dft_var <- c("cltvV0", "cltvV60", "cltvV120", "VCFLBRQ", "ageV0",
             "ageV1", "ageV8", "ageV80", "FICOV300", "FICOV650",
             "FICOV900", "SingleHouse", "Apt", "Mobile", "Duplex",
             "Row", "Modular", "Rural", "FirstTimeBuyer",
             "FirstTimeBuyerMissing", "brwtotinMissing", "IncomeRatio",
             "VintageBefore2001", "NFLD", "yoy.fcpwti:province_n")
logit1 <- speedglm(formula = paste("DefaultFlag ~ ",
                                   paste(dft_var, collapse = "+"),
                                   sep = ""),
                   family = binomial(logit),
                   na.action = na.exclude,
                   data = default.data,
                   chunksize = 1*10^7)

Body:
Update:

Based on my investigation below, @James figured out that the problem can be avoided by providing non-NULL value for the parameter sparse in the call of the speedglm function, as it prevents the internal call of the is.sparse function.

Using the example above, the following should now work:

speedglm(fo, data = da, family = Gamma(log), sparse = FALSE)

My original answer:

Both the warning and the error come from the same line in the function is.sparse in the package speedglm.

The line is:

sample(X,round((nrow(X)*ncol(X)*camp),digits=0),replace=FALSE)

The warning happens because of the use of nrow(X)*ncol(X) for a large matrix. The nrow and ncol functions return integer values, which can overflow. here is an illustration.

nr = 1000000L
nc = 1000000L
nr*nc
# [1] NA
# Warning message:
# In nr * nc : NAs produced by integer overflow

The error happens because the sample function is confused when X is a large matrix and size = NA. Here is an illustration:

sample(matrix(1,3000,1000000), NA, replace=FALSE)
# Error in if (useHash) .Internal(sample2(n, size)) else .Internal(sample(n,  :
# missing value where TRUE/FALSE needed


问:
How to assign a value of 10^100 to an integer variable in C?
I was working on a problem to count number of digits in a number but according to the constraints the number should be of the range 10^100(10 to the power 100). I have tried it using limits.h but it did not work. Could anyone suggest a way to do that?</p>

```<code>int main(){

    int n=LONG_MAX;
    int count;
    scanf("%d",&n);
    while(n!=0)
    {
        n=n/10;
        count++;
    }
    printf("%d",count);
    return 0;
}
</code>```

答:
Well, in C 10^100 can be easily stored to an int:

```<code>int xored = 10^100;
</code>```

After that, xored will store 110.

```<code>1100100
0001010
-------
1101110
</code>```

Body:
I was working on a problem to count number of digits in a number but according to the constraints the number should be of the range 10^100(10 to the power 100). I have tried it using limits.h but it did not work. Could anyone suggest a way to do that?

int main(){

    int n=LONG_MAX;
    int count;
    scanf("%d",&n);
    while(n!=0)
    {
        n=n/10;
        count++;
    }
    printf("%d",count);
    return 0;
}

Body:
Well, in C 10^100 can be easily stored to an int:

int xored = 10^100;

After that, xored will store 110.

1100100
0001010
-------
1101110


问:
Rails tests don't seem to be loading any classes, NameError: uninitialized constant
Suddenly whenever I run 'rake test' or 'bundle exe rake test' I get the following error.

```<code>NameError: uninitialized constant FactoryGirl
</code>```

Before anyone tells me to add require 'factory_girl'  to my test_helper.rb file, the same updated branch is running the tests without any problem in another computer.

Still I've tried adding require 'factory_girl'. Then it raised another error saying NameError: uninitialized constant Faker, and so I added require 'faker' and there was always something it required, and the tests for this project always worked fine without all those requires.

Info that might be useful:

Ubuntu 16.10

Rails 5.1.1

Ruby 2.3.3 (using rbenv)

I'm using minitest, not RSPEC

Error bracktrace:

```<code>** Invoke test (first_time)
** Execute test
rake aborted!
NameError: uninitialized constant FactoryGirl
/home/samir/Projects/Tuuris/test/test_helper.rb:10:in `<top (required)>'
/home/samir/Projects/Tuuris/test/controllers/admin_controller_test.rb:1:in `<top (required)>'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:14:in `block in require_files'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:13:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:13:in `require_files'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/minitest_plugin.rb:67:in `rake_run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/testing.rake:14:in `block in <top (required)>'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
/home/samir/.rbenv/versions/2.3.3/bin/rake:22:in `load'
/home/samir/.rbenv/versions/2.3.3/bin/rake:22:in `<main>'
Tasks: TOP => test
</code>```

Any clue?

答:
Okay, so when I had given up, I found the problem already.

tl;dr : had to remove RAILS_ENV=development from .rbenv-vars

Complete answer:

Test gems were in a group to run only in the test environment like this:

```<code>group :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
  gem 'faker'
  gem 'cpf_faker'
  gem 'factory_girl'
  gem 'capybara'
  gem 'minitest-capybara'
  gem 'poltergeist'
  gem "capybara-webkit"
  gem 'selenium-webdriver'
  gem 'minitest-rails'
end
</code>```

The thing is... I'm using whenever gem to run some tasks every day, but whenever is not able to find which environment it is being run, so I was using RAILS_ENV=development in my .rbenv-vars file.

Because of that, even rake test was being run on development environment, I don't know why this is allowed to happen though.

Body:
Suddenly whenever I run 'rake test' or 'bundle exe rake test' I get the following error.

NameError: uninitialized constant FactoryGirl

Before anyone tells me to add require 'factory_girl'  to my test_helper.rb file, the same updated branch is running the tests without any problem in another computer.

Still I've tried adding require 'factory_girl'. Then it raised another error saying NameError: uninitialized constant Faker, and so I added require 'faker' and there was always something it required, and the tests for this project always worked fine without all those requires.

Info that might be useful:

Ubuntu 16.10

Rails 5.1.1

Ruby 2.3.3 (using rbenv)

I'm using minitest, not RSPEC

Error bracktrace:

** Invoke test (first_time)
** Execute test
rake aborted!
NameError: uninitialized constant FactoryGirl
/home/samir/Projects/Tuuris/test/test_helper.rb:10:in `<top (required)>'
/home/samir/Projects/Tuuris/test/controllers/admin_controller_test.rb:1:in `<top (required)>'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:14:in `block in require_files'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:13:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/test_requirer.rb:13:in `require_files'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/minitest_plugin.rb:67:in `rake_run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.1/lib/rails/test_unit/testing.rake:14:in `block in <top (required)>'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/home/samir/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
/home/samir/.rbenv/versions/2.3.3/bin/rake:22:in `load'
/home/samir/.rbenv/versions/2.3.3/bin/rake:22:in `'
Tasks: TOP => test

Any clue?

Body:
Okay, so when I had given up, I found the problem already.

tl;dr : had to remove RAILS_ENV=development from .rbenv-vars

Complete answer:

Test gems were in a group to run only in the test environment like this:

group :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
  gem 'faker'
  gem 'cpf_faker'
  gem 'factory_girl'
  gem 'capybara'
  gem 'minitest-capybara'
  gem 'poltergeist'
  gem "capybara-webkit"
  gem 'selenium-webdriver'
  gem 'minitest-rails'
end

The thing is... I'm using whenever gem to run some tasks every day, but whenever is not able to find which environment it is being run, so I was using RAILS_ENV=development in my .rbenv-vars file.

Because of that, even rake test was being run on development environment, I don't know why this is allowed to happen though.


问:
Real name (Full name) of USB device?
DriveInfo[] mydrives = DriveInfo.GetDrives();

```<code> if (mydrive.DriveType == DriveType.Removable)
</code>```

in this way i get all the devices that connected to my machine
 and their name :  mydrive.Name

 can i know which kind of device is each one of them?-
 like DOK , external HDD and so on.....
 or to get their real name like- MyBook (the name of the external HDD)-
 it will also help me a lot.

答:
Seen here on MSDN:

You can get the Volume Label from the DriveInfo : Drive_Info.VolumeLabel

Another useful link about all information available from DriveInfo.

Title: Real name (Full name) of USB device?

Body:
DriveInfo[] mydrives = DriveInfo.GetDrives();

 if (mydrive.DriveType == DriveType.Removable)

in this way i get all the devices that connected to my machine
 and their name :  mydrive.Name

 can i know which kind of device is each one of them?-
 like DOK , external HDD and so on.....
 or to get their real name like- MyBook (the name of the external HDD)-
 it will also help me a lot.