问:
Registering partially-closed generic type with ASP.NET Core Microsoft.Extensions.DependencyInjection
In an ASP.NET Core 1.1.2 web project, which depends on Microsoft.Extensions.DependencyInjection 1.1.1, I'm trying to register a generic FluentValidation validator both with its implementation and with its interface. At runtime, during host building, I got following exception:

```<code>An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.Extensions.DependencyInjection.dll

Cannot instantiate implementation type 'MyProj.Shared.Api.WithUserCommandValidator`1[T]' for service type 'FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[T]]'.

   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceTable..ctor(IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, Boolean validateScopes)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at MyProj.Program.Main(String[] args) in X:\MySolution\src\MyProj\Program.cs:line 31
</code>```

This is the (generic, non-abstract) validator class:

public class WithUserCommandValidator<TCommand> : AbstractValidator<WithUser<TCommand>>
    where TCommand : ICommand
{
    public WithUserCommandValidator(IValidator<TCommand> commandValidator)
    {
        RuleFor(cmd => cmd).NotNull();

        RuleFor(cmd => cmd.UserId).NotEqual(Guid.Empty);

        RuleFor(cmd => cmd.Content).NotNull()
            .SetValidator(commandValidator);
    }
}
```

<p>(not sure is important to show <code>WithUser<T></code> class, it just holds a <code>Guid UserId</code> and a <code>T Content</code>).</p>

<p>Registration happens like so:</p>

<pre class="lang-cs prettyprint-override"><code>someInterface = typeof(FluentValidation.IValidator<WithUser<>>);
someImplementation = typeof(Shared.Api.WithUserCommandValidator<>);

// this is for top-level command validators, injected by interface
services.AddScoped(someInterface, someImplementation);

// this is for nested validators, injected by implementation
services.AddScoped(someImplementation);
</code>```

and at runtime those variables hold:

```<code>+ someInterface  {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]}  System.Type {System.RuntimeType}
+ someImplementation  {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]}  System.Type {System.RuntimeType}
</code>```

which seems correct.

I've looked around for similar problems and questions on SO as well, but they're not really related, as they were about generic implementation, while this is a concrete one.

I've stepped through DependencyInjection module code, and exception is thrown here. For some reason, serviceTypeInfo.IsGenericTypeDefinition returns false (shouldn't that be true, as the interface type is generic?) and so the else-branch is taken. There, instead, the implementation type return true to implementationTypeInfo.IsGenericTypeDefinition, so there you have the exception.

Runtime values are:

```<code>+ serviceTypeInfo {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]} System.Reflection.TypeInfo {System.RuntimeType}
+ implementationTypeInfo {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]}   System.Reflection.TypeInfo {System.RuntimeType}
</code>```

While fiddling, I tried registering only the implementation, without also registering interface+implementation, and that exception goes away. But I'd like to inject the interface, if possible, not the implementation.

What am I doing wrong? TA

答:
What you are trying to do is to map a partially closed type (namely IValidator<WithUser<T>>), which is something that is not supported by .NET Core's DI container. When it comes to generic types, the .NET Core container is a very minimalistic, simplistic implementation. It is unable to handle things like:

generic type constraints

partially closed types

implementations with less generic type arguments than the abstraction

implementations with generic type arguments in a different order than the abstraction

having generic type arguments being nested as part of a type argument of the partially closed abstraction (which is your exact case)

Curiously recurring template pattern

If you require this behavior and want to keep continuing to use the built-in container for this, you will have to register each closed implementation by hand:

```<code>AddScoped(typeof(IValidator<WithUser<Cmd1>>),typeof(WithUserCommandValidator<Cmd1>));
AddScoped(typeof(IValidator<WithUser<Cmd2>>),typeof(WithUserCommandValidator<Cmd2>));
AddScoped(typeof(IValidator<WithUser<Cmd3>>),typeof(WithUserCommandValidator<Cmd3>));
// etc
</code>```

If this is leads to an unmaintainable Composition Root, you should pick a different container. The only DI Container that I know actually fully supports these kinds of generic designs is Simple Injector.

With Simple Injector, you can simply do the following registration:

```<code>container.Register(
    typeof(IValidator<>),
    typeof(WithUserCommandValidator<>),
    Lifestyle.Scoped);
</code>```

Body:
In an ASP.NET Core 1.1.2 web project, which depends on Microsoft.Extensions.DependencyInjection 1.1.1, I'm trying to register a generic FluentValidation validator both with its implementation and with its interface. At runtime, during host building, I got following exception:

An unhandled exception of type 'System.ArgumentException' occurred in Microsoft.Extensions.DependencyInjection.dll

Cannot instantiate implementation type 'MyProj.Shared.Api.WithUserCommandValidator`1[T]' for service type 'FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[T]]'.

   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceTable..ctor(IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, Boolean validateScopes)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at MyProj.Program.Main(String[] args) in X:\MySolution\src\MyProj\Program.cs:line 31

This is the (generic, non-abstract) validator class:

public class WithUserCommandValidator<TCommand> : AbstractValidator<WithUser<TCommand>>
    where TCommand : ICommand
{
    public WithUserCommandValidator(IValidator<TCommand> commandValidator)
    {
        RuleFor(cmd => cmd).NotNull();

        RuleFor(cmd => cmd.UserId).NotEqual(Guid.Empty);

        RuleFor(cmd => cmd.Content).NotNull()
            .SetValidator(commandValidator);
    }
}

(not sure is important to show WithUser<T> class, it just holds a Guid UserId and a T Content).

Registration happens like so:

someInterface = typeof(FluentValidation.IValidator<WithUser<>>);
someImplementation = typeof(Shared.Api.WithUserCommandValidator<>);

// this is for top-level command validators, injected by interface
services.AddScoped(someInterface, someImplementation);

// this is for nested validators, injected by implementation
services.AddScoped(someImplementation);

and at runtime those variables hold:

+ someInterface  {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]}  System.Type {System.RuntimeType}
+ someImplementation  {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]}  System.Type {System.RuntimeType}

which seems correct.

I've looked around for similar problems and questions on SO as well, but they're not really related, as they were about generic implementation, while this is a concrete one.

I've stepped through DependencyInjection module code, and exception is thrown here. For some reason, serviceTypeInfo.IsGenericTypeDefinition returns false (shouldn't that be true, as the interface type is generic?) and so the else-branch is taken. There, instead, the implementation type return true to implementationTypeInfo.IsGenericTypeDefinition, so there you have the exception.

Runtime values are:

+ serviceTypeInfo {FluentValidation.IValidator`1[MyProj.Shared.Model.WithUser`1[TCommand]]} System.Reflection.TypeInfo {System.RuntimeType}
+ implementationTypeInfo {MyProj.Shared.Api.WithUserCommandValidator`1[TCommand]}   System.Reflection.TypeInfo {System.RuntimeType}

While fiddling, I tried registering only the implementation, without also registering interface+implementation, and that exception goes away. But I'd like to inject the interface, if possible, not the implementation.

What am I doing wrong? TA

Body:
What you are trying to do is to map a partially closed type (namely IValidator<WithUser<T>>), which is something that is not supported by .NET Core's DI container. When it comes to generic types, the .NET Core container is a very minimalistic, simplistic implementation. It is unable to handle things like:

generic type constraints

partially closed types

implementations with less generic type arguments than the abstraction

implementations with generic type arguments in a different order than the abstraction

having generic type arguments being nested as part of a type argument of the partially closed abstraction (which is your exact case)

Curiously recurring template pattern

If you require this behavior and want to keep continuing to use the built-in container for this, you will have to register each closed implementation by hand:

AddScoped(typeof(IValidator<WithUser<Cmd1>>),typeof(WithUserCommandValidator<Cmd1>));
AddScoped(typeof(IValidator<WithUser<Cmd2>>),typeof(WithUserCommandValidator<Cmd2>));
AddScoped(typeof(IValidator<WithUser<Cmd3>>),typeof(WithUserCommandValidator<Cmd3>));
// etc

If this is leads to an unmaintainable Composition Root, you should pick a different container. The only DI Container that I know actually fully supports these kinds of generic designs is Simple Injector.

With Simple Injector, you can simply do the following registration:

container.Register(
    typeof(IValidator<>),
    typeof(WithUserCommandValidator<>),
    Lifestyle.Scoped);


来源: stackexchange

问:
WebDriver Portable Firefox c#
I tried to load Portable Firefox

```<code>FirefoxProfile profile = new FirefoxProfile();
var binary = new FirefoxBinary(Directory.GetCurrentDirectory()+ @"\FirefoxPortable64\FirefoxPortable.exe");

var driver = new FirefoxDriver(binary, profile);
</code>```

But i get error Unable to find a matching set of capabilities in line var driver = new FirefoxDriver(binary, profile);

can u help me pls ?

And in line var driver = new FirefoxDriver(binary, profile); i have warning:

FirefoxDriver should not be constructed with a FirefoxBinary object. Use FirefoxOptions instead. This constructor will be removed in a future release.

how i can rewrite the code ?

UPD:
I rewrite code:

```<code>FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = Directory.GetCurrentDirectory() + @"\FirefoxPortable64\FirefoxPortable.exe";
var driver = new FirefoxDriver( options);
</code>```

But it doesnt work, again have error Unable to find a matching set of capabilities

答:
Solution ;</p>

```<code> options.BrowserExecutableLocation = Directory.GetCurrentDirectory() + @"\FirefoxPortable32\App\Firefox\firefox.exe";
</code>```

ContentLicense: CC BY-SA 3.0

Title: WebDriver Portable Firefox c#

Body:
I tried to load Portable Firefox

FirefoxProfile profile = new FirefoxProfile();
var binary = new FirefoxBinary(Directory.GetCurrentDirectory()+ @"\FirefoxPortable64\FirefoxPortable.exe");

var driver = new FirefoxDriver(binary, profile);

But i get error Unable to find a matching set of capabilities in line var driver = new FirefoxDriver(binary, profile);

can u help me pls ?

And in line var driver = new FirefoxDriver(binary, profile); i have warning:

FirefoxDriver should not be constructed with a FirefoxBinary object. Use FirefoxOptions instead. This constructor will be removed in a future release.

how i can rewrite the code ?

UPD:
I rewrite code:

FirefoxProfile profile = new FirefoxProfile();
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
options.BrowserExecutableLocation = Directory.GetCurrentDirectory() + @"\FirefoxPortable64\FirefoxPortable.exe";
var driver = new FirefoxDriver( options);

But it doesnt work, again have error Unable to find a matching set of capabilities

Body:
Solution ;

 options.BrowserExecutableLocation = Directory.GetCurrentDirectory() + @"\FirefoxPortable32\App\Firefox\firefox.exe";


问:
Laravel Composer require issue with Mac Sierra
I'm trying to include Laravel 5 Facade for Goutte in my application. However I am getting the following error:

```<code> Problem 1
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- Installation request for namshi/jose (locked at 5.0.2) -> satisfiable by namshi/jose[5.0.2].
</code>```

I have searched online and it suggests installing a new version of PHP and try using that instead however I have installed php56 via homebrew and its still not working. When i run:

```<code>which php
</code>```

it says the path is:

```<code>/usr/bin/php
</code>```

However brew installed PHP to:

```<code>/usr/local/Cellar/php56/5.6.30_6/bin
</code>```

I have updated my .bash_profile with the following line:

```<code>export PATH=$PATH:/usr/local/Cellar/php56/5.6.30_6/bin
</code>```

However even after restarting the terminal which php still returns /usr/bin/php.

答:
You can try to create a symlink for new php version this way :

```<code>sudo ln /usr/local/Cellar/php56/5.6.30_6/bin/php /usr/local/bin/php
</code>```

Then run your composer command

```<code>php composer require weidner/goutte
</code>```

or

```<code>php composer.phar require weidner/goutte
</code>```

Hope this helps !

Body:
I'm trying to include Laravel 5 Facade for Goutte in my application. However I am getting the following error:

 Problem 1
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- namshi/jose 5.0.2 requires lib-openssl * -> the requested linked library openssl has the wrong version installed or is missing from your system, make sure to have the extension providing it.
- Installation request for namshi/jose (locked at 5.0.2) -> satisfiable by namshi/jose[5.0.2].

I have searched online and it suggests installing a new version of PHP and try using that instead however I have installed php56 via homebrew and its still not working. When i run:

which php

it says the path is:

/usr/bin/php

However brew installed PHP to:

/usr/local/Cellar/php56/5.6.30_6/bin

I have updated my .bash_profile with the following line:

export PATH=$PATH:/usr/local/Cellar/php56/5.6.30_6/bin

However even after restarting the terminal which php still returns /usr/bin/php.

Body:
You can try to create a symlink for new php version this way :

sudo ln /usr/local/Cellar/php56/5.6.30_6/bin/php /usr/local/bin/php

Then run your composer command

php composer require weidner/goutte

or

php composer.phar require weidner/goutte

Hope this helps !


问:
javascript array - separate values and values of values by single quotes
I have an array that looks like this:

```<code>var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
</code>```

I want to return the results like this:

```<code>'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
</code>```

This is what I have done so far:

```<code>includes = tagsI.map(tag => `'${tag}'`).join(',')
</code>```

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you

答:
split tag by comma and use another map

var tagsI = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]

var result = tagsI.map(tag => tag.split(',').map(tag => `'${tag}'`)).join(',');

console.log(result)```

Body:
I have an array that looks like this:

var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]

I want to return the results like this:

'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'

This is what I have done so far:

includes = tagsI.map(tag => `'${tag}'`).join(',')

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you


问:
Custom JsonReader throws Current JsonReader item is not an object: String. on all objects
I'm creating a custom JsonConverter to convert a property "Type" : "A" (or "D", "E", etc) to an enum that contains Article, Disambuigation, etc. Here is the relevant code in the converter class:

```<code>public override bool CanConvert(Type objectType) => objectType == typeof(SearchResultType);

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var jsonObject = JObject.Load(reader);
    var typeProperty = jsonObject.Properties().FirstOrDefault(p => p.Name == "Type");
    switch ((string)typeProperty.Value)
    {
        case "A": return SearchResultType.Article;
        default: return SearchResultType.None;
    }
}
</code>```

My problem is that it always throws an exception with message:

Error reading JObject from JsonReader. Current JsonReader item is not an object: String.

I understand this to mean that it expected something like "Name" : "Hello world!" but got "Name" : 123. However, I know for sure that the properties it's failing to parse are strings. Is there a problem with my converter?

答:
Yes, there is a problem with your converter.  Your converter is intended to read a string value from JSON to convert it into an enum value.  A string value is not an  object in JSON, therefore you cannot load it into a JObject.  Instead, you can  just get the string value directly from the reader:

```<code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var type = (string)reader.Value;
    switch (type)
    {
        case "A": return SearchResultType.Article;
        case "D": return SearchResultType.Disambuigation;
        ...
        default: return SearchResultType.None;
    }
}
</code>```

Fiddle: https://dotnetfiddle.net/tnyZaT

Body:
I'm creating a custom JsonConverter to convert a property "Type" : "A" (or "D", "E", etc) to an enum that contains Article, Disambuigation, etc. Here is the relevant code in the converter class:

public override bool CanConvert(Type objectType) => objectType == typeof(SearchResultType);

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var jsonObject = JObject.Load(reader);
    var typeProperty = jsonObject.Properties().FirstOrDefault(p => p.Name == "Type");
    switch ((string)typeProperty.Value)
    {
        case "A": return SearchResultType.Article;
        default: return SearchResultType.None;
    }
}

My problem is that it always throws an exception with message:

Error reading JObject from JsonReader. Current JsonReader item is not an object: String.

I understand this to mean that it expected something like "Name" : "Hello world!" but got "Name" : 123. However, I know for sure that the properties it's failing to parse are strings. Is there a problem with my converter?

Body:
Yes, there is a problem with your converter.  Your converter is intended to read a string value from JSON to convert it into an enum value.  A string value is not an  object in JSON, therefore you cannot load it into a JObject.  Instead, you can  just get the string value directly from the reader:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var type = (string)reader.Value;
    switch (type)
    {
        case "A": return SearchResultType.Article;
        case "D": return SearchResultType.Disambuigation;
        ...
        default: return SearchResultType.None;
    }
}

Fiddle: https://dotnetfiddle.net/tnyZaT


答:
You'll first need to split each element in the array.</p>

```<code>var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");
</code>```

Title: javascript array - separate values and values of values by single quotes

Body:
You'll first need to split each element in the array.

var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");


问:
variable-sized object may not be initialized confusion
The below code is attempting to randomly initialize array z of  0 or 1. I receive the following error message

error: variable-sized object may
      not be initialized
int z[x]= rand()%2;

1 error generated.
isn't Z size given as 10?

```<code> int z[10];
     for(int x =0; x <=(sizeof(z) / sizeof(z[0]));x++)
     {
            srand((unsigned)time(NULL));
            int z[x]= rand()%2;
            std ::cout<<z[x];
     }
</code>```

答:
int z[x] looks like a variable definition, rather than an assignment.

Remove the int to make this:

```<code>z[x]= rand()%2;
</code>```

Additionally, you only have to seed the random number generator once using srand, so move that to before your loop

Body:
The below code is attempting to randomly initialize array z of  0 or 1. I receive the following error message

error: variable-sized object may
      not be initialized
int z[x]= rand()%2;

1 error generated.
isn't Z size given as 10?

 int z[10];
     for(int x =0; x <=(sizeof(z) / sizeof(z[0]));x++)
     {
            srand((unsigned)time(NULL));
            int z[x]= rand()%2;
            std ::cout<<z[x];
     }

Body:
int z[x] looks like a variable definition, rather than an assignment.

Remove the int to make this:

z[x]= rand()%2;

Additionally, you only have to seed the random number generator once using srand, so move that to before your loop


问:
Swift Generics: Cannot convert value of type to expected argument type
Here is my code:

```<code>protocol SomeProtocol {
}

class A: SomeProtocol {
}

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {
}

func g() {
    let l1: (SomeProtocol?) -> Void = ...
    let l2: ([SomeProtocol]?) -> Void = ...
    f1(ofType: A.self, listener: l1) // NO ERROR
    f2(ofType: A.self, listener: l2) // COMPILE ERROR: Cannot convert value of type '([SomeProtocol]?) -> Void' to expected argument type '([_]?) -> Void'
}
</code>```

What is the problem with the second closure having an argument of an array of generic type objects?

答:
The listener closure in func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {...} requires its argument to be an array of T, where T is a type that implements SomeProtocol. By writing <T: SomeProtocol>, you are enforcing that all elements of that array are of the same type.

Say for example you have two classes: A and B. Both are completely distinct. Yet both implement SomeProtocol. In this case, the input array cannot be [A(), B()] because of the type constraint. The input array can either be [A(), A()] or [B(), B()].

But, when you define l2 as let l2: ([SomeProtocol]?) -> Void = ..., you allow the closure to accept an argument such as [A(), B()]. Hence this closure, and the closure you define in f2 are incompatible and the compiler cannot convert between the two.

Unfortunately, you cannot add type enforcement to a variable such as l2 as stated here. What you can do is if you know that l2 is going to work on arrays of class A, you could redefine it as follows:

```<code>let l2: ([A]?) -> Void = { ... }
</code>```

Let me try and explain this with a simpler example. Let's say you write a generic function to find the greatest element in an array of comparables:

```<code>func greatest<T: Comparable>(array: [T]) -> T {
    // return greatest element in the array
}
</code>```

Now if you try calling that function like so:

```<code>let comparables: [Comparable] = [1, "hello"]
print(greatest(array: comparables))
</code>```

The compiler will complain since there is no way to compare an Int and a String. What you must instead do is follows:

```<code>let comparables: [Int] = [1, 5, 2]
print(greatest(array: comparables))
</code>```

Body:
Here is my code:

protocol SomeProtocol {
}

class A: SomeProtocol {
}

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {
}

func g() {
    let l1: (SomeProtocol?) -> Void = ...
    let l2: ([SomeProtocol]?) -> Void = ...
    f1(ofType: A.self, listener: l1) // NO ERROR
    f2(ofType: A.self, listener: l2) // COMPILE ERROR: Cannot convert value of type '([SomeProtocol]?) -> Void' to expected argument type '([_]?) -> Void'
}

What is the problem with the second closure having an argument of an array of generic type objects?

Body:
The listener closure in func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {...} requires its argument to be an array of T, where T is a type that implements SomeProtocol. By writing <T: SomeProtocol>, you are enforcing that all elements of that array are of the same type.

Say for example you have two classes: A and B. Both are completely distinct. Yet both implement SomeProtocol. In this case, the input array cannot be [A(), B()] because of the type constraint. The input array can either be [A(), A()] or [B(), B()].

But, when you define l2 as let l2: ([SomeProtocol]?) -> Void = ..., you allow the closure to accept an argument such as [A(), B()]. Hence this closure, and the closure you define in f2 are incompatible and the compiler cannot convert between the two.

Unfortunately, you cannot add type enforcement to a variable such as l2 as stated here. What you can do is if you know that l2 is going to work on arrays of class A, you could redefine it as follows:

let l2: ([A]?) -> Void = { ... }

Let me try and explain this with a simpler example. Let's say you write a generic function to find the greatest element in an array of comparables:

func greatest<T: Comparable>(array: [T]) -> T {
    // return greatest element in the array
}

Now if you try calling that function like so:

let comparables: [Comparable] = [1, "hello"]
print(greatest(array: comparables))

The compiler will complain since there is no way to compare an Int and a String. What you must instead do is follows:

let comparables: [Int] = [1, 5, 2]
print(greatest(array: comparables))


问:
Laravel 5.4 and Wordpress integration on ubuntu nginx
I am not finding a complete guide on how to integrate a wordpress to a already deployed laravel application for a begginer on ubuntu 14.04 nginx server (I am using digital ocean ) to create a blog with it using subdomain like example.com/blog

答: Themosis is a really great way to integrate laravel with WordPress while still keeping the cool functionality from both.</p>


答: Inside for loop change int z[x]= rand()%2; into z[x]= rand()%2;. Look I remove int from there.

Title: variable-sized object may not be initialized confusion


问:
'System.Collections.Generic.List`1[<>f__AnonymousType1 but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable ERROR
Controller

public ActionResult Index()
{
   try
   {
      using (var DB =  new CekTakipOtomasyonEntities())
         {
            var model = (from f in DB.FirmaCek
                         join k in DB.KullaniciHesap
                         on f.KullaniciID equals k.ID
                         select new
                         {
                             f.ID,
                             f.Tutar,
                             f.KayitTarihi,
                             f.VadeTarihi,
                             tutar = f.Tutar,
                             f.SeriNo,
                             f.Banka,
                             f.Sube,
                             f.Iban,
                             f.Kesideci,
                             f.CiroEdilen,
                             f.TeslimEden,
                             k.Ad,
                             k.Soyad
                         }).OrderByDescending(f => f.KayitTarihi).ToList();
            if (model == null) return View();
            return View(model);
        }
    }
    catch { return View(); }
}
```

<p>View</p>

```@using CekTakipOtomasyon.Models
@model IEnumerable<FirmaCek>

@foreach (var firma in Model)
                            {

                                    <input type="checkbox" name="secili" value="@firma.ID" />
                                    @firma.KayitTarihi.ToLongDateString()
                                    @firma.VadeTarihi.Value.ToLongDateString()
                                    @Convert.ToInt32(firma.Tutar).ToString() TL
                                    @firma.SeriNo
                                    @firma.Banka
                                    @firma.Sube
                                    @firma.Iban
                                    @firma.Kesideci
                                    @firma.CiroEdilen
                                    @firma.TeslimEden
                                    @firma.KullaniciHesap.Ad @firma.KullaniciHesap.Soyad
                                    <button id="btn_Guncelle" value="@firma.ID" class="btn btn-block btn-info">Güncelle</button>

                            }
```

I think I am misrepresenting variable type in view, what is the solution? Thank you from now

答:
Model must be known or understandable type in your view. Change it as

@model IEnumerable<FirmaCek> or @model IEnumerable<YourModelTypeInYourController>. model is sent by Index action and it should have same type in the view.

Body:
Controller

public ActionResult Index()
{
   try
   {
      using (var DB =  new CekTakipOtomasyonEntities())
         {
            var model = (from f in DB.FirmaCek
                         join k in DB.KullaniciHesap
                         on f.KullaniciID equals k.ID
                         select new
                         {
                             f.ID,
                             f.Tutar,
                             f.KayitTarihi,
                             f.VadeTarihi,
                             tutar = f.Tutar,
                             f.SeriNo,
                             f.Banka,
                             f.Sube,
                             f.Iban,
                             f.Kesideci,
                             f.CiroEdilen,
                             f.TeslimEden,
                             k.Ad,
                             k.Soyad
                         }).OrderByDescending(f => f.KayitTarihi).ToList();
            if (model == null) return View();
            return View(model);
        }
    }
    catch { return View(); }
}

View

@using CekTakipOtomasyon.Models
@model IEnumerable<FirmaCek>

@foreach (var firma in Model)
                            {

                                    <input type="checkbox" name="secili" value="@firma.ID" />
                                    @firma.KayitTarihi.ToLongDateString()
                                    @firma.VadeTarihi.Value.ToLongDateString()
                                    @Convert.ToInt32(firma.Tutar).ToString() TL
                                    @firma.SeriNo
                                    @firma.Banka
                                    @firma.Sube
                                    @firma.Iban
                                    @firma.Kesideci
                                    @firma.CiroEdilen
                                    @firma.TeslimEden
                                    @firma.KullaniciHesap.Ad @firma.KullaniciHesap.Soyad
                                    <button id="btn_Guncelle" value="@firma.ID" class="btn btn-block btn-info">Güncelle</button>

                            }

I think I am misrepresenting variable type in view, what is the solution? Thank you from now


问:
Filter to Month-Day Interval
I have a data frame with daily observations across years. I would like to filter to a range, such as "March 10 to May 12" every year. Perhaps it's my poor googling skills, but I couldn't find some sort of month-day construction.

Here's a sample df:

```<code>set.seed(123)

dates <- seq.Date(from=as.Date("1970-01-01"), to=as.Date("2007-08-31"), by="days")

sample.df <- data.frame(date=dates,
                        data=rnorm(length(dates)))
</code>```

Another addition to complicate is to keep a range that crosses over years, such as "December 10 to February 2." It can be assumed all needed dates are contained within the dataframe, but might need to make some NA such as when the dataframe goes to 2007, so we cannot do December 10, 2007 to February 2, 2008.

答:
You can use dplyr and lubridate:

```<code>library(dplyr)
library(lubridate)

sample.df %>% filter(between(date, ymd("2006-03-10"), ymd("2006-05-12")))

sample.df %>% filter(between(date, ymd("2006-10-11"), ymd("2007-02-01")))
</code>```

Ignoring year:

```<code>sample.df %>%
   mutate(dummy = (month(date)*100) + day(date)) %>%
   filter(between(dummy,310,512)) %>%
   select(-dummy)
</code>```

Title: Filter to Month-Day Interval

Body:
I have a data frame with daily observations across years. I would like to filter to a range, such as "March 10 to May 12" every year. Perhaps it's my poor googling skills, but I couldn't find some sort of month-day construction.

Here's a sample df:

set.seed(123)

dates <- seq.Date(from=as.Date("1970-01-01"), to=as.Date("2007-08-31"), by="days")

sample.df <- data.frame(date=dates,
                        data=rnorm(length(dates)))

Another addition to complicate is to keep a range that crosses over years, such as "December 10 to February 2." It can be assumed all needed dates are contained within the dataframe, but might need to make some NA such as when the dataframe goes to 2007, so we cannot do December 10, 2007 to February 2, 2008.

Body:
You can use dplyr and lubridate:

library(dplyr)
library(lubridate)

sample.df %>% filter(between(date, ymd("2006-03-10"), ymd("2006-05-12")))

sample.df %>% filter(between(date, ymd("2006-10-11"), ymd("2007-02-01")))

Ignoring year:

sample.df %>%
   mutate(dummy = (month(date)*100) + day(date)) %>%
   filter(between(dummy,310,512)) %>%
   select(-dummy)


问:
How to replace everything with blank after question mark in a string?
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

```<code>var str = "/root/Users?SkillId=201;"
</code>```

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

```<code>var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable
</code>```

I don't want to use for loop for this. Isn't there is any better way to do this?

答:
A solution without using a Regular Expression;

Pseudocode

```<code>Find the index location of the '?' character,
    if the resulting index is greater than -1; then;
        extract the new string; starts at index 0 to the
        nth index location of the '?' character
</code>```

JS Code

```<code>// get the index of the first occurrence of '?'
var qMarkIndex = str.indexOf('?');

// '?` character exist
if(qMarkIndex > -1)
    str = str.substr(0, qMarkIndex);

console.log(str);
</code>```

Adding a conditional statement that checks if the ? character exists ensures that; if for some reason the str doesn't contain the ? character then the string stays the same.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?

Body:
A solution without using a Regular Expression;

Pseudocode

Find the index location of the '?' character,
    if the resulting index is greater than -1; then;
        extract the new string; starts at index 0 to the
        nth index location of the '?' character

JS Code

// get the index of the first occurrence of '?'
var qMarkIndex = str.indexOf('?');

// '?` character exist
if(qMarkIndex > -1)
    str = str.substr(0, qMarkIndex);

console.log(str);

Adding a conditional statement that checks if the ? character exists ensures that; if for some reason the str doesn't contain the ? character then the string stays the same.


问:
Like Page Photo From Website PHP SDK 5.0
Was wondering if its possible to like a page post photo on Facebook from a website using the PHP SDK version 5?

I have managed to authenticate a user using the SDK but having troubles finding out if this is possible.

Any examples would be appreciated (if its possible).

Thanks.

答:
No, it is not. Not in the name of the app user.

Facebook has recently removed the possibility to like Facebook objects such as posts, photos and comments via API in the name of a user.

https://developers.facebook.com/docs/apps/changelog#nov-17th--2016


问:
Populate combobox options using javascript from api call
I'm looking to populate the elements of a combobox using an api call using this url
https://api.mercadolibre.com/categories/MLA1744.
Basically, this api returns a list of brands that should be my options in the combobox.
This is my html

```<code><div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMarca" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      Marca
      <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" aria-labelledby="dropdownMarca"></ul>
</div>
</code>```

And my function is

```<code><script src="js/bootstrap.min.js">
  (function() {
    var dropdownMarca = document.getElementById("dropdownMarca");
    var option = document.createElement("option");
    var mlAPI = "https://api.mercadolibre.com/categories/MLA1744";
    $.getJSON(mlAPI)
      .done(function( data ) {
        $.each( data.items, function( i, item ) {
            option.text = item.value);
            dropdownMarca.add(option);
          };
        });
      });
  });
</script>
</code>```

I can't manage to make it work and as you can see I'm pretty rookie.
Thanks in advance!!

答:
There were couple of issues in your code.

You are missing bootstrap js reference

Second there was no id available on your ul on which you want to add options. I have added id attribute.

Your callback function was not parsing data returned correctly.

You are attaching option element to your ul. You need to append li instead of option

I have made required adjustments in your code and now dropdown is being populated with data properly.

var mlAPI = "https://api.mercadolibre.com/categories/MLA1744";
    $.getJSON(mlAPI)
      .done(function(data){
           var dropdownMarca = $("#dropdownMarcaOptions");
           $.each(data.children_categories, function(index, item){                 dropdownMarca.append('
' + item.name + '
');
           });
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMarca" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
          Marca
          <span class="caret"></span>
        </button>
        <ul id="dropdownMarcaOptions"  class="dropdown-menu" aria-labelledby="dropdownMarca"></ul>
      </div></code>```

Body:
I'm looking to populate the elements of a combobox using an api call using this url
https://api.mercadolibre.com/categories/MLA1744.
Basically, this api returns a list of brands that should be my options in the combobox.
This is my html

    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMarca" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      Marca

    </button>

And my function is

I can't manage to make it work and as you can see I'm pretty rookie.
Thanks in advance!!

Body:
There were couple of issues in your code.

You are missing bootstrap js reference

Second there was no id available on your ul on which you want to add options. I have added id attribute.

Your callback function was not parsing data returned correctly.

You are attaching option element to your ul. You need to append li instead of option

I have made required adjustments in your code and now dropdown is being populated with data properly.

var mlAPI = "https://api.mercadolibre.com/categories/MLA1744";
    $.getJSON(mlAPI)
      .done(function(data){
           var dropdownMarca = $("#dropdownMarcaOptions");
           $.each(data.children_categories, function(index, item){                 dropdownMarca.append('<li>' + item.name + '</li>');
           });
      });

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMarca" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
          Marca
          <span class="caret"></span>
        </button>
        <ul id="dropdownMarcaOptions"  class="dropdown-menu" aria-labelledby="dropdownMarca"></ul>
      </div>


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
You could print a backspace character ('\b'):

```<code>for i in xrange(20):
    print '\ba',
</code>```

result:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
You could print a backspace character ('\b'):

for i in xrange(20):
    print '\ba',

result:

aaaaaaaaaaaaaaaaaaaa


问:
Should HttpMessageHandler use ConfigureAwait(false)
If I have an asynchronous call inside a HttpMessageHandler, should it use the .ConfigureAwait method e.g.</p>

```<code>/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash().ConfigureAwait(false);

        var response = await base.SendAsync(request, cancellationToken);

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

答:
You should always use ConfigureAwait(false) when the code after the awaited code doesn't need to get back to the context provided by the synchronization context.

```<code>/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            await request.Content.AssignMd5Hash().ConfigureAwait(false);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}
</code>```

Body:
If I have an asynchronous call inside a HttpMessageHandler, should it use the .ConfigureAwait method e.g.

///
/// Handler to assign the MD5 hash value if content is present
///
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash().ConfigureAwait(false);

        var response = await base.SendAsync(request, cancellationToken);

        return response;
    }
}

Body:
You should always use ConfigureAwait(false) when the code after the awaited code doesn't need to get back to the context provided by the synchronization context.

/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            await request.Content.AssignMd5Hash().ConfigureAwait(false);
        }

        return await base.SendAsync(request, cancellationToken);
    }
}


问:
Test Bench not reaching last test case in verilog
I wrote the following test bench to test my Verilog code:

```<code>module HalfAdder_Test;
wire sum;
wire carry;
reg a = 0;
reg b = 0;

initial begin
    $dumpvars(0, HalfAdder_Test);

    # 10 a = 0; b = 0;
    # 30 a = 1; b = 0;
    # 50 a = 0; b = 1;
    # 70 a = 1; b = 1;

    # 90 $stop;
end

HalfAdder ha (a, b, sum, carry);

initial begin
    $monitor("a: %h, b: %h, sum: %h carry: %h", a, b, sum, carry);
end
endmodule

module FullAdder_Test;
wire sum;
wire carry;
reg a = 0;
reg b = 0;
reg c = 0;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, FullAdder_Test);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end

FullAdder fa (a, b, c, sum, carry);

initial begin
    $monitor("a: %h, b: %h, c: %h, sum: %h carry: %h", a, b, c, sum, carry);
end
endmodule
</code>```

When I run the test I never get an output for my # 70.  This is surprising to me because I don't get any errors and everything seems to be running fine so I can't figure out why it wouldn't reach the last test.  Here is what my output looks like:

Also another thing to note is that I never get the output in my console for the FullAdder_Test (this line):

```<code>$monitor("a: %h, b: %h, c: %h, sum: %h carry: %h", a, b, c, sum, carry);
</code>```

答: I figured it out.  I had another Test file that was compiling and ending the program early.  It turns out if you have one file that ends a test at a certain time (with $stop) it will end ALL tests at that time.</p>

Body:
I wrote the following test bench to test my Verilog code:

module HalfAdder_Test;
wire sum;
wire carry;
reg a = 0;
reg b = 0;

initial begin
    $dumpvars(0, HalfAdder_Test);

    # 10 a = 0; b = 0;
    # 30 a = 1; b = 0;
    # 50 a = 0; b = 1;
    # 70 a = 1; b = 1;

    # 90 $stop;
end

HalfAdder ha (a, b, sum, carry);

initial begin
    $monitor("a: %h, b: %h, sum: %h carry: %h", a, b, sum, carry);
end
endmodule

module FullAdder_Test;
wire sum;
wire carry;
reg a = 0;
reg b = 0;
reg c = 0;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, FullAdder_Test);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end

FullAdder fa (a, b, c, sum, carry);

initial begin
    $monitor("a: %h, b: %h, c: %h, sum: %h carry: %h", a, b, c, sum, carry);
end
endmodule

When I run the test I never get an output for my # 70.  This is surprising to me because I don't get any errors and everything seems to be running fine so I can't figure out why it wouldn't reach the last test.  Here is what my output looks like:

Also another thing to note is that I never get the output in my console for the FullAdder_Test (this line):

$monitor("a: %h, b: %h, c: %h, sum: %h carry: %h", a, b, c, sum, carry);


问:
Shadow map perspective aliasing
It seems impossible to remove this sort of perspective aliasing when the surface is nearly parallel to the light direction.

I have tested several different shadow acne removing techniques:

Constant bias doesn't work: Introduces peter panning on biases large enough to remove the issue

Slope-scale bias doesn't work completely, only lessens the problem slightly

Normal offset shadows don't work, and introduce extra shadow deformations

glPolygonOffset doesn't work, and I suspect it's the same as slope-scale bias

PCL just slightly antialiases the patterns, doesn't actually solve the problem. The amount of filtering required to kill the pattern would make giant blob shadows

VSM doesn't do much, just changes the patterns slightly

Increasing the shadow map resolution and pixel depth lessen the problem, but the resolution large enough to completely fix the issue would bring down frame rate considerably

Expanding the near and far planes of the projection transform for the shadow map creation also doesn't do anything

From what it seems at looking at everything I can find at Google and my books, this is basically an unsolvable issue. I know there must be ways around it however, because even some indie games have perfect and smooth shadow map shadows.

Anybody willing to share this tightly kept secret?

答:
Maybe you have already found an answer since the question is three years old, but I'd still want to say that artifacts on surfaces parallel to light direction must be fixed with normal offset. At least I just solved the same problem with that approach. It was

```<code>vec4 shadowPosition = lightMatrix * vec4(_position, 1.0);
float bias = 0.0002;
float visibility = (texture(shadow, shadowPosition.xy / 2. + .5).r - .5) * 2. < shadowPosition.z - bias ? 0.1: 1.0;
</code>```

And now it is

```<code>float bias = 0.02;
vec4 shadowPosition = lightMatrix * vec4(_position + _normal * bias, 1.);
float visibility = (texture(shadow, shadowPosition.xy / 2. + .5).r - .5) * 2. < shadowPosition.z ? 0.1: 1.0;
</code>```

Yes, the shadow's border is now jagged, but I'll hope some other techniques would help me to smooth it later.

Title: Shadow map perspective aliasing

Body:
Maybe you have already found an answer since the question is three years old, but I'd still want to say that artifacts on surfaces parallel to light direction must be fixed with normal offset. At least I just solved the same problem with that approach. It was

vec4 shadowPosition = lightMatrix * vec4(_position, 1.0);
float bias = 0.0002;
float visibility = (texture(shadow, shadowPosition.xy / 2. + .5).r - .5) * 2. < shadowPosition.z - bias ? 0.1: 1.0;

And now it is

float bias = 0.02;
vec4 shadowPosition = lightMatrix * vec4(_position + _normal * bias, 1.);
float visibility = (texture(shadow, shadowPosition.xy / 2. + .5).r - .5) * 2. < shadowPosition.z ? 0.1: 1.0;

Yes, the shadow's border is now jagged, but I'll hope some other techniques would help me to smooth it later.


问:
Angular4 MdDialog appears but no html is displayed inside
I'm not sure why the html inside of my dialog isn't displayed

Here are my app and dialog components. All of the imports seem to be working correctly, and I'm not getting any error messages in the browser console.

import { Component, Input } from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  dialogRef : MdDialogRef<Dialog>;
  title = 'Code Share app';
  admin = false;
  userID : string = "";

  constructor(public dialog: MdDialog ){
    this.openDialog();
  }

  openDialog() {
  this.dialogRef = this.dialog.open(Dialog);
  this.dialogRef.afterClosed().subscribe(result => {
    console.log(result);
    this.dialogRef = null;
  });
 }

}

@Component({
  selector: 'dialog',
  template: `
Dialog

What would you like to do?

    <button md-button (click)="dialogRef.close('Option 1')">Option 1</button>
    <button md-button (click)="dialogRef.close('Option 2')">Option 2</button>

hello
`,
})

export class Dialog {
  constructor(public dialogRef: MdDialogRef<Dialog>){}
}```

答: It turns out that the HTML selector "dialog" was in a namespace conflict with a selector from one of the libraries I'm using. I changed the name and it worked.</p>


问:
Returning a variable declared inside a Mongoose find()
I'm having lots of trouble combining a for loop with promises. In essence, my workflow is:

Take an array of Artist objects in Node.js, and grab their
biographies and IDs using Mongoose.

Use their IDs to get all the artwork (more specifically, all the
artwork keywords) created by that artist.

Train them in a natural language processor classifier (this part
isn't super relevant- just know that I need to have access to
biography and keywords within the same outer scope.

However, I can't seem to use the bioText object inside the Mongoose promise, and I can't seem to return the keywords from the Mongoose promise.

```<code>            if (!isBlank(bioText) && bioText){
                bioText = artist.BIO;
                artworkIdArray.forEach((id)=> {
                        console.log(bioText) // <- prints correct values
                        var getKey = function(){
                    var words = Artwork.findById(id).then((artwork)=>{
                        console.log(bioText) // <- empty string
                    if(artwork.artworkKeywords.length > 0){
                        keywords = artwork.artistKeywords;
                        return keywords;
                    }
                }
                )
                return words;
                }
                t=getKey();
                t.then((t)=>{
                    console.log(t); // <--- always undefined
                })
            }, this);
        }
</code>```

As you can see, I try to console.log() after exiting the promise, but the t object is always undefined.

Additionally,

I know that in my example bioText is available right up until the Mongoose find() promise. But I also don't know how to inject bioText into the promise (because then I could simply just train the classifier inside the then() statement.

So my post is basically two questions:

Can Promises use outside variables inside then()?

How do I return a variable declared inside then() so it is
available in the outer scope?

答:
Can Promises use outside variables inside then()?

Yes, but you have to be careful with what happens to those variables later on.
That's why console.log(bioText) may log a value just before DB call, and then log null just after DB response.

I would suggest you try the immediate invokation pattern to ensure the value is the expected one:

```<code>(function(x){...; console.log(x);})(bioText)
</code>```

How do I return a variable declared inside then() so it is available
  in the outer scope?

You cannot, at least without complicated promise management, which you may not need here.
That's why t=getKey(); is always undefined.

I think you want to get all the values before going on with your process. So you should retrieve all from DB in a single query, then call all your code in the callback.

You can have a try with this:

```<code>Artwork
    .find({_id: {$in: artworkIdArray}})
    .then( (artworks) => {
        var keywords = [];
        artworks.forEach( (artwork) => {
            if(artwork.artworkKeywords.length > 0)
                keywords.append(artwork.artistKeywords);
        });
        // Now do your job with all the retrieved keywords
    });
</code>```

Body:
I'm having lots of trouble combining a for loop with promises. In essence, my workflow is:

Take an array of Artist objects in Node.js, and grab their
biographies and IDs using Mongoose.

Use their IDs to get all the artwork (more specifically, all the
artwork keywords) created by that artist.

Train them in a natural language processor classifier (this part
isn't super relevant- just know that I need to have access to
biography and keywords within the same outer scope.

However, I can't seem to use the bioText object inside the Mongoose promise, and I can't seem to return the keywords from the Mongoose promise.

            if (!isBlank(bioText) && bioText){
                bioText = artist.BIO;
                artworkIdArray.forEach((id)=> {
                        console.log(bioText) // <- prints correct values
                        var getKey = function(){
                    var words = Artwork.findById(id).then((artwork)=>{
                        console.log(bioText) // <- empty string
                    if(artwork.artworkKeywords.length > 0){
                        keywords = artwork.artistKeywords;
                        return keywords;
                    }
                }
                )
                return words;
                }
                t=getKey();
                t.then((t)=>{
                    console.log(t); // <--- always undefined
                })
            }, this);
        }

As you can see, I try to console.log() after exiting the promise, but the t object is always undefined.

Additionally,

I know that in my example bioText is available right up until the Mongoose find() promise. But I also don't know how to inject bioText into the promise (because then I could simply just train the classifier inside the then() statement.

So my post is basically two questions:

Can Promises use outside variables inside then()?

How do I return a variable declared inside then() so it is
available in the outer scope?

Body:
Can Promises use outside variables inside then()?

Yes, but you have to be careful with what happens to those variables later on.
That's why console.log(bioText) may log a value just before DB call, and then log null just after DB response.

I would suggest you try the immediate invokation pattern to ensure the value is the expected one:

(function(x){...; console.log(x);})(bioText)

How do I return a variable declared inside then() so it is available
  in the outer scope?

You cannot, at least without complicated promise management, which you may not need here.
That's why t=getKey(); is always undefined.

I think you want to get all the values before going on with your process. So you should retrieve all from DB in a single query, then call all your code in the callback.

You can have a try with this:

Artwork
    .find({_id: {$in: artworkIdArray}})
    .then( (artworks) => {
        var keywords = [];
        artworks.forEach( (artwork) => {
            if(artwork.artworkKeywords.length > 0)
                keywords.append(artwork.artistKeywords);
        });
        // Now do your job with all the retrieved keywords
    });


问:
how to display table view cells whenever we need to click on one cell
i am writing one app in that app i have to display tableview with two cells.while the first cell touched by the user then it have to show some other cells within the view (i cant use navigation here) and also second cell also visible..can any one tell me the suggestion for this.
thank you all.</p>

答:
make a bool (isRowClick) variable and

set YES in didSelectRow and then write this line

```<code>[yourTable reloadData];
</code>```

and

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if(isRowClick)
  return 7;//according to you
else
  return 2;
}

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

  isRowSelect=YES;
 //stuff
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//stuff according to you
}
</code>```

this will hep you.

Body:
make a bool (isRowClick) variable and

set YES in didSelectRow and then write this line

[yourTable reloadData];

and

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if(isRowClick)
  return 7;//according to you
else
  return 2;
}

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

  isRowSelect=YES;
 //stuff
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

//stuff according to you
}

this will hep you.


答:
You're declaring your model as IEnumerable but try to use it with a List of anonymous types.

Your options are:

Declare it as IEnumerable of YourType and create instances of this type in your Select clause. Currently it creates an anonymous object.

Here's an example of non-anonymous creation:

```<code>                     var model = (from f in DB.FirmaCek
                                 join k in DB.KullaniciHesap
                                 on f.KullaniciID equals k.ID
                                 select new MyViewModel
                                 {
                                     ID = f.ID //add properties here
                                 }).OrderByDescending(f => f.KayitTarihi).ToList();
</code>```

If you want to keep using anonymous object, use IEnumerable together with ExpandoObject like this.

Title: 'System.Collections.Generic.List`1[<>f__AnonymousType1 but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable ERROR

Body:
You're declaring your model as IEnumerable but try to use it with a List of anonymous types.

Your options are:

Declare it as IEnumerable of YourType and create instances of this type in your Select clause. Currently it creates an anonymous object.

Here's an example of non-anonymous creation:

                     var model = (from f in DB.FirmaCek
                                 join k in DB.KullaniciHesap
                                 on f.KullaniciID equals k.ID
                                 select new MyViewModel
                                 {
                                     ID = f.ID //add properties here
                                 }).OrderByDescending(f => f.KayitTarihi).ToList();

If you want to keep using anonymous object, use IEnumerable together with ExpandoObject like this.


问:
Pythonic way to merge keys with common values for a single dictionary
How do I merge the keys of a dictionary with common values into a tuple. For example:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}
</code>```

My attempt:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)
</code>```

This prints:

```<code>OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}
</code>```

答:
I would make the transformation in two passes:

```<code>>>> A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

# First pass:  Create a reverse one-to-many mapping.
# The original set() value gets converted to a hashable frozenset()
# and used as a key.  The original scalar string key gets accumulated
# in a list to track the multiple occurrences.
>>> reverse = {}
>>> for key, value in A.items():
        reverse.setdefault(frozenset(value), []).append(key)

# Second pass:  reverse the keys and values.  The list of matching
# values gets converted to a hashable tuple (as specified by the OP)
# and the frozenset() gets restored back to the original set() type.
>>> {tuple(value) : set(key) for key, value in reverse.items()}
{('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'8', '4'}}
</code>```

This gives the output expected by the OP.

Note, the input dictionary doesn't have guaranteed order, nor do any of the sets in the original input.  Accordingly, the output cannot have a guaranteed ordering of terms.

Body:
How do I merge the keys of a dictionary with common values into a tuple. For example:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}

My attempt:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)

This prints:

OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}

Body:
I would make the transformation in two passes:

>>> A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

# First pass:  Create a reverse one-to-many mapping.
# The original set() value gets converted to a hashable frozenset()
# and used as a key.  The original scalar string key gets accumulated
# in a list to track the multiple occurrences.
>>> reverse = {}
>>> for key, value in A.items():
        reverse.setdefault(frozenset(value), []).append(key)

# Second pass:  reverse the keys and values.  The list of matching
# values gets converted to a hashable tuple (as specified by the OP)
# and the frozenset() gets restored back to the original set() type.
>>> {tuple(value) : set(key) for key, value in reverse.items()}
{('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'8', '4'}}

This gives the output expected by the OP.

Note, the input dictionary doesn't have guaranteed order, nor do any of the sets in the original input.  Accordingly, the output cannot have a guaranteed ordering of terms.


问:
custom font will not display not matter what i do
i want to add a custom font to my html page, but it does not work, i tried everything possible, checked other questions, trying to solve it their way, but nothing.

the font is in the same folder as my html file(the css is in the html file)

In html css i wrote:

```<code>@font-face {
    font-family: regular;
    src: url("8bitoperator_jve.ttf");
    //src: local("8bitoperator_jve.ttf"); i tried this too
}
body {
    background-color: #000;
    color: #FFF;
    font-family: regular;
}
</code>```

答:
The src attribute of @font-face specifies the resource containing the font data. This can be:

url: a URL to a remote font file location;

local: the name of a font on the user's computer.

In your case, you are passing a URL to local. Instead, you should use url:

```<code>@font-face {
    src: url('8bitoperator_jve.ttf');
}
</code>```

If you want, you can also use both. But remember to give precedence to local, i.e.:

```<code>@font-face {
    src: local('Name of your font here'), url('8bitoperator_jve.ttf');
}
</code>```

Body:
i want to add a custom font to my html page, but it does not work, i tried everything possible, checked other questions, trying to solve it their way, but nothing.

the font is in the same folder as my html file(the css is in the html file)

In html css i wrote:

@font-face {
    font-family: regular;
    src: url("8bitoperator_jve.ttf");
    //src: local("8bitoperator_jve.ttf"); i tried this too
}
body {
    background-color: #000;
    color: #FFF;
    font-family: regular;
}

Body:
The src attribute of @font-face specifies the resource containing the font data. This can be:

url: a URL to a remote font file location;

local: the name of a font on the user's computer.

In your case, you are passing a URL to local. Instead, you should use url:

@font-face {
    src: url('8bitoperator_jve.ttf');
}

If you want, you can also use both. But remember to give precedence to local, i.e.:

@font-face {
    src: local('Name of your font here'), url('8bitoperator_jve.ttf');
}


问:
Do executables built with CodeBlocks + GCC run on any Windows?
When building with Visual C++, I noticed that a simple executable helloworld.exe (displaying a WinAPI MessageBox) can be shipped to any computer using Windows XP, Vista, 7, 8, 10, and will run without any third-party dll or redistribuable packages.

Now that I'm moving to CodeBlocks + GCC, will the same be true? i.e. will a simple executable displaying a WinAPI MessageBox be able to run on all Win XP, Vista, 7, 8, 10 without any other packages needed, specific to GCC ?

答: As with all programs, including those built with VS, guaranteeing the program will work across all those Windows versions is not trivial. But yes, you can generally write console applications with GCC that will work across them without any third-party DLLs - my own CSVfix application certainly does. And you can certainly use GCC to display a message box without such things. I would recommend using TDM GCC, a version of which comes with one of the Code::Blocks packages, as the most straightforward way of doing such a thing.</p>


问:
Convert string to array in Java?
I have a string which has the values like this (format is the same):

```<code>name:xxx
occupation:yyy
phone:zzz
</code>```

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

答:
Sounds like you want to convert to a property Map rather than an array.

e.g.

```<code>String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
   String[] parts = keyValue.split(":", 2);
   properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx
</code>```

This approach allows your values to be in any order.  If a key is missing, the get() will return null.

Title: Convert string to array in Java?

Body:
I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

Body:
Sounds like you want to convert to a property Map rather than an array.

e.g.

String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
   String[] parts = keyValue.split(":", 2);
   properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx

This approach allows your values to be in any order.  If a key is missing, the get() will return null.


问:
Can I use formulas in select case
I have a function with the following select case statement.  The function does not work if I have an Excel in the condition section.

Like:   Case Is >= Sheets("list").Range("M50")

The function works if I put in a value for the condition,
 such as:         Case Is >= 5

The select is shown below.  Is using a formula not allowed? Is there a work around?

```<code>Select Case distance

Case Is >= Sheets("list").Range("M50")
RightPlace = Sheets("list").Range("n50").Value

Case Is >= Sheets("list").Range("M51").Value
RightPlace = Sheets("list").Range("n51").Value

Case Is >= Sheets("list").Range("M52").Value
RightPlace = Sheets("list").Range("n52").Value

Case Is >= Sheets("list").Range("M53").Value
RightPlace = Sheets("list").Range("n53").Value

Case Is >= Sheets("list").Range("M54").Value
RightPlace = Sheets("list").Range("n54").Value

Case Is >= Sheets("list").Range("M55").Value
RightPlace = Sheets("list").Range("n55").Value

Case Is >= Sheets("list").Range("M56").Value
RightPlace = Sheets("list").Range("n56").Value

Case Is >= Sheets("list").Range("M57").Value
RightPlace = Sheets("list").Range("n57").Value

Case Is >= Sheets("list").Range("M58").Value
RightPlace = Sheets("list").Range("n58").Value

End Select
</code>```

答:
Why use a Case statement at all? You are looking up data in spreadsheet cells, so you might as well use</p>

```<code>RightPlace = Application.WorksheetFunction.VLookup(distance, Sheets("list").Range("M50:N58"), 2, False)
</code>```

Title: Can I use formulas in select case

Body:
I have a function with the following select case statement.  The function does not work if I have an Excel in the condition section.

Like:   Case Is >= Sheets("list").Range("M50")

The function works if I put in a value for the condition,
 such as:         Case Is >= 5

The select is shown below.  Is using a formula not allowed? Is there a work around?

Select Case distance

Case Is >= Sheets("list").Range("M50")
RightPlace = Sheets("list").Range("n50").Value

Case Is >= Sheets("list").Range("M51").Value
RightPlace = Sheets("list").Range("n51").Value

Case Is >= Sheets("list").Range("M52").Value
RightPlace = Sheets("list").Range("n52").Value

Case Is >= Sheets("list").Range("M53").Value
RightPlace = Sheets("list").Range("n53").Value

Case Is >= Sheets("list").Range("M54").Value
RightPlace = Sheets("list").Range("n54").Value

Case Is >= Sheets("list").Range("M55").Value
RightPlace = Sheets("list").Range("n55").Value

Case Is >= Sheets("list").Range("M56").Value
RightPlace = Sheets("list").Range("n56").Value

Case Is >= Sheets("list").Range("M57").Value
RightPlace = Sheets("list").Range("n57").Value

Case Is >= Sheets("list").Range("M58").Value
RightPlace = Sheets("list").Range("n58").Value

End Select

Body:
Why use a Case statement at all? You are looking up data in spreadsheet cells, so you might as well use

RightPlace = Application.WorksheetFunction.VLookup(distance, Sheets("list").Range("M50:N58"), 2, False)


问:
Android how to detect if outgoing call is answered
I'm developing an app that will only be used in house for testing purpose. I have searched a lot and tried different suggestions as suggested in different post but none seems to be working for me.

I'm open to any suggestions like Reflections, Accessibility Service, root or any other hack. Please help.

Regards

答:
You can use accessibility events to detect the call duration and from that you can detect if the outgoing call is answered or not..

I have answered it in detail in Here` you can check that.


问:
Error: Bootstrap datetimepicker is not a function
I am very new to html and bootstraping. I am trying to use datetimepicker function.

I know this question has been asked several times and I tried several different answers on the similar questions and still it throws the same error that datetimepicker is not a function. I appreciate if you could let e know what I am doing wrong. Following is my code:

```<code>     <div class="col-lg-4">
      <div class="form-group">
        <label for="datetimepicker1">Date:</label>
          <div class ='input-group date' id='datetimepicker1'>
            <input type="text" class="form-control">
            <span class="input-group-addon">
              <span class="glyphicon glyphicon-calendar"></span>
            </span>
          </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
        <script type="text/javascript">
          $(function () {
            $('#datetimepicker1').datetimepicker();
          });
        </script>
      </div>
    </div>
</code>```

答:
datetimepicker() needs to be initizialized on an input element inside of a div with the position:relative style rule.

JS Fiddle

```<code><form class="form-inline">
  <div class="form-group">
    <label for="dtp">Date: </label>
    <div style="position:relative">
      <input type="text" class="form-control" id="dtp">
      <script>
        $(function() {
          $('#dtp').datetimepicker();
        });
      </script>
    </div>
  </div>
</form>
</code>```

Body:
I am very new to html and bootstraping. I am trying to use datetimepicker function.

I know this question has been asked several times and I tried several different answers on the similar questions and still it throws the same error that datetimepicker is not a function. I appreciate if you could let e know what I am doing wrong. Following is my code:

        Date:

            <input type="text" class="form-control">

Body:
datetimepicker() needs to be initizialized on an input element inside of a div with the position:relative style rule.

JS Fiddle

<form class="form-inline">
  <div class="form-group">
    <label for="dtp">Date: </label>
    <div style="position:relative">
      <input type="text" class="form-control" id="dtp">
      <script>
        $(function() {
          $('#dtp').datetimepicker();
        });
      </script>
    </div>
  </div>
</form>


问:
Determine if Axios request is done
Is there any way to determine if a Axios request like the following received an answer and is done?</p>

```<code>axios.get('/api')
.then(response => this.data = response.data);
</code>```

答:
Yes, this is a promise and you can reference and then it:

```<code>var req = axios.get('/api')
               .then(response => this.data = response.data);
</code>```

Now I want to react to it being done:

```<code>req.then(x => console.log("Done!"));
</code>```

Or save that state outside:

```<code>var isReqDone = false;
req.then(x => isReqDone = true);
</code>```

Title: Determine if Axios request is done

Body:
Is there any way to determine if a Axios request like the following received an answer and is done?

axios.get('/api')
.then(response => this.data = response.data);

Body:
Yes, this is a promise and you can reference and then it:

var req = axios.get('/api')
               .then(response => this.data = response.data);

Now I want to react to it being done:

req.then(x => console.log("Done!"));

Or save that state outside:

var isReqDone = false;
req.then(x => isReqDone = true);


问:
Load a UIView from nib in Swift
Here is my Objective-C code which I'm using to load a nib for my customised UIView:

```<code>-(id)init{

    NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil];
    return [subviewArray objectAtIndex:0];

}
</code>```

What is the equivalent code in Swift?

答:
I just do this way :

if let myView = UINib.init(nibName: "MyView", bundle: nil).instantiate(withOwner: self)[0] as? MyView {
    // Do something with myView
}
```
<p>This sample uses the first view in the nib "MyView.xib" in the main bundle. But you can vary either the index, the nib name, or the bundle ( main by default ).</p>
<p>I used to awake views into the view init method or make generic methods as in the proposed answers above ( which are smart by the way ), but I don't do it anymore because I have noticed use cases are often different, and to cover all cases, generic methods become as complex as using the UINib.instantiate method.</p>
<p>I prefer to use a factory object, usually the ViewController that will use the view, or a dedicated factory object or view extension if the view needs to be used in multiple places.</p>
<p>In this example, a ViewController loads a view from nib.
The nib file can be changed to use different layouts for the same view class. ( This not nice code, it just illustrates the idea )</p>
<pre class="lang-swift prettyprint-override"><code>class MyViewController {
    // Use "MyView-Compact" for compact version
    var myViewNibFileName = "MyView-Standard"

    lazy var myView: MyView = {
        // Be sure the Nib is correct, or it will crash
        // We don't want to continue with a wrong view anyway, so ! is ok
        UINib.init(nibName: myViewNibFileName, bundle: nil).instantiate(withOwner: self)[0] as! MyView
    }()
}
</code>```

Title: Load a UIView from nib in Swift

Body:
Here is my Objective-C code which I'm using to load a nib for my customised UIView:

-(id)init{

    NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil];
    return [subviewArray objectAtIndex:0];

}

What is the equivalent code in Swift?

Body:
I just do this way :

if let myView = UINib.init(nibName: "MyView", bundle: nil).instantiate(withOwner: self)[0] as? MyView {
    // Do something with myView
}

This sample uses the first view in the nib "MyView.xib" in the main bundle. But you can vary either the index, the nib name, or the bundle ( main by default ).

I used to awake views into the view init method or make generic methods as in the proposed answers above ( which are smart by the way ), but I don't do it anymore because I have noticed use cases are often different, and to cover all cases, generic methods become as complex as using the UINib.instantiate method.

I prefer to use a factory object, usually the ViewController that will use the view, or a dedicated factory object or view extension if the view needs to be used in multiple places.

In this example, a ViewController loads a view from nib.
The nib file can be changed to use different layouts for the same view class. ( This not nice code, it just illustrates the idea )

class MyViewController {
    // Use "MyView-Compact" for compact version
    var myViewNibFileName = "MyView-Standard"

    lazy var myView: MyView = {
        // Be sure the Nib is correct, or it will crash
        // We don't want to continue with a wrong view anyway, so ! is ok
        UINib.init(nibName: myViewNibFileName, bundle: nil).instantiate(withOwner: self)[0] as! MyView
    }()
}


问:
How to convert Image into BufferedImage
Right now I have an image and I want to convert it into a BufferedImage...

This is my code -

```<code>private BufferedImage toBufferedImage(Image img, int width, int height){
    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics bGr = bimage.getGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}
</code>```

But it doesn't work. Can someone explain what's wrong?

答:
Try the new JRE that includes JavaFX.

You could use SwingFXUtils. There is a method which does what you ask for:

BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>BufferedImage image = ImageIO.read(new File(filename));
</code>```

Title: How to convert Image into BufferedImage

Body:
Right now I have an image and I want to convert it into a BufferedImage...

This is my code -

private BufferedImage toBufferedImage(Image img, int width, int height){
    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    // Draw the image on to the buffered image
    Graphics bGr = bimage.getGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    // Return the buffered image
    return bimage;
}

But it doesn't work. Can someone explain what's wrong?

Body:
Try the new JRE that includes JavaFX.

You could use SwingFXUtils. There is a method which does what you ask for:

BufferedImage image = SwingFXUtils.fromFXImage(fxImage, null);

or

BufferedImage image = ImageIO.read(new File(filename));


问:
Active Record STI Confused
STI is not working as I think it should under certain conditions.

The models (simplified):

```<code>class Order < ApplicationRecord
  has_many :items, class_name: 'OrderItem', inverse_of: :order
end

class OrderItem < ApplicationRecord
  belongs_to :order, inverse_of: :items
  has_one :spec, inverse_of: :order_item
end

class Spec < ApplicationRecord
  belongs_to :order_item, inverse_of: :spec
end

class FooSpec < Spec
end

class BarSpec < Spec
end
</code>```

Schema (simplified):

```<code>create_table "specs", force: :cascade do |t|
  t.string "type", null: false
  t.bigint "order_item_id", null: false
  ...
end
</code>```

I'm using ActiveRecord::Associations::Preloader to avoid n+1 problems in my GraphQL server. I've started getting some STI errors.

From a console, this works fine and returns a FooSpec or BarSpec:

```<code>Order.includes(items: :spec).first.items.first.spec
</code>```

Same with this:

```<code>Order.includes(:items).first.items.includes(:spec).first.spec
</code>```

And this too:

```<code>ActiveRecord::Associations::Preloader.new
  .preload(Order.all, :items).first.owners.first.items.first.spec
</code>```

However, this:

```<code>ActiveRecord::Associations::Preloader.new.preload(Order.all, items: :spec)
</code>```

And this:

```<code>ActiveRecord::Associations::Preloader.new
  .preload(Order.all.map{|o| o.items}.flatten, :spec)
</code>```

Raise an error:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism
  failed to locate the subclass: 'FooSpec'. This error is raised
  because the column 'type' is reserved for storing the class in case of
  inheritance. Please rename this column if you didn't intend it to be
  used for storing the inheritance class or overwrite
  Spec.inheritance_column to use another column for that information.

Sometimes I'm getting a slightly different error from the app but I cannot reproduce it in the console:

ActiveRecord::SubclassNotFound (Invalid single-table inheritance type:
  FooSpec is not a subclass of Spec)

Hmm...as you can see, FooSpec is most definitely a subclass of Spec. These errors usually mean you used type as an attribute and did not tell ActiveRecord it's not an STI discriminator. That's not the case here. Ideas?

答:
I found the culprit. I had this:

```<code>class FooSpec < Spec
  validates :my_field, inclusion: {in: MyClass::CHOICES}
end
</code>```

When I changed it to this, the problem disappeared:

```<code>class FooSpec < Spec
  validates :my_field, inclusion: {in: -> (_instance) {MyClass::CHOICES}}
end
</code>```

I do not understand why. MyClass::CHOICES is a simple constant holding an array. The class is a classy_enum.

```<code>class MyClass < MyClassyEnum
  CHOICES = %w[
    choiceOne
    choiceTwo
  ].freeze
  ...
end
</code>```

Title: Active Record STI Confused

Body:
STI is not working as I think it should under certain conditions.

The models (simplified):

class Order < ApplicationRecord
  has_many :items, class_name: 'OrderItem', inverse_of: :order
end

class OrderItem < ApplicationRecord
  belongs_to :order, inverse_of: :items
  has_one :spec, inverse_of: :order_item
end

class Spec < ApplicationRecord
  belongs_to :order_item, inverse_of: :spec
end

class FooSpec < Spec
end

class BarSpec < Spec
end

Schema (simplified):

create_table "specs", force: :cascade do |t|
  t.string "type", null: false
  t.bigint "order_item_id", null: false
  ...
end

I'm using ActiveRecord::Associations::Preloader to avoid n+1 problems in my GraphQL server. I've started getting some STI errors.

From a console, this works fine and returns a FooSpec or BarSpec:

Order.includes(items: :spec).first.items.first.spec

Same with this:

Order.includes(:items).first.items.includes(:spec).first.spec

And this too:

ActiveRecord::Associations::Preloader.new
  .preload(Order.all, :items).first.owners.first.items.first.spec

However, this:

ActiveRecord::Associations::Preloader.new.preload(Order.all, items: :spec)

And this:

ActiveRecord::Associations::Preloader.new
  .preload(Order.all.map{|o| o.items}.flatten, :spec)

Raise an error:

ActiveRecord::SubclassNotFound: The single-table inheritance mechanism
  failed to locate the subclass: 'FooSpec'. This error is raised
  because the column 'type' is reserved for storing the class in case of
  inheritance. Please rename this column if you didn't intend it to be
  used for storing the inheritance class or overwrite
  Spec.inheritance_column to use another column for that information.

Sometimes I'm getting a slightly different error from the app but I cannot reproduce it in the console:

ActiveRecord::SubclassNotFound (Invalid single-table inheritance type:
  FooSpec is not a subclass of Spec)

Hmm...as you can see, FooSpec is most definitely a subclass of Spec. These errors usually mean you used type as an attribute and did not tell ActiveRecord it's not an STI discriminator. That's not the case here. Ideas?

Body:
I found the culprit. I had this:

class FooSpec < Spec
  validates :my_field, inclusion: {in: MyClass::CHOICES}
end

When I changed it to this, the problem disappeared:

class FooSpec < Spec
  validates :my_field, inclusion: {in: -> (_instance) {MyClass::CHOICES}}
end

I do not understand why. MyClass::CHOICES is a simple constant holding an array. The class is a classy_enum.

class MyClass < MyClassyEnum
  CHOICES = %w[
    choiceOne
    choiceTwo
  ].freeze
  ...
end


问:
Drawing on canvas using vector graphics android
I don't know alot about graphics and drawings but I am trying to do something on canvas, and that is using vector graphics instead of bitmap to draw path on canvas with finger , I cant find any documentation or tutorials to understand how to do that, but I know that this implementation is used by some drawing apps.

According to my searching I deduced that using vector graphics will never show pixels on the edges of the path even if you zoomed.

Please suggest any thing that might help me use vector graphics and attach it to canvas to draw, thanks.

答:
If you just want to draw with the finger :

Assuming you have a custom View that covers the drawing area ...

On onTouch handler on ACTION_DOWN create a new Path object with origin at touch point, on ACTION_MOVE you add new segments to the Path and call invalidate().

On onDraw you draw the Path on the Canvas.


问:
What is Class Index in WEKA?
I have to use WEKA in my java code for prediction. Basically I have to study a given code and reuse it.

testdata.setClassIndex(data.numAttributes() - 1);

I am unable to understand what the above line means.
What is a Class Index?

testdata and data are  Intances object.

答: The class index indicates the target attribute used for classification. By default, in an ARFF file, it is the last attribute, which explains why it's set to numAttributes-1.</p>

Title: What is Class Index in WEKA?


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

```<code>>>> from __future__ import print_function
>>> print('a', end='')
</code>```

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was  removed and became the print() function by default in Python 3.0.

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
From PEP 3105: print As a Function in the What’s New in Python 2.6 document:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function at the beginning). The print statement was  removed and became the print() function by default in Python 3.0.


问:
Inheriting class methods Javascript
Lets say I have two APIs and I would like to inherit classes from the first, but modify the response with .prototype.toJSON().

When I inherit from the first class, how can I inherit class methods as well.

An example

```<code>//file v1/models/users.js
var UserModel = function() {
  this.id = 0;
  this.firstName = '';
  this.lastName = '';
}

UserModel.find = function(q, callback) {
  //find any user that matches q and map them to UserModel
  if (err) return callback(err, null);
  callback(null, users);
}

module.exports = UserModel;
</code>```

And the the next version

```<code>//file v2/models/users.js
var UserModel = require('../v1/models/users');

function UserModelV2() {
  UserModel.call(this);
}

UserModelV2 = Object.create(UserModel.prototype);
UserModelV2.prototype.constructor = UserModel;

UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}
module.exports = UserModelV2;
</code>```

When I now try to call

```<code>var User = require('./v2/models/users');
User.find(1);
</code>```

I get an error saying User.find does not exists.

I am aware I am only inheriting prototypal properties, but I cannot find an example of inheriting class methods anywhere.

答:
Don't add find directly onto UserModel because that causes the method to be added only to one instance.

Add it to the prototype:

```<code>UserModel.prototype.find = function(id) {
  //find the user by id and return
}
</code>```

Because all instances of UserModel will inherit from the prototype of your constructor function.

Then, your next version would inherit from the first like this:

```<code>// Constructor of sub-class
function UserModelV2() {
  // Call the prototype.constructor, not just .constructor
  UserModel.prototype.constructor.call(this);
}

// Perform inheritance
UserModelV2.prototype = new UserModel();

// Correct the constructor of the prototype
UserModelV2.prototype.constructor = UserModelV2;

// Extend the sub-class
UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}
</code>```

By the way (and this could be why you got stuck on this), technically (and despite the class keyword), JavaScript does not have classes, it has prototypes and they are the basis for inheritance.

Title: Inheriting class methods Javascript

Body:
Lets say I have two APIs and I would like to inherit classes from the first, but modify the response with .prototype.toJSON().

When I inherit from the first class, how can I inherit class methods as well.

An example

//file v1/models/users.js
var UserModel = function() {
  this.id = 0;
  this.firstName = '';
  this.lastName = '';
}

UserModel.find = function(q, callback) {
  //find any user that matches q and map them to UserModel
  if (err) return callback(err, null);
  callback(null, users);
}

module.exports = UserModel;

And the the next version

//file v2/models/users.js
var UserModel = require('../v1/models/users');

function UserModelV2() {
  UserModel.call(this);
}

UserModelV2 = Object.create(UserModel.prototype);
UserModelV2.prototype.constructor = UserModel;

UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}
module.exports = UserModelV2;

When I now try to call

var User = require('./v2/models/users');
User.find(1);

I get an error saying User.find does not exists.

I am aware I am only inheriting prototypal properties, but I cannot find an example of inheriting class methods anywhere.

Body:
Don't add find directly onto UserModel because that causes the method to be added only to one instance.

Add it to the prototype:

UserModel.prototype.find = function(id) {
  //find the user by id and return
}

Because all instances of UserModel will inherit from the prototype of your constructor function.

Then, your next version would inherit from the first like this:

// Constructor of sub-class
function UserModelV2() {
  // Call the prototype.constructor, not just .constructor
  UserModel.prototype.constructor.call(this);
}

// Perform inheritance
UserModelV2.prototype = new UserModel();

// Correct the constructor of the prototype
UserModelV2.prototype.constructor = UserModelV2;

// Extend the sub-class
UserModelV2.prototype.toJSON = function() {
    var obj = {};
    obj.firstName = 'foo';
    return obj;
}

By the way (and this could be why you got stuck on this), technically (and despite the class keyword), JavaScript does not have classes, it has prototypes and they are the basis for inheritance.


问:
Openlayers Set Map Target with Jquery
But I didn't do this yet.

I have a div element

```<code><div id="map" class="map"></div>
</code>```

And I have a map

```<code>    var map = new ol.Map({
    layers: [map_layer],
    target: 'map',
    view: Map_1_view
});
</code>```

I try this to set target

```<code>$("#map").data("my_map",  map);
</code>```

but it didn't work. How can I solve this?

答:
I solve this with</p>

```<code> map.setTarget($("#map")[0]);
</code>```

Title: Openlayers Set Map Target with Jquery

Body:
But I didn't do this yet.

I have a div element

And I have a map

    var map = new ol.Map({
    layers: [map_layer],
    target: 'map',
    view: Map_1_view
});

I try this to set target

$("#map").data("my_map",  map);

but it didn't work. How can I solve this?

Body:
I solve this with

 map.setTarget($("#map")[0]);