问:
Mapbox-gl typing won't allow accessToken assignment
I'm using the mapbox-gl library with TypeScript, and I've installed its community sourced type definitions with @types/mapbox-gl. When I try to import and set an accessToken to use the library, my TypeScript compiler throws this error:
TS2540: Cannot assign to 'accessToken' because it is a constant or a read-only property.

So I pulled up the .d.ts file and the variable in question looks extremely assignable (seen here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/mapbox-gl/index.d.ts):

```<code>declare namespace mapboxgl {
   let accessToken: string;
   ...
</code>```

This is my code:

```<code>import * as mapbox from 'mapbox-gl';
mapbox.accessToken = 'token';
</code>```

Versions!

```<code>"@types/mapbox-gl": "^0.35.0",
"typescript": "^2.3.4",
"mapbox-gl": "^0.37.0",
</code>```

TypeScript hackery says that I can cast mapbox to any and it will work, but I'm very curious what about the typing is going wrong here.

答:
Here's a temporary workaround I've been using:

```<code>Object.getOwnPropertyDescriptor(mapboxgl, "accessToken").set('YOUR_TOKEN');
</code>```

Explanation

Since the object was redefined to use a custom setter which places the token inside an internal closure - we can call the setter function directly as shown in the example.

Diving a little deeper, we can see that es6 modules are constants by definition:
https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

we can then do something like: (mapboxgl as any).accessToken = ... which will work.

Body:
I'm using the mapbox-gl library with TypeScript, and I've installed its community sourced type definitions with @types/mapbox-gl. When I try to import and set an accessToken to use the library, my TypeScript compiler throws this error:
TS2540: Cannot assign to 'accessToken' because it is a constant or a read-only property.

So I pulled up the .d.ts file and the variable in question looks extremely assignable (seen here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/mapbox-gl/index.d.ts):

declare namespace mapboxgl {
   let accessToken: string;
   ...

This is my code:

import * as mapbox from 'mapbox-gl';
mapbox.accessToken = 'token';

Versions!

"@types/mapbox-gl": "^0.35.0",
"typescript": "^2.3.4",
"mapbox-gl": "^0.37.0",

TypeScript hackery says that I can cast mapbox to any and it will work, but I'm very curious what about the typing is going wrong here.

Body:
Here's a temporary workaround I've been using:

Object.getOwnPropertyDescriptor(mapboxgl, "accessToken").set('YOUR_TOKEN');

Explanation

Since the object was redefined to use a custom setter which places the token inside an internal closure - we can call the setter function directly as shown in the example.

Diving a little deeper, we can see that es6 modules are constants by definition:
https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

we can then do something like: (mapboxgl as any).accessToken = ... which will work.


来源: stackexchange

问:
This not available in complete function
I have this jQuery function

```<code>$("#edit-modal").animate({ width: "90%" }, 400, function () {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});
</code>```

however in the function() is seems like this. isn't known or available, meaning console.log(this.modalWidth); results in undefined.

How can I use my this.property in my complete function?

答:
When you pass in an anonymous function, it gets its own this variable.

The quickest way to get around this would be to create a closure reference to this in the outer scope, and use the reference variable inside your callback.

```<code>var self = this;
$("#edit-modal").animate({ width: "90%" }, 400, function () {
    self.registrationsPanelWidth = $("#edit-modal").width() - self.modalWidth - 20;
    console.log(self.modalWidth);
});
</code>```

This is a perfect use case for ES6 arrow functions, by the way. From the documentation on MDN:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

If you're able to use arrow functions in your project, it would look like this:

```<code>$("#edit-modal").animate({ width: "90%" }, 400, () => {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});
</code>```

See the documentation on MDN for more information on arrow functions.

ContentLicense: CC BY-SA 3.0

Title: This not available in complete function

Body:
I have this jQuery function

$("#edit-modal").animate({ width: "90%" }, 400, function () {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});

however in the function() is seems like this. isn't known or available, meaning console.log(this.modalWidth); results in undefined.

How can I use my this.property in my complete function?

Body:
When you pass in an anonymous function, it gets its own this variable.

The quickest way to get around this would be to create a closure reference to this in the outer scope, and use the reference variable inside your callback.

var self = this;
$("#edit-modal").animate({ width: "90%" }, 400, function () {
    self.registrationsPanelWidth = $("#edit-modal").width() - self.modalWidth - 20;
    console.log(self.modalWidth);
});

This is a perfect use case for ES6 arrow functions, by the way. From the documentation on MDN:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

If you're able to use arrow functions in your project, it would look like this:

$("#edit-modal").animate({ width: "90%" }, 400, () => {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});

See the documentation on MDN for more information on arrow functions.


问:
Get TYPO3 Extbase mm relation count
We created a simple mm relation between to models like so:

```<code><?php
namespace VENDOR\COMPANY\Domain\Model;

class Posts extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{

//..

 /**
   * users
   *
   * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\VENDOR\COMPANY\Domain\Model\Users>
   */
   protected $likedBy = null;

 //..

}
</code>```

The MySQL database creates a new mm table and also creates a counter column users in the ..domain_post table. Is there a "lighter" way to get this counting than call all related users and count them?

```<code>$amountLikes = $post->getLikedBy()->count();
</code>```

Imagine a list of posts with ~ 30000 likes each. The script starts to build up 30000 objects in the memory. Asking the posts table for the number sounds more realistic to me. But how to?

答:
Extbase Repositories got countAll() / countByProperty() by default. You can also add your own functions to the repository for just returning the object count of any query.

You may try something like this in your controller:

```<code>$amountLikes = $this->usersRepository->countByLikedPosts($anyPost);
</code>```

This requires that your Users-model got something like a backreference property (like "likedPosts") to all posts that has been liked by a user.

Edit:
The likedPosts-property of users must be an Objectstorage, too. Because of this, the default countByXy function maybe does not work because Objectstorages requires contains()-constraints in a repository. So you may have to add your own function to the usersRespository - something like this:

```<code>public function countByLikedPost($post) {
    $query = $this->createQuery();
    return $query->matching($query->contains('likedPosts',$post))->count();
}
</code>```

Title: Get TYPO3 Extbase mm relation count

Body:
We created a simple mm relation between to models like so:

<?php
namespace VENDOR\COMPANY\Domain\Model;

class Posts extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{

//..

 /**
   * users
   *
   * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\VENDOR\COMPANY\Domain\Model\Users>
   */
   protected $likedBy = null;

 //..

}

The MySQL database creates a new mm table and also creates a counter column users in the ..domain_post table. Is there a "lighter" way to get this counting than call all related users and count them?

$amountLikes = $post->getLikedBy()->count();

Imagine a list of posts with ~ 30000 likes each. The script starts to build up 30000 objects in the memory. Asking the posts table for the number sounds more realistic to me. But how to?

Body:
Extbase Repositories got countAll() / countByProperty() by default. You can also add your own functions to the repository for just returning the object count of any query.

You may try something like this in your controller:

$amountLikes = $this->usersRepository->countByLikedPosts($anyPost);

This requires that your Users-model got something like a backreference property (like "likedPosts") to all posts that has been liked by a user.

Edit:
The likedPosts-property of users must be an Objectstorage, too. Because of this, the default countByXy function maybe does not work because Objectstorages requires contains()-constraints in a repository. So you may have to add your own function to the usersRespository - something like this:

public function countByLikedPost($post) {
    $query = $this->createQuery();
    return $query->matching($query->contains('likedPosts',$post))->count();
}


问:
Entity framework migrations throws exception when using extension method for fluent API
I'm using Entity Framework 6, Code-First with Fluent-API.

I have the following extension method to set the primary key on my entities:

```<code>public static class ConfigurationExtensions
{
    public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
        where TEntityType : class, IEntity
    {
        configuration
            .HasKey(m => m.Id)
            .Property(t => t.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}
</code>```

with every Code-First Entity implementing the following simple interface:

```<code>public interface IEntity
{
    int Id { get; }
}
</code>```

Now suppose I have the following Entity:

```<code>public class MyEntity : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

which I'm configuring with Fluent-API in my DbContext

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new MyEntityConfiguration());
}
</code>```

with the configuration class for the entity:

```<code>public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        this.HasPrimaryKey()
    }
}
</code>```

Oddly when I execute Add-Migration in the Package Manager Console I get the following exception:

```<code>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The property 'Id' cannot be used as a key property on the entity 'MyEntity' because the property type is not a valid key type. Only scalar types, string and byte[] are supported key types.
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(PropertyInfo propertyInfo, Nullable`1 overridableConfigurationParts)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(IEnumerable`1 keyProperties)
   at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.HasKey[TKey](Expression`1 keyExpression)
   at ConfigurationExtensions.HasPrimaryKey[TEntityType](EntityTypeConfiguration`1 configuration) in C:\path\ConfigurationExtensions.cs
</code>```

It is odd because when I refactor the code in the extension method back into the constructor, like this:

```<code>public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        HasKey(m => m.Id)
        .Property(t => t.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}
</code>```

then, the exception is not thrown by the framework and everything works as expected. Why? Framework bug?

答:
The exception message is misleading. The actual issue is quite trivial. EF supports only properties that have a property setter.

Since the expression m => m.Id in your generic extension method binds to the Id property of the IEntity interface, which has no setter (in contrast with the implementing class), EF does not consider it a valid property and throws the exception with the misleading message about property type.

To fix it, simply define setter for the Id property inside the interface:

```<code>public interface IEntity
{
    int Id { get; set; }
}
</code>```

It can also be resolved by building the lambda expression manually using the Expression class methods, but I think modifying the interface is easier :) But here it is for completeness and in case you don't want to break your interface design:

```<code>public static class ConfigurationExtensions
{
    public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
        where TEntityType : class, IEntity
    {
        var parameter = Expression.Parameter(typeof(TEntityType), "m");
        var keyProperty = Expression.Lambda<Func<TEntityType, int>>(Expression.Property(parameter, nameof(IEntity.Id)), parameter);
        configuration
            .HasKey(keyProperty)
            .Property(keyProperty)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}
</code>```

Body:
I'm using Entity Framework 6, Code-First with Fluent-API.

I have the following extension method to set the primary key on my entities:

public static class ConfigurationExtensions
{
    public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
        where TEntityType : class, IEntity
    {
        configuration
            .HasKey(m => m.Id)
            .Property(t => t.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

with every Code-First Entity implementing the following simple interface:

public interface IEntity
{
    int Id { get; }
}

Now suppose I have the following Entity:

public class MyEntity : IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}

which I'm configuring with Fluent-API in my DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new MyEntityConfiguration());
}

with the configuration class for the entity:

public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        this.HasPrimaryKey()
    }
}

Oddly when I execute Add-Migration in the Package Manager Console I get the following exception:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The property 'Id' cannot be used as a key property on the entity 'MyEntity' because the property type is not a valid key type. Only scalar types, string and byte[] are supported key types.
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(PropertyInfo propertyInfo, Nullable`1 overridableConfigurationParts)
   at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Key(IEnumerable`1 keyProperties)
   at System.Data.Entity.ModelConfiguration.EntityTypeConfiguration`1.HasKey[TKey](Expression`1 keyExpression)
   at ConfigurationExtensions.HasPrimaryKey[TEntityType](EntityTypeConfiguration`1 configuration) in C:\path\ConfigurationExtensions.cs

It is odd because when I refactor the code in the extension method back into the constructor, like this:

public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
    public MyEntityConfiguration()
    {
        HasKey(m => m.Id)
        .Property(t => t.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

then, the exception is not thrown by the framework and everything works as expected. Why? Framework bug?

Body:
The exception message is misleading. The actual issue is quite trivial. EF supports only properties that have a property setter.

Since the expression m => m.Id in your generic extension method binds to the Id property of the IEntity interface, which has no setter (in contrast with the implementing class), EF does not consider it a valid property and throws the exception with the misleading message about property type.

To fix it, simply define setter for the Id property inside the interface:

public interface IEntity
{
    int Id { get; set; }
}

It can also be resolved by building the lambda expression manually using the Expression class methods, but I think modifying the interface is easier :) But here it is for completeness and in case you don't want to break your interface design:

public static class ConfigurationExtensions
{
    public static void HasPrimaryKey<TEntityType>(this EntityTypeConfiguration<TEntityType> configuration)
        where TEntityType : class, IEntity
    {
        var parameter = Expression.Parameter(typeof(TEntityType), "m");
        var keyProperty = Expression.Lambda<Func<TEntityType, int>>(Expression.Property(parameter, nameof(IEntity.Id)), parameter);
        configuration
            .HasKey(keyProperty)
            .Property(keyProperty)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}


问:
True memory locations of C variables
In an effort to learn more about C, I have been playing with it for the past 2 days. I wanted to start looking at how C is structured during runtime so, I built a crappy program that asks a user for two integer values, then prints the memory location of the integer variables. I then want to verify that the data is actually there so, I have the program suspended with getchar() in order to open up GDB and mine the memory segment to verify the data but, the data at those locations is not making much sense to me. Can someone please explain what is going on here.

Program Code:

```<code>#include <stdio.h>

void pause();

int main() {
   int a, b;
   printf("Please enter number one:");
   scanf("%d", &a);
   printf("Please enter number two:");
   scanf("%d", &b);
   printf("number one is %d, number two is %d\n", a, b);
  // find the memory location of vairables:
   printf("Address of 'a' %pn\n", &a);
   printf("Address of 'b' %pn\n", &b);
   pause();
}

void pause() {
   printf("Please hit enter to continue...\n");
   getchar();
   getchar();
}
</code>```

Output:

```<code>[josh@TestBox c_code]$ ./memory
Please enter number one:265
Please enter number two:875
number one is 265, number two is 875
Address of 'a' 0x7fff9851314cn
Address of 'b' 0x7fff98513148n
Please hit enter to continue...
</code>```

GDB Hex dump of memory Segments:

```<code>(gdb) dump memory ~/dump2.hex 0x7fff98513148 0x7fff98513150

[josh@TestBox ~]$ xxd dump2.hex
0000000: 6b03 0000 0901 0000                      k.......
</code>```

答:
6b030000 and 09010000 are little-endian (least significant byte first). To read them in a more natural fashion, reverse the order of the bytes:

6b030000 => 0000036b => 875 in decimal

09010000 => 00000109 => 265 in decimal

Title: True memory locations of C variables

Body:
In an effort to learn more about C, I have been playing with it for the past 2 days. I wanted to start looking at how C is structured during runtime so, I built a crappy program that asks a user for two integer values, then prints the memory location of the integer variables. I then want to verify that the data is actually there so, I have the program suspended with getchar() in order to open up GDB and mine the memory segment to verify the data but, the data at those locations is not making much sense to me. Can someone please explain what is going on here.

Program Code:

#include <stdio.h>

void pause();

int main() {
   int a, b;
   printf("Please enter number one:");
   scanf("%d", &a);
   printf("Please enter number two:");
   scanf("%d", &b);
   printf("number one is %d, number two is %d\n", a, b);
  // find the memory location of vairables:
   printf("Address of 'a' %pn\n", &a);
   printf("Address of 'b' %pn\n", &b);
   pause();
}

void pause() {
   printf("Please hit enter to continue...\n");
   getchar();
   getchar();
}

Output:

[josh@TestBox c_code]$ ./memory
Please enter number one:265
Please enter number two:875
number one is 265, number two is 875
Address of 'a' 0x7fff9851314cn
Address of 'b' 0x7fff98513148n
Please hit enter to continue...

GDB Hex dump of memory Segments:

(gdb) dump memory ~/dump2.hex 0x7fff98513148 0x7fff98513150

[josh@TestBox ~]$ xxd dump2.hex
0000000: 6b03 0000 0901 0000                      k.......


问:
Using Traits to cover implementation requirements of Interfaces
Recently i came across multiple articles that are implying using Traits to cover implementation of Interfaces.
Example:

```<code>interface ArticleInterface
{
    /**
     * @return mixed
     */
    public function getTitle();
}

trait ArticleTrait
{
   /**
     * @return string
     */
    public function getTitle()
    {
        return "article_title";
    }
}

abstract class AbstractArticle implements ArticleInterface
{
    use ArticleTrait;
}
</code>```

Some even think that Traits implementing Interfaces should be available in PHP core.

Therefore i am trying to get a proper response on a question if this design pattern should be followed ?
If yes, should PHPDoc description be written in both interface and trait (meaning it will be duplicated) ?
Any other details that i should take notice of when using this design ?

答:
Traits provide for compiler-assisted copy-and-paste. They are a form of code re-use. While class inheritance gives you code re-use vertically (child classes share code defined in their parents), traits give you code re-use horizontally: interface-sharing classes can use code defined in the trait.

So, yes, if you have multiple siblings sharing the same interface and implementation, then you may use traits to reduce code duplication. But, no, if you have only one class implementing an interface - as in your example - then traits add undeserved complexity.

I'd like to add one important point: traits don't, themselves, store state. Any member variable in the trait will ultimately be stored in the object consuming the trait. If you have some state information that should be considered "private" to the trait (and therefore unavailable in the object), then don't use traits for re-use. Instead, use service delegates.

Body:
Recently i came across multiple articles that are implying using Traits to cover implementation of Interfaces.
Example:

interface ArticleInterface
{
    /**
     * @return mixed
     */
    public function getTitle();
}

trait ArticleTrait
{
   /**
     * @return string
     */
    public function getTitle()
    {
        return "article_title";
    }
}

abstract class AbstractArticle implements ArticleInterface
{
    use ArticleTrait;
}

Some even think that Traits implementing Interfaces should be available in PHP core.

Therefore i am trying to get a proper response on a question if this design pattern should be followed ?
If yes, should PHPDoc description be written in both interface and trait (meaning it will be duplicated) ?
Any other details that i should take notice of when using this design ?


问:
How can I check HttpListenerRequest connection is still open?
I want to check if the connection is still open. If it isn't, I'll stop the process.

```<code>         //Process request code goes here

         while (!isComplete) {
            //Check HttpListenerRequest if connection is still open...

            if (IsTimedOut && !timeoutTriggered)
            {
                timeoutTriggered = triggerTimeout();
            }

            Thread.Sleep(100);
        }
        stopWatch.Stop();
        //Process response code goes here
</code>```

How can I do that?

答:
I've resolved the problem with a write/flush pair.
Flush throws an exception when the connection has closed.</p>

```<code>try
{
    //Checks whether the connection is still open
    var encoding = Encoding.Default;
    byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encoding.GetBytes(" "));
    listenerContext.Response.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
    listenerContext.Response.OutputStream.Flush();
}
catch (Exception e)
{
    Console.WriteLine(e);
    eventStream.TriggerEvent(new ActionEventArgs(this, ActionEventStreamer.SYSTEM_CANCEL));
    break;
}
</code>```

Body:
I want to check if the connection is still open. If it isn't, I'll stop the process.

         //Process request code goes here

         while (!isComplete) {
            //Check HttpListenerRequest if connection is still open...

            if (IsTimedOut && !timeoutTriggered)
            {
                timeoutTriggered = triggerTimeout();
            }

            Thread.Sleep(100);
        }
        stopWatch.Stop();
        //Process response code goes here

How can I do that?

Body:
I've resolved the problem with a write/flush pair.
Flush throws an exception when the connection has closed.

try
{
    //Checks whether the connection is still open
    var encoding = Encoding.Default;
    byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encoding.GetBytes(" "));
    listenerContext.Response.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
    listenerContext.Response.OutputStream.Flush();
}
catch (Exception e)
{
    Console.WriteLine(e);
    eventStream.TriggerEvent(new ActionEventArgs(this, ActionEventStreamer.SYSTEM_CANCEL));
    break;
}


问:
Convert com.google.gson.JsonObject to org.json.simple.JSONObject
Simple but tricky, how could I convert com.google.gson.JsonObject to org.json.simple.JSONObject without know the inner properties or manually parsing?

答:
My solution so far is use org.json.simple.parser.JSONParser to do it:

```<code>(JSONObject) new JSONParser().parse("{...}"); // JSON string generated via `com.google.gson.Gson`
</code>```

Enjoy!

Body:
My solution so far is use org.json.simple.parser.JSONParser to do it:

(JSONObject) new JSONParser().parse("{...}"); // JSON string generated via `com.google.gson.Gson`

Enjoy!


问:
How to describe object in Mongoose schema to store any property including defined?
How to describe object in Mongoose schema to store any property including defined property that should be indexed?

I have Mongoose schema with structure like this:

{
    a: { type: Object, require: true }
}```
</div>
</div>
</p>

<p>I don't know all fields in object <code>a</code> but I know it contain string <code>b</code>, and I should create index at this field.</p>

<p>I can do something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
    a: {
        b: { type: String, require: true, index: true }
    }
}</code>```

But in this case other properties of object a will be lost.

答:
You can define index on schema level:</p>

```<code>yourSchema.index({ "a.b": 1, type: 1 });
</code>```

Body:
How to describe object in Mongoose schema to store any property including defined property that should be indexed?

I have Mongoose schema with structure like this:

{
    a: { type: Object, require: true }
}

I don't know all fields in object a but I know it contain string b, and I should create index at this field.

I can do something like this:

{
    a: {
        b: { type: String, require: true, index: true }
    }
}

But in this case other properties of object a will be lost.

Body:
You can define index on schema level:

yourSchema.index({ "a.b": 1, type: 1 });


问:
Exception while parsing wsdl
```<code>Description Resource    Path    Location    Type
WS-I: A problem occured while running the WS-I WSDL conformance check:
org.eclipse.wst.wsi.internal.analyzer.WSIAnalyzerException: null

  Nested exception is:

  java.lang.NullPointerException
The WSDLAnalyzer was unable to validate the given WSDL File.
ChangedElements.wsdl    /wstest/WebContent/wsdl line 1  WSDL Problem
</code>```

Update:

Netbeans gives this error:

```<code>cvc-elt.1: Cannot find the declaration of element 'wsdl:definitions'. [7]
</code>```

The part of wsdl:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                    xmlns:tns="http://www.example.org/xxx/"
                    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    name="xxx"
                    targetNamespace="http://www.example.org/xxx/">
</code>```

答:
I'm having the same issue and it appears to be mainly on referencing dotnet WCF and WSE services.

The only thing I have found to work is to build up the WSDL manually.

ContentLicense: CC BY-SA 2.5

Title: Exception while parsing wsdl

Body:
Description Resource    Path    Location    Type
WS-I: A problem occured while running the WS-I WSDL conformance check:
org.eclipse.wst.wsi.internal.analyzer.WSIAnalyzerException: null

  Nested exception is:

  java.lang.NullPointerException
The WSDLAnalyzer was unable to validate the given WSDL File.
ChangedElements.wsdl    /wstest/WebContent/wsdl line 1  WSDL Problem

Update:

Netbeans gives this error:

cvc-elt.1: Cannot find the declaration of element 'wsdl:definitions'. [7]

The part of wsdl:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions   xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                    xmlns:tns="http://www.example.org/xxx/"
                    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    name="xxx"
                    targetNamespace="http://www.example.org/xxx/">


问:
span tag text-align not working
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="price">
  <span class="previous-price"><s>Tk. 350000</s></span>
   <span class="present-price">Tk. 227500</span>
   <span class="discount-price">(35% OFF)</span>
  </p></code>```

答:
See my answer for CSS text-align does not work

    .previous-price {
        float: left;
    }
    .present-price {
        text-align: center;
    }
    .discount-price {
        float:right;
    } ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <p class="price">
        <span class="previous-price"><s>Tk. 350000</s></span>
        <span class="discount-price">(35% OFF)</span>
        <div class="present-price">Tk. 227500</div>

    </p></code>```

Plus you should really try to write correct html. Tk. 227500
 is certainly invalid. Just because most browsers give you a lot of leeway, you should try nevertheless to write correct code.

Title: span tag text-align not working

Body:
I'm trying to make a line for price and I want the text-align like the first one on the left, second one on the center and the third one will be on right.

Normally the text-align works but I can't keep all three of them in them in the same line. Should I use something different? or there's a solution for this!?

First I tried like this:

.price span {
  display: inline;
  /* also tried with block and inline-block */
}

.previous-price {
  text-align: left;
}

.present-price {
  text-align: center;
}

.discount-price {
  text-align: right;
}

  <s>Tk. 350000</s>
   Tk. 227500
   (35% OFF)

Body:
See my answer for CSS text-align does not work

    .previous-price {
        float: left;
    }
    .present-price {
        text-align: center;
    }
    .discount-price {
        float:right;
    }

    <p class="price">
        <span class="previous-price"><s>Tk. 350000</s></span>
        <span class="discount-price">(35% OFF)</span>
        <div class="present-price">Tk. 227500</div>

    </p>

Plus you should really try to write correct html. <span class="present-price">Tk. 227500</p> is certainly invalid. Just because most browsers give you a lot of leeway, you should try nevertheless to write correct code.


问:
How to transpose Excel columns into a new range ignoring blank cells
I'm new at VBA and tried finding already existing solutions but none answered fully my requirements:

My initial list has holes (blanks) and I need to list the results as transposed without these blank fields

column A has files # and then 5 columns with prices but some are having only one price others 2 others 3 etc but never more than 3 prices. And these are varying from one month to another with hundred lines of it.

My first trials were no success as I couldn't find the totals expected.
My initial code was the following but it doesn't catch last 2 columns as there are blank fields in between:

```<code>Dim LR As Long, Rw As Long, Col As Long, LastCol As Long, CurRw As Long
Application.ScreenUpdating = False

LR = Range("A" & Rows.Count).End(xlUp).Row
Range("B:B").Insert xlShiftToRight

For Rw = LR To 2 Step -1
    If Range("D" & Rw) <> "" Then
        LastCol = Cells(Rw, Columns.Count).End(xlToLeft).Column
        Rows(Rw + 1).Resize(LastCol - 3).Insert xlShiftDown
        Range("A" & Rw).Resize(LastCol - 2) = Range("A" & Rw)
        Range("B" & Rw).Resize(LastCol - 2).Value = Range("C" & Rw).Resize(LastCol + 5).Value
        Range("C" & Rw).Resize(1, LastCol - 2).Copy
        Range("B" & Rw).Resize(LastCol - 2).PasteSpecial xlPasteAll, Transpose:=True
        Range("C1").Resize(1, LastCol - 2).Copy
        Range("C" & Rw).PasteSpecial xlPasteAll, Transpose:=True
    Else
        Range("C" & Rw).Copy Range("B" & Rw)
        Range("C1").Copy Range("C" & Rw)
    End If
Next Rw"
</code>```

Thanks for your help. wishing this is now easier to understand and assist ;-)

Result to reach:

答:
using your image with file in A1, would be along these lines

```<code>Sub Example()

    Range("b2").Resize(1, 10).SpecialCells(xlCellTypeConstants, xlNumbers).Copy
    Range("m2").Value = Range("b2").Resize(1, 10).SpecialCells(xlCellTypeConstants, xlNumbers).Count
    Range("n2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=True

End Sub
</code>```

count will be in M and Transposed in N

Body:
I'm new at VBA and tried finding already existing solutions but none answered fully my requirements:

My initial list has holes (blanks) and I need to list the results as transposed without these blank fields

column A has files # and then 5 columns with prices but some are having only one price others 2 others 3 etc but never more than 3 prices. And these are varying from one month to another with hundred lines of it.

My first trials were no success as I couldn't find the totals expected.
My initial code was the following but it doesn't catch last 2 columns as there are blank fields in between:

Dim LR As Long, Rw As Long, Col As Long, LastCol As Long, CurRw As Long
Application.ScreenUpdating = False

LR = Range("A" & Rows.Count).End(xlUp).Row
Range("B:B").Insert xlShiftToRight

For Rw = LR To 2 Step -1
    If Range("D" & Rw) <> "" Then
        LastCol = Cells(Rw, Columns.Count).End(xlToLeft).Column
        Rows(Rw + 1).Resize(LastCol - 3).Insert xlShiftDown
        Range("A" & Rw).Resize(LastCol - 2) = Range("A" & Rw)
        Range("B" & Rw).Resize(LastCol - 2).Value = Range("C" & Rw).Resize(LastCol + 5).Value
        Range("C" & Rw).Resize(1, LastCol - 2).Copy
        Range("B" & Rw).Resize(LastCol - 2).PasteSpecial xlPasteAll, Transpose:=True
        Range("C1").Resize(1, LastCol - 2).Copy
        Range("C" & Rw).PasteSpecial xlPasteAll, Transpose:=True
    Else
        Range("C" & Rw).Copy Range("B" & Rw)
        Range("C1").Copy Range("C" & Rw)
    End If
Next Rw"

Thanks for your help. wishing this is now easier to understand and assist ;-)

Result to reach:

Body:
using your image with file in A1, would be along these lines

Sub Example()

    Range("b2").Resize(1, 10).SpecialCells(xlCellTypeConstants, xlNumbers).Copy
    Range("m2").Value = Range("b2").Resize(1, 10).SpecialCells(xlCellTypeConstants, xlNumbers).Count
    Range("n2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=True

End Sub

count will be in M and Transposed in N


问:
Scrapy keeps return empty value
I'm scraping http://www.germandeli.com/Meats/Sausages

I would like to extract the link for every product(or item) from the page. I use scrapy shell to test but it keeps return the empty value [ ].

Here is the code I use:

```<code>response.xpath('*//h2[@class="item-cell-name"]/a/@href')
</code>```

Any helps would be greatly appreciated.

答:
Well unfortunately the item content is rendered through JS. But luckily the URL sends a AJAX request to fetch a JSON of the items. This makes it much easier for us to parse it. You can check the XHR tab in the google chrome console to imitate the request with the required headers.

This URL returns the list of products. The limit and the offset parameters in the URL can be played around with to fetch the next set of data. Also to parse the JSON content you can use json.loads from the standard library.

Title: Scrapy keeps return empty value

Body:
I'm scraping http://www.germandeli.com/Meats/Sausages

I would like to extract the link for every product(or item) from the page. I use scrapy shell to test but it keeps return the empty value [ ].

Here is the code I use:

response.xpath('*//h2[@class="item-cell-name"]/a/@href')

Any helps would be greatly appreciated.


问:
SVG getTotalLength() won't return the right size for non-scaling-stroke - get SVG scale
I'm using javascript to get a path length and apply half of it to the stroke-DashArray. My problem is that I use vector-effect="non-scaling-stroke" so that no mather the scale, it allways keeps a stroke-width:2px; The non-scaling seems to affect every part of the stroke properties including the DashArray so I need to get the scale of the svg to then scale path.getTotalLength();.

Is there a way to get the SVG computed scale using javascript to use as multiplier of the path lenght?

I made a codepen.io to demonstrate the issue. Just resize the view port to see the stroke change.

答:
I think that you must divide the viewbox size / SVG width

  <!doctype html>

    <meta charset="UTF-8">
    <title>Document</title>

    <button onclick="dashAni(myPath, 50, 3500)">start</button>
    <svg id="mySVG"  width="200" height="200" viewBox="0 0 500 500">
        <path
        vector-effect="non-scaling-stroke"
        id="myPath" d="M 50,250 c 0 -100   150 -100   200 0
                                      c 50 100   200 100   200 0
                                      c -0 -100   -150 -100   -200 0
                                      c -50 100   -200 100   -200 0
                                      z"
        stroke="#eee"
        stroke-width="5" fill="none" />
    </svg>

  ```

Body:
I think that you must divide the viewbox size / SVG width

  <!doctype html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>
    <button onclick="dashAni(myPath, 50, 3500)">start</button>
    <svg id="mySVG"  width="200" height="200" viewBox="0 0 500 500">
        <path
        vector-effect="non-scaling-stroke"
        id="myPath" d="M 50,250 c 0 -100   150 -100   200 0
                                      c 50 100   200 100   200 0
                                      c -0 -100   -150 -100   -200 0
                                      c -50 100   -200 100   -200 0
                                      z"
        stroke="#eee"
        stroke-width="5" fill="none" />
    </svg>
    <script>
      var dashAni = function(path, length, duration){
        var dashPath = path.cloneNode(true);
        mySVG.appendChild(dashPath);
        var pathLen=path.getTotalLength()/2.5;
        var aktPos=0
        var sumSteps = duration / (1000/60) // 60 pics per second
        var step=0;
        var pathAnim;
        dashPath.setAttribute('stroke-dasharray', length + ' ' + (pathLen - length));
        dashPath.setAttribute('stroke', "red");
        dashPath.setAttribute('stroke-dashoffset', aktPos);

        var anim=function(){
           aktPos = pathLen/sumSteps*step*-1;
            //aktLen = easeInOutQuad(step/sumSteps)*len;
           dashPath.setAttribute('stroke-dasharray', length + ' ' + pathLen);
           dashPath.setAttribute('stroke-dashoffset', aktPos);

           if (step <= (sumSteps)){
            step++;
            pathAnim = setTimeout(anim, 1000/60) //1000/60 pics/second
            } else {
              mySVG.removeChild(dashPath);
              clearTimeout(pathAnim);
            }
        }
       anim();
      }
    </script>
  </body>
  </html>


问:
Right click to query temporal tables not working
I have SQL Server Management Studio 2016 loaded with Microsoft's test database (WideWorldImporters) but for some reason, any table that is a temporal table does not give me the option of right clicking and selecting the last 1000 rows as all other non-temporal tables allow. </p>

<p>Am I missing something which needs to be installed or is there an alternative way of querying the table for data? </p>

答: Right Clicking does not work. But in the session that created the table you can do any kind of query that can be done against any other table.</p>

Body:
I have SQL Server Management Studio 2016 loaded with Microsoft's test database (WideWorldImporters) but for some reason, any table that is a temporal table does not give me the option of right clicking and selecting the last 1000 rows as all other non-temporal tables allow.

Am I missing something which needs to be installed or is there an alternative way of querying the table for data?


问:
Buttons won't go side by side
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

```<code><div class="navbar navbar-default navbar-fixed-top">
                    <div class="navbar-header">
                        <button type="button" id="searchbuttonmobile" ><img src="~/Images/SearchBtn.png" /></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">
                            <img src="~/Images/MobileMenuBtn.png" />
                        </button>
</div>
</code>```

CSS:

```<code>/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}
</code>```

答: Change display: block to display: inline-block in .navbar-toggle

Title: Buttons won't go side by side

Body:
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

                        <button type="button" id="searchbuttonmobile" ></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">

                        </button>

CSS:

/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}


问:
Missing argument 'toptext' for parameter in call
```<code>import UIKit
import Foundation

struct MemeModel{
    var topText:String
    var bottomText:String
    var originalImage:UIImage!
    var memedImage:UIImage
   }

struct MemeCollection{

    func getMemeStorage() ->AppDelegate{
        let appDelegate = UIApplication.shared.delegate
        return appDelegate as!AppDelegate
    }

    //get memeModel count number
    func count() ->Int{
        return getMemeStorage().memes.count
    }

    //append meme
    func addMeme(Meme meme:MemeModel){
        print("meme added")
        getMemeStorage().memes.append(meme)
        print(getMemeStorage().memes.count)
    }

    //getMeme
    func getMeme(index:Int)->MemeModel{
        return getMemeStorage().memes[index]
    }

 }
</code>```

When I declare a MemeModel in this way in detailViewcontroller:

```<code>var detailmemecontroller = MemeModel()
</code>```

the compiler complains with the following:

missing argument 'toptext' for paramenter in call.

There is no complaint if I declare a memeCollection this way:

```<code>var memeCollection = Memecollection()
</code>```

What do I need to do?

https://github.com/zetaosun/Udacity_meme

答:
MemeCollection has no mandatory variables and MemeModel has 4 mandatory variables topText, bottomText originalImage and memedImage. So if you add any mandatory variable in MemeCollection you will also get the same error there.

To fix the error for MemeModel. You have two options.

Option 1  Either pass all the mandatory parameters like this.

```<code>var detailmemecontroller = MemeModel(topText: "", bottomText: "", originalImage: UIImage.init(), memedImage: UIImage.init())
</code>```

Option 2 Make all variables optionals.

```<code>struct MemeModel{
    var topText:String?
    var bottomText:String?
    var originalImage:UIImage?
    var memedImage:UIImage?
}
</code>```

Body:
import UIKit
import Foundation

struct MemeModel{
    var topText:String
    var bottomText:String
    var originalImage:UIImage!
    var memedImage:UIImage
   }

struct MemeCollection{

    func getMemeStorage() ->AppDelegate{
        let appDelegate = UIApplication.shared.delegate
        return appDelegate as!AppDelegate
    }

    //get memeModel count number
    func count() ->Int{
        return getMemeStorage().memes.count
    }

    //append meme
    func addMeme(Meme meme:MemeModel){
        print("meme added")
        getMemeStorage().memes.append(meme)
        print(getMemeStorage().memes.count)
    }

    //getMeme
    func getMeme(index:Int)->MemeModel{
        return getMemeStorage().memes[index]
    }

 }

When I declare a MemeModel in this way in detailViewcontroller:

var detailmemecontroller = MemeModel()

the compiler complains with the following:

missing argument 'toptext' for paramenter in call.

There is no complaint if I declare a memeCollection this way:

var memeCollection = Memecollection()

What do I need to do?

https://github.com/zetaosun/Udacity_meme

Body:
MemeCollection has no mandatory variables and MemeModel has 4 mandatory variables topText, bottomText originalImage and memedImage. So if you add any mandatory variable in MemeCollection you will also get the same error there.

To fix the error for MemeModel. You have two options.

Option 1  Either pass all the mandatory parameters like this.

var detailmemecontroller = MemeModel(topText: "", bottomText: "", originalImage: UIImage.init(), memedImage: UIImage.init())

Option 2 Make all variables optionals.

struct MemeModel{
    var topText:String?
    var bottomText:String?
    var originalImage:UIImage?
    var memedImage:UIImage?
}


问:
Are there any databases that support protocol buffers?
Are there any databases, in either the SQL or NoSQL worlds, that support protocol buffers?  (Support could mean various things, but hopefully would include being able to index on fields in protocol buffers.)</p>

答:
Here is a project I found: https://github.com/google/mysql-protobuf

It's sql that speaks protobuf, looks promising but last commit was in mid March 2016.


问:
How to save and return to newly created item in previous page?
I have an interactive report and a form associated to it. After creating a new entry using the form, my end-users want to put the focus on that specific new entry in the interactive report (it's a lot of entrys, and today they need to scroll down a lot to see the new one).

They also want the same funcionality when updating a row of the report.

How can I do this the correct way in APEX 5.1?

答:
Interesting question, another solution:

Create a item in your report page, something like P3_ANCHOR

Add data-anchor="#< YOUR_COLUMN_ID >#" to your report link attribute

Configure your form page to return the created/modified item id to item P3_ANCHOR in your report page.

Create a Dynamic Action on report page

Action: Execute Javascript Code

Code:

```<code>var container = $('body'),
    scrollTo = $('[data-anchor="'+$v('P3_ANCHOR')+'"]');

container.animate({
    scrollTop: scrollTo.offset().top - $(document).scrollTop()
}, 2000);
</code>```

Body:
Interesting question, another solution:

Create a item in your report page, something like P3_ANCHOR

Add data-anchor="#< YOUR_COLUMN_ID >#" to your report link attribute

Configure your form page to return the created/modified item id to item P3_ANCHOR in your report page.

Create a Dynamic Action on report page

Action: Execute Javascript Code

Code:

var container = $('body'),
    scrollTo = $('[data-anchor="'+$v('P3_ANCHOR')+'"]');

container.animate({
    scrollTop: scrollTo.offset().top - $(document).scrollTop()
}, 2000);


问:
Problem rotating simple line image
It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point.
Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.

Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):

```<code>x0:=200;
y0:=200;

  bx:=StrToInt(Edit1.Text);
  by:=StrToInt(Edit2.Text);
  cx:=StrToInt(Edit4.Text);
  cy:=StrToInt(Edit5.Text);
  a:=StrToInt(Edit3.Text);

  //Original triangle

  Form1.Canvas.Pen.Color:=clBlue;
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(bx,by);
  Form1.Canvas.LineTo(cx,cy);
  Form1.Canvas.LineTo(x0,y0);

  //New triangle
  Form1.Canvas.Pen.Color:=clGreen;
  Form1.Canvas.MoveTo(x0,y0);
  b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));
  b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
  c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180));
  c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
  Form1.Canvas.LineTo(b1x,b1y);
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(c1x,c1y);
  Form1.Canvas.LineTo(b1x,b1y);

end;
</code>```

Well, I'm out of ideas. What am I doing wrong?

Thanks for your time.

答: You appear to be rotating each individual line round its initial start point coordinates. So line 1 will get rotated about its start point (x0,y0); then line 2 will get rotated about bx,by; then line 3 will get rotated round cx. This will result in a twisted triangle. Instead you will need to rotate all three lines round the start point of the first line.</p>

Title: Problem rotating simple line image

Body:
It is stated, that to rotate a line by a certain angle, you multiply its end point coordinates by the matrix ({Cos(a), Sin(a)} {-Sin(a) Cos(a)}), where a is rotation angle. The resulting two numbers in matrix will be x and y coordinates of rotated line's end point. Rotation goes around line's start point.
Simplifying it, new coordinates will be {x*Cos(a) - y*Sin(a)} for x and {x*Sin(a) + y*Cos(a)} for y.

Task is to rotate a triangle, using this method. But the following code that uses this method, is giving out some crap instead of rotated image (twisted form of original triangle, rotated by "random" angle):

x0:=200;
y0:=200;

  bx:=StrToInt(Edit1.Text);
  by:=StrToInt(Edit2.Text);
  cx:=StrToInt(Edit4.Text);
  cy:=StrToInt(Edit5.Text);
  a:=StrToInt(Edit3.Text);

  //Original triangle

  Form1.Canvas.Pen.Color:=clBlue;
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(bx,by);
  Form1.Canvas.LineTo(cx,cy);
  Form1.Canvas.LineTo(x0,y0);

  //New triangle
  Form1.Canvas.Pen.Color:=clGreen;
  Form1.Canvas.MoveTo(x0,y0);
  b1x:=Round(bx*cos(a*pi/180)-by*sin(a*pi/180));
  b1y:=Round(bx*sin(a*pi/180)+by*cos(a*pi/180));
  c1x:=Round(cx*cos(a*pi/180)-cy*sin(a*pi/180));
  c1y:=Round(cx*sin(a*pi/180)+cy*cos(a*pi/180));
  Form1.Canvas.LineTo(b1x,b1y);
  Form1.Canvas.MoveTo(x0,y0);
  Form1.Canvas.LineTo(c1x,c1y);
  Form1.Canvas.LineTo(b1x,b1y);

end;

Well, I'm out of ideas. What am I doing wrong?

Thanks for your time.


问:
Set type for function parameters?
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

```<code>function myFunction(Date myDate, String myString)
{
    //do stuff
}
</code>```

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

答:
Use typeof or instanceof:

```<code>const assert = require('assert');

function myFunction(Date myDate, String myString)
{
    assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
    assert( myDate instanceof Date,         'Error message about incorrect arg type');
}
</code>```

Title: Set type for function parameters?

Body:
Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

function myFunction(Date myDate, String myString)
{
    //do stuff
}

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

Body:
Use typeof or instanceof:

const assert = require('assert');

function myFunction(Date myDate, String myString)
{
    assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
    assert( myDate instanceof Date,         'Error message about incorrect arg type');
}


问:
Mongodb: Not able to add new key in nested object
I have a schema in mongodb like

```<code>var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      education: String
    }
});
</code>```

Now i want to add a new property desgnName in profDtl

```<code>var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      desgnName: String, // trying to add new property
      education: String
    }
});
</code>```

but it is not reflected in database

答:
I got a solution for it, whenever add new property in mongodb schema, it required a default value to reflect on new entry

for Eg:

```<code>var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      desgnName: {
        type: String,
        default: ""
      },
      education: String
    }
});
</code>```

now its working fine

Body:
I have a schema in mongodb like

var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      education: String
    }
});

Now i want to add a new property desgnName in profDtl

var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      desgnName: String, // trying to add new property
      education: String
    }
});

but it is not reflected in database

Body:
I got a solution for it, whenever add new property in mongodb schema, it required a default value to reflect on new entry

for Eg:

var schema = new mongoose.Schema({
  agentCode: String,
  data: {
    type: Object,
    profDtl: {
      desgnName: {
        type: String,
        default: ""
      },
      education: String
    }
});

now its working fine


问:
Twilio answering machine detection not leaving message
We are leaving a voice message (using an MP3) using Twilio's answering machine detection. We are seeing in our logs the correct calls to/from the API (answered by answering machine, post of our recorded message)...no error.

But the persons were are testing on, only 1/4 are actually getting a voicemail. The rest receive no voicemail, even though the logs show the correct API calls...? What is happening here?

Here is the code to call the twiml.

```<code> if (Request.Form["AnsweredBy"] != null)
        {
            switch (Request.Form["AnsweredBy"])
            {
                case "machine_end_beep":
                case "machine_end_silence":
                case "machine_end_other":
                    SaveTwilioMessage(transaction.Campaign.Id.ToString());
                    //var machineResponse = new VoiceResponse();
                    if (!string.IsNullOrWhiteSpace(transaction.Campaign.VoicemailMessageUrl))
                    {
                        response.Play(transaction.Campaign.VoicemailMessageUrl);
                    }
                    else
                    {
                        response.Say(transaction.Campaign.VoicemailMessage, voice: _voice);
                    }
                    return new TwiMLResult(response);
                case "human":
                case "fax":
                case "unknown":
                default:
                    break;
            }
</code>```

And here is the call that generates this:

```<code> var call = await CallResource.CreateAsync(url: callbackUrl, to: new PhoneNumber(phoneNumber), from: new PhoneNumber(fromPhone),machineDetection: "DetectMessageEnd");
        var result = new TelephonicResource(call.Sid);
        return result;
</code>```

Any thoughts?

答:
Twilio developer evangelist here.

When using Twilio's answering machine detection you have two options for detecting a machine. You set answering machine detection to on by supplying a MachineDetection parameter to the REST API request to make a call.

The MachineDetection parameter can be either Enable or DetectMessageEnd. If you want to leave a message after the answering machine message is complete you need to use DetectMessageEnd.

Then, when you get the webhook callback for the start of the call you get an extra parameter, AnsweredBy, which is either machine_end_beep, machine_end_silence, machine_end_other, human, fax or unknown.

If you get machine_end_beep, machine_end_silence or machine_end_other then you should be able to leave your message then. For other results you can handle them as you would a normal call.

If you just use MachineDetection=Enable then Twilio will attempt to connect you to the call with the result as soon as it has figured out if it is human or machine. If you want to leave a message, I would not choose this option.

Let me know if this helps at all.

Body:
We are leaving a voice message (using an MP3) using Twilio's answering machine detection. We are seeing in our logs the correct calls to/from the API (answered by answering machine, post of our recorded message)...no error.

But the persons were are testing on, only 1/4 are actually getting a voicemail. The rest receive no voicemail, even though the logs show the correct API calls...? What is happening here?

Here is the code to call the twiml.

 if (Request.Form["AnsweredBy"] != null)
        {
            switch (Request.Form["AnsweredBy"])
            {
                case "machine_end_beep":
                case "machine_end_silence":
                case "machine_end_other":
                    SaveTwilioMessage(transaction.Campaign.Id.ToString());
                    //var machineResponse = new VoiceResponse();
                    if (!string.IsNullOrWhiteSpace(transaction.Campaign.VoicemailMessageUrl))
                    {
                        response.Play(transaction.Campaign.VoicemailMessageUrl);
                    }
                    else
                    {
                        response.Say(transaction.Campaign.VoicemailMessage, voice: _voice);
                    }
                    return new TwiMLResult(response);
                case "human":
                case "fax":
                case "unknown":
                default:
                    break;
            }

And here is the call that generates this:

 var call = await CallResource.CreateAsync(url: callbackUrl, to: new PhoneNumber(phoneNumber), from: new PhoneNumber(fromPhone),machineDetection: "DetectMessageEnd");
        var result = new TelephonicResource(call.Sid);
        return result;

Any thoughts?


问:
Video display in html
I am learning html, css, javascript for creating a simple website for learning purpose. I am able to display a video saved in my drive using video element in html page. I also want to display the title of the video, total length of the video, total views of the video in the same video. Please help me which part I need to concentrate more also where I can get information to learn these and able to display all the things I need in each video.

My html code:

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html lang = "en">
  <head>
  <title>Videos</title>
      <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="videos.css">
  </head>

<body>
   <header>
  <nav>
  <h1> Main logo </h1>
   <ul id="nav">
    <li>Home</li>
    <li>Videos</li>

 </ul>
 </nav>
 </header>
 <div class="divider"></div>
 <div id="navBar">

<ul>
 <li>education videos </li>
 <li>film videos</li>
 <li>other videos </li>
</ul>

 </div>
<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>

    <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

  </body>
</html></code>```

答:
You won't be able to keep track of views on the client-side (HTML, CSS, Javascript). Once a user leaves the page, that information is gone. You'll have to have some kind of back end to maintain that information (database, logging file, etc.)

As far as other metadata like the length of the video, that wouldn't be included in the native HTML5  tag. But you can just add that to the markup elsewhere.

Possible duplicate: How to display views on html5 video?

Title: Video display in html

Body:
I am learning html, css, javascript for creating a simple website for learning purpose. I am able to display a video saved in my drive using video element in html page. I also want to display the title of the video, total length of the video, total views of the video in the same video. Please help me which part I need to concentrate more also where I can get information to learn these and able to display all the things I need in each video.

My html code:

* {
 padding:0px;
 margin:0px;
}

body{
  margin: 0;
 }

header {
  background: green;
  color: white;
  padding: 8px 0px 6px 40px;
  height: 50px;
}

header h1 {
 display: inline;
 font-family: 'Oswald',sans-serif;
 font-weight: 400;
 font-size: 32px;
 float: left;
 margin-top: 0px;
 margin-right: 10px;
}

nav ul{
  display: inline;
 padding: 0px;
float: left;
}

nav ul li{
 display: inline-block;
 list-style-type:none;
 color: white;
 float: left;
 margin-left: 15px;
}

nav ul li a{
 color: white;
 text-decoration: none;
}

#nav {
 font-family: 'Montserrat', sans-serif;
}

.homered{
 background-color: red;
 padding: 30px 10px 25px 10px;

}

.divider{
 background-color: red;
 height: 5px;

}

.homeblack:hover{
 background-color: blue;
 padding: 30px 10px 25px 10px;
}
div{
 width:250px;
 height:666px;
 background:#1A8DA9;
}
div a{
 text-decoration:none;
 color:white;
 padding:20px;
 padding-right:100px
}
div ul li{
 list-style-type:none;
 display:block;
 padding :15px;

 border-bottom:1px solid #236D7F;
 }
 div ul li :hover{
  background:#4097AD;
  transition:linear all 0.40s;
  margin-left:10px;
 }
 div ul li a:hover{
  color:black;
 }

 #navBar {
   float: left;
 }

<!DOCTYPE HTML>

  <title>Videos</title>

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

 Main logo

Home

Videos

education videos

film videos

other videos

<video title="abcd" controls width="250" height="160">
<source  src="videoplayback.mp4" />
</video>
<video title="abcd" controls width="250" height="160">
<source src="videoplayback (1).mp4" />
</video>

<video title="abcd" controls width="250" height="160">
<source src="1 Ton.mp4" />
</video>


问:
which "process scheduling algorithm" Ubuntu 11.10 use
I want to know some OS algorithms about Ubuntu 11.10, but the information is so little. For example, I want to know which algorithm Ubuntu use with it's "process scheduling algorithm"?</p>

答: Since kernel 2.6.23 (that would be as of Hardy 8.04 LTS) Completely Fair Scheduler (CFS) based on "Rotating Staircase Deadline". [Overview from kernel.org]: 2</p>


问:
SQL lat longs within lat long bounds
I am using MySQL 5.5.52. Abbreviations: Lat = Latitude, Long = Longitude, NE = North East, SW = South West.

I have two SQL tables:

First table contains "Areas". Each Area consists of ID, NE Lat, NE Long, SW Lat, SW Long.

Second table contains "Points". Each Point consists of ID, Lat, Long.

I need a SQL statement that given a list of Area IDs will return the Points in those Areas. A Point is defined being in an Area if its Lat-Long lies within the square where the top-right and bottom-left corners are defined by the Area's NE Lat-Long and SW Lat-Long.

Note: I could change the Areas to be defined as a single Lat-Long with a radius, where Points are found within the 'circles'. But ideally I don't want to do this unless there is a much more efficient SQL statement to solve this way.

答:
Join two tables based on condition that point location falls within area bounds.

```<code>Select areaTable.*, pointsTable.*
From pointsTable
Join areaTable
On pointTable.lat between areaTable.SWLat and areaTable.NELat
and
pointTable.long between areaTable.SWLong and areaTable.NELong
</code>```

Gives you each area and the corresponding points.

Parameterize further if needed with where clause for specific area.

```<code>Where areaTable.NELat=@areaNELat
and areaTable.NELong=@areaNELong
and areaTable.SWLat=@areaSWLat
and areaTable.SWLong=@areaSWLong
</code>```

Just substitute @s with the area lat and long values you like.

Title: SQL lat longs within lat long bounds

Body:
Join two tables based on condition that point location falls within area bounds.

Select areaTable.*, pointsTable.*
From pointsTable
Join areaTable
On pointTable.lat between areaTable.SWLat and areaTable.NELat
and
pointTable.long between areaTable.SWLong and areaTable.NELong

Gives you each area and the corresponding points.

Parameterize further if needed with where clause for specific area.

Where areaTable.NELat=@areaNELat
and areaTable.NELong=@areaNELong
and areaTable.SWLat=@areaSWLat
and areaTable.SWLong=@areaSWLong

Just substitute @s with the area lat and long values you like.


问:
Test case removing original file while uploading a file through test case
This is my test case

```<code>public function testSelfieFileUpload()
{
    $path = public_path().'/uploads/sample1.jpg';
    $name = 'sample1.jpg';
    $file = new UploadedFile($path, $name, 'image/png', filesize($path), null, true);
    $response = $this->post($this->endpoint, ['file' => $file], $this->setHeaders());
    $response->assertStatus(200)
        ->assertJsonFragment(array("status" => "success"));
}
</code>```

But the problem is that it is deleting the original file from the folder i.e sample1.jpg

Help me out. Am i missing something here? Although the test case is running fine.

答:
When having the same problem, after looking in the source code, I couldn't find a flag that fixes it.

As I workaround, I created a copy when running the test, which gets deleted but it's no longer a problem.

```<code>$temporaryFilePath = $this->createTempFile($this->testFilePath);
$file = new \Illuminate\Http\UploadedFile($path, $name, $mime, filesize($path), null, true);
//do your test logic

...

private function createTempFile($path) {

    $tempFilePath = $this->basePath . 'temp.xlsx';
    copy($path, $tempFilePath);

    return $tempFilePath;
}
</code>```

You might want to refine this depending on your needs.

Body:
This is my test case

public function testSelfieFileUpload()
{
    $path = public_path().'/uploads/sample1.jpg';
    $name = 'sample1.jpg';
    $file = new UploadedFile($path, $name, 'image/png', filesize($path), null, true);
    $response = $this->post($this->endpoint, ['file' => $file], $this->setHeaders());
    $response->assertStatus(200)
        ->assertJsonFragment(array("status" => "success"));
}

But the problem is that it is deleting the original file from the folder i.e sample1.jpg

Help me out. Am i missing something here? Although the test case is running fine.

Body:
When having the same problem, after looking in the source code, I couldn't find a flag that fixes it.

As I workaround, I created a copy when running the test, which gets deleted but it's no longer a problem.

$temporaryFilePath = $this->createTempFile($this->testFilePath);
$file = new \Illuminate\Http\UploadedFile($path, $name, $mime, filesize($path), null, true);
//do your test logic

...

private function createTempFile($path) {

    $tempFilePath = $this->basePath . 'temp.xlsx';
    copy($path, $tempFilePath);

    return $tempFilePath;
}

You might want to refine this depending on your needs.


问:
How to use c# tuple value types in a switch statement
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

```<code>using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}
</code>```

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

答:
There's nothing wrong with using tuples or pattern matching. If anything, these allow you to write cleaner code and avoid spreading your logic to multiple methods.

C# 7 doesn't allow you to match against tuple values yet. You can't compare two tuples with the == operator either. What you can do, is use Equals two compare two value tuples:

```<code> if (_test.Equals(('A','B'))
{
    Console.WriteLine("Case A ok.");
}
else if (_test.Equals(('D','\0'))
{
    Console.WriteLine("Case D ok.");
}
</code>```

It would seem that you are trying to create a state matchine for a parser(?), that matches specific patterns. This can work with pattern matching if you specify different state classes instead of using a single tuple for all cases.

All you need to do is specify a single IState interface without methods, and use it in all state  classes, eg:

```<code>interface IMyState {};
public class StateA:IMyState{ public string PropA{get;set;} };
public class StateD:IMyState{ public string PropD{get;set;} };

...
IMyState _test= new StateD(...);

switch (_test)
{
    case StateA a:
        Console.WriteLine($"Case A ok. {a.PropA}");
        break;
    case StateD d:
        Console.WriteLine($"Case D ok. {d.PropD}");
        break;
    default :
        throw new InvalidOperationException("Where's my state ?");
}
</code>```

The a, d variables are strongly typed, which means you don't have to add anything to the IState interface. It's there only to satisfy the compiler.

By using structs instead of classes for the state types, you'll get the same memory benefits you would with tuples. If you want to use deconstruction, you can add a Deconstruct method to each type, or use Deconstruct extension methods in a separate static class.

ContentLicense: CC BY-SA 4.0

Body:
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

Body:
There's nothing wrong with using tuples or pattern matching. If anything, these allow you to write cleaner code and avoid spreading your logic to multiple methods.

C# 7 doesn't allow you to match against tuple values yet. You can't compare two tuples with the == operator either. What you can do, is use Equals two compare two value tuples:

 if (_test.Equals(('A','B'))
{
    Console.WriteLine("Case A ok.");
}
else if (_test.Equals(('D','\0'))
{
    Console.WriteLine("Case D ok.");
}

It would seem that you are trying to create a state matchine for a parser(?), that matches specific patterns. This can work with pattern matching if you specify different state classes instead of using a single tuple for all cases.

All you need to do is specify a single IState interface without methods, and use it in all state  classes, eg:

interface IMyState {};
public class StateA:IMyState{ public string PropA{get;set;} };
public class StateD:IMyState{ public string PropD{get;set;} };

...
IMyState _test= new StateD(...);

switch (_test)
{
    case StateA a:
        Console.WriteLine($"Case A ok. {a.PropA}");
        break;
    case StateD d:
        Console.WriteLine($"Case D ok. {d.PropD}");
        break;
    default :
        throw new InvalidOperationException("Where's my state ?");
}

The a, d variables are strongly typed, which means you don't have to add anything to the IState interface. It's there only to satisfy the compiler.

By using structs instead of classes for the state types, you'll get the same memory benefits you would with tuples. If you want to use deconstruction, you can add a Deconstruct method to each type, or use Deconstruct extension methods in a separate static class.


问:
Unable to save gplot to file in R as displayed
I have produced a plot of a RasterLayer using gplot and rasterVis (a wrapper around gplot). In order to display the raster output at full resolution I have to set the gplot parameter maxpixels = 10000000.
Although the raster resolution looks fine in R, when I try to write it to a file, the image is again downsampled to the standard resolution. Following the code I used:

```<code>png(paste0(pathAndFilename, ".png"))

gplot(myRaster, maxpixels = 10000000) +
    geom_raster(aes(fill = factor(value))) +
    scale_fill_manual(values=c(someColors), legendSpecs) +
    coord_equal() +
    labs(title = "SomeTitle", x = "Lng", y = "Lat")

dev.off()
</code>```

Any help appreciated!

答:
In the help of the png() function it says this:

```<code>png(filename = "Rplot%03d.png",
    width = 480, height = 480, units = "px", pointsize = 12,
    bg = "white", res = NA, family = "", restoreConsole = TRUE,
    type = c("windows", "cairo", "cairo-png"), antialias)
</code>```

All parameters that have an equal sign and a value, have defaults in case you don't mention them explicitly. Set width and height to the correct numbers from the raster you want to print and you will not have any resampling.

You probably want something like this:

```<code>png(paste0(pathAndFilename, ".png"), width = ncol(myRaster), height = nrow(myRaster))

gplot(myRaster, maxpixels = 10000000) +
    geom_raster(aes(fill = factor(value))) +
    scale_fill_manual(values=c(someColors), legendSpecs) +
    coord_equal() +
    labs(title = "SomeTitle", x = "Lng", y = "Lat")

dev.off()
</code>```

Body:
I have produced a plot of a RasterLayer using gplot and rasterVis (a wrapper around gplot). In order to display the raster output at full resolution I have to set the gplot parameter maxpixels = 10000000.
Although the raster resolution looks fine in R, when I try to write it to a file, the image is again downsampled to the standard resolution. Following the code I used:

png(paste0(pathAndFilename, ".png"))

gplot(myRaster, maxpixels = 10000000) +
    geom_raster(aes(fill = factor(value))) +
    scale_fill_manual(values=c(someColors), legendSpecs) +
    coord_equal() +
    labs(title = "SomeTitle", x = "Lng", y = "Lat")

dev.off()

Any help appreciated!

Body:
In the help of the png() function it says this:

png(filename = "Rplot%03d.png",
    width = 480, height = 480, units = "px", pointsize = 12,
    bg = "white", res = NA, family = "", restoreConsole = TRUE,
    type = c("windows", "cairo", "cairo-png"), antialias)

All parameters that have an equal sign and a value, have defaults in case you don't mention them explicitly. Set width and height to the correct numbers from the raster you want to print and you will not have any resampling.

You probably want something like this:

png(paste0(pathAndFilename, ".png"), width = ncol(myRaster), height = nrow(myRaster))

gplot(myRaster, maxpixels = 10000000) +
    geom_raster(aes(fill = factor(value))) +
    scale_fill_manual(values=c(someColors), legendSpecs) +
    coord_equal() +
    labs(title = "SomeTitle", x = "Lng", y = "Lat")

dev.off()


问:
MD5 of a file in JS and in Python/Django
I need to check the md5 of an image in django and in javascript. However I don't obtain the same results. The django code give me the same md5 as md5sum on a terminal.

Django code :

```<code>file0 = request.FILES.get('file')
buffer0 = file0.read()
print hashlib.md5(buffer0).hexdigest() //9f982242d24ab97a7254edd7e28e3921
</code>```

I tried two javascript md5 library, which give me the same results ( https://github.com/blueimp/JavaScript-MD5 and https://github.com/sytelus/CryptoJS ).
I have tried different methods (readAsArrayBuffer, readAsBinaryString, ...) and none of them give me the same md5 as python and md5sum.

Javascript :

```<code>var reader = new FileReaderSync();
var datas = reader.readAsArrayBuffer(file);
console.log(md5(datas)); //060e4e9e30bcb9ae675a80328a87a687

var string0 = reader.readAsBinaryString(file);
console.log(md5(string0)); //2e4cac0a23ddf95683c6538d64b26e21
console.log(CryptoJS.MD5(string0).toString(CryptoJS.enc.Hex)); //2e4cac0a23ddf95683c6538d64b26e21

var string1 = reader.readAsText(file,'ascii');
console.log(md5(string1)); //329c4271b8eda786213b2468e378b251
console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex));//329c4271b8eda786213b2468e378b251

var view   = new Uint8Array(datas);
var str = ""
for (var i=0, strLen=view.length; i < strLen; i++) {
  str+= String.fromCharCode(view[i]);
}
console.log(md5(str)); //2e4cac0a23ddf95683c6538d64b26e21
console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex));
</code>```

I think the problem come from how I read the file in JS.

答: I used SparkMD5 (https://github.com/satazor/js-spark-md5) which can worked directly on an array buffer and it give me the same md5 than in python.</p>

Body:
I need to check the md5 of an image in django and in javascript. However I don't obtain the same results. The django code give me the same md5 as md5sum on a terminal.

Django code :

file0 = request.FILES.get('file')
buffer0 = file0.read()
print hashlib.md5(buffer0).hexdigest() //9f982242d24ab97a7254edd7e28e3921

I tried two javascript md5 library, which give me the same results ( https://github.com/blueimp/JavaScript-MD5 and https://github.com/sytelus/CryptoJS ).
I have tried different methods (readAsArrayBuffer, readAsBinaryString, ...) and none of them give me the same md5 as python and md5sum.

Javascript :

var reader = new FileReaderSync();
var datas = reader.readAsArrayBuffer(file);
console.log(md5(datas)); //060e4e9e30bcb9ae675a80328a87a687

var string0 = reader.readAsBinaryString(file);
console.log(md5(string0)); //2e4cac0a23ddf95683c6538d64b26e21
console.log(CryptoJS.MD5(string0).toString(CryptoJS.enc.Hex)); //2e4cac0a23ddf95683c6538d64b26e21

var string1 = reader.readAsText(file,'ascii');
console.log(md5(string1)); //329c4271b8eda786213b2468e378b251
console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex));//329c4271b8eda786213b2468e378b251

var view   = new Uint8Array(datas);
var str = ""
for (var i=0, strLen=view.length; i < strLen; i++) {
  str+= String.fromCharCode(view[i]);
}
console.log(md5(str)); //2e4cac0a23ddf95683c6538d64b26e21
console.log(CryptoJS.MD5(string1).toString(CryptoJS.enc.Hex));

I think the problem come from how I read the file in JS.


问:
React Native Build Commands Failed: PhaseScriptExecution ... (domain=NSPOSIXErrorDomain, code=2)
Environment

```<code>Mac OS X Version 10.11.3 (15D21)
Xcode Version 7.2 (7C68)
Simulator Version 9.2 (SimulatorApp-643)
react-native-cli 0.1.10
node v5.5.0
</code>```

What I did before running the app

```<code>npm install -g react-native-cli
react-native init DemoProjectDELETEME
cd ./DemoProjectDELETEME
react-native run-ios
</code>```

I am new to React Native. When I try to run the default app on iOS simulator I got the following errors. I found a similar issue but it does not solve my problem.

Xcode6 can't run any app in simulator ( Domain = NSPOSIXErrorDomain, Code = 3 )

After restart the machine and simulator the issues still persistent.

```<code>** BUILD FAILED **

The following build commands failed:
    PhaseScriptExecution Run\ Script /Users/x/Desktop/DemoProjectDELETEME/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F38006873D1.sh
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/DemoProjectDELETEME.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/done.js:10
      throw err;
      ^

Error: Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/DemoProjectDELETEME.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

    at checkExecSyncError (child_process.js:464:13)
    at Object.execFileSync (child_process.js:484:13)
    at _runIOS (runIOS.js:77:34)
    at runIOS.js:24:5
    at tryCallTwo (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:45:5)
    at doResolve (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:200:13)
    at new Promise (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:66:3)
    at Array.runIOS (runIOS.js:23:10)
    at Object.run (/Users/x/Desktop/DemoProjectDELETEME/node_modules/react-native/local-cli/cli.js:86:13)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:73:7)
</code>```

Got the follower error when I am trying to launch the app from Xcode.

sudo npm start in project root solves the issue, but react-native run-ios still BUILD FAILED.

Thanks for your time viewing my question.

答:
I fixed my issue, you can try it if you are in the same condition.

I encountered the same error:

Print: Entry, ":CFBundleIdentifier", Does Not Exist

When I clone an existing react-native project from learning react native.

I initialize (using {react-native init yourProjectName}) a new project with the same name in a different directory

copy every useful *.ios.js file to this new project from the one I clone elsewhere.

This works for me.

Body:
Environment

Mac OS X Version 10.11.3 (15D21)
Xcode Version 7.2 (7C68)
Simulator Version 9.2 (SimulatorApp-643)
react-native-cli 0.1.10
node v5.5.0

What I did before running the app

npm install -g react-native-cli
react-native init DemoProjectDELETEME
cd ./DemoProjectDELETEME
react-native run-ios

I am new to React Native. When I try to run the default app on iOS simulator I got the following errors. I found a similar issue but it does not solve my problem.

Xcode6 can't run any app in simulator ( Domain = NSPOSIXErrorDomain, Code = 3 )

After restart the machine and simulator the issues still persistent.

** BUILD FAILED **

The following build commands failed:
    PhaseScriptExecution Run\ Script /Users/x/Desktop/DemoProjectDELETEME/ios/build/Build/Intermediates/React.build/Debug-iphonesimulator/React.build/Script-006B79A01A781F38006873D1.sh
(1 failure)
Installing build/Build/Products/Debug-iphonesimulator/DemoProjectDELETEME.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/done.js:10
      throw err;
      ^

Error: Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/DemoProjectDELETEME.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

    at checkExecSyncError (child_process.js:464:13)
    at Object.execFileSync (child_process.js:484:13)
    at _runIOS (runIOS.js:77:34)
    at runIOS.js:24:5
    at tryCallTwo (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:45:5)
    at doResolve (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:200:13)
    at new Promise (/Users/x/Desktop/DemoProjectDELETEME/node_modules/promise/lib/core.js:66:3)
    at Array.runIOS (runIOS.js:23:10)
    at Object.run (/Users/x/Desktop/DemoProjectDELETEME/node_modules/react-native/local-cli/cli.js:86:13)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:73:7)

Got the follower error when I am trying to launch the app from Xcode.

sudo npm start in project root solves the issue, but react-native run-ios still BUILD FAILED.

Thanks for your time viewing my question.


问:
Predis cluster slots manual set
is there any way in Predis to define the cluster slots manually when creating the instance in order to avoid the random server selection and getting the slots config so the request is directly sent to the right server at once making the process faster?</p>

答:
Yes you can do that using connection parameters:

```<code>$client = new Predis\Client([
    'tcp://node01?slots=0-5460',
    'tcp://node02?slots=5461-10922',
    'tcp://node03?slots=10923-16383',
], ['cluster' => 'redis']);
</code>```

The "slots" connection parameter can accept a comma-separated list of single slots and ranges of contiguous slots, e.g.:

```<code>tcp://node01?slots=0,20-30,5461-10922
</code>```

Title: Predis cluster slots manual set

Body:
Yes you can do that using connection parameters:

$client = new Predis\Client([
    'tcp://node01?slots=0-5460',
    'tcp://node02?slots=5461-10922',
    'tcp://node03?slots=10923-16383',
], ['cluster' => 'redis']);

The "slots" connection parameter can accept a comma-separated list of single slots and ranges of contiguous slots, e.g.:

tcp://node01?slots=0,20-30,5461-10922


问:
Which alt text is best for screen readers for example "smiling kid"?
Which would be good write ALT text for a photo of kid which is smiling and sitting in garden?

This

```<code>alt="Photo of smiling kid sitting in the garden"
</code>```

or this

```<code>alt="Photo of smiling kid"
</code>```

or this

```<code>alt="Smiling kid sitting in the garden"
</code>```

or this

```<code>alt="Smiling kid"
</code>```

my purpose is to ask this question, I want to know should we include "Photo of..." in every alt text and And how much we should describe the photo in alt text.

答:
Why not follow the standards? WCAG 2.0 guideline "1.1.1 Non-text Content" says that for content (e.g. images) that are used for decorative or formatting purposes then they should be implemented in a way that assistive technology (e.g. screen readers) can ignore it. If the "smiling kid" is decorative, then use an empty alt="" attribute.

http://www.w3.org/WAI/WCAG20/quickref/#text-equiv-all

Body:
Which would be good write ALT text for a photo of kid which is smiling and sitting in garden?

This

alt="Photo of smiling kid sitting in the garden"

or this

alt="Photo of smiling kid"

or this

alt="Smiling kid sitting in the garden"

or this

alt="Smiling kid"

my purpose is to ask this question, I want to know should we include "Photo of..." in every alt text and And how much we should describe the photo in alt text.


问:
Different manifest files to same web project office add-in
I have recently published an Outlook Add-in (simple one task pane firing an API call with inserting text received back).

Now I am interested in developing the same for the other Office products (Word, Excel , etc).

I was wondering if it is possible to have, let's say, a Word manifest, Excel manifest and Outlook manifest all pointing to the same web project but different folders in the project.

答:
@rick-kirkham I have managed to create multiple manifest files with one web project holding the different folders to which the manifests point. I currently have an Outlook, Word and Excel add-in using the same web project.

One thing I had to do is remove the reference in the manifest file project that points to the web folder.


问:
EJB relationship
I'm writing a web application of management of the computer consumables to develop in JEE.  In my database the personal table is linked to the login table; I make an insertion of a staff with his login, and then just after insertion, I execute the following code:

```<code>Personnel personnel = personnelFacade.find(id);
    List<Page> pages = pageFacade.findByNiveau(personnel.getLoginList().get(0).getNiveauAcces());
</code>```

I get this error:

Avertissement:   StandardWrapperValve[SettingPersonnal]: Servlet.service() for servlet SettingPersonnal threw exception
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0
    at java.util.Vector.get(Vector.java:748)
    at org.eclipse.persistence.indirection.IndirectList.get(IndirectList.java:442)
```

Can anyone help me?

答:
Your LoginList is empty. The error is thrown when you try to get(0) from the LoginList. If you do not want to be able to insert a record with no values in the loginlist you can use Bean Validation like this:

```<code>@NotNull @Size(min = 1)
List<MyLoginClass> loginList;
</code>```

Title: EJB relationship

Body:
I'm writing a web application of management of the computer consumables to develop in JEE.  In my database the personal table is linked to the login table; I make an insertion of a staff with his login, and then just after insertion, I execute the following code:

Personnel personnel = personnelFacade.find(id);
    List<Page> pages = pageFacade.findByNiveau(personnel.getLoginList().get(0).getNiveauAcces());

I get this error:

Avertissement:   StandardWrapperValve[SettingPersonnal]: Servlet.service() for servlet SettingPersonnal threw exception
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0
    at java.util.Vector.get(Vector.java:748)
    at org.eclipse.persistence.indirection.IndirectList.get(IndirectList.java:442)

Can anyone help me?

Body:
Your LoginList is empty. The error is thrown when you try to get(0) from the LoginList. If you do not want to be able to insert a record with no values in the loginlist you can use Bean Validation like this:

@NotNull @Size(min = 1)
List<MyLoginClass> loginList;