问:
How to create a CSS Grid Layout box that spans 2 columns and 2 rows?
I've created a grid layout following the newest CSS Grid spec, but am not completely familiar with it yet. I'm trying to create the following layout without having to define grid areas for each grid child.

codepen

body {
  max-width: 1024px;
  margin: 10px auto;
}

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: "a a b" "a a c" "d e f";
}

.grid__thing {
  background-color: rebeccapurple;
}

.a {
  grid-area: a;
}

.b {
  grid-area: b;
}

.c {
  grid-area: c;
}

.d {
  grid-area: d;
}

.e {
  grid-area: e;
}

.f {
  grid-area: f;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="grid__thing a">
    <img src="https://placehold.it/1360x880" alt="" />
  </div>
  <div class="grid__thing b">
    <img src="https://placehold.it/660x405" alt="" />
  </div>
  <div class="grid__thing c">
    <img src="https://placehold.it/660x405" alt="" />
  </div>
  <div class="grid__thing d">
    <img src="https://placehold.it/660x405" alt="" />
  </div>
  <div class="grid__thing e">
    <img src="https://placehold.it/1327x817" alt="" />
  </div>
  <div class="grid__thing f">
    <img src="https://placehold.it/1327x817" alt="" />
  </div>
</div></code>```

Ideally, I'd like to be able to set all the grid sizing properties in the grid parent and then ONLY define properties in grid item A to span across 2 columns and rows.

Currently specifying each grid area and attaching a unique class like so:

```<code>.grid {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows:  1fr 1fr 1fr;
    grid-template-areas: "a a b"
                         "a a c"
                         "d e f";
.a {
    grid-area: a;
}
.b {
    grid-area: b;
}
.c {
    grid-area: c;
}
.d {
    grid-area: d;
}
.e {
    grid-area: e;
}
.f {
    grid-area: f;
}
</code>```

Would like to do something like this so I don't have to create a unique CSS class for each grid item:

```<code>.grid {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows:  1fr 1fr 1fr;
    grid-template-areas: "a a b"
                         "a a c"
                         "d e f";
}
.a {
    // The only unique selector, so this is the only thing that
    // should be given unique styling
}
</code>```

答:
If you don't want to define grid areas for each grid item, then don't use the grid-template-areas property, which requires you to define names for each grid item.

Instead, just work with grid-template-columns and grid-template-rows on the container.

Then apply your 2x2 sizing to the first grid item using grid-column and grid-row.

grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
  grid-gap: 10px;
}

grid_item:first-child {
  grid-column: 1 / 3; /* span from grid column line 1 to 3 (i.e., span 2 columns) */
  grid-row: 1 / 3;    /* same concept, but for rows */
}

/* non-essential decorative styles */
grid_item {
  background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.5em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><grid-container>
  <grid_item>A</grid_item>
  <grid_item>B</grid_item>
  <grid_item>C</grid_item>
  <grid_item>D</grid_item>
  <grid_item>E</grid_item>
  <grid_item>F</grid_item>
</grid-container></code>```

codepen demo

Body:
I've created a grid layout following the newest CSS Grid spec, but am not completely familiar with it yet. I'm trying to create the following layout without having to define grid areas for each grid child.

codepen

body {
  max-width: 1024px;
  margin: 10px auto;
}

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-areas: "a a b" "a a c" "d e f";
}

.grid__thing {
  background-color: rebeccapurple;
}

.a {
  grid-area: a;
}

.b {
  grid-area: b;
}

.c {
  grid-area: c;
}

.d {
  grid-area: d;
}

.e {
  grid-area: e;
}

.f {
  grid-area: f;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Ideally, I'd like to be able to set all the grid sizing properties in the grid parent and then ONLY define properties in grid item A to span across 2 columns and rows.

Currently specifying each grid area and attaching a unique class like so:

.grid {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows:  1fr 1fr 1fr;
    grid-template-areas: "a a b"
                         "a a c"
                         "d e f";
.a {
    grid-area: a;
}
.b {
    grid-area: b;
}
.c {
    grid-area: c;
}
.d {
    grid-area: d;
}
.e {
    grid-area: e;
}
.f {
    grid-area: f;
}

Would like to do something like this so I don't have to create a unique CSS class for each grid item:

.grid {
    display: grid;
    grid-gap: 10px;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows:  1fr 1fr 1fr;
    grid-template-areas: "a a b"
                         "a a c"
                         "d e f";
}
.a {
    // The only unique selector, so this is the only thing that
    // should be given unique styling
}

Body:
If you don't want to define grid areas for each grid item, then don't use the grid-template-areas property, which requires you to define names for each grid item.

Instead, just work with grid-template-columns and grid-template-rows on the container.

Then apply your 2x2 sizing to the first grid item using grid-column and grid-row.

grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 100px);
  grid-gap: 10px;
}

grid_item:first-child {
  grid-column: 1 / 3; /* span from grid column line 1 to 3 (i.e., span 2 columns) */
  grid-row: 1 / 3;    /* same concept, but for rows */
}

/* non-essential decorative styles */
grid_item {
  background-color: aqua;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.5em;
}

<grid-container>
  <grid_item>A</grid_item>
  <grid_item>B</grid_item>
  <grid_item>C</grid_item>
  <grid_item>D</grid_item>
  <grid_item>E</grid_item>
  <grid_item>F</grid_item>
</grid-container>

codepen demo


来源: stackexchange

问:
`clEnqueueFillBuffer()` fills a buffer correctly only at random
I'm trying to fill OpenCL cl_int2 buffer with default values ({-1, -2}), however the OpenCL function clEnqueueFillBuffer() fills my buffer with different values each time I run it – the buffer is filled with the expected values only at random. The function returns error code 0.

Examples of the snippet's output at multiple runs:

0 : -268435456

0 : -2147483648

0 : -536870912

0 :  268435456

0 :          0

0 : -1342177280

-1:         -2

I'm running OS X 10.11.6 with Radeon HD 6750M and OpenCL version 1.2.

```<code>clbParticle_hashmap_lookup_table = clCreateBuffer(context,
                                                  CL_MEM_READ_WRITE,
                                                  sizeof(cl_int2)*this->CUBE_CELLS,
                                                  nullptr,
                                                  &err_code);

// ...

cl_int2 default_hashmap_pattern = { .s = {-1, -2} };

clEnqueueFillBuffer(queue,
                    clbParticle_hashmap_lookup_table,
                    &default_hashmap_pattern,
                    sizeof(cl_int2),
                    0,
                    sizeof(cl_int2)*this->CUBE_CELLS,
                    0,
                    nullptr, nullptr);

clFinish(queue);

// copy and print the data:
size_t   hashmap_lookup_table_size  = sizeof(cl_int2)*this->CUBE_CELLS;
cl_int2* hashmap_lookup_table_bytes = (cl_int2*) malloc(hashmap_lookup_table_size);

clEnqueueReadBuffer(queue,
                    clbParticle_hashmap_lookup_table,
                    CL_TRUE,
                    0,
                    hashmap_lookup_table_size,
                    hashmap_lookup_table_bytes,
                    0,
                    nullptr, nullptr);

clFinish(queue);

cout << endl << "Lookup table: " << endl;
for (int i=0; i<this->CUBE_CELLS; i++)
    cout << setw(10) << hashmap_lookup_table_bytes[i].s[0] << " : "
         << setw(10) << hashmap_lookup_table_bytes[i].s[1] << endl;
</code>```

答: The problem is that your fill pattern is larger too large for your GPU. I ran into the same problem trying to fill a pattern with a cl_double which is 64 bits like your cl_int2. I think clEnqueueFillBuffer is invoking a built in kernel which doesn't allow patterns

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to fill OpenCL cl_int2 buffer with default values ({-1, -2}), however the OpenCL function clEnqueueFillBuffer() fills my buffer with different values each time I run it – the buffer is filled with the expected values only at random. The function returns error code 0.

Examples of the snippet's output at multiple runs:

0 : -268435456

0 : -2147483648

0 : -536870912

0 :  268435456

0 :          0

0 : -1342177280

-1:         -2

I'm running OS X 10.11.6 with Radeon HD 6750M and OpenCL version 1.2.

clbParticle_hashmap_lookup_table = clCreateBuffer(context,
                                                  CL_MEM_READ_WRITE,
                                                  sizeof(cl_int2)*this->CUBE_CELLS,
                                                  nullptr,
                                                  &err_code);

// ...

cl_int2 default_hashmap_pattern = { .s = {-1, -2} };

clEnqueueFillBuffer(queue,
                    clbParticle_hashmap_lookup_table,
                    &default_hashmap_pattern,
                    sizeof(cl_int2),
                    0,
                    sizeof(cl_int2)*this->CUBE_CELLS,
                    0,
                    nullptr, nullptr);

clFinish(queue);

// copy and print the data:
size_t   hashmap_lookup_table_size  = sizeof(cl_int2)*this->CUBE_CELLS;
cl_int2* hashmap_lookup_table_bytes = (cl_int2*) malloc(hashmap_lookup_table_size);

clEnqueueReadBuffer(queue,
                    clbParticle_hashmap_lookup_table,
                    CL_TRUE,
                    0,
                    hashmap_lookup_table_size,
                    hashmap_lookup_table_bytes,
                    0,
                    nullptr, nullptr);

clFinish(queue);

cout << endl << "Lookup table: " << endl;
for (int i=0; i<this->CUBE_CELLS; i++)
    cout << setw(10) << hashmap_lookup_table_bytes[i].s[0] << " : "
         << setw(10) << hashmap_lookup_table_bytes[i].s[1] << endl;


问:
MySQL Stored Procedure Multiplication
```<code>DELIMITER $$

CREATE PROCEDURE `calc_ytd2` (IN val_id INT(11),
                              OUT frstname VARCHAR(45),
                              OUT lstname VARCHAR(45),
                              OUT pay DECIMAL(10,2))
BEGIN
    select fname,
           lname,
           (ytdhours * positionpay)
      into frstname,
           lstname,
           pay
      from employees,
           jobposition
     where idemployees = val_id;
end $$
delimiter ;
</code>```

Note = Its my first time playing around with MySQL. Im trying to figure out how to use the multiplication in the select statement so I can call the procedure. Can I even use that in the select statement and if so how can I call the procedure? thanks in advance for the help :)

答:
calling procedure like id 12 :

```<code>set @out1 = null;
call calc_ytd2(12,@out1);
 SELECT @out1;
</code>```

this is an example if you have an output of only 1...

Title: MySQL Stored Procedure Multiplication

Body:
DELIMITER $$

CREATE PROCEDURE `calc_ytd2` (IN val_id INT(11),
                              OUT frstname VARCHAR(45),
                              OUT lstname VARCHAR(45),
                              OUT pay DECIMAL(10,2))
BEGIN
    select fname,
           lname,
           (ytdhours * positionpay)
      into frstname,
           lstname,
           pay
      from employees,
           jobposition
     where idemployees = val_id;
end $$
delimiter ;

Note = Its my first time playing around with MySQL. Im trying to figure out how to use the multiplication in the select statement so I can call the procedure. Can I even use that in the select statement and if so how can I call the procedure? thanks in advance for the help :)

Body:
calling procedure like id 12 :

set @out1 = null;
call calc_ytd2(12,@out1);
 SELECT @out1;

this is an example if you have an output of only 1...


问:
Why isn't this code compressing spaces correctly?
I'm working through K&R's The C Programming Language. I'm working through an exercise here that says to  "Write a program that copies all of its input to its output, replacing each string of one or more blanks by a single blank."

I believe I have solved it. Somewhat. When first running the program with a.out, I can type in a number with multiple spaces and will get it returned with just one space. But, when I go to the next line and try again, it will return the numbers with no spaces at all. Also, if I type in a string of letters like "33  33 33" it will only leave one space for the entire line. It becomes "33 3333".

I know that I could just Google the answer to the exercise itself but I don't think that that would help me learn why my code is behaving the way it is. Any help would be much appreciated.

```<code>main()
{
    int c, nl, upper;
    nl = 0;
    upper = 2;
    while( ( c = getchar() ) != EOF )
    {
        if( c == ' ' )
        {
            ++nl;
            if( nl >= upper )
            {
                --c;
                --nl;
            }
        }
        putchar(c);
    }
}
</code>```

答:
```<code>int main()
{
    int c, nl;
    nl = 0;
    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            nl ++;
        }
        else
        {
            nl = 0;
        }

        if (nl <= 1)
        {
            putchar(c);
        }
    }
    return 0;
}
</code>```

Body:
I'm working through K&R's The C Programming Language. I'm working through an exercise here that says to  "Write a program that copies all of its input to its output, replacing each string of one or more blanks by a single blank."

I believe I have solved it. Somewhat. When first running the program with a.out, I can type in a number with multiple spaces and will get it returned with just one space. But, when I go to the next line and try again, it will return the numbers with no spaces at all. Also, if I type in a string of letters like "33  33 33" it will only leave one space for the entire line. It becomes "33 3333".

I know that I could just Google the answer to the exercise itself but I don't think that that would help me learn why my code is behaving the way it is. Any help would be much appreciated.

main()
{
    int c, nl, upper;
    nl = 0;
    upper = 2;
    while( ( c = getchar() ) != EOF )
    {
        if( c == ' ' )
        {
            ++nl;
            if( nl >= upper )
            {
                --c;
                --nl;
            }
        }
        putchar(c);
    }
}


问:
Symfony loading schema from old project
I created a symfony project in the same directory as another symfony project. This old project has a column type "phone_number" using another bundle. This project does not use that.

I've tried deleting composer.lock and vendor and composer installing. I've tried composer update (I was on lts). I've tried deleting cache both manually and via cli.

For some reason when I try to run app/console schema:update

```<code>  [Doctrine\DBAL\DBALException]
  Unknown column type "phone_number" requested. Any Doctrine type that you us
  e has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can g
  et a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMa
  p(). If this error occurs during database introspection then you might have
  forgot to register all database types for a Doctrine Type. Use AbstractPla
  tform#registerDoctrineTypeMapping() or have your custom types implement Typ
  e#getMappedDatabaseTypes(). If the type name is empty you might have a prob
  lem with the cache or forgot some mapping information.
</code>```

my app/config/config.yml

```<code># Doctrine Configuration
doctrine:
    dbal:
        default_connection: photoProject
        connections:
            photoProject:
                driver: pdo_pgsql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8
                # if using pdo_sqlite as your database driver:
                #   1. add the path in parameters.yml
                #     e.g. database_path: '%kernel.root_dir%/data/data.db    3'
                #   2. Uncomment database_path in parameters.yml.dist
                #   3. Uncomment next line:
                #path: '%database_path%'

    orm:
        default_entity_manager: photoProject
        entity_managers:
            photoProject:
                connection: photoProject
                naming_strategy: doctrine.orm.naming_strategy.underscore
                auto_mapping: true
                #auto_generate_proxy_classes: '%kernel.debug%'

doctrine_migrations:
    dir_name: "%kernel.root_dir%/app/DoctrineMigrations"
    namespace: Application\Migrations
    table_name: migration_versions
    name: Application Migrations
</code>```

I've even deleted the old project and still getting the same error. I think this has to do with autloading some cached version of the old db schema, but I'm not sure where to find the problem.

Thanks!

```<code>{
"name": "root/photoproject",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"autoload-dev": {
    "files": [
        "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "doctrine/annotations": "^1.4",
    "doctrine/doctrine-bundle": "~1.4",
    "doctrine/doctrine-migrations-bundle": "^1.0",
    "doctrine/migrations": "^1.5",
    "doctrine/orm": "^2.5",
    "egulias/email-validator": "^2.1",
    "incenteev/composer-parameter-handler": "~2.0",
    "sensio/distribution-bundle": "~4.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "symfony/monolog-bundle": "^3.0.2",
    "symfony/swiftmailer-bundle": "~2.3,>=2.3.10",
    "symfony/symfony": "2.8.*",
    "twig/twig": "^1.0||^2.0"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "symfony/phpunit-bridge": "~2.7"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "bin-dir": "bin",
    "sort-packages": true
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": null
}
</code>```

}

答:
Found the solution. I had reused the exact same doctrine migration/db settings from an old project. I think there was a table named doctrine_migrations in my db and somehow when I was running anything it was erroring out.

Posting in case anyone else sees it. Look in your database and see if you have a table there with old migrations.

Title: Symfony loading schema from old project

Body:
I created a symfony project in the same directory as another symfony project. This old project has a column type "phone_number" using another bundle. This project does not use that.

I've tried deleting composer.lock and vendor and composer installing. I've tried composer update (I was on lts). I've tried deleting cache both manually and via cli.

For some reason when I try to run app/console schema:update

  [Doctrine\DBAL\DBALException]
  Unknown column type "phone_number" requested. Any Doctrine type that you us
  e has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can g
  et a list of all the known types with \Doctrine\DBAL\Types\Type::getTypesMa
  p(). If this error occurs during database introspection then you might have
  forgot to register all database types for a Doctrine Type. Use AbstractPla
  tform#registerDoctrineTypeMapping() or have your custom types implement Typ
  e#getMappedDatabaseTypes(). If the type name is empty you might have a prob
  lem with the cache or forgot some mapping information.

my app/config/config.yml

# Doctrine Configuration
doctrine:
    dbal:
        default_connection: photoProject
        connections:
            photoProject:
                driver: pdo_pgsql
                host: '%database_host%'
                port: '%database_port%'
                dbname: '%database_name%'
                user: '%database_user%'
                password: '%database_password%'
                charset: UTF8
                # if using pdo_sqlite as your database driver:
                #   1. add the path in parameters.yml
                #     e.g. database_path: '%kernel.root_dir%/data/data.db    3'
                #   2. Uncomment database_path in parameters.yml.dist
                #   3. Uncomment next line:
                #path: '%database_path%'

    orm:
        default_entity_manager: photoProject
        entity_managers:
            photoProject:
                connection: photoProject
                naming_strategy: doctrine.orm.naming_strategy.underscore
                auto_mapping: true
                #auto_generate_proxy_classes: '%kernel.debug%'

doctrine_migrations:
    dir_name: "%kernel.root_dir%/app/DoctrineMigrations"
    namespace: Application\Migrations
    table_name: migration_versions
    name: Application Migrations

I've even deleted the old project and still getting the same error. I think this has to do with autloading some cached version of the old db schema, but I'm not sure where to find the problem.

Thanks!

{
"name": "root/photoproject",
"license": "proprietary",
"type": "project",
"autoload": {
    "psr-4": {
        "": "src/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},
"autoload-dev": {
    "files": [
        "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
    ]
},
"require": {
    "php": ">=5.3.9",
    "doctrine/annotations": "^1.4",
    "doctrine/doctrine-bundle": "~1.4",
    "doctrine/doctrine-migrations-bundle": "^1.0",
    "doctrine/migrations": "^1.5",
    "doctrine/orm": "^2.5",
    "egulias/email-validator": "^2.1",
    "incenteev/composer-parameter-handler": "~2.0",
    "sensio/distribution-bundle": "~4.0",
    "sensio/framework-extra-bundle": "^3.0.2",
    "symfony/monolog-bundle": "^3.0.2",
    "symfony/swiftmailer-bundle": "~2.3,>=2.3.10",
    "symfony/symfony": "2.8.*",
    "twig/twig": "^1.0||^2.0"
},
"require-dev": {
    "sensio/generator-bundle": "~3.0",
    "symfony/phpunit-bridge": "~2.7"
},
"scripts": {
    "symfony-scripts": [
        "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
        "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
    ],
    "post-install-cmd": [
        "@symfony-scripts"
    ],
    "post-update-cmd": [
        "@symfony-scripts"
    ]
},
"config": {
    "bin-dir": "bin",
    "sort-packages": true
},
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "incenteev-parameters": {
        "file": "app/config/parameters.yml"
    },
    "branch-alias": null
}

}


问:
Product form for common users in Spree
I have a question about e-commerce offered by Spree in Ruby on Rails. I need to do an e-commerce where the users can create products to offer them to the public as well as that they can buy. Currently, Spree only allows you to add products to the administrator, but I also need common users can offer their products and also to link them with the user in the database.

There is a way to make a form that allows an common user to offer a product in Spree?, and if not, what other e-commerce would be easier to propose an e-commerce as I described. It is a project to do in a very short time and that is why I do it in RoR.

答:
IMHO, I would build a marketplace and allow users to register as vendors, so that they can offer their products (either free or paid).

You could look at the following gems to determine your needs:

SpreeMarketplace

SpreeDropShip

There is also non Rails options, like WooCommerce for Wordpress with a MarketPlace extension.

I hope this helps.

Title: Product form for common users in Spree


问:
Creating trigger in mysql for generation UUID
how can this throw an error when trying to create a trigger before insert in MySQL so that it generates new UUID for every input.

```<code>CREATE TRIGGER insert_guid
BEFORE INSERT ON guid_tool (FOR EACH  ROW
BEGIN
  SET NEW.guid_key = UUID());
END;
</code>```

and here is my table

```<code>create table guid_tool (
    ID INT NOT NULL AUTO_INCREMENT,
    guid_key CHAR(40) NOT NULL,
    PRIMARY KEY(ID)
) CHARSET=LATIN1;
</code>```

I must be doing something wrong.

答:
You can define that trigger in one statement, i.e.:</p>

```<sup><b>CREATE TRIGGER insert_guid BEFORE INSERT ON guid_tool FOR EACH ROW SET NEW.guid_key = UUID();</b></sup>```

Body:
how can this throw an error when trying to create a trigger before insert in MySQL so that it generates new UUID for every input.

CREATE TRIGGER insert_guid
BEFORE INSERT ON guid_tool (FOR EACH  ROW
BEGIN
  SET NEW.guid_key = UUID());
END;

and here is my table

create table guid_tool (
    ID INT NOT NULL AUTO_INCREMENT,
    guid_key CHAR(40) NOT NULL,
    PRIMARY KEY(ID)
) CHARSET=LATIN1;

I must be doing something wrong.

Body:
You can define that trigger in one statement, i.e.:

CREATE TRIGGER insert_guid BEFORE INSERT ON guid_tool FOR EACH ROW SET NEW.guid_key = UUID();


问:
Xamarin Forms Video Player (MediaManager Plugin)
I am very new to Xamarin...

I am trying to create a youtube like app. I have no idea how to play video inside of my app. Ive tried to use the MediaManager plugin https://github.com/martijn00/XamarinMediaManager but simply cannot figure it out.

If anyone could suggest a different plugin, or explain IN DETAIL how to use the MediaManager Plugin, that would be fantastic.

The docs on the plugin are atrocious, i cannot understand it at all.

Heres what I have so far: I am simply trying to play a video through a button click.

Xaml file:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Video_Play_Page"
         Title="Video_Play_Page"
         BackgroundColor="#4B1388">
<ContentPage.Content>
    <StackLayout Padding="10, 10, 10, 10">

        <Label Text="video Player..." />

        <Button Clicked="PlayVideo" Text="Play me!"/>
    </StackLayout>
</ContentPage.Content>
</code>```

Xaml.cs file:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Plugin.MediaManager;

namespace App2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Video_Play_Page : ContentPage
{
    public Video_Play_Page()
    {
        InitializeComponent();
    }

    private void PlayVideo(object sender, EventArgs e)
    {
        CrossMediaManager.Current.Play("https://www.youtube.com/watch?v=Gm8bQxnold0");
    }
}
}
</code>```

NOTE: I dont know if I have installed everything correctly. If someone could please explain that, it would be great too.

答:
You should put forms:VideoView in your Xaml file
Here is a sample to use it in Xamarin.Forms, check this
https://github.com/martijn00/XamarinMediaManager/tree/develop/Samples/Forms</p>

Body:
I am very new to Xamarin...

I am trying to create a youtube like app. I have no idea how to play video inside of my app. Ive tried to use the MediaManager plugin https://github.com/martijn00/XamarinMediaManager but simply cannot figure it out.

If anyone could suggest a different plugin, or explain IN DETAIL how to use the MediaManager Plugin, that would be fantastic.

The docs on the plugin are atrocious, i cannot understand it at all.

Heres what I have so far: I am simply trying to play a video through a button click.

Xaml file:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App2.Video_Play_Page"
         Title="Video_Play_Page"
         BackgroundColor="#4B1388">
<ContentPage.Content>
    <StackLayout Padding="10, 10, 10, 10">

        <Button Clicked="PlayVideo" Text="Play me!"/>
    </StackLayout>
</ContentPage.Content>

Xaml.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Plugin.MediaManager;

namespace App2
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Video_Play_Page : ContentPage
{
    public Video_Play_Page()
    {
        InitializeComponent();
    }

    private void PlayVideo(object sender, EventArgs e)
    {
        CrossMediaManager.Current.Play("https://www.youtube.com/watch?v=Gm8bQxnold0");
    }
}
}

NOTE: I dont know if I have installed everything correctly. If someone could please explain that, it would be great too.


问:
Memory management problem in GTMTest
Hello
I have a problem with the following code in a GTMTestCase:

```<code>- (void)testSomething {
myType *year = [myType valueFromString:@"1978"];
STAssertTrue([year isKindOfClass:[XBNumberAttribute class]], @"Must be subtype.");
}
</code>```

If I build this (=execute the tests), I get a "segmentation fault "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents, Command /bin/sh failed with exit code 139 " error. This however goes away as soon as I retain the year object (which is actually autoreleased in the valueFromString method, see below):

```<code>- (void)testSomething {
myType *year = [[myType valueFromString:@"1978"] retain];
    //STAssertTrue(([year retainCount] == 2), @"Retain count wrong");
STAssertTrue([year isKindOfClass:[XBNumberAttribute class]], @"Must be subtype.");
}
</code>```

Uncommenting the retainCount assertion indeed shows that the retain count is 2 at this point. However, if I put [year release] at the end of the method, the build fails again with the same error as explained above.

What is the matter here?

For the sake of completeness I include the code of valueFromString:

```<code>+ (id)valueFromString:(NSString *)pString {
return [[[myType alloc] initWithString:pString] autorelease];
}
</code>```

And here the initWithString method:

```<code>- (id)initWithString:(NSString *)pString  {
if (self = [super initWithString:pString]){
}
return self;
}
</code>```

pointing to the following super type method:

```<code>- (id)initWithString:(NSString *)pString
{
if (self = [super init]) {
theNumber = [NSNumber numberWithInt:[pString intValue]];
}
 return self;
}
</code>```

答:
After switching on all the autorelease debug options (see http://www.cocoabuilder.com/archive/cocoa/87251-how-do-debug-an-autorelease-crash.html), I found the solution:

The variable theNumber is not accessed via the property accessor, so it is not actually retained (in the initWithString of the super type method, last code snippet). As it is however receiving a release in this type's dealloc method because it is marked as a @property (retain) (information not included here, but important!), I got an error when the autorelease of the child object was called (first code snippet): it released the supertype and with it the attribute which was not there anymore.

ContentLicense: CC BY-SA 2.5

Title: Memory management problem in GTMTest

Body:
Hello
I have a problem with the following code in a GTMTestCase:

- (void)testSomething {
myType *year = [myType valueFromString:@"1978"];
STAssertTrue([year isKindOfClass:[XBNumberAttribute class]], @"Must be subtype.");
}

If I build this (=execute the tests), I get a "segmentation fault "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents, Command /bin/sh failed with exit code 139 " error. This however goes away as soon as I retain the year object (which is actually autoreleased in the valueFromString method, see below):

- (void)testSomething {
myType *year = [[myType valueFromString:@"1978"] retain];
    //STAssertTrue(([year retainCount] == 2), @"Retain count wrong");
STAssertTrue([year isKindOfClass:[XBNumberAttribute class]], @"Must be subtype.");
}

Uncommenting the retainCount assertion indeed shows that the retain count is 2 at this point. However, if I put [year release] at the end of the method, the build fails again with the same error as explained above.

What is the matter here?

For the sake of completeness I include the code of valueFromString:

+ (id)valueFromString:(NSString *)pString {
return [[[myType alloc] initWithString:pString] autorelease];
}

And here the initWithString method:

- (id)initWithString:(NSString *)pString  {
if (self = [super initWithString:pString]){
}
return self;
}

pointing to the following super type method:

- (id)initWithString:(NSString *)pString
{
if (self = [super init]) {
theNumber = [NSNumber numberWithInt:[pString intValue]];
}
 return self;
}


问:
Grails RestBuilder sending weird JSON
I've recently upgraded my project's grails version from 2.3.6 to 2.5.0 in order to use a version that is compliant with Java 8.  I upgraded quite a few plugin version to work with with the upgraded Grails version. However the RestBuilder is acting funky. Instead of sending the regular JSON object that it was before, it is wrapping it in the actual object (i.e. {"target": {"var1":"value", "var2":"value"}, "prettyPrint": true} ).

Here are my dependencies:

```<code>    plugins {
    //runtime ":hibernate4:4.3.1.2"
    runtime ":hibernate:3.6.10.14"
    runtime ":resources:1.2.14"
    runtime ":database-migration:1.4.0"
    runtime ":httplogger:1.1"

    // Uncomment these (or add new ones) to enable additional resources capabilities
    //runtime ":zipped-resources:1.0"
    //runtime ":cached-resources:1.0"
    //runtime ":yui-minify-resources:0.1.5"

    build ":tomcat:7.0.52.1"

    compile ":spring-security-core:2.0-RC5"
    compile ":rest-client-builder:2.1.1"
}
</code>```

and here is the code:

```<code>def createCustomer(Customer customer, String customerId) {

    def enrollmentResponse = new CustomerEnrollmentResponse()
    def customerJson = customer as JSON
    def partnerKey = springSecurityService.getCurrentUser().partnerKey
    def baseUrl = grailsApplication.config.rest.baseUrl
    String url = "${baseUrl}${customerApiContextUrl}${partnerKey}/${customerId}"
    def resp = new RestBuilder().post(url) {
        contentType: "application/json"
        json: customerJson
    }
    enrollmentResponse.responseCode = resp.status
    if (enrollmentResponse.responseCode != 200) {
        enrollmentResponse.error = new APIError(resp.json)
    }
    return enrollmentResponse
}
</code>```

答:
The default groovy json library has some issues.

If were you i would use jackson library, which is the best json library.

Regards.

Title: Grails RestBuilder sending weird JSON

Body:
I've recently upgraded my project's grails version from 2.3.6 to 2.5.0 in order to use a version that is compliant with Java 8.  I upgraded quite a few plugin version to work with with the upgraded Grails version. However the RestBuilder is acting funky. Instead of sending the regular JSON object that it was before, it is wrapping it in the actual object (i.e. {"target": {"var1":"value", "var2":"value"}, "prettyPrint": true} ).

Here are my dependencies:

    plugins {
    //runtime ":hibernate4:4.3.1.2"
    runtime ":hibernate:3.6.10.14"
    runtime ":resources:1.2.14"
    runtime ":database-migration:1.4.0"
    runtime ":httplogger:1.1"

    // Uncomment these (or add new ones) to enable additional resources capabilities
    //runtime ":zipped-resources:1.0"
    //runtime ":cached-resources:1.0"
    //runtime ":yui-minify-resources:0.1.5"

    build ":tomcat:7.0.52.1"

    compile ":spring-security-core:2.0-RC5"
    compile ":rest-client-builder:2.1.1"
}

and here is the code:

def createCustomer(Customer customer, String customerId) {

    def enrollmentResponse = new CustomerEnrollmentResponse()
    def customerJson = customer as JSON
    def partnerKey = springSecurityService.getCurrentUser().partnerKey
    def baseUrl = grailsApplication.config.rest.baseUrl
    String url = "${baseUrl}${customerApiContextUrl}${partnerKey}/${customerId}"
    def resp = new RestBuilder().post(url) {
        contentType: "application/json"
        json: customerJson
    }
    enrollmentResponse.responseCode = resp.status
    if (enrollmentResponse.responseCode != 200) {
        enrollmentResponse.error = new APIError(resp.json)
    }
    return enrollmentResponse
}


问:
MYSQL ORDER BY FIELD from a list from and other table
I'm scraching my head on this one for a long time and I don't know how to solve this.

I have 2 mysql tables

Table1

```<code>+----+----------------------+
| id | name    | order_list |
+----+----------------------+
|  1 | Bob     |    3       |
|  2 | Marc    |    2       |
|  3 | Edith   |    1       |
|  4 | John    |    4       |
+----+----------------------+
</code>```

Table2

```<code>+----+-------------------+
| id | user_id |  sale   |
+----+-------------------+
|  1 |   3     |   30    |
|  2 |   2     |   40    |
|  3 |   1     |   100   |
|  4 |   3     |   75    |
|  5 |   2     |   40    |
|  6 |   1     |   100   |
|  7 |   4     |   75    |
+----+-------------------+
</code>```

I need to have all purchase from table2 ORDER BY the order_list from table 1 of the user_id from table 2.

Right now I'm doing this in PHP like this.
1 query to get the id from employee from table 1 order by order_list.
A loop
Inside 1 query for each employee to get the sale

I need every sale independent, not sum or group by.

```<code>query to get the id from table 1 order by order_list
loop
    query the table2 for the sale of the looped employee
end loop
</code>```

I know that this can be done with something like this.

```<code>SELECT * FROM table2 ORDER BY FIELD (id,order from table 1)
</code>```

答:
A basic join should suffice:

```<code>select t2.*
from table2 t2 join
     table1 t1
     on t2.user_id = t1.id
order by t1.order_list;
</code>```

Or, if you prefer, put a subquery in the order by:

```<code>select t2.*
from table2 t2
order by (select t1.order_list from table1 t1 where t1.id = t2.user_id);
</code>```

Body:
I'm scraching my head on this one for a long time and I don't know how to solve this.

I have 2 mysql tables

Table1

+----+----------------------+
| id | name    | order_list |
+----+----------------------+
|  1 | Bob     |    3       |
|  2 | Marc    |    2       |
|  3 | Edith   |    1       |
|  4 | John    |    4       |
+----+----------------------+

Table2

+----+-------------------+
| id | user_id |  sale   |
+----+-------------------+
|  1 |   3     |   30    |
|  2 |   2     |   40    |
|  3 |   1     |   100   |
|  4 |   3     |   75    |
|  5 |   2     |   40    |
|  6 |   1     |   100   |
|  7 |   4     |   75    |
+----+-------------------+

I need to have all purchase from table2 ORDER BY the order_list from table 1 of the user_id from table 2.

Right now I'm doing this in PHP like this.
1 query to get the id from employee from table 1 order by order_list.
A loop
Inside 1 query for each employee to get the sale

I need every sale independent, not sum or group by.

query to get the id from table 1 order by order_list
loop
    query the table2 for the sale of the looped employee
end loop

I know that this can be done with something like this.

SELECT * FROM table2 ORDER BY FIELD (id,order from table 1)

Body:
A basic join should suffice:

select t2.*
from table2 t2 join
     table1 t1
     on t2.user_id = t1.id
order by t1.order_list;

Or, if you prefer, put a subquery in the order by:

select t2.*
from table2 t2
order by (select t1.order_list from table1 t1 where t1.id = t2.user_id);


答:
Nice try.
But you have made some mistakes.

You didn't set counter to the initial value when character other then the space is encountered. So if your input have multiple white spaces in between non white space character like 33 33 33 then the first white space will be printed & others are skipped. So the output would be 33 3333

you have to understand that the char data type only store single character & in ASCII encoding. When you apply arithmetic operations on char, it just change the character Value. So when you decrease the char variable it refers to a another character. So ultimately it prints garbage value.

Try this one.

```<code>while ((c = getchar()) != EOF){
    if (c == ' '){
        ++nl;
        if (nl >= upper){
            continue;
        }
    }
    else{
        nl=0;
    }
    putchar(c);
}
</code>```

Logic is simple...

If there is multiple spaces, put the first space & skip others.

Title: Why isn't this code compressing spaces correctly?

Body:
Nice try.
But you have made some mistakes.

You didn't set counter to the initial value when character other then the space is encountered. So if your input have multiple white spaces in between non white space character like 33 33 33 then the first white space will be printed & others are skipped. So the output would be 33 3333

you have to understand that the char data type only store single character & in ASCII encoding. When you apply arithmetic operations on char, it just change the character Value. So when you decrease the char variable it refers to a another character. So ultimately it prints garbage value.

Try this one.

while ((c = getchar()) != EOF){
    if (c == ' '){
        ++nl;
        if (nl >= upper){
            continue;
        }
    }
    else{
        nl=0;
    }
    putchar(c);
}

Logic is simple...

If there is multiple spaces, put the first space & skip others.


问:
How to add background color to chart`s legend
I am working with library to build a great charts in my app. Everything works good but today I encountered a problem. I want to add simply background color below chart`s legend.

My legend looks like this:

I want to achieve something like this:

My current implementation of chart`s legend part:

```<code>private func prepareLegend() {
    lineChart.legend.drawInside = true
    lineChart.legend.horizontalAlignment = .right
    lineChart.legend.verticalAlignment = .top
    lineChart.legend.orientation = .vertical
    lineChart.legend.formSize = 14.0
    lineChart.legend.yEntrySpace = 6.0
    lineChart.legend.font = UIFont.pmd_robotoRegular(ofSize: 12.0)
    lineChart.legend.textColor = UIColor.pmd_darkGrey

    let upperLegend = LegendEntry()
    upperLegend.label = "Upper Thershold"
    upperLegend.form = .square
    upperLegend.formColor = UIColor.pmd_red

    let lowerLegend = LegendEntry()
    lowerLegend.label = "Lower Thershold"
    lowerLegend.form = .square
    lowerLegend.formColor = UIColor.pmd_red

    lineChart.legend.extraEntries = [upperLegend, lowerLegend]
}
</code>```

Anybody here is familiar with this library and can help me?

答: you can easily add a property rect in legend class and fill it with color. And override renderLegend(context: CGContext) where you can fill the background color in that rect.

Body:
I am working with library to build a great charts in my app. Everything works good but today I encountered a problem. I want to add simply background color below chart`s legend.

My legend looks like this:

I want to achieve something like this:

My current implementation of chart`s legend part:

private func prepareLegend() {
    lineChart.legend.drawInside = true
    lineChart.legend.horizontalAlignment = .right
    lineChart.legend.verticalAlignment = .top
    lineChart.legend.orientation = .vertical
    lineChart.legend.formSize = 14.0
    lineChart.legend.yEntrySpace = 6.0
    lineChart.legend.font = UIFont.pmd_robotoRegular(ofSize: 12.0)
    lineChart.legend.textColor = UIColor.pmd_darkGrey

    let upperLegend = LegendEntry()
    upperLegend.label = "Upper Thershold"
    upperLegend.form = .square
    upperLegend.formColor = UIColor.pmd_red

    let lowerLegend = LegendEntry()
    lowerLegend.label = "Lower Thershold"
    lowerLegend.form = .square
    lowerLegend.formColor = UIColor.pmd_red

    lineChart.legend.extraEntries = [upperLegend, lowerLegend]
}

Anybody here is familiar with this library and can help me?


问:
Inquiries on Cloudflare Caching works?

I would like to ask about a few things about cloudflare since this is fairly new to me. Please do direct me to the correct forum if I am asking this in the wrong place.

We have an issue right now where a user needs to clear his/her cache before they can successfully log in after a password reset. So I was looking for a way to force a user to clear his/her cache when visiting our website and found
This topic about forcing a user to clear cache if I am not mistaken it was advised here that we can adjust the browser cache expiration in Cloudflare so that the users would be force to reload everything after the set time in Cloudflare. My question now is how will this affect the page speed of the site and how do I determine how many hours will I set it to, to avoid any problems?

答:
The proper forum (aside from StackOverflow) is https://community.cloudflare.com/c/setup

CloudFlare's cache applies to static resources like images, css files, and javascript files. Pages are not cached by CloudFlare. Browsers... well, you can't control them all.

But if you really want to force a browser to not cache a page, you can send it some headers. Here is some coldfusion code to accomplish that, in case you're using that language:

```<code><cfheader
    name="Expires"
    value="0">
<cfheader
    name="Expires"
    value="Mon, 26 Jul 1997 05:00:00 GMT">
<cfheader
    name="Cache-Control"
    value="no-store, no-cache, must-revalidate">
<cfheader
    name="Cache-Control"
    value="post-check=0, pre-check=0">
</code>```

Title: Inquiries on Cloudflare Caching works?

Body:
The proper forum (aside from StackOverflow) is https://community.cloudflare.com/c/setup

CloudFlare's cache applies to static resources like images, css files, and javascript files. Pages are not cached by CloudFlare. Browsers... well, you can't control them all.

But if you really want to force a browser to not cache a page, you can send it some headers. Here is some coldfusion code to accomplish that, in case you're using that language:

<cfheader
    name="Expires"
    value="0">
<cfheader
    name="Expires"
    value="Mon, 26 Jul 1997 05:00:00 GMT">
<cfheader
    name="Cache-Control"
    value="no-store, no-cache, must-revalidate">
<cfheader
    name="Cache-Control"
    value="post-check=0, pre-check=0">


问:
generic duck typing in F#?
using let inline and member constraints I'll be able to make duck typing for known members but what if I would like to define a generic function like so:

let duckwrapper<'a> duck = ...

with the signature 'b -> 'a and where the returned value would be an object that implemented 'a (which would be an interface) and forwarded the calls to duck.

I've done this in C# using Reflection.Emit but I'm wondering if F# reflection, quotations or other constructs would make it easier.

Any suggestions on how to accomplish this?

EDIT
after reading Tims answer I thought I'd give a bit more details

What I was thinking of when I wrote about using quotations to help was something like:

```<code>{new IInterface with member x.SayHello() = !!<@ %expr @>}
</code>```

!! being an operator translating the quotation to a function and %expr being the unit of work for the method. I'd be able to translate the expression to a function (I guess) but wouldn't know how to

of course this wouldn't do the trick completely either since IInterface would be 'a which is where I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values

EDIT
As an update to Tomas Petricek answer I'll give some code to explain my needs

```<code>type SourceRole =
   abstract transfer : decimal -> context

and context(sourceAccount:account, destinationAccount) =
   let source = sourceAccount
   let destination = destinationAccount

   member self.transfer amount =
     let sourcePlayer =
       {new SourceRole with
          member this.transfer amount =
              use scope =  new TransactionScope()
              let source = source.decreaseBalance amount
              let destination = destination.increaseBalance amount
              scope.Complete()
              context(source,destination)
              }
     sourcePlayer.transfer(amount)
</code>```

which is a try at porting "the" textbook example of DCI in F#.  The source and destination are DCI roles. It's the idea that any data object that adhere's to a specific contract can play those. In this case the contract is simple. source needs a memberfunction called decreaseBalance and destination needs a member function called increaseBalance.
I can accomplish that for this specific case with let inline and member constraints.
But I'd like to write a set of functions that given an interface and an object. In this case it could be source (as the object) and

```<code>type sourceContract =
   abstract decreaseBalance : decimal -> sourceContract
</code>```

as the type. The result would be an object of type sourceContract that would pipe method calls to a method with the same name on the source object.

答:
F# reflection (Microsoft.FSharp.Reflection) is an F#-friendly wrapper around the plain System.Reflection APIs, so I don't think it would add anything here.

Quotations can't define new types: (you'd need to define a new type to do your interface-based duck typing)

```<code>> <@ { new IInterface with member x.SayHello = "hello" } @>;;

  <@ { new IInterface with member x.SayHello = "hello" } @>;;
  ---^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(7,4): error FS0449: Quotations cannot contain object expressions
> <@ type Test() = class end @>;;

  <@ type Test() = class end @>;;
  ---^^^^

stdin(8,4): error FS0010: Unexpected keyword 'type' in quotation literal
</code>```

Reflection.Emit is still the way to go with this.

Edit:

I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values

I'm afraid it doesn't. Here's the documentation on F# reflection: http://msdn.microsoft.com/en-gb/library/ee353491.aspx

Title: generic duck typing in F#?

Body:
using let inline and member constraints I'll be able to make duck typing for known members but what if I would like to define a generic function like so:

let duckwrapper<'a> duck = ...

with the signature 'b -> 'a and where the returned value would be an object that implemented 'a (which would be an interface) and forwarded the calls to duck.

I've done this in C# using Reflection.Emit but I'm wondering if F# reflection, quotations or other constructs would make it easier.

Any suggestions on how to accomplish this?

EDIT
after reading Tims answer I thought I'd give a bit more details

What I was thinking of when I wrote about using quotations to help was something like:

{new IInterface with member x.SayHello() = !!<@ %expr @>}

!! being an operator translating the quotation to a function and %expr being the unit of work for the method. I'd be able to translate the expression to a function (I guess) but wouldn't know how to

of course this wouldn't do the trick completely either since IInterface would be 'a which is where I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values

EDIT
As an update to Tomas Petricek answer I'll give some code to explain my needs

type SourceRole =
   abstract transfer : decimal -> context

and context(sourceAccount:account, destinationAccount) =
   let source = sourceAccount
   let destination = destinationAccount

   member self.transfer amount =
     let sourcePlayer =
       {new SourceRole with
          member this.transfer amount =
              use scope =  new TransactionScope()
              let source = source.decreaseBalance amount
              let destination = destination.increaseBalance amount
              scope.Complete()
              context(source,destination)
              }
     sourcePlayer.transfer(amount)

which is a try at porting "the" textbook example of DCI in F#.  The source and destination are DCI roles. It's the idea that any data object that adhere's to a specific contract can play those. In this case the contract is simple. source needs a memberfunction called decreaseBalance and destination needs a member function called increaseBalance.
I can accomplish that for this specific case with let inline and member constraints.
But I'd like to write a set of functions that given an interface and an object. In this case it could be source (as the object) and

type sourceContract =
   abstract decreaseBalance : decimal -> sourceContract

as the type. The result would be an object of type sourceContract that would pipe method calls to a method with the same name on the source object.

Body:
F# reflection (Microsoft.FSharp.Reflection) is an F#-friendly wrapper around the plain System.Reflection APIs, so I don't think it would add anything here.

Quotations can't define new types: (you'd need to define a new type to do your interface-based duck typing)

> <@ { new IInterface with member x.SayHello = "hello" } @>;;

  <@ { new IInterface with member x.SayHello = "hello" } @>;;
  ---^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(7,4): error FS0449: Quotations cannot contain object expressions
> <@ type Test() = class end @>;;

  <@ type Test() = class end @>;;
  ---^^^^

stdin(8,4): error FS0010: Unexpected keyword 'type' in quotation literal

Reflection.Emit is still the way to go with this.

Edit:

I hope F# reflection might have some handy functions so that I could construct a type based on a type object and some function values

I'm afraid it doesn't. Here's the documentation on F# reflection: http://msdn.microsoft.com/en-gb/library/ee353491.aspx


问:
explode function doesn't work for me?
I want to change the string into array after using foreach() so
          how is it done? </p>

```<code>$g = "";
$changer = explode(",", $g);
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}
</code>```

答:
I found the answer myself the only problem is the position of my explode function:</p>

```<code><!-- my code -->
$g ="";
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}
$changer = explode(",", $g);
</code>```

Title: explode function doesn't work for me?

Body:
I want to change the string into array after using foreach() so
          how is it done?

$g = "";
$changer = explode(",", $g);
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}

Body:
I found the answer myself the only problem is the position of my explode function:

<!-- my code -->
$g ="";
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}
$changer = explode(",", $g);


答:
The solution you've posted is more complicated than it needs to be - your also performs some operations that seem meaningless to me, such as c -= ' '.

I think you should practice on devising algorithms and problem-solving in general, outside of programming in any specific language. Think about how you would do it yourself given nothing more than input strings and piece of square-lined paper and a pencil.

In pseudo-code, the minimal solution is as-follows:

```<code>1. Read character C from input (if there is no input, end program)
2. If character is a space character:
    2.1. Was the last printed character a space character too? If so, don't print anything and loop back to step 1.
3. Else, print character C and loop back to step 1.
</code>```

In C, this can be written minimally (in C11) as:

```<code>int main( void )
{
    bool last_char_was_space = false;
    int c;
    while( ( c = getchar() ) != EOF )
    {
        if( last_char_was_space )
        {
            if( c == ' ' ) continue; // don't print anything
            else
            {
                putchar( c );
                last_char_was_space = false;
            }
        }
        else
        {
            putchar( c );
            if( c == ' ' )
            {
                last_char_was_space = true;
            }
        }
    }

    return 0;
}
</code>```

This program is a simple example of a "finite-state machine", which is an example of a stateful algorithm and the foundational building-block of things like Regular Expressions and other types of parsers. It's an essential technique to familiarise yourself with if you want to write a program that can quickly process data with maximum performance and minimal memory usage.

Body:
The solution you've posted is more complicated than it needs to be - your also performs some operations that seem meaningless to me, such as c -= ' '.

I think you should practice on devising algorithms and problem-solving in general, outside of programming in any specific language. Think about how you would do it yourself given nothing more than input strings and piece of square-lined paper and a pencil.

In pseudo-code, the minimal solution is as-follows:

1. Read character C from input (if there is no input, end program)
2. If character is a space character:
    2.1. Was the last printed character a space character too? If so, don't print anything and loop back to step 1.
3. Else, print character C and loop back to step 1.

In C, this can be written minimally (in C11) as:

int main( void )
{
    bool last_char_was_space = false;
    int c;
    while( ( c = getchar() ) != EOF )
    {
        if( last_char_was_space )
        {
            if( c == ' ' ) continue; // don't print anything
            else
            {
                putchar( c );
                last_char_was_space = false;
            }
        }
        else
        {
            putchar( c );
            if( c == ' ' )
            {
                last_char_was_space = true;
            }
        }
    }

    return 0;
}

This program is a simple example of a "finite-state machine", which is an example of a stateful algorithm and the foundational building-block of things like Regular Expressions and other types of parsers. It's an essential technique to familiarise yourself with if you want to write a program that can quickly process data with maximum performance and minimal memory usage.


问:
how to run ffmpeg command(windows) in java
I executed the below FFMPEG terminal command in command prompt successfully. But I am unable to execute this command in my java program. I can execute all other ffmpeg commands which doesn't have double quotation marks, in my java program. Here I have confusing only with double quotation marks("...").

```<code>ffmpeg -i "concat:C:\\journalism\\videos\\vid1.ts|C:\\journalism\\videos\\vid2.ts" -c copy C:\\journalism\\videos\\output.mp4
</code>```

I can execute above in command prompt successfully. But I tried as below in my java code.

```<code>Runtime.getRuntime().exec("C:\\ffmpeg\\bin\\ffmpeg -i 'concat:C:\\journalism\\videos\\vid1.ts|C:\\journalism\\videos\\vid2.ts' -c copy C:\\journalism\\videos\\output.mp4");
</code>```

Even I tried by replaced the double quotation marks("...") with single quotation marks('...'). But not succeeded.

Can anyone please help me to get out of this issue...

Thanks in advance...

答:
My program is running, i just use as below. Hope it help you :

String cmd = "ffmpeg -i http://117.103.224.78/videoinput/Video1.mp4 -s 1920x1080 -c:a copy D:\\tmp\\Video2.mp4";

Process p = Runtime.getRuntime().exec(cmd);

Body:
I executed the below FFMPEG terminal command in command prompt successfully. But I am unable to execute this command in my java program. I can execute all other ffmpeg commands which doesn't have double quotation marks, in my java program. Here I have confusing only with double quotation marks("...").

ffmpeg -i "concat:C:\\journalism\\videos\\vid1.ts|C:\\journalism\\videos\\vid2.ts" -c copy C:\\journalism\\videos\\output.mp4

I can execute above in command prompt successfully. But I tried as below in my java code.

Runtime.getRuntime().exec("C:\\ffmpeg\\bin\\ffmpeg -i 'concat:C:\\journalism\\videos\\vid1.ts|C:\\journalism\\videos\\vid2.ts' -c copy C:\\journalism\\videos\\output.mp4");

Even I tried by replaced the double quotation marks("...") with single quotation marks('...'). But not succeeded.

Can anyone please help me to get out of this issue...

Thanks in advance...


问:
Round NaN in Haskell
To my great surprise, I found that rounding a NaN value in Haskell returns a gigantic negative number:

```<code>round (0/0)
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824
</code>```

The same thing happens with floor and ceiling.

What is happening here? Is this behavior intended? Of course, I understand that anyone who doesn't want this behavior can always write another function that checks isNaN - but are there existing alternative standard library functions that handle NaN more sanely (for some definition of "more sanely")?

答:
This has long been observed as a problem. Here're a few tickets filed against GHC on this very topic:

https://ghc.haskell.org/trac/ghc/ticket/3070

https://ghc.haskell.org/trac/ghc/ticket/11553

https://ghc.haskell.org/trac/ghc/ticket/3676

Unfortunately, this is a thorny issue with lots of ramifications. My personal belief is that this is a genuine bug and it should be fixed properly by throwing an error. But you can read the comments on these tickets to get an understanding of the tricky issues preventing GHC from implementing a proper solution. Essentially, it comes down to speed vs. correctness, and this is one point where (i) the Haskell report is woefully underspecified, and (ii) GHC compromises the latter for the former.

Title: Round NaN in Haskell

Body:
To my great surprise, I found that rounding a NaN value in Haskell returns a gigantic negative number:

round (0/0)
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824

The same thing happens with floor and ceiling.

What is happening here? Is this behavior intended? Of course, I understand that anyone who doesn't want this behavior can always write another function that checks isNaN - but are there existing alternative standard library functions that handle NaN more sanely (for some definition of "more sanely")?


问:
Loading Page Fragments with .load() excludes embeded javascript
I have a form that is loaded using the .load() method.

```<code>$(function() {
    $('#items,#button-search').hide();
    $("#companies").click(function() {
        $(this).attr("value","");
        $('#address,#new-company-form').empty();
    });
    $( "#companies" ).autocomplete({
        source: ";companies",
        minLength: 2,
        select: function( event, ui ) {
            if(ui.item.id == "create-new-company") {
                // call the new company form
                $('#address').empty();
                $('#new-company-form').load(';company_form #autoform');
            }
            else
            {
                $('#new-company-form').empty();
                $.ajax({
                    type: 'GET',
                    url: ';addresses?company=' + ui.item.id,
                    dataType: 'json',
                    // process the addresses
                    success: function(json) {
                        var opts = '';
                        $.each(json, function(k, v) {
                            opts += '<option>' + v + '</option>';
                        });
                        $('#address').html('<select>' + opts + '</select>');
                    }
                }); //end ajax call to address
            }
        } // end select address
    }); // end autocomplete
}); // end function
</code>```

on line 15, i have

```<code>$('#new-company-form').load(';company_form #autoform');
</code>```

if i remove the #autoform the javascript that is in the ;company_form html works, otherwise it is not loaded.

how do i get this to work?

thanks

答:
Yeah he wants to load just the page fragment. The first argument is indeed url, so just put the name of the page that 'company_form' resides in then add the fragment you want. So it should look something like this...

```<code>$('#new-company-form').load('company_form.php #autoform');
</code>```

I guess the only change is add the extension to 'company_form'

Body:
I have a form that is loaded using the .load() method.

$(function() {
    $('#items,#button-search').hide();
    $("#companies").click(function() {
        $(this).attr("value","");
        $('#address,#new-company-form').empty();
    });
    $( "#companies" ).autocomplete({
        source: ";companies",
        minLength: 2,
        select: function( event, ui ) {
            if(ui.item.id == "create-new-company") {
                // call the new company form
                $('#address').empty();
                $('#new-company-form').load(';company_form #autoform');
            }
            else
            {
                $('#new-company-form').empty();
                $.ajax({
                    type: 'GET',
                    url: ';addresses?company=' + ui.item.id,
                    dataType: 'json',
                    // process the addresses
                    success: function(json) {
                        var opts = '';
                        $.each(json, function(k, v) {
                            opts += '<option>' + v + '</option>';
                        });
                        $('#address').html('<select>' + opts + '</select>');
                    }
                }); //end ajax call to address
            }
        } // end select address
    }); // end autocomplete
}); // end function

on line 15, i have

$('#new-company-form').load(';company_form #autoform');

if i remove the #autoform the javascript that is in the ;company_form html works, otherwise it is not loaded.

how do i get this to work?

thanks

Body:
Yeah he wants to load just the page fragment. The first argument is indeed url, so just put the name of the page that 'company_form' resides in then add the fragment you want. So it should look something like this...

$('#new-company-form').load('company_form.php #autoform');

I guess the only change is add the extension to 'company_form'


问:
LC.exe could not be run
On compilation I receive error for LC.EXE

The specified task executable "LC.exe" could not be run. The filename or extension is too long

This error occurs when I compile my unit test project.  Of the google tricks I've seen, nothing has worked.

I am set to Target framework = ".NET Framework 4" not client profile.

This started today.  There's hardly anything in source control history.  The changes all have to do with AssemblyInfo.cs where a 3rd party utility increments our version #'s.

UPDATE

Looking out my output window the command line call to LC.EXE is HUGE

CompileLicxFiles:

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\LC.exe /target:BuildAll.Tests.dll /complist:Properties\licenses.licx /outdir:obj\Debug\ /i:C:\

There's 100's of /i params...

答:
I used the command-line utility "Subst" as mentioned in this blog post to resolve my issue with LC.exe.

Turn on Normal or higher Verbosity for your build.

In the Output window, examine the line where the LC task is being executed. Notice there will be many /i parameters with paths to other binaries.

Find one or more paths that you can use "Subst" to help shorten the path to help reduce the total length of all parameters passed to "LC.exe".

Next, open the problem project's properties window in Visual Studio and select the References tab and then add the new drives you defined with Subst.

Build the project.

Remember, Subst does not persist through reboot.

Title: LC.exe could not be run


问:
OpenIdConnectAuthenticationNotifications.AuthorizationCodeReceived event not firing
using this sample:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect

This works as expected when running it locally
But when we deploy it (azure web app), it still authenticates, but the OpenIdConnectAuthenticationNotifications.AuthorizationCodeReceived event is not firing.

This the code.

```<code>    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = Authority,
            PostLogoutRedirectUri = redirectUri,
            RedirectUri = redirectUri,

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed
            }
        });

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
    var code = context.Code;

    ClientCredential credential = new ClientCredential(clientId, appKey);
    string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));

    Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);
}
</code>```

This is a problem because it requires caching of the token to make an outbound call.
Since it doesn’t have it, it throws.

There was an issue that caused this related to a trailing slash after the redir url but we’ve already tried that.

So two questions…
1)  Under what conditions would event get fired and why would this work when running locally? According to the docs it should be "Invoked after security token validation if an authorization code is present in the protocol message."

2)  What is the best way to debug this?  Not clear on what to look for here.

答:
1) Under what conditions would event get fired and why would this work when running locally? According to the docs it should be "Invoked after security token validation if an authorization code is present in the protocol message."

As the document point, this event will fire when the web app verify the  authorization code is present in the protocol message.

2) What is the best way to debug this? Not clear on what to look for here.

There are many reason may cause the exception when you call the request with the access_token. For example, based on the code you were using the NaiveSessionCache which persist the token using the Sesstion object. It means that you may also get the exception when you deploy the web app with multiple instance. To trouble shoot this issue, I suggest that you remote debug the project to find the root cause. For remote debug, you can refer the document below:

Introduction to Remote Debugging on Azure Web Sites

ContentLicense: CC BY-SA 4.0

Body:
using this sample:
https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect

This works as expected when running it locally
But when we deploy it (azure web app), it still authenticates, but the OpenIdConnectAuthenticationNotifications.AuthorizationCodeReceived event is not firing.

This the code.

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = Authority,
            PostLogoutRedirectUri = redirectUri,
            RedirectUri = redirectUri,

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed
            }
        });

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
    var code = context.Code;

    ClientCredential credential = new ClientCredential(clientId, appKey);
    string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));

    Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

    AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);
}

This is a problem because it requires caching of the token to make an outbound call.
Since it doesn’t have it, it throws.

There was an issue that caused this related to a trailing slash after the redir url but we’ve already tried that.

So two questions…
1)  Under what conditions would event get fired and why would this work when running locally? According to the docs it should be "Invoked after security token validation if an authorization code is present in the protocol message."

2)  What is the best way to debug this?  Not clear on what to look for here.


问:
how to execute different system commands in differrent threads with python3
I want to execute two different commands in different thread with python3,below is my code:

```<code>import time
import threading
import os

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result():
        return self.result

def sniffdata1():
    while 1:
        time.sleep(1)
        os.system("echo 2")

def sniffdata2():
        time.sleep(1)
        os.system("echo 1")

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
sniffThread1.join()
sniffThread2.join()
</code>```

But I can not get my 121212...,the result is 1 2 2 2 2 2 2 2 ...(no more 1),but alway echo 2,can someone help me?

答:
When I use multi process to deal with it,it works,but I am not very clear about the reason,below is my solution code:</p>

```<code>from multiprocessing import Process
import os
import time

def worker1():
  """test python multi process"""
  while 1:
      time.sleep(1)
      os.system("echo 1")
      #os.system("ping www.baidu.com")

def worker2():
  """test python multi process"""
  while 1:
      time.sleep(2)
      os.system("echo 2")
      #os.system("ping www.bing.com")

def main():
  jobs = []
  p1 = Process(target=worker1,args=())
  p2 = Process(target=worker2,args=())
  jobs.append(p1)
  jobs.append(p2)
  p1.start()
  p2.start()
  ##to avoid defunct process,you should call join()
  for j in jobs:
    j.join()

if __name__=='__main__':
  main()
</code>```

Body:
I want to execute two different commands in different thread with python3,below is my code:

import time
import threading
import os

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result():
        return self.result

def sniffdata1():
    while 1:
        time.sleep(1)
        os.system("echo 2")

def sniffdata2():
        time.sleep(1)
        os.system("echo 1")

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
sniffThread1.join()
sniffThread2.join()

But I can not get my 121212...,the result is 1 2 2 2 2 2 2 2 ...(no more 1),but alway echo 2,can someone help me?

Body:
When I use multi process to deal with it,it works,but I am not very clear about the reason,below is my solution code:

from multiprocessing import Process
import os
import time

def worker1():
  """test python multi process"""
  while 1:
      time.sleep(1)
      os.system("echo 1")
      #os.system("ping www.baidu.com")

def worker2():
  """test python multi process"""
  while 1:
      time.sleep(2)
      os.system("echo 2")
      #os.system("ping www.bing.com")

def main():
  jobs = []
  p1 = Process(target=worker1,args=())
  p2 = Process(target=worker2,args=())
  jobs.append(p1)
  jobs.append(p2)
  p1.start()
  p2.start()
  ##to avoid defunct process,you should call join()
  for j in jobs:
    j.join()

if __name__=='__main__':
  main()


问:
Dynamic Column Names with Pivot SQL
Hello all I'm still relatively new to SQL and a search online haven't provided me a solution yet (or its been right in front of me but out of my sphere of knowledge :/). So hoping to try my luck here thanks!

```<code>Table:   Servers
Columns: ServerUrl               ServerName
Rows:    //server0001/space0/    Telescope1
         //server0001/space1/    Space
         //server0001/space2/    Planet

Table:   Projects
Columns: ServerUrl               Name          Entity     Type
Rows:    //server0001/space0/    Field1        E          T1
         //server0001/space1/    Field2        T          T1
         //server0001/space2/    Field3        E          T3
</code>```

With the stored procedure below I was able to return the data as:

So the ServerUrl gets used as the column names as seen below but I want it to be the ServerName instead. I know its possible to set the columns to be ServerNames but how would I go about doing it dynamically since the ServerUrl may change.

```<code>--- Returned Data Begin ---
Stored Procedure Results:
Columns: Name    Entity  //server0001/space0/   ...space1  ...space2
Rows:    Field1  E       T1                     NULL       NULL
         Field2  T       NULL                   T2         NULL
         Field3  E       NULL                   NULL       T3

--- Returned Data End ---
</code>```

***Stored Procedure below used to get Results Above

```<code>--- STORED PROCEDURE BEGIN ---
DECLARE @Projects varchar(max)
SELECT @ProgramList = COALESCE(@Projects + '], [', '') + ServerURL FROM
Servers ORDER BY ServerURL

SET @ProgramList = CONCAT ('[', @ProgramList + ']')

DECLARE @sql nvarchar(max)
SET @sql = 'select * from ( select P.Name, P.Entity, P.Field, P.ServerUrl
FROM ProjectFields as P ) as P pivot (min(P.Field) for P.ServerUrl in (' +
@Projects + ')) as PIV ORDER BY Name'

EXEC sp_executesql @sql1
--- STORED PROCEDURE END ---
</code>```

Thank you :)

答:
Your stored procedure looks like it's incomplete or you've changed certain things, but I believe you're looking for something like the following:</p>

```<code>DECLARE @ProgramList VARCHAR(MAX);
SELECT @ProgramList = STUFF((SELECT ',' + QUOTENAME(ServerName) FROM [Servers] ORDER BY ServerURL FOR XML PATH ('')), 1, 1, '');

DECLARE @sql VARCHAR(MAX);
SELECT @sql = '
SELECT *
FROM
(
    SELECT P.Name,
           P.Entity,
           P.Field,
           S.ServerName
    FROM ProjectFields AS P
    JOIN [Servers] AS S
        ON S.ServerURL = P.ServerURL
) AS P
PIVOT
(
    MIN(Field) FOR ServerName IN (' + @ProgramList + ')
) AS PIV
ORDER BY PIV.Name;';

--PRINT @sql;
EXEC sp_executesql @sql;
</code>```

Title: Dynamic Column Names with Pivot SQL

Body:
Hello all I'm still relatively new to SQL and a search online haven't provided me a solution yet (or its been right in front of me but out of my sphere of knowledge :/). So hoping to try my luck here thanks!

Table:   Servers
Columns: ServerUrl               ServerName
Rows:    //server0001/space0/    Telescope1
         //server0001/space1/    Space
         //server0001/space2/    Planet

Table:   Projects
Columns: ServerUrl               Name          Entity     Type
Rows:    //server0001/space0/    Field1        E          T1
         //server0001/space1/    Field2        T          T1
         //server0001/space2/    Field3        E          T3

With the stored procedure below I was able to return the data as:

So the ServerUrl gets used as the column names as seen below but I want it to be the ServerName instead. I know its possible to set the columns to be ServerNames but how would I go about doing it dynamically since the ServerUrl may change.

--- Returned Data Begin ---
Stored Procedure Results:
Columns: Name    Entity  //server0001/space0/   ...space1  ...space2
Rows:    Field1  E       T1                     NULL       NULL
         Field2  T       NULL                   T2         NULL
         Field3  E       NULL                   NULL       T3

--- Returned Data End ---

***Stored Procedure below used to get Results Above

--- STORED PROCEDURE BEGIN ---
DECLARE @Projects varchar(max)
SELECT @ProgramList = COALESCE(@Projects + '], [', '') + ServerURL FROM
Servers ORDER BY ServerURL

SET @ProgramList = CONCAT ('[', @ProgramList + ']')

DECLARE @sql nvarchar(max)
SET @sql = 'select * from ( select P.Name, P.Entity, P.Field, P.ServerUrl
FROM ProjectFields as P ) as P pivot (min(P.Field) for P.ServerUrl in (' +
@Projects + ')) as PIV ORDER BY Name'

EXEC sp_executesql @sql1
--- STORED PROCEDURE END ---

Thank you :)

Body:
Your stored procedure looks like it's incomplete or you've changed certain things, but I believe you're looking for something like the following:

DECLARE @ProgramList VARCHAR(MAX);
SELECT @ProgramList = STUFF((SELECT ',' + QUOTENAME(ServerName) FROM [Servers] ORDER BY ServerURL FOR XML PATH ('')), 1, 1, '');

DECLARE @sql VARCHAR(MAX);
SELECT @sql = '
SELECT *
FROM
(
    SELECT P.Name,
           P.Entity,
           P.Field,
           S.ServerName
    FROM ProjectFields AS P
    JOIN [Servers] AS S
        ON S.ServerURL = P.ServerURL
) AS P
PIVOT
(
    MIN(Field) FOR ServerName IN (' + @ProgramList + ')
) AS PIV
ORDER BY PIV.Name;';

--PRINT @sql;
EXEC sp_executesql @sql;


问:
How do I create a directory, and any missing parent directories?
How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.

答:
I would personally recommend that you use os.path.isdir() to test instead of os.path.exists().

```<code>>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
</code>```

If you have:

```<code>>>> directory = raw_input(":: ")
</code>```

And a foolish user input:

```<code>:: /tmp/dirname/filename.etc
</code>```

... You're going to end up with a directory named filename.etc when you pass that argument to os.makedirs() if you test with os.path.exists().

OwnerDisplayName: Parand

LastEditorDisplayName: Parand

Body:
I would personally recommend that you use os.path.isdir() to test instead of os.path.exists().

>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False

If you have:

>>> directory = raw_input(":: ")

And a foolish user input:

:: /tmp/dirname/filename.etc

... You're going to end up with a directory named filename.etc when you pass that argument to os.makedirs() if you test with os.path.exists().

OwnerDisplayName: crimsonstone


问:
Using the DetailView how do I get the selected row value on the DetailViewController.m file?
I trying to save my plist after a simple detail change.

Here's the line that I need fixed.

```<code>[plist replaceObjectAtIndex:0 withObject:nameDictionary];
</code>```

I need to replace the 0 with a variable that gets the row that was selected.  Remember, I'm using the codebase from the tutorial above.

something like indexPath.row would be great but I can't get it to work.

My array is no longer accessible on the detail view.

答:
One easy way...
Create a NSInterger object in DetailsView.lets say mySelectedIndex

inside RootViewControlle didSelectRowAtIndexPath ..you can access mySelectedIndex

```<code>DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];

dvController.mySelectedIndex = indexPath.row;

[self.navigationController pushViewController:dvController animated:YES];
</code>```

inside DetailsView

```<code>[plist replaceObjectAtIndex:mySelectedIndex withObject:nameDictionary];
</code>```

Second..
Singleton Variable to store the data and access it anywhere in the App.

Third..
Use NSUSerDefaults..

Body:
I trying to save my plist after a simple detail change.

Here's the line that I need fixed.

[plist replaceObjectAtIndex:0 withObject:nameDictionary];

I need to replace the 0 with a variable that gets the row that was selected.  Remember, I'm using the codebase from the tutorial above.

something like indexPath.row would be great but I can't get it to work.

My array is no longer accessible on the detail view.

Body:
One easy way...
Create a NSInterger object in DetailsView.lets say mySelectedIndex

inside RootViewControlle didSelectRowAtIndexPath ..you can access mySelectedIndex

DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];

dvController.mySelectedIndex = indexPath.row;

[self.navigationController pushViewController:dvController animated:YES];

inside DetailsView

[plist replaceObjectAtIndex:mySelectedIndex withObject:nameDictionary];

Second..
Singleton Variable to store the data and access it anywhere in the App.

Third..
Use NSUSerDefaults..


问:
An object with the name already exist in the database just when I use constraint
When I use this script:

```<code>IF OBJECT_ID('dbo.TableX', 'U') IS NOT NULL
    DROP TABLE dbo.TableX

CREATE TABLE TableX
(
    ...
    ...
    ...

    CONSTRAINT TableX PRIMARY KEY (column1, column2, column3)
)
</code>```

I get an error

An object with the name 'TableX' already exist in the database

but that is only when I use the CONSTRAINT line.

Why do I get an error only when I use CONSTRAINT and how can I solve it?

答:
Tables and constraints all are treated as objects in SQL Server database.
Check sys.objects system table.

So you cannot have the same name for Table and Constraint. When you run the create statement, SQL server will first creates the table and then tries to create the Constraint which fails as the name already exists in sys.objects for table.

Try a different name for the primary key constraint. As per standards, primary keys are prefixed with PK_. So here you can name your primary key as PK_TableX

Body:
When I use this script:

IF OBJECT_ID('dbo.TableX', 'U') IS NOT NULL
    DROP TABLE dbo.TableX

CREATE TABLE TableX
(
    ...
    ...
    ...

    CONSTRAINT TableX PRIMARY KEY (column1, column2, column3)
)

I get an error

An object with the name 'TableX' already exist in the database

but that is only when I use the CONSTRAINT line.

Why do I get an error only when I use CONSTRAINT and how can I solve it?