问:
Cannot connect to MSSQL via PHP
Connection to MsSQL failed.
Error message:

```<code>SQLSTATE: HYT00

Code: 0

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired

SQLSTATE: 08001

Code: 10057

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: Error code 0x2749

SQLSTATE: 08001

Code: 10057

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
</code>```

OS: Ubuntu 16.04

I installed all driver needed according to the guide.

```<code>try {
  $conn = new PDO ("sqlsrv:Server=host.com\instance; Database = DBName",NULL,NULL);
  $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ){
  die(print_r( $e->getMessage()));
}
</code>```

Since I used windows NT authentication, I leaved username and password blank.

Really need HELP !!!!

Thanks!!

答:
Best I can offer you (and at the risk of just providing a link) is the following MSDN post: SQL Server Driver for PHP: Understanding Windows Authentication

Here's probably the most interesting piece:

(Following is not my work, but Brian Swan's)

But understanding what identity was being used in the connection
  attempt was confusing. What helped clear up my confusion was learning
  this: The identity that is used to connect to the server will always
  be the identity of the process in which PHP is running. That may be a
  bit oversimplified (impersonation allows the process to temporarily
  use a different identity), but understanding this allowed me to move
  forward. After some more digging and some experimentation, I found I
  needed to answer two questions to know what identity would be used in
  the connection attempt:

1) What was the authentication mode for IIS? (Anonymous authentication? Windows authentication? Both?)

2) Was impersonation for the FastCGI module on or off? (i.e. Was the
  fastcgi.impersonate setting in my php.ini file set to 0 or 1?)

Here’s what I found:

A. IIS Anonymous Authentication enabled and fastcgi.impersonate = 1: Because I was connecting to IIS anonymously, the built-in anonymous
  account (which is NT AUTHORITY\IUSER by default in IIS 7.0+) was
  impersonated. So, my connection attempt failed because this identity
  does not map to a valid login on my server.

B. IIS Anonymous Authentication enabled and fastcgi.impersonate = 0: Because
  impersonation was off, my identity was not used as the identity of the
  PHP process. Instead, the actual identity of the PHP process was used
  in the connection attempt. In IIS 7.5, the identity of the PHP process
  depends on the identity of the application pool it is running in. In
  this case, PHP was in the default application pool and the identity
  used in the connection attempt was IIS APPPOOL\DefaultAppPool (so my
  connection attempt failed). This article provides more information
  about different versions of IIS and the identity of applications: Who
  is my IIS Application Process Identity?

C. IIS Windows Authentication enabled and fastcgi.impersonate = 1: With Windows
  authentication enabled (and Anonymous Authentication disabled), I
  connected to IIS with the identity that my Web browser was running
  under (Microsoft\brian.swan, the identity I logged in with). And, with
  impersonation on, the PHP process ran under the Microsoft\brian.swan
  identity. So, since that identity mapped to a valid login on my
  server, my connection attempt succeeded.

D. IIS Windows Authentication enabled and fastcgi.impersonate = 0: The results here were the same as with Anonymous authentication enabled and
  fastcgi.impersonate = 0 (the connection attempt failed). The only
  difference occurred when I requested the page from the Web server: a
  pop-up window asked for my identity when I requested the page.

E.Both Anonymous and Windows Authentication enabled: Web browsers will
  try to access a Web server by using anonymous authentication first.
  So, if both Anonymous and Windows Authentication are both enabled, the
  results will be the same as those above where Anonymous Authentication
  is enabled (A and B). For more background on this, see How IIS
  authenticates Web browser clients.

Title: Cannot connect to MSSQL via PHP

Body:
Connection to MsSQL failed.
Error message:

SQLSTATE: HYT00

Code: 0

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired

SQLSTATE: 08001

Code: 10057

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: Error code 0x2749

SQLSTATE: 08001

Code: 10057

Message: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.

OS: Ubuntu 16.04

I installed all driver needed according to the guide.

try {
  $conn = new PDO ("sqlsrv:Server=host.com\instance; Database = DBName",NULL,NULL);
  $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ){
  die(print_r( $e->getMessage()));
}

Since I used windows NT authentication, I leaved username and password blank.

Really need HELP !!!!

Thanks!!


来源: stackexchange

问:
Add a custom header to scala WebSocketRequest
I am following the example here to create a websocket client in Scala. I want to pass a custom header in the websocket request. I created a CustomHeader class by extending HttpHeader.

```<code>final class CustomHeader(headerName: String, headerValue: String) extends HttpHeader {
  override def name(): String = headerName

  override def value(): String = headerValue

  override def lowercaseName(): String = name.toLowerCase

  override def renderInRequests(): Boolean = true

  override def renderInResponses(): Boolean = true
}
</code>```

Then in the client,

```<code>val headers = Seq(new CustomHeader("X-Auth-Token", authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
</code>```

When I run activator compile, it throws the following error:

```<code>type mismatch;
[error]  found   : Seq[com.apple.geo.neutron.services.notification.event.CustomHeader]
[error]  required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader]
[error] Error occurred in an application involving default arguments.
[error]     val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
</code>```

How do I resolve this error, or add a custom header to the websocket request?

答:
Answering my own question. Thanks to this thread, I found a working way to add custom headers. Here is what I did:

```<code>final class CustomHeader(headerValue: String) extends ModeledCustomHeader[CustomHeader] {
    override val companion = CustomHeader

    override def value(): String = headerValue

    override def renderInRequests(): Boolean = true

    override def renderInResponses(): Boolean = true
}

object CustomHeader extends ModeledCustomHeaderCompanion[CustomHeader] {
    override val name = "X-Auth-Token"

    override def parse(value: String) = Try(new CustomHeader(value))
}
</code>```

And then, the websocket request is created as:

```<code>val headers = scala.collection.immutable.Seq(new CustomHeader(authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am following the example here to create a websocket client in Scala. I want to pass a custom header in the websocket request. I created a CustomHeader class by extending HttpHeader.

final class CustomHeader(headerName: String, headerValue: String) extends HttpHeader {
  override def name(): String = headerName

  override def value(): String = headerValue

  override def lowercaseName(): String = name.toLowerCase

  override def renderInRequests(): Boolean = true

  override def renderInResponses(): Boolean = true
}

Then in the client,

val headers = Seq(new CustomHeader("X-Auth-Token", authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)

When I run activator compile, it throws the following error:

type mismatch;
[error]  found   : Seq[com.apple.geo.neutron.services.notification.event.CustomHeader]
[error]  required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader]
[error] Error occurred in an application involving default arguments.
[error]     val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)

How do I resolve this error, or add a custom header to the websocket request?

Body:
Answering my own question. Thanks to this thread, I found a working way to add custom headers. Here is what I did:

final class CustomHeader(headerValue: String) extends ModeledCustomHeader[CustomHeader] {
    override val companion = CustomHeader

    override def value(): String = headerValue

    override def renderInRequests(): Boolean = true

    override def renderInResponses(): Boolean = true
}

object CustomHeader extends ModeledCustomHeaderCompanion[CustomHeader] {
    override val name = "X-Auth-Token"

    override def parse(value: String) = Try(new CustomHeader(value))
}

And then, the websocket request is created as:

val headers = scala.collection.immutable.Seq(new CustomHeader(authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)


问:
Function object called via class attribute fails
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

```<code>class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()
</code>```

```<code>input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)
</code>```

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

```<code>class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()
</code>```

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

答:
The documentation actually provides an example very similar to yours. In the description of "Method Objects":

When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object.

and from "Random Remarks":

It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok.

The latter quote is followed by the example I am referring to.

Basically, the idea is that any function named in a class definition becomes a method of that class. Since you are not instantiating your class, your method never gets bound to an instance object (hence ... unbound method Bar() ...). Methods are always called with a first parameter containing the object on which they are invoked, whether you like it or not.

This is the reason that you need to have a special decorator for @classmethod by the way. The decorator wraps the function you created to give it the required interface, but pass the class object instead of the instance object to the wrapped function that you defined.

Since your second version creates _callback as a data object, it just stores a normal function pointer in a list and calls it as-is.

If you were to try to pass in something like None to Foo._callback(None), you will get rid of the original error you are getting, but of course then run into the problem of passing in a parameter the function was not expecting. You can work around this issue by giving Bar an argument (which you would ignore in this case):

```<code>def Bar(self):
    print "Called"
</code>```

Body:
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()

input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

Body:
The documentation actually provides an example very similar to yours. In the description of "Method Objects":

When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object.

and from "Random Remarks":

It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok.

The latter quote is followed by the example I am referring to.

Basically, the idea is that any function named in a class definition becomes a method of that class. Since you are not instantiating your class, your method never gets bound to an instance object (hence ... unbound method Bar() ...). Methods are always called with a first parameter containing the object on which they are invoked, whether you like it or not.

This is the reason that you need to have a special decorator for @classmethod by the way. The decorator wraps the function you created to give it the required interface, but pass the class object instead of the instance object to the wrapped function that you defined.

Since your second version creates _callback as a data object, it just stores a normal function pointer in a list and calls it as-is.

If you were to try to pass in something like None to Foo._callback(None), you will get rid of the original error you are getting, but of course then run into the problem of passing in a parameter the function was not expecting. You can work around this issue by giving Bar an argument (which you would ignore in this case):

def Bar(self):
    print "Called"


问:
Error in R h2o.find_threshold_by_max_metric
I'm using h2o v3.10.4.6 version with R. Built a DL Binomial classification model using h2o.deeplearning() function, would like to find some thresholds using this function h2o.find_threshold_by_max_metric(). However I got error like this:

Error in h2o.find_threshold_by_max_metric(NNmodel, "F1") :    No F1
  for H2OBinomialModel

I use this documentation as reference, but there is no examples

How can I solve this error?

答:
```<code>perf_oot <- h2o.performance(NNmodel, newdata=oot_data.hex)
</code>```


问:
Getting JavaScript object key list
I have a JavaScript object like

```<code>var obj = {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
   key4: 'value4'
}
</code>```

How can I get the length and list of keys in this object?

答:
Recursive solution for browsers that support ECMAScript 5:</p>

```<code>var getObjectKeys = function(obj) {
    var keys = Object.keys(obj);
    var length = keys.length;

    if (length !== 0) {
        for (var i = 0; i < length; i++) {
            if (typeof obj[keys[i]] === 'object') {
                keys[keys[i]] = getObjectKeys(obj[keys[i]]);
            }
        }
    }

    return keys;
};
</code>```

Title: Getting JavaScript object key list

Body:
I have a JavaScript object like

var obj = {
   key1: 'value1',
   key2: 'value2',
   key3: 'value3',
   key4: 'value4'
}

How can I get the length and list of keys in this object?

Body:
Recursive solution for browsers that support ECMAScript 5:

var getObjectKeys = function(obj) {
    var keys = Object.keys(obj);
    var length = keys.length;

    if (length !== 0) {
        for (var i = 0; i < length; i++) {
            if (typeof obj[keys[i]] === 'object') {
                keys[keys[i]] = getObjectKeys(obj[keys[i]]);
            }
        }
    }

    return keys;
};


问:
String matching
Let me explain the problem:

Let's say I have a library, the library contains many books, each book contains chapters, each chapter contains string (and the string begins and ends with dot ".").

The sequence again, library -> book -> chapter -> string.

I extracted the strings from books, let's call them "books strings".

I have a system, where a user can enter a string in the search form, and the system should return the exact match of the entered string from "books strings". If the entered string doesn't match any string from books strings nothing will be returned.

I think about it and found a solution, I'll MD5 all books strings and save the hashed books strings. When a user enters a string to search, I'll hash it too and search for a match in the hashed books strings. It's cheaper (32 or 64 char for each string), faster than plain searching and it only returns the exact match(es).

Do have any comments, ideas, better solutions?

P.S. What is the name of such an algorithm? searching or matching?

答: I agree with a Trie - with one addition, use a soundx algorithm to convert the string for the trie id/node - so misspellings are taken into consideration</p>

OwnerDisplayName: Khaled Al Hourani

ContentLicense: CC BY-SA 2.5

Title: String matching

LastEditorDisplayName: Khaled Al Hourani

OwnerDisplayName: meade


问:
invoke-rc.d on Xenial doesn't work when daemon is killed
I use an /etc/init.d script to launch a daemon. On Wheezy and Trusty even if the daemon would stop running for abnormal reasons (killed, seg fault, etc) I could start again with invoke-rc.d daemon start (or service daemon start). Also, invoke-rc.d daemon status would return with a non-zero value (I used that to in a script that would check the status of the daemon every 10 seconds and restart if it wasn't running).

Moving on to Xenial and systemd, if the daemon is killed, then invoke-rc.d daemon start doesn't work and invoke-rc.d daemon status says that the daemon is still running (exits with 0).

I know that systemd can handle init files, but it looks like this corner case is not handled properly.

In systemd you can cover this cases with SuccessExitStatus=exit_code, but not when systemd uses an init script coming from Trusty.

Any idea of how I can modify my init file cover that case on Xenial (I don't want to create an systemd file to avoid maintaining both version).

答:
I hear that you don't want to create a systemd .service file, but it will be likely be faster than what you are trying to do which is to have systemd to manage a legacy SysV init script. As you quickly discovered, the extra layer of indirection adds complexity and additional potential for bugs.

Without seeing the init.d script you are trying to get working, it's not immediately clear what the problem could be.

As for the time to maintain an additional version-- the file should not really need be changed at all unless something really very fundamental about the service changes over time, so the additional maintenance time should be near zero.

Key docs to check out for setting up a .service file are man systemd.service, man systemd.unit and possibly man systemd.exec. But the simplest solution is likely just to copy/paste/modify a .service file from a comparable service.


问:
React Native 0.45 - Cannot find entry file index.ios.js
I just updated my react native project to version 0.45
and when using this command : react-native run-ios on the root of this project
I am getting this error :

Cannot find entry file index.ios.js in any of the roots ....
and i can see that the server is trying to look for JS files in

Looking for JS files in
   /Users/someUser/Code/ReactTest/node_modules/react-native/packager

when using this command : npm run start -- --root .

i can see that the server is looking for js file in the correct location

Looking for JS files in
   /Users/someUser/Code/ReactTest

and every thing is working from here

why the react-native run-ios is try to look in the wrong location ?

答:
The react-native launched new release 0.45 a few days back. So, the commands to create a react-native application and running locally have many differences.

```<code>npm install -g create-react-native-app
</code>```

Then run the following commands to create a new React Native project called "AwesomeProject":

the new way of creating a react-native application as follows

```<code>create-react-native-app AwesomeProject

cd AwesomeProject
npm start
</code>```

Please follow the official documentation for creating an application and running the application on locally. hope the below link will help you.
https://facebook.github.io/react-native/docs/getting-started.html

Once you've set these up, you can launch your app on an Android Virtual Device by running npm run android, or on the iOS Simulator by running npm run ios(macOS only).

Enjoy, Happy coding :)

Body:
The react-native launched new release 0.45 a few days back. So, the commands to create a react-native application and running locally have many differences.

npm install -g create-react-native-app

Then run the following commands to create a new React Native project called "AwesomeProject":

the new way of creating a react-native application as follows

create-react-native-app AwesomeProject

cd AwesomeProject
npm start

Please follow the official documentation for creating an application and running the application on locally. hope the below link will help you.
https://facebook.github.io/react-native/docs/getting-started.html

Once you've set these up, you can launch your app on an Android Virtual Device by running npm run android, or on the iOS Simulator by running npm run ios(macOS only).

Enjoy, Happy coding :)


问:
How to render a child collection in a view so that it rolls back into the parent model upon post?
Let's say I have a model hierarchy like so:

public class TabModel
{
  public PolicyModel Policy {get;set;}
}

public class PolicyModel
{
  public IEnumerable<PersonModel> Insured {get;set;}
}

public class PersonModel
{
  public string Name {get;set;}
}
```

<p>and I want to render a grid in the view with a editor for <code>Person Name</code> right in the grid.</p>

<p>I know that if I can just get the html to be like so:</p>

```<input name="Policy.Insured[0].Name" />
<input name="Policy.Insured[1].Name" />
...
etc
```

that upon post, my main model will have a policy and that policy will have some insured with names.

What in my razor do I call to make this happen automagically™?

I'd bet a dozen donuts there's something in the framework that knows about Collection[N].PropertyName when iterating over a collection but I don't know how to invoke it.

答:
If I put:

```<code>@Html.EditorFor(model => model.Policy.Insured)
</code>```

and in the Views\Shared\EditorTemplates folder put a PersonModel.cshtml, then in that file create my editors, it works as I hoped.

Body:
Let's say I have a model hierarchy like so:

public class TabModel
{
  public PolicyModel Policy {get;set;}
}

public class PolicyModel
{
  public IEnumerable<PersonModel> Insured {get;set;}
}

public class PersonModel
{
  public string Name {get;set;}
}

and I want to render a grid in the view with a editor for Person Name right in the grid.

I know that if I can just get the html to be like so:

<input name="Policy.Insured[0].Name" />
<input name="Policy.Insured[1].Name" />
...
etc

that upon post, my main model will have a policy and that policy will have some insured with names.

What in my razor do I call to make this happen automagically™?

I'd bet a dozen donuts there's something in the framework that knows about Collection[N].PropertyName when iterating over a collection but I don't know how to invoke it.

Body:
If I put:

@Html.EditorFor(model => model.Policy.Insured)

and in the Views\Shared\EditorTemplates folder put a PersonModel.cshtml, then in that file create my editors, it works as I hoped.


问:
Cannot get list of file on an external hard disk
I cannot get a list of files and folder using the following lines:

```<code><?php
    $dir    = '/media/me/n4m3-0f-my-h4rd-d1sk';
    $files1 = scandir($dir);
    print_r(error_get_last());
    print_r($files1);

?>
</code>```

I followed the first example here: https://secure.php.net/manual/en/function.scandir.php and this snippet of code works only if the dir is /tmp

I get the following error:

```<code>Array ( [type] => 2 [message] => scandir(): (errno 13): Permission denied [file] => /var/www/html/index.php [line] => 8 )
</code>```

答:
The PHP user does not have read access to the disk.

To see the user PHP is set to, you can add this line:

```<code>echo exec('whoami`);
</code>```

To fix this, give that user access to the drive.  This might mean giving at least read access to everyone.

Body:
I cannot get a list of files and folder using the following lines:

<?php
    $dir    = '/media/me/n4m3-0f-my-h4rd-d1sk';
    $files1 = scandir($dir);
    print_r(error_get_last());
    print_r($files1);

?>

I followed the first example here: https://secure.php.net/manual/en/function.scandir.php and this snippet of code works only if the dir is /tmp

I get the following error:

Array ( [type] => 2 [message] => scandir(): (errno 13): Permission denied [file] => /var/www/html/index.php [line] => 8 )

Body:
The PHP user does not have read access to the disk.

To see the user PHP is set to, you can add this line:

echo exec('whoami`);

To fix this, give that user access to the drive.  This might mean giving at least read access to everyone.


问:
Generate number of random sample of specified length in R
I think it's my poor knowledge of R, especially poor knowledge of loop-related codes.

Here is what I am trying to do. Assuming I have numbers from 1 to 500. first, generate 300 sets of two randomly picked numbers  from 1 to 500, assign to each set  a number from 1 to 300, and then combine them into one dataset, let it be dataset A.

So A will look like

```<code>A_no  random_num
1       26
1       256
2       3
2      113
...
</code>```

Then I need to create a dataset B where I will have sets of 3 random numbers out of 500, also counted

```<code>B_no  random_num
1       16
1       113
1       4
2       67
2       25
2       7
</code>```

I believe the R code will look very elegant and simple.  Will really appreciate any help with this solution.

答:
This is simplifying somewhat, taking advantage of the (assumed) fact that all randomly picked numbers will be independent.    </p>

```<code>df1 <- data.frame(A_no=rep(1:500,each=2), random_num=sample(1:300,2*500,replace=T))
head(df1)
##   A_no random_num
## 1    1        249
## 2    1        117
## 3    2        108
## 4    2         44
## 5    3        138
## 6    3        247

dim(df1)
## [1] 1000   2

df2 <- data.frame(A_no=rep(1:500,each=3), random_num=sample(1:300,3*500,replace=T))
head(df2)
##   A_no random_num
## 1    1        276
## 2    1         50
## 3    1        237
## 4    2        153
## 5    2        225
## 6    2          4

dim(df2)
## [1] 1500   2
</code>```

Body:
I think it's my poor knowledge of R, especially poor knowledge of loop-related codes.

Here is what I am trying to do. Assuming I have numbers from 1 to 500. first, generate 300 sets of two randomly picked numbers  from 1 to 500, assign to each set  a number from 1 to 300, and then combine them into one dataset, let it be dataset A.

So A will look like

A_no  random_num
1       26
1       256
2       3
2      113
...

Then I need to create a dataset B where I will have sets of 3 random numbers out of 500, also counted

B_no  random_num
1       16
1       113
1       4
2       67
2       25
2       7

I believe the R code will look very elegant and simple.  Will really appreciate any help with this solution.

Body:
This is simplifying somewhat, taking advantage of the (assumed) fact that all randomly picked numbers will be independent.

df1 <- data.frame(A_no=rep(1:500,each=2), random_num=sample(1:300,2*500,replace=T))
head(df1)
##   A_no random_num
## 1    1        249
## 2    1        117
## 3    2        108
## 4    2         44
## 5    3        138
## 6    3        247

dim(df1)
## [1] 1000   2

df2 <- data.frame(A_no=rep(1:500,each=3), random_num=sample(1:300,3*500,replace=T))
head(df2)
##   A_no random_num
## 1    1        276
## 2    1         50
## 3    1        237
## 4    2        153
## 5    2        225
## 6    2          4

dim(df2)
## [1] 1500   2


问:
Longest word test from appacademy practice in ruby
I am trying to do this test and there are bunch of solutions online and here but  I first want to figure out why my solution is wrong even though it seems that it puts right results when I enter certain strings :

Here is what they are asking :

Write a method that takes in a string. Return the longest word in the
  string. You may assume that the string contains only letters and
  spaces.

You may use the String split method to aid you in your quest.

Here is my solution where I thought I could turn string into array, sort it from max length descending and then just print first element in that new string like this :

```<code>def longest_word(sentence)
  sentence = sentence.split

  sentence.sort_by! { |longest| -longest.length }

  return sentence[0]
end
</code>```

That doesn't seem to work obviously since their test gives me all false..here is the test :

```<code>puts("\nTests for #longest_word")
puts("===============================================")
    puts(
      'longest_word("short longest") == "longest": ' +
      (longest_word('short longest') == 'longest').to_s
    )
    puts(
      'longest_word("one") == "one": ' +
      (longest_word('one') == 'one').to_s
    )
    puts(
      'longest_word("abc def abcde") == "abcde": ' +
      (longest_word('abc def abcde') == 'abcde').to_s
    )
puts("===============================================")
</code>```

So the question is why? And can I just fix my code or the idea is all wrong and I need to do it completely different?

答:
```<code>str = "Which word in this string is longest?"

r = /[[:alpha:]]+/
str.scan(r).max_by(&:length)
  #=> "longest"
</code>```

This regular expression reads, "match one or more characters". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

To deal with words that are hyphenated or contain single quotes, the following is an imperfect modification1:

```<code>str = "Who said that chicken is finger-licken' good?"

r = /[[[:alpha:]]'-]+/
str.scan(r).max_by(&:length)
  #=> "finger-licken'"
</code>```

This regular expression reads, "match one or more characters that are a letter, apostrophe or hyphen". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

1 I've successfully used "finger-licken'" in scrabble.

Body:
I am trying to do this test and there are bunch of solutions online and here but  I first want to figure out why my solution is wrong even though it seems that it puts right results when I enter certain strings :

Here is what they are asking :

Write a method that takes in a string. Return the longest word in the
  string. You may assume that the string contains only letters and
  spaces.

You may use the String split method to aid you in your quest.

Here is my solution where I thought I could turn string into array, sort it from max length descending and then just print first element in that new string like this :

def longest_word(sentence)
  sentence = sentence.split

  sentence.sort_by! { |longest| -longest.length }

  return sentence[0]
end

That doesn't seem to work obviously since their test gives me all false..here is the test :

puts("\nTests for #longest_word")
puts("===============================================")
    puts(
      'longest_word("short longest") == "longest": ' +
      (longest_word('short longest') == 'longest').to_s
    )
    puts(
      'longest_word("one") == "one": ' +
      (longest_word('one') == 'one').to_s
    )
    puts(
      'longest_word("abc def abcde") == "abcde": ' +
      (longest_word('abc def abcde') == 'abcde').to_s
    )
puts("===============================================")

So the question is why? And can I just fix my code or the idea is all wrong and I need to do it completely different?

Body:
str = "Which word in this string is longest?"

r = /[[:alpha:]]+/
str.scan(r).max_by(&:length)
  #=> "longest"

This regular expression reads, "match one or more characters". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

To deal with words that are hyphenated or contain single quotes, the following is an imperfect modification1:

str = "Who said that chicken is finger-licken' good?"

r = /[[[:alpha:]]'-]+/
str.scan(r).max_by(&:length)
  #=> "finger-licken'"

This regular expression reads, "match one or more characters that are a letter, apostrophe or hyphen". The outer brackets constitute a character class, meaning one of the characters within the brackets must be matched.

1 I've successfully used "finger-licken'" in scrabble.


答:
```<code># Set random seed
set.seed(83)
# Generate sequence
z <- seq(1, 300)
# Generate first sample
x <- sample(1:500, 300)
# Combine
zx <- data.frame(z, x)
# Set seed again
set.seed(82)
# Generate second sample
x <- sample(1:500, 300)
# Combine
zy <- data.frame(z, x)
xyz <- rbind(zx, zy)
</code>```

Or you could do this way

```<code># Set random seed
set.seed(83)
# Generate sequence
B_no <- seq(1, 300)
# Generate first sample
x <- sample(1:500, 300)
y <- sample(1:500, 300)
z <- sample(1:500, 300)

wide <- data.frame(B_no, x, y, z)

library(reshape2)
B <- melt(wide, id.vars = c("B_no"))
Bx <- B[order(B$B_no),]
</code>```

Title: Generate number of random sample of specified length in R

Body:
# Set random seed
set.seed(83)
# Generate sequence
z <- seq(1, 300)
# Generate first sample
x <- sample(1:500, 300)
# Combine
zx <- data.frame(z, x)
# Set seed again
set.seed(82)
# Generate second sample
x <- sample(1:500, 300)
# Combine
zy <- data.frame(z, x)
xyz <- rbind(zx, zy)

Or you could do this way

# Set random seed
set.seed(83)
# Generate sequence
B_no <- seq(1, 300)
# Generate first sample
x <- sample(1:500, 300)
y <- sample(1:500, 300)
z <- sample(1:500, 300)

wide <- data.frame(B_no, x, y, z)

library(reshape2)
B <- melt(wide, id.vars = c("B_no"))
Bx <- B[order(B$B_no),]


问:
Passing requests_mock adapter into tested function
I am trying to use requests_mock on a function that I am testing.

```<code>#the function
def getModificationTimeHTTP(url):
    head = requests.head(url)

    modtime = head.headers['Last-Modified'] if 'Last-Modified' in head.headers  \
        else datetime.fromtimestamp(0, pytz.UTC)
    return modtime

#in a test_ file
def test_needsUpdatesHTTP():
    session = requests.Session()
    adapter = requests_mock.Adapter()
    session.mount('mock', adapter)

    adapter.register_uri('HEAD', 'mock://test.com', headers= \
        {'Last-Modified': 'Mon, 30 Jan 1970 15:33:03 GMT'})

    update = getModificationTimeHTTP('mock://test.com')
    assert update
</code>```

This returns an error which suggests the mock adapter is not making its way into the tested function.

```<code>       InvalidSchema: No connection adapters were found for 'mock://test.com'
</code>```

How can I pass the mock adapter into the function?

答:
This won't work because you have to use session.head instead of requests.head.
One possibility to do so without messing with the main function's code is to use patch:

```<code>from unittest.mock import patch

[...]

with patch('requests.head', session.head):
    update = getModificationTimeHTTP('mock://test.com')
assert update
</code>```

Body:
I am trying to use requests_mock on a function that I am testing.

#the function
def getModificationTimeHTTP(url):
    head = requests.head(url)

    modtime = head.headers['Last-Modified'] if 'Last-Modified' in head.headers  \
        else datetime.fromtimestamp(0, pytz.UTC)
    return modtime

#in a test_ file
def test_needsUpdatesHTTP():
    session = requests.Session()
    adapter = requests_mock.Adapter()
    session.mount('mock', adapter)

    adapter.register_uri('HEAD', 'mock://test.com', headers= \
        {'Last-Modified': 'Mon, 30 Jan 1970 15:33:03 GMT'})

    update = getModificationTimeHTTP('mock://test.com')
    assert update

This returns an error which suggests the mock adapter is not making its way into the tested function.

       InvalidSchema: No connection adapters were found for 'mock://test.com'

How can I pass the mock adapter into the function?

Body:
This won't work because you have to use session.head instead of requests.head.
One possibility to do so without messing with the main function's code is to use patch:

from unittest.mock import patch

[...]

with patch('requests.head', session.head):
    update = getModificationTimeHTTP('mock://test.com')
assert update


问:
Talend: how to fork the output of a parent job and call either of child job based on some condition
I am learning Talend. I have a scenario where I have to apply if else if condition to the output from the parent job and based on the outcome, call either of the child jobs. I have thought of few options such as using global variables or context variables. Is it possible to configure the child jobs to listen to the global/context variable change and run if the condition match? I tried looking to configure this, but failed to understand where can I do these configurations.

I even tried taking the output from the parent job component's into a tjavarow where I can write java code with if else if conditions. I was thinking to explicitly call the sub jobs from the if else branching, but I am not able to make any headway. Can someone please direct me through the right approach? Any new approach is also welcomed.

NOTE: We are using free version of Talend.

答:
If I understand correctly, this can be achieved using "Run If" triggers, like this:

Inside tJava, you can write some logic to calculate your variables.
On the If trigger, you write a condition that determines whether or not the component after it is run.

In my example, I'm not actually making use of what's inside tJava, I'm just getting the number of lines output by tLogRow, so it can be left out and the "Run If" triggers connected directly to tLogRow.


问:
how to get title of of row selected in UITableview
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

but how can i get that title of that row ?

thanks in advance

regards

答:
```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = selectedCell.textLabel.text;
}
</code>```

This snippet retrieves the selected cell and stores its text property in a NSString.

However, I do not recommend this. It is better to keep the data and presentation layers separate. Use a backing data store (e.g. an array) and access it using the data in the passed indexPath object (e.g. the index to use to access the array). This data store will be the same one used to populate the table.

Body:
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

but how can i get that title of that row ?

thanks in advance

regards

Body:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *cellText = selectedCell.textLabel.text;
}

This snippet retrieves the selected cell and stores its text property in a NSString.

However, I do not recommend this. It is better to keep the data and presentation layers separate. Use a backing data store (e.g. an array) and access it using the data in the passed indexPath object (e.g. the index to use to access the array). This data store will be the same one used to populate the table.


问:
javascript function to round current time (from epoch) to nearest minute
I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:

```<code><?php
$id  = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>
</code>```

I've been trying variations on this:

```<code>var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');
</code>```

utilizing an md5 script from here

I merely need lock and key to match. Seems simple to me. What am I doing wrong?

答:
To put it in concrete terms (my comment was slightly facetious):

PHP is a server-side language. When your browser fires a request for a page over the internet (or even to a listening port on your local machine), the instance of apache running on the server (or your local machine) executes the PHP on the page, then spits it back out to the browser.

The browser then executes any JavaScript on the page, we refer to this as client-side.

Because you are using Math.round, if it takes more than 30 seconds between the time your server executes the PHP (server-side) and the time your browser starts executing the relevant Javascript (client-side) then the time in minutes will be different. Using Math.floor instead would give you 59 seconds of wiggle room but that's still dicey, especially on mobile.

Even assuming the page executes the JavaScript immediately after loading and loads pretty quickly 30 seconds of latency is not totally off the table, and on mobile neither is 59.

Body:
I've been banging my head against the wall trying to get a JavaScript equivalent to this php snippet:

<?php
$id  = 'uniqueID'
$now = round(time()/60);
$lock = md5($now . $id);
?>

I've been trying variations on this:

var timeInMin = new Date().getTime() / 60000;
var timestamp = Math.round(timeInMin);
var key = md5(timestamp + 'uniqueID');

utilizing an md5 script from here

I merely need lock and key to match. Seems simple to me. What am I doing wrong?


问:
how do i set the cpp_cppckeck opitions?
I've downloaded the vim plugin cpp_cppcheck but have copied it to ~/.vim/ftplugin/c_cppcheck.vim for it to work with C files too. It seems to work well but I now would like to activate the option --enable-all like one can on the shell. In the cppcheck help window it says the following:

```<code>g:cpp_cppcheck_options  The command line options you want to pass to
                        Cppcheck. View your Cppcheck documentation for the
                        possible options.

                        Note that you shouldn't specify a template here! If
                        you do so, Vim won't be able to correctly parse the
                        output of Cppcheck for the quickfix-window.

                        The default value is empty (no options).
</code>```

but :c_cppcheck_options nor :cpp_cppcheck_options does not give me anything and when i hit g head of the colon, it does not seem to accept it in the command line one the bottom. How can I set the config I want?

答:
This is a global variable. See :h :let

```<code>:let g:cpp_cppcheck_options = 'whatever'
</code>```

Title: how do i set the cpp_cppckeck opitions?

Body:
I've downloaded the vim plugin cpp_cppcheck but have copied it to ~/.vim/ftplugin/c_cppcheck.vim for it to work with C files too. It seems to work well but I now would like to activate the option --enable-all like one can on the shell. In the cppcheck help window it says the following:

g:cpp_cppcheck_options  The command line options you want to pass to
                        Cppcheck. View your Cppcheck documentation for the
                        possible options.

                        Note that you shouldn't specify a template here! If
                        you do so, Vim won't be able to correctly parse the
                        output of Cppcheck for the quickfix-window.

                        The default value is empty (no options).

but :c_cppcheck_options nor :cpp_cppcheck_options does not give me anything and when i hit g head of the colon, it does not seem to accept it in the command line one the bottom. How can I set the config I want?

Body:
This is a global variable. See :h :let

:let g:cpp_cppcheck_options = 'whatever'


问:
How to disable sort in DataGridView?
How can I disable sort in DataGridView? I need to disable the header DataGridView sorting.

答:
```<code>private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
           dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
      }
}
</code>```

Title: How to disable sort in DataGridView?


问:
How to use softdelete withTrashed in Laravel
I'm building an application in laravel where I've two models company and contact with belongs to relationship as following:

```<code>class Contact extends Model
{
    use SoftDeletes;

    public function company()
    {
        return $this->belongsTo('App\Company');
    }

}
</code>```

I'm using softdeletes in company model too, Now suppose even if any company is deleted, I want the contact to be shown with there company details.

I'm trying to do something like this to retrieve the data:

```<code>$allData = Contact::with('company')->withTrashed()->get();
</code>```

It is not working, it is only showing company details which are not deleted. Any ideas to overcome this problem?

答:
Try this solution:

Contacts with trashed:

$allСontacts = Contact::withTrashed()->get();
```
<ul>
<li>Without:</li>
</ul>
<pre class="lang-php prettyprint-override"><code>$contacts = Contact::all();
</code>```

Get companies:

$companies = $contacts->company()->withTrashed()->get();

$allCompanies = $allСontacts->company()->withTrashed()->get();
```

Body:
I'm building an application in laravel where I've two models company and contact with belongs to relationship as following:

class Contact extends Model
{
    use SoftDeletes;

    public function company()
    {
        return $this->belongsTo('App\Company');
    }

}

I'm using softdeletes in company model too, Now suppose even if any company is deleted, I want the contact to be shown with there company details.

I'm trying to do something like this to retrieve the data:

$allData = Contact::with('company')->withTrashed()->get();

It is not working, it is only showing company details which are not deleted. Any ideas to overcome this problem?

Body:
Try this solution:

Contacts with trashed:

$allСontacts = Contact::withTrashed()->get();

Without:

$contacts = Contact::all();

Get companies:

$companies = $contacts->company()->withTrashed()->get();

$allCompanies = $allСontacts->company()->withTrashed()->get();

ContentLicense: CC BY-SA 4.0


问:
Custom attributes not shown in user profile in Azure AD B2C
I have added custom attributes during Sign-up and added the same in the application claim in Azure AD B2C management portal.
I was expecting these custom attributes to be added as part of the user profile who signed-up using their social identity provider.

Could someone help me on getting these custom attributes in the user profile screen of Azure AD B2C?

答:
Besides creating the custom attribute, you need to add it to your policy's Attributes. Optionally you can also configure the attribute as an application claim.

You do this in the "Sign-up attributes" or "Edit profile attributes" section while editing you policy.

Keep in mind this is different from adding the attribute to your application claims.

While the former shows it in the UI allowing the user to edit the attribute, the latter sends the value of that attribute to the application in the id_token.

See the use a custom attribute in your policy documentation for more info.

It is also worth noting that at this time, custom attributes do not show up in the Azure portal's Users & Groups blade. As an admin, you can only view and update those using the Graph. You can request this as a feature in the Azure AD B2C feedback forum


问:
Can i use a DefaultBinder to do dependency injection?
i am trying to implement dependency injection for our custom ModelBinders. Right now i have

```<code>    protected void Application_Start()
    {
        // removed IoC configuration code

        ModelBinders.Binders.DefaultBinder = new CastleWindsorModelBinder(this.container, ModelBinders.Binders.DefaultBinder);

        // removed configuration code
    }

    public class CastleWindsorModelBinder : IModelBinder
    {
    private readonly IWindsorContainer container;
    private readonly IModelBinder fallback;

    public CastleWindsorModelBinder(IWindsorContainer container, IModelBinder fallback)
    {
        this.container = container;
        this.fallback = fallback;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        try
        {
            var binder = (IModelBinder)this.container.Resolve(
                    bindingContext.ModelType.FullName, typeof (IModelBinder));

            return binder.BindModel(controllerContext, bindingContext);
        }
        catch (ComponentNotFoundException)
        {
            return fallback.BindModel(controllerContext, bindingContext);
        }
    }
    }
</code>```

but i'am not sure if this will result in overall poor performance. Can anybody share his own experience with this approach?

答: MvcContrib already has this. See the source code and tests.</p>

Body:
i am trying to implement dependency injection for our custom ModelBinders. Right now i have

    protected void Application_Start()
    {
        // removed IoC configuration code

        ModelBinders.Binders.DefaultBinder = new CastleWindsorModelBinder(this.container, ModelBinders.Binders.DefaultBinder);

        // removed configuration code
    }

    public class CastleWindsorModelBinder : IModelBinder
    {
    private readonly IWindsorContainer container;
    private readonly IModelBinder fallback;

    public CastleWindsorModelBinder(IWindsorContainer container, IModelBinder fallback)
    {
        this.container = container;
        this.fallback = fallback;
    }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        try
        {
            var binder = (IModelBinder)this.container.Resolve(
                    bindingContext.ModelType.FullName, typeof (IModelBinder));

            return binder.BindModel(controllerContext, bindingContext);
        }
        catch (ComponentNotFoundException)
        {
            return fallback.BindModel(controllerContext, bindingContext);
        }
    }
    }

but i'am not sure if this will result in overall poor performance. Can anybody share his own experience with this approach?


问:
Show echo in previous php file
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

```<code><input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">
</code>```

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

答:
You can define a successful result in the URI when passing back to the overview.php file.

In your mailinfo.php file, put something like this if the result is successful.

```<code>if($result) {
header("Location: ../overview.php?result=success");
} else
header("Location: ../overview.php?result=failed");
}
</code>```

Then in your overview.php file, get the info from the URI, like:

```<code>$result = $_GET['result'];
$success = "success";
if ($result = $success) {
echo "Success";
}
else {
echo "Failed";
}
</code>```

You might need to make a few adjustments, but should do the trick

Title: Show echo in previous php file

Body:
I'm Probably searching with the wrong keywords, but I can not find the correct answer.

I have a php file(overview.php) which contains a button, this button executes another php script(mailinfo.php) which sends a email and shows a echo line when successful .

<input onclick="location.href = 'mailinfo.php';" type="button" value="Nee" class="btn btn-danger btn-md">

When I click the button, mail.php is loaded and i only see the echo. I would like to see this echo on overview.php without showing the mail.php page.

Body:
You can define a successful result in the URI when passing back to the overview.php file.

In your mailinfo.php file, put something like this if the result is successful.

if($result) {
header("Location: ../overview.php?result=success");
} else
header("Location: ../overview.php?result=failed");
}

Then in your overview.php file, get the info from the URI, like:

$result = $_GET['result'];
$success = "success";
if ($result = $success) {
echo "Success";
}
else {
echo "Failed";
}

You might need to make a few adjustments, but should do the trick


问:
How to prevent attacks on WordPress wp-login.php page
On my website, the highest GPU usage is actually on the WordPress login page, not the home page. I have basically come to the conclusion that it is being attacked by a brute force attack, or something similar.

I have installed a plugin that prevents password attacks from bots, but it doesn't prevent the bots from actually visiting the page in the first place.

I want to change the location of the login page to something like wp-login-here.php, or perhaps there is a better solution. The Stealth Plugin seems like it would do the trick, but it is not compatible with recent versions of WordPress. Any ideas?

EDIT: The real solution to this problem was for me to do a clean install of WordPress, this time in a version that was supported by the Stealth plugin. After installing WP and the Stealth plugin on this earlier version of WP, I used the .htaccess file that the plugin created and copied it over (after making a few modifications) to the production site. The reason I accepted the answer I did was because Bad Behavior ended up being a good plugin, and the other advice was useful.

答: What's the issue with just limiting the number of login attempts by IP address? http://wordpress.org/extend/plugins/limit-login-attempts/</p>


问:
PowerShell to list multiple AD groups membership from specific Organizational Unit
I have a need to get all of the AD groups and their respective memberships out of a specific AD OU.  The code I have does that when writing to the host screen but I am not able to output it cleanly to .xml, which was the requested format, but at this point I will take it in any format. Management would like output file similar to :

```<code>Group1 User1
Group1 User2
Group1 User3
Group2 User1
Group2 User2
Group2 User3
etc...
</code>```

Anyone have any ideas?

```<code>$groupName = Get-ADGroup -SearchBase "OU=Groups,DC=domain,DC=com" -Filter * | Select-Object sAMAccountName

foreach ( $groupMember in $groupName )
{
   # $groupMember
   Get-ADGroupMember -Identity $groupMember.sAMAccountName | Export-Clixml -Path C:\temp.xml -Force
</code>```

答:
With the assumption that you want the two column text file like you displayed, which is not an XML formatted file. You could use a calculated property using Select-Object then export that information with the formatting of choice:

```<code>$GroupName = Get-ADGroup -SearchBase "OU=Groups,DC=domain,DC=com" -Filter * | Select-Object -ExpandProperty sAMAccountName

$Members = foreach ($GroupMember in $GroupName) {
   Get-ADGroupMember -Identity $GroupMember | Select-Object @{Name="Group";Expression={$GroupMember}},name
}
"$(Members.Group) $($Members.Name)"  | Out-File C:\temp.txt
#Alternatively for a .CSV
$Members | Export-CSV C:\temp.csv
</code>```

Body:
I have a need to get all of the AD groups and their respective memberships out of a specific AD OU.  The code I have does that when writing to the host screen but I am not able to output it cleanly to .xml, which was the requested format, but at this point I will take it in any format. Management would like output file similar to :

Group1 User1
Group1 User2
Group1 User3
Group2 User1
Group2 User2
Group2 User3
etc...

Anyone have any ideas?

$groupName = Get-ADGroup -SearchBase "OU=Groups,DC=domain,DC=com" -Filter * | Select-Object sAMAccountName

foreach ( $groupMember in $groupName )
{
   # $groupMember
   Get-ADGroupMember -Identity $groupMember.sAMAccountName | Export-Clixml -Path C:\temp.xml -Force

Body:
With the assumption that you want the two column text file like you displayed, which is not an XML formatted file. You could use a calculated property using Select-Object then export that information with the formatting of choice:

$GroupName = Get-ADGroup -SearchBase "OU=Groups,DC=domain,DC=com" -Filter * | Select-Object -ExpandProperty sAMAccountName

$Members = foreach ($GroupMember in $GroupName) {
   Get-ADGroupMember -Identity $GroupMember | Select-Object @{Name="Group";Expression={$GroupMember}},name
}
"$(Members.Group) $($Members.Name)"  | Out-File C:\temp.txt
#Alternatively for a .CSV
$Members | Export-CSV C:\temp.csv


问:
Where is my Electron App located
I have an electron app, that also operates on files in the same directory. These are not files the user selects, or files bundled inside the electron application, but I do need to reference them

for example:

/Users/test/Documents/myapp.app

/Users/test/Documents/example.zip

I need to know where that application is located, e.g.:

/Users/test/Documents

But instead when test.app is ran I get:

/Users/test/Documents/myapp.app/Contents/Resources/app/

Resulting in errors when it tries to access /Users/test/Documents/myapp.app/Contents/Resources/app/test.zip, or if I use a relative path, /test.zip.

How would I reliably access example.zip in this scenario? Note that I cannot bundle it with my app, it's being placed there by somebody else, so moving it is not an option, and it's a file I'm expecting to be there.

答:
Where are you running the Electron App? If it is running under 'Documents' (I am assuming Windows), you can pass in the documents to app.getPath like so: app.getPath('documents').

If you are calling this from the render process, you might have to import remote and do the following if you are in a render process remote.app.getPath('documents');.

This electron doc will be better at explaining the path options you can pass in.

Title: Where is my Electron App located


问:
How to nest Vue.nextTick when testing?
I'm trying to test what happens in my app on two consecutive ticks. This is what I have so far (the tests fail in the karma devtools, but fail in the command line):

```<code>import { mount } from 'avoriaz';
import MyComponent from './MyComponent';

describe('testing', function() {
  it('should do something', (done) => {
    const wrapper = mount(MyComponent, { store });
    wrapper.vm.changeData();
    Vue.nextTick(() => {
      expect(wrapper.vm.something).to.eql(somethingElse);
      wrapper.vm.changeData();
      Vue.nextTick(() => {
        expect(wrapper.vm.something2).to.eql(somethingElse2);
        done();
      });
      done();
    });
  });
});
</code>```

I also tried using then() and catch(), but karma still thinks my failing tests are passing.

Should I only have one done() call? I'm not really sure what this callback is doing.

答:
As indicated here, there is an even better solution, which prevents Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.:

```<code>it('should do something', (done) => {
  const wrapper = mount(MyComponent, { store });
  wrapper.vm.changeData();
  Vue.nextTick(() => {
    expect(wrapper.vm.something).to.eql(somethingElse);
    wrapper.vm.changeData();
    Vue.nextTick().then(() => {
      expect(wrapper.vm.something2).to.eql(somethingElse2);
    }).then(done, done);
  });
});
</code>```

I'd like to also use the async/await version, but I wasn't able to get it to work.

Title: How to nest Vue.nextTick when testing?

Body:
I'm trying to test what happens in my app on two consecutive ticks. This is what I have so far (the tests fail in the karma devtools, but fail in the command line):

import { mount } from 'avoriaz';
import MyComponent from './MyComponent';

describe('testing', function() {
  it('should do something', (done) => {
    const wrapper = mount(MyComponent, { store });
    wrapper.vm.changeData();
    Vue.nextTick(() => {
      expect(wrapper.vm.something).to.eql(somethingElse);
      wrapper.vm.changeData();
      Vue.nextTick(() => {
        expect(wrapper.vm.something2).to.eql(somethingElse2);
        done();
      });
      done();
    });
  });
});

I also tried using then() and catch(), but karma still thinks my failing tests are passing.

Should I only have one done() call? I'm not really sure what this callback is doing.

Body:
As indicated here, there is an even better solution, which prevents Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.:

it('should do something', (done) => {
  const wrapper = mount(MyComponent, { store });
  wrapper.vm.changeData();
  Vue.nextTick(() => {
    expect(wrapper.vm.something).to.eql(somethingElse);
    wrapper.vm.changeData();
    Vue.nextTick().then(() => {
      expect(wrapper.vm.something2).to.eql(somethingElse2);
    }).then(done, done);
  });
});

I'd like to also use the async/await version, but I wasn't able to get it to work.


问:
Is it possible to interact with hidden elements with capybara?
I have a file field that has opacity: 0 and is overlaping a fake button. Its a common css technic to fake a sort of "Upload button" that displays consistently across different browsers.

Capybara doesn't allows me to call attach_file on that input. The error is Selenium::WebDriver::Error::ElementNotVisibleError: Element is not currently visible and so may not be interacted with.

Anybody knows any way to force capybara to interact with invisible elements?

The answer is still unanswered, but I've found a work around. Nothing intelligent, just make visible the element with a simple script

```<code>  page.execute_script %Q{
    $('#photos').css({opacity: 1, transform: 'none'});
  }
</code>```

I post it for the record.

答:
In general interacting with non-visible elements should not be possible when using Capybara (you can find them using the visible: false/hidden option in most finders but not actually do anything to them).  However, the file input is a special case because of how common it is to hide the element and, due to security restrictions, no other way to actually add a file by interacting with the pages visible elements.  Because of this attach_file has a make_visible option which can be used to have Capybara make the element visible, attach the file, and then reset the CSS to the original setting.

```<code>attach_file('photos', file_path, make_visible: true)
</code>```

Body:
I have a file field that has opacity: 0 and is overlaping a fake button. Its a common css technic to fake a sort of "Upload button" that displays consistently across different browsers.

Capybara doesn't allows me to call attach_file on that input. The error is Selenium::WebDriver::Error::ElementNotVisibleError: Element is not currently visible and so may not be interacted with.

Anybody knows any way to force capybara to interact with invisible elements?

The answer is still unanswered, but I've found a work around. Nothing intelligent, just make visible the element with a simple script

  page.execute_script %Q{
    $('#photos').css({opacity: 1, transform: 'none'});
  }

I post it for the record.

Body:
In general interacting with non-visible elements should not be possible when using Capybara (you can find them using the visible: false/hidden option in most finders but not actually do anything to them).  However, the file input is a special case because of how common it is to hide the element and, due to security restrictions, no other way to actually add a file by interacting with the pages visible elements.  Because of this attach_file has a make_visible option which can be used to have Capybara make the element visible, attach the file, and then reset the CSS to the original setting.

attach_file('photos', file_path, make_visible: true)


问:
TypeError: fit() got an unexpected keyword argument 'monitor' in mxnet python
When I run the example/image-classification/train_mnist.py, I was told that TypeError: fit() got an unexpected keyword argument 'monitor'. I have change nothing in this file. And I have just download the latest version from the github.

```<code>example\image-classification>python train_mnist.py
INFO:root:start with arguments Namespace(batch_size=64, disp_batches=100, gpus=N
one, kv_store='device', load_epoch=None, lr=0.05, lr_factor=0.1, lr_step_epochs=
'10', model_prefix=None, mom=0.9, monitor=0, network='mlp', num_classes=10, num_
epochs=20, num_examples=60000, num_layers=None, optimizer='sgd', test_io=0, top_
k=0, wd=0.0001)
Traceback (most recent call last):
  File "train_mnist.py", line 76, in <module>
    fit.fit(args, sym, get_mnist_iter)
  File "D:\Zhenxingjian\MxNet\mxnet-0.9.3\mxnet-0.9.3\example\image-classificati
on\common\fit.py", line 183, in fit
    monitor            = monitor)
TypeError: fit() got an unexpected keyword argument 'monitor'
</code>```

答: I was able to successfully run train_mnist.py example on v09.3, v0.9.5 and v0.10.0. If the problem still persists for you, maybe checkout the latest version and try again. </p>

Body:
When I run the example/image-classification/train_mnist.py, I was told that TypeError: fit() got an unexpected keyword argument 'monitor'. I have change nothing in this file. And I have just download the latest version from the github.

example\image-classification>python train_mnist.py
INFO:root:start with arguments Namespace(batch_size=64, disp_batches=100, gpus=N
one, kv_store='device', load_epoch=None, lr=0.05, lr_factor=0.1, lr_step_epochs=
'10', model_prefix=None, mom=0.9, monitor=0, network='mlp', num_classes=10, num_
epochs=20, num_examples=60000, num_layers=None, optimizer='sgd', test_io=0, top_
k=0, wd=0.0001)
Traceback (most recent call last):
  File "train_mnist.py", line 76, in <module>
    fit.fit(args, sym, get_mnist_iter)
  File "D:\Zhenxingjian\MxNet\mxnet-0.9.3\mxnet-0.9.3\example\image-classificati
on\common\fit.py", line 183, in fit
    monitor            = monitor)
TypeError: fit() got an unexpected keyword argument 'monitor'


问:
Entry Point in Spring
I am working on a codebase which uses Spring dependency injection framework. I was checking the spring but I am unable to find how Spring XML files gets executed as the first thing in code. Who defines this entry point? Like in code, I know main() method is the starting point. </p>

答:
The Application Context is Spring's advanced container.

spring it's container . entry point it's ApplicationContext .
The ApplicationContext includes all functionality of the BeanFactory, It is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications.

**The most commonly used ApplicationContext implementations are : **

FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH.

You can run container with your xml config :

```<code> public static void main(String[] args) {
      ApplicationContext context = new FileSystemXmlApplicationContext
         ("FILE PATH TO application-context.xml");
      --application-context.xml - is your cofing file
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }

 public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext
         ("classthat:/application-context.xml");
      --application-context.xml - is your cofing file
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }
</code>```

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. eagerly means that all beans that were not marked as lazy will be created as spring container started.

Title: Entry Point in Spring

Body:
The Application Context is Spring's advanced container.

spring it's container . entry point it's ApplicationContext .
The ApplicationContext includes all functionality of the BeanFactory, It is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications.

**The most commonly used ApplicationContext implementations are : **

FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look like bean configuration XML file in CLASSPATH.

You can run container with your xml config :

 public static void main(String[] args) {
      ApplicationContext context = new FileSystemXmlApplicationContext
         ("FILE PATH TO application-context.xml");
      --application-context.xml - is your cofing file
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }

 public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext
         ("classthat:/application-context.xml");
      --application-context.xml - is your cofing file
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
   }

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. eagerly means that all beans that were not marked as lazy will be created as spring container started.


问:
Get types implementing interface in ASP.NET Core web application
I am trying to port some of my plain ASP.NET (MVC) code to the ASP.NET Core web application. My code looked like this:

```<code>    System.Web.Compilation.BuildManager.GetReferencedAssemblies()
       .Cast<System.Reflection.Assembly>()
       .SelectMany(
           a => a.GetTypes()).Where(type => typeof(IGoogleSitemap).IsAssignableFrom(type)
        )
        .ToList();
</code>```

But I am not getting that to work on ASP.NET Core (1.1). For one thing Assembly does not have GetReferencedAssemblies() only GetEntryAssembly(). And GetEntryAssembly().GetReferencedAssemblies() gives me a list of AssemblyName instead of Assembly objects.

Basically I am looking for all controllers implementing the IGoogleSitemap interface (defined in a separate assembly).

答:
As I mentioned, .NET Core being so streamlined causes some things to be more complicated. I got it to work by changing the code to this (.NET Core 1.1)

```<code>IEnumerable<System.Reflection.TypeInfo> all =
        Assembly.GetEntryAssembly().DefinedTypes.Where(type =>
              typeof(FullNamespace.IGoogleSitemap).IsAssignableFrom(type.AsType()));
 foreach (TypeInfo ti in all)
 {
     Type t = ti.AsType();
     // of all candidates filter out the actual interface definition
     if (!t.Equals(typeof(IGoogleSitemap)))
     {
            // do work here
     }
 }
</code>```

Well, that does it for the Entry Assembly at least, still have not figured out how to do it for all referenced assemblies because GetReferencedAssemblies() returns AssemblyName rather than Assembly.

Body:
I am trying to port some of my plain ASP.NET (MVC) code to the ASP.NET Core web application. My code looked like this:

    System.Web.Compilation.BuildManager.GetReferencedAssemblies()
       .Cast<System.Reflection.Assembly>()
       .SelectMany(
           a => a.GetTypes()).Where(type => typeof(IGoogleSitemap).IsAssignableFrom(type)
        )
        .ToList();

But I am not getting that to work on ASP.NET Core (1.1). For one thing Assembly does not have GetReferencedAssemblies() only GetEntryAssembly(). And GetEntryAssembly().GetReferencedAssemblies() gives me a list of AssemblyName instead of Assembly objects.

Basically I am looking for all controllers implementing the IGoogleSitemap interface (defined in a separate assembly).

Body:
As I mentioned, .NET Core being so streamlined causes some things to be more complicated. I got it to work by changing the code to this (.NET Core 1.1)

IEnumerable<System.Reflection.TypeInfo> all =
        Assembly.GetEntryAssembly().DefinedTypes.Where(type =>
              typeof(FullNamespace.IGoogleSitemap).IsAssignableFrom(type.AsType()));
 foreach (TypeInfo ti in all)
 {
     Type t = ti.AsType();
     // of all candidates filter out the actual interface definition
     if (!t.Equals(typeof(IGoogleSitemap)))
     {
            // do work here
     }
 }

Well, that does it for the Entry Assembly at least, still have not figured out how to do it for all referenced assemblies because GetReferencedAssemblies() returns AssemblyName rather than Assembly.


问:
How to make AssistoLab/DropDown datasource dynamic?
dropDown.dataSource = ["Car", "Motorcycle", "Truck"] //static

//Array which needs to be passed inside drop down datasource.

public var pMaster = ProductMaster

//how to pass dynamic array for datasource.

selectProduct.dataSource = ["Select product type","Industrial Lubricant","Automotive Lubricant","GREASES"]  //static

selectProduct.dataSource = pMaster         // error cannot assign [ProductMaster] to type [String]

答: As the error states, you have to assign array of String ([String]) to the datasource, not your custom object ([ProductMaster]).


问:
Newbe need to be Pointed in the right direction
hi again
have bent my head on getting this to work for 3 days now.
The serviceBinder is always NULL when i select picture in Share menu.
I debug this with LogCat, stepping the code.. and see no obvious error. Also the bindService return false. I have a service class but think the hickup is here somewhere.
Please point me in the right direction!

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

public class ServicesDemo extends Activity {

 private MyService serviceBinder = null;
 private static final String TAG = "ServicesDemo";
 boolean mIsBound;
 ServiceConnection mConnection = null;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  startService(new Intent(this, MyService.class));

  Intent intent = getIntent();
  Bundle extras = intent.getExtras();
  final String mimeType = intent.getType();
  String action = intent.getAction();

   mConnection = new ServiceConnection() {

  public void onServiceConnected(ComponentName className, IBinder service) {
   serviceBinder = ((MyService.MyBinder) service).getService();
   }
   public void onServiceDisconnected(ComponentName className) {
    serviceBinder = null;
   }
  };

  Intent bindIntent = new Intent(ServicesDemo.this, MyService.class);
  bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
  mIsBound = true;

  if (Intent.ACTION_SEND.equals(action)) {
   if (extras.containsKey(Intent.EXTRA_STREAM)) {
    Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
    try {
     if(serviceBinder != null)
     // here i call my service to do stuff with the
                                        //picture i got from "share" menu
     serviceBinder.addAttachment(mimeType, uri, false);
    } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    return;
   } else if (extras.containsKey(Intent.EXTRA_TEXT)) {

     return;
   }
  }
 }
 void doUnbindService() {
  if (mIsBound) {
   // Detach our existing connection.
   unbindService(mConnection);
   mIsBound = false;
  }
 }

 protected void onDestroy() {
  super.onDestroy();
  doUnbindService();
 }
}
</code>```

package com.example.ptpp;

public class MyService extends Service {

```<code>private static final String TAG = "MyService";

private final IBinder binder = new MyBinder();
private ServicesDemo callingActivity = null;

public void setActivity(ServicesDemo i) {
    callingActivity = i;
}
public IBinder onBind(Intent intent) {
    return binder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

public void onCreate() {

}

public void onDestroy() {

}

public void onStart(Intent intent, int startid) {

}
public int onStartCommand(Intent intent, int flags, int startId)
{
    return START_STICKY;
}

public void addAttachment(String mimeType, Uri uri, boolean b) throws UnknownHostException, IOException {

}
</code>```

}

答:
A problem is right here:

```<code>bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
  mIsBound = true;
</code>```

Binding to a service is asynchronous. You're not guaranteed to be bound after the call to bindService() returns.

Body:
hi again
have bent my head on getting this to work for 3 days now.
The serviceBinder is always NULL when i select picture in Share menu.
I debug this with LogCat, stepping the code.. and see no obvious error. Also the bindService return false. I have a service class but think the hickup is here somewhere.
Please point me in the right direction!

package com.example.ptpp;

public class ServicesDemo extends Activity {

 private MyService serviceBinder = null;
 private static final String TAG = "ServicesDemo";
 boolean mIsBound;
 ServiceConnection mConnection = null;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  startService(new Intent(this, MyService.class));

  Intent intent = getIntent();
  Bundle extras = intent.getExtras();
  final String mimeType = intent.getType();
  String action = intent.getAction();

   mConnection = new ServiceConnection() {

  public void onServiceConnected(ComponentName className, IBinder service) {
   serviceBinder = ((MyService.MyBinder) service).getService();
   }
   public void onServiceDisconnected(ComponentName className) {
    serviceBinder = null;
   }
  };

  Intent bindIntent = new Intent(ServicesDemo.this, MyService.class);
  bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
  mIsBound = true;

  if (Intent.ACTION_SEND.equals(action)) {
   if (extras.containsKey(Intent.EXTRA_STREAM)) {
    Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
    try {
     if(serviceBinder != null)
     // here i call my service to do stuff with the
                                        //picture i got from "share" menu
     serviceBinder.addAttachment(mimeType, uri, false);
    } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    return;
   } else if (extras.containsKey(Intent.EXTRA_TEXT)) {

     return;
   }
  }
 }
 void doUnbindService() {
  if (mIsBound) {
   // Detach our existing connection.
   unbindService(mConnection);
   mIsBound = false;
  }
 }

 protected void onDestroy() {
  super.onDestroy();
  doUnbindService();
 }
}

package com.example.ptpp;

public class MyService extends Service {

private static final String TAG = "MyService";

private final IBinder binder = new MyBinder();
private ServicesDemo callingActivity = null;

public void setActivity(ServicesDemo i) {
    callingActivity = i;
}
public IBinder onBind(Intent intent) {
    return binder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

public void onCreate() {

}

public void onDestroy() {

}

public void onStart(Intent intent, int startid) {

}
public int onStartCommand(Intent intent, int flags, int startId)
{
    return START_STICKY;
}

public void addAttachment(String mimeType, Uri uri, boolean b) throws UnknownHostException, IOException {

}

}

Body:
A problem is right here:

bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
  mIsBound = true;

Binding to a service is asynchronous. You're not guaranteed to be bound after the call to bindService() returns.


问:
How to revert theme from Darcula to default in Android Studio
I have changed my Android Studio theme from Default to Darcula.

But when I want to search anything then I need to go to browser which is very bright.

Now I want to revert the theme from Darcula to default theme in Android Studio. When I do that, it just changes background color and font color of Editor window. I want to change the whole window to be default instead of black.

Edited

I have changed theme from Android Studio | Preferences | Editor | Colors & Fonts.

Check out this link for more detail about how to change theme in Android Studio.

答:
Go to File -> Settings -> Appearance under IDE section ->change theme to intelij or default or windows.

see here for more.


问:
Use php require for local directory
I have recently been trying to add PHPMailer script to my site, following the accepted answer from here:

Send attachments with PHP Mail()?

I have never used a require statment before so I assume I must be doing it wrong, currently testing on my local host version of the site. I have downloaded the entire zip of git (unzipped it) and moved it to the dir my scripts are in.

In my script I added the following line:

```<code>require_once(__DIR__.'/PHPMailer-master/class.phpmailer.php');
</code>```

Which to my understanding was all I needed to do to use it. However I get this error:

Warning:
  require_once(C:\xampp\htdocs\Website\PHPMailer-master\class.phpmailer.php):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\Website\include\mailer.php on line 10

Fatal error: require_once(): Failed opening required
  'C:\xampp\htdocs\Website\PHPMailer-master\class.phpmailer.php'
  (include_path='C:\xampp\php\PEAR') in
  C:\xampp\htdocs\Website\include\mailer.php on line 10

Any ideas what is causing this error? Am running PHP 5.6.21 if this is relevant.

答: Try to use the full path to the file, using realpath() - http://php.net/realpath, and use dirname(__FILE__) to get your current directory:

Title: Use php require for local directory

Body:
I have recently been trying to add PHPMailer script to my site, following the accepted answer from here:

Send attachments with PHP Mail()?

I have never used a require statment before so I assume I must be doing it wrong, currently testing on my local host version of the site. I have downloaded the entire zip of git (unzipped it) and moved it to the dir my scripts are in.

In my script I added the following line:

require_once(__DIR__.'/PHPMailer-master/class.phpmailer.php');

Which to my understanding was all I needed to do to use it. However I get this error:

Warning:
  require_once(C:\xampp\htdocs\Website\PHPMailer-master\class.phpmailer.php):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\Website\include\mailer.php on line 10

Fatal error: require_once(): Failed opening required
  'C:\xampp\htdocs\Website\PHPMailer-master\class.phpmailer.php'
  (include_path='C:\xampp\php\PEAR') in
  C:\xampp\htdocs\Website\include\mailer.php on line 10

Any ideas what is causing this error? Am running PHP 5.6.21 if this is relevant.


问:
Web app feels less responsive when added to iPhone's home screen
This Angular 2 app feels less responsive when added to the Home Screen on the iPhone that when running inside Safari.

I made it web app capable by adding this to index.html:

```<code><meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Angular NavTabs">
</code>```

If you have a couple of minutes, check it out on Github Pages.

Switching between tabs feel very responsive when it runs in Safari. However, it feels lagging when the app is launched from the Home Screen.

Is there something that I could change in or add to the code to fix this behavior?

Note: The same thing happens if I remove the animations from the app.

I recorded a couple of animated GIFs to try to show the difference but it's difficult to appreciate unless you're actually interacting with the app.

答:
You're experiencing the infamous "300ms seconds delay", which was fixed for quite some time in Safari Mobile, but still here once your app is added to the home screen.

Using the FastClick library should solve the problem.

To use it in an Angular application, install the npm package:

npm install --save fastclick

Then add this to your main.ts file:

```<code>import * as fastClick from 'fastclick';
fastClick.attach(document.body);
</code>```

Edit:

With iOS 11, web-apps added to the home sreen will now be hosted in a WKWebView instead of UIWebView, which will make use of FastClick obsolete: https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Safari_11_0/Safari_11_0.html

Hope it helps.

Body:
This Angular 2 app feels less responsive when added to the Home Screen on the iPhone that when running inside Safari.

I made it web app capable by adding this to index.html:

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Angular NavTabs">

If you have a couple of minutes, check it out on Github Pages.

Switching between tabs feel very responsive when it runs in Safari. However, it feels lagging when the app is launched from the Home Screen.

Is there something that I could change in or add to the code to fix this behavior?

Note: The same thing happens if I remove the animations from the app.

I recorded a couple of animated GIFs to try to show the difference but it's difficult to appreciate unless you're actually interacting with the app.

Body:
You're experiencing the infamous "300ms seconds delay", which was fixed for quite some time in Safari Mobile, but still here once your app is added to the home screen.

Using the FastClick library should solve the problem.

To use it in an Angular application, install the npm package:

npm install --save fastclick

Then add this to your main.ts file:

import * as fastClick from 'fastclick';
fastClick.attach(document.body);

Edit:

With iOS 11, web-apps added to the home sreen will now be hosted in a WKWebView instead of UIWebView, which will make use of FastClick obsolete: https://developer.apple.com/library/content/releasenotes/General/WhatsNewInSafari/Safari_11_0/Safari_11_0.html

Hope it helps.


问:
Populating a FormView with custom queryset
I'd like to set the logged in user's data to a profile form. Why isn't the below view populating the model form?

```<code>class UpdateProfile(FormView):
    model = User
    form_class = ProfileForm

    def get_queryset(self):
        return self.model.objects.get(pk=self.request.user.id)

class ProfileForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['email', 'name', 'company', 'title']
</code>```

All my fields end up empty.

答:
For single object views, you need to override get_object and use an UpdateView.

So to get the logged in user you could do:

```<code>from django.views.generic import UpdateView

class UpdateProfile(UpdateView):
    model = User
    form_class = ProfileForm

    def get_object(self):
        return self.request.user
</code>```

Body:
I'd like to set the logged in user's data to a profile form. Why isn't the below view populating the model form?

class UpdateProfile(FormView):
    model = User
    form_class = ProfileForm

    def get_queryset(self):
        return self.model.objects.get(pk=self.request.user.id)

class ProfileForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['email', 'name', 'company', 'title']

All my fields end up empty.

Body:
For single object views, you need to override get_object and use an UpdateView.

So to get the logged in user you could do:

from django.views.generic import UpdateView

class UpdateProfile(UpdateView):
    model = User
    form_class = ProfileForm

    def get_object(self):
        return self.request.user


问:
HQL wildcard with Hibernate UserType
I have created Hibernate UserType for my PhoneNumber class backed by single VARCHAR column in db. Generally it works fine. But now I need something like this

```<code>String hql = "FROM Call c WHERE c.calledNumber LIKE :param";
...
query.setParameter("param", "%385%");
</code>```

which ends with

```<code>java.lang.IllegalArgumentException: Parameter value [%385%] did not match expected type [PhoneNumber]
</code>```

How can I do that?

答:
c.calledNumber is a PhoneNumber object and you're trying to compare it with a string '%385%'. What's happening is like comparing a table to a column.

What you should do write is this:

String QUERY = "FROM Call c join c.calledNumber pn WHERE pn.number LIKE :myNumber";

where pn.number field is a java string.

Title: HQL wildcard with Hibernate UserType

Body:
I have created Hibernate UserType for my PhoneNumber class backed by single VARCHAR column in db. Generally it works fine. But now I need something like this

String hql = "FROM Call c WHERE c.calledNumber LIKE :param";
...
query.setParameter("param", "%385%");

which ends with

java.lang.IllegalArgumentException: Parameter value [%385%] did not match expected type [PhoneNumber]

How can I do that?


问:
Should I use TitanDB?
I am thinking of using TitanDB. It seems to really fit our needs (we have full control over the storage engine and we can build it on top of DynamoDB). However I am worried about the fact that the project is not maintained anymore and a fork was created, JanusGraph, to continue the project. Is it still safe to use TitanDB? Should I use JanusGraph instead (Is it ready for production and can it be deployed on AWS using DynamoDB)?</p>

答:
Unless you plan on maintaining it by yourself, no, you should not use TitanDB. Titan has not seen updates in almost 2 years. It is far out of date on its core dependencies.

You should use JanusGraph. It was established as a project at the Linux Foundation in January 2017, and 2 releases have already been made. Many individuals and companies are involved in the open community.

If you check out the AWS Labs DynamoDB Titan Storage adapter, you'll see that Alex Patrikalakis has already integrated JanusGraph 0.1.1 on the master branch. Alex is also a committer on JanusGraph.

Title: Should I use TitanDB?


问:
Populate tableview in javafx
I want to populate a TableView in JavaFX. My class is Manual and it has another object like attribute (User). How can I populate a table column with the username from the User object.

```<code>columnVanzator.setCellFactory(new Callback<TableColumn<Manual, User>,
                                                        TableCell<Manual, User>>() {

   @Override
   public TableCell<Manual, User> call(TableColumn<Manual, User> arg0) {
        final TableCell<Manual, User> cell = new TableCell<Manual, User>() {
             @Override
             public void updateItem(final User item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        this.setText("");
                    }
                    else {
                          this.setText(item.getUsername());
                    }
             }
         };
         return cell;
    }
});
</code>```

I received NullPointerException on this.setText(item.getUsername());

答:
What you're looking for is not a cellFactory, but a cellValueFactory.
A custom cellFactory is used if you the type which is displayed in your Column is more complex than a String or a Number (e.g. a Date, State or even more complex types).

JavaFX' cellValueFactory works best with Properties:

```<code>column.setCellValueFactory((p) -> p.getValue().yourContentProperty());
</code>```

But it looks like you don't have a JavaFX Property for that in your Object, so we have to build a little workaround:

```<code>column.setCellValueFactory((p) -> new SimpleStringProperty(p.getValue().getUsername());
</code>```

I would recommend to build your Model in JavaFX-Style and have Properties inside it. If a value changes inside a Property, the TableView will update the Cell automatically. Same goes for almost every control in JavaFX. But if you don't can or simply don't want to, feel free to use the way above, but keep in mind that value changes won't automatically notify the view!

Title: Populate tableview in javafx

Body:
I want to populate a TableView in JavaFX. My class is Manual and it has another object like attribute (User). How can I populate a table column with the username from the User object.

columnVanzator.setCellFactory(new Callback<TableColumn<Manual, User>,
                                                        TableCell<Manual, User>>() {

   @Override
   public TableCell<Manual, User> call(TableColumn<Manual, User> arg0) {
        final TableCell<Manual, User> cell = new TableCell<Manual, User>() {
             @Override
             public void updateItem(final User item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        this.setText("");
                    }
                    else {
                          this.setText(item.getUsername());
                    }
             }
         };
         return cell;
    }
});

I received NullPointerException on this.setText(item.getUsername());

Body:
What you're looking for is not a cellFactory, but a cellValueFactory.
A custom cellFactory is used if you the type which is displayed in your Column is more complex than a String or a Number (e.g. a Date, State or even more complex types).

JavaFX' cellValueFactory works best with Properties:

column.setCellValueFactory((p) -> p.getValue().yourContentProperty());

But it looks like you don't have a JavaFX Property for that in your Object, so we have to build a little workaround:

column.setCellValueFactory((p) -> new SimpleStringProperty(p.getValue().getUsername());

I would recommend to build your Model in JavaFX-Style and have Properties inside it. If a value changes inside a Property, the TableView will update the Cell automatically. Same goes for almost every control in JavaFX. But if you don't can or simply don't want to, feel free to use the way above, but keep in mind that value changes won't automatically notify the view!