问:
Use a regex for matching the value of an attribute parsing with beautifulsoup
Hi from the clumsyland,

I'm trying to parse a forum. More specifically, the threads' names.

the threads are offered by the forum engine (vbulletin) as this

```<code><a href="http://www.example.com/showthread.php?t=555555" id="thread_title_555555">NAME OF THE TITLE</a>
</code>```

Using python and beautifulsoup, I have obtain successes with other fields. However, I'm not able to parse "id" attribute using a regex. I need that these lines of the parser find every "a" element with a six-figure id and get the text from it

something like this

```<code>for elements in soup.findAll("a"):
    if re.match("thread_title_", element['id']) is not None:
        print element.text
</code>```

or in pseudopython:

```<code>for elements in soup.finAll("a", {"id": "thread_title_".*}):
    print element.text
</code>```

I tried dozens of variations, for no avail. What can I do?

Thanks in advance

答:
\D*(\d{6})

Does that not match what you want?  If not, what else have you tried?

EDITED: If the thread titles can include digits the above will not match, so consider using the regex \w*(\d{6})

The difference is \D matches all non-digits while \w matches any letter, digit or underscore.

Body:
Hi from the clumsyland,

I'm trying to parse a forum. More specifically, the threads' names.

the threads are offered by the forum engine (vbulletin) as this

NAME OF THE TITLE

Using python and beautifulsoup, I have obtain successes with other fields. However, I'm not able to parse "id" attribute using a regex. I need that these lines of the parser find every "a" element with a six-figure id and get the text from it

something like this

for elements in soup.findAll("a"):
    if re.match("thread_title_", element['id']) is not None:
        print element.text

or in pseudopython:

for elements in soup.finAll("a", {"id": "thread_title_".*}):
    print element.text

I tried dozens of variations, for no avail. What can I do?

Thanks in advance


来源: stackexchange

问:
Error on adding extension to FirefoxProfile
After searching I found a way to add extension to the Firefox via .FirefoxProfile(). However, the same solution is mentioned everywhere.

I don't understand why I am facing an error. Here is the code:

```<code> String firebugFilePath = "C:\FF_addons\firebug.xpi";
        FirefoxProfile profile = new FirefoxProfile();
        try {
            profile.addExtension(new File(firebugFilePath));
            // Add more FF addons if required
        } catch (IOException err) {
        }
        driver = new FirefoxDriver(profile);
</code>```

Error I am facing is on the 4th line: incompatible types: com.gargoylesoftware.htmlunit.javascript.host.file.File cannot be converted to java.io.File.

答:
It sounds like you are importing the wrong File class.

change your

```<code>import com.gargoylesoftware.htmlunit.javascript.host.file.File
</code>```

to

```<code>import java.io.File
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After searching I found a way to add extension to the Firefox via .FirefoxProfile(). However, the same solution is mentioned everywhere.

I don't understand why I am facing an error. Here is the code:

 String firebugFilePath = "C:\FF_addons\firebug.xpi";
        FirefoxProfile profile = new FirefoxProfile();
        try {
            profile.addExtension(new File(firebugFilePath));
            // Add more FF addons if required
        } catch (IOException err) {
        }
        driver = new FirefoxDriver(profile);

Error I am facing is on the 4th line: incompatible types: com.gargoylesoftware.htmlunit.javascript.host.file.File cannot be converted to java.io.File.

Body:
It sounds like you are importing the wrong File class.

change your

import com.gargoylesoftware.htmlunit.javascript.host.file.File

to

import java.io.File


问:
How to Accomplish a Where on a joined table with Entity Framework
I have the following 2 tables in my database:

```<code>[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)
</code>```

and:

```<code>[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)
</code>```

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

```<code>select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()
</code>```

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

```<code>var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );
</code>```

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.

答:
Something like

```<code>context.Schedule.Where(y => y.Time < DateTime.Now).Select( s => s.Patient);
</code>```

or

```<code>context.Patient.Where( p => p.Schedules.Any( s => s.Time < DateTime.Now) );
</code>```

Body:
I have the following 2 tables in my database:

[Schedule](
    [Time] [datetime] NULL,
    [ScheduleID] [bigint] IDENTITY(1,1) NOT NULL,
    [PatientID] [varchar](20) NULL,
 CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
    [ScheduleID] ASC
)

and:

[Patient](
    [NameLast] [varchar](20) NOT NULL,
    [NameMiddle] [varchar](20) NULL,
    [NameFirst] [varchar](20) NOT NULL,
    [DOB] [varchar](20) NULL,
    [PatientID] [varchar](20) NOT NULL,
 CONSTRAINT [PK_Patient] PRIMARY KEY CLUSTERED
(
    [PatientID] ASC
)

And I want to accomplish the following SQL, except using linq methods with Entity Framework:

select NameFirst, NameLast, DOB
from Patient
join Schedule on Schedule.PatientID = Patient.PatientID
where Schedule.Time < GETDATE()

I know how to create a join, using my mappings, so creating a join isn't the problem.  I also know how to do the date functionality I need so that isn't the problem.

I need to know how to accomplish (using linq methods) the part that says: where Schedule.Time < SOMETHING

Here's what I have tried, but it threw an error:

var patients = context.Patient
    .Include(x =>
        x.Schedule.Where(y => y.Time < DateTime.Now)
    );

The error it gave me was:  "The Include path expression must refer to a navigation property defined on the type."

So, how can I accomplish a "Where" on a joined table, like I can in SQL, using linq methods with Entity Framework?

I can't do context.Patients.Where(x => x.Schedules.Time == DateTime.Now); because Patient.Schedules is a collection, since this is a one-to-many relationship.

Body:
Something like

context.Schedule.Where(y => y.Time < DateTime.Now).Select( s => s.Patient);

or

context.Patient.Where( p => p.Schedules.Any( s => s.Time < DateTime.Now) );


问:
Using GD in PHP, how can I make a transparent PNG watermark on PNG and GIF files ? (JPG files work fine)
I have an image (let's call it original image) on which I want to watermark another image (let's call it logo).

The logo is a transparent PNG, whereas the original image can be png, jpg, or gif.

I have the following code:

```<code>function watermarkImage($originalFileContents, $originalWidth, $originalHeight) {
    $logoImage = imagecreatefrompng('logo.png');
    imagealphablending($logoImage, true);

    $logoWidth  = imagesx($logoImage);
    $logoHeight = imagesy($logoImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth  - $logoWidth;
    $destY = $originalHeight - $logoHeight;

    imagecopy(
        // source
        $originalImage,
        // destination
        $logoImage,
        // destination x and y
        $destX, $destY,
        // source x and y
        0, 0,
        // width and height of the area of the source to copy
        $logoWidth, $logoHeight
    );
    imagepng($originalImage);
}
</code>```

This code works good (good = keep the transparency of the logo) only when the original image is a JPG file.

When the original file is a GIF or PNG, the logo has a solid white background, meaning the transparency is not working.

Why ? What do I need to change so it'll work ?

Thanks

UPDATE:

Here is my recoded version:

```<code>function generate_watermarked_image($originalFileContents, $originalWidth, $originalHeight, $paddingFromBottomRight = 0) {
    $watermarkFileLocation = 'watermark.png';
    $watermarkImage = imagecreatefrompng($watermarkFileLocation);
    $watermarkWidth = imagesx($watermarkImage);
    $watermarkHeight = imagesy($watermarkImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth - $watermarkWidth - $paddingFromBottomRight;
    $destY = $originalHeight - $watermarkHeight - $paddingFromBottomRight;

    // creating a cut resource
    $cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);

    // copying that section of the background to the cut
    imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);

    // placing the watermark now
    imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);

    // merging both of the images
    imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
}
</code>```

答:
imagecopy does not support using two images with alpha channels.
take a look at imagecopymerge.

http://php.net/manual/en/function.imagecopymerge.php

There are plenty examples in the user comments sections, and a finished implementation for what you want:

http://www.php.net/manual/en/function.imagecopymerge.php#92787

ContentLicense: CC BY-SA 2.5

Body:
I have an image (let's call it original image) on which I want to watermark another image (let's call it logo).

The logo is a transparent PNG, whereas the original image can be png, jpg, or gif.

I have the following code:

function watermarkImage($originalFileContents, $originalWidth, $originalHeight) {
    $logoImage = imagecreatefrompng('logo.png');
    imagealphablending($logoImage, true);

    $logoWidth  = imagesx($logoImage);
    $logoHeight = imagesy($logoImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth  - $logoWidth;
    $destY = $originalHeight - $logoHeight;

    imagecopy(
        // source
        $originalImage,
        // destination
        $logoImage,
        // destination x and y
        $destX, $destY,
        // source x and y
        0, 0,
        // width and height of the area of the source to copy
        $logoWidth, $logoHeight
    );
    imagepng($originalImage);
}

This code works good (good = keep the transparency of the logo) only when the original image is a JPG file.

When the original file is a GIF or PNG, the logo has a solid white background, meaning the transparency is not working.

Why ? What do I need to change so it'll work ?

Thanks

UPDATE:

Here is my recoded version:

function generate_watermarked_image($originalFileContents, $originalWidth, $originalHeight, $paddingFromBottomRight = 0) {
    $watermarkFileLocation = 'watermark.png';
    $watermarkImage = imagecreatefrompng($watermarkFileLocation);
    $watermarkWidth = imagesx($watermarkImage);
    $watermarkHeight = imagesy($watermarkImage);

    $originalImage = imagecreatefromstring($originalFileContents);

    $destX = $originalWidth - $watermarkWidth - $paddingFromBottomRight;
    $destY = $originalHeight - $watermarkHeight - $paddingFromBottomRight;

    // creating a cut resource
    $cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);

    // copying that section of the background to the cut
    imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);

    // placing the watermark now
    imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);

    // merging both of the images
    imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
}


问:
How do I combine AWS API Gateway and Application Load Balancer for HTTPS outside of us-east-1?
I am attempting to route traffic through the AWS API Gateway to my ECS containers running in a private subnet via an Application Load Balancer running in a public subnet. Using plain old HTTP everything works perfectly fine, but now I want to add transport layer security (TLS, fka SSL) to the communication between the gateway and the load balancer. In other words, terminate SSL at the load balancer.

I've got a custom domain name configured and working on my gateway that was already exposing a HTTPS endpoint.

I've got a HTTPS listener configured on my load balancer, which scolds me for having a dodgy certificate but if I ignore the warning when I hit it directly I get routed to my service correctly. Thus load balancer routing is correct.

When I attempt to point the gateway to the balancer it breaks. Furthermore, it seems the I can only use certificates for custom domain names that are in the us-east-1 region. At present they are failing with the following error in CloudWatch (details obscured for privacy).

Execution failed due to configuration error: Host name
  'XXXXXXXXX-lb-XXXXXXXXX..elb.amazonaws.com' does not match the
  certificate subject provided by the peer (CN=)

Given my load balancer is not in the us-east-1 region how can I achieve my goal?

答: Assign a custom domain name to the load balancer. Then assign a valid SSL certificate to the load balancer using the ACM service. Then reference the load balancer using the custom domain name.</p>


问:
Segmentation Fault - linked lists (UNIX)
I'm trying to understand why i'm receiving a segmentation fault.

I have a linked list 'head' with prev and next pointers and i'm trying to delete a specific node in the list. The specific node's address is held by 'ptr'.
I've attached an image showing the debugger,
the following code gives me segmentation fault:
(I'm showing only what's relevant)

```<code>void someFunc(char str[], int atmSN){

/*some code */

switch(ch){    /// ch is char

/* some code */

case 'Q':
    if (ptr == head){                   // if ptr head of linked list
        head = head->next;
        if (head != NULL)
            head->prev = NULL;
    }
    else{
        ptr->prev->next = ptr->next;
        if (ptr->next != NULL)  // if ptr is not last
            ptr->next->prev = ptr->prev;
    }

    free(ptr);
break;

/*some code */
</code>```

debugger

My code is using multi-threads, so perhaps another thread is writing to the specific node while the current thread is trying to delete it.
In my task I have to implement semaphores as well, But does this can give us a segmentation fault?

Correct me if i'm wrong: segmentation fault happens when we try to reach a memory which does "not exist"?

If someone could enlighten me, I would be grateful.

EDIT: debugger info:

```<code> Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff5ff9700 (LWP 3350)]
0x00000000004011cb in operation (str=0x7ffff5ff8e00 "Q 1111 1111", atmSN=3)
    at hw4.c:175
175                     ptr->prev->next = ptr->next;
</code>```

答:
My code is using multi-thread

Multi-threaded environments must make you consider lock context, such as mutexes or semaphores. Any time you have more than one thread of execution running simultaneously (HyperThreading, multi-core, or pre-emptive multithreading on single core systems), consider that the thread of execution can change at any moment. It's up to you to guard the logic to ensure that you don't blow off your own foot.

So, consider the following scenarios:

You have two threads, T1 and T2. You have a two-node linked list.

T1 calls your code and sees (ptr == head), and moves along.

Context switch!

T2 calls your code and sees (ptr == head), and moves along.

T2 sets head = head->next

T2 checks if (head != NULL), sees it's not NULL.

Context switch!

T1 sets head = head->next

What do you think T1 assigns to head? Continuing:

Context switch!

T2 assigns head->prev = NULL. It just dereferenced head which was assigned by T1. What do you think happens?

Imagine this kind of context switching for all of your logic flow. How do you guard against it?

The answer to this question is generally well-understood and often asked (and frequently answered). You should be able to find the answers you seek from here.

Body:
I'm trying to understand why i'm receiving a segmentation fault.

I have a linked list 'head' with prev and next pointers and i'm trying to delete a specific node in the list. The specific node's address is held by 'ptr'.
I've attached an image showing the debugger,
the following code gives me segmentation fault:
(I'm showing only what's relevant)

void someFunc(char str[], int atmSN){

/*some code */

switch(ch){    /// ch is char

/* some code */

case 'Q':
    if (ptr == head){                   // if ptr head of linked list
        head = head->next;
        if (head != NULL)
            head->prev = NULL;
    }
    else{
        ptr->prev->next = ptr->next;
        if (ptr->next != NULL)  // if ptr is not last
            ptr->next->prev = ptr->prev;
    }

    free(ptr);
break;

/*some code */

debugger

My code is using multi-threads, so perhaps another thread is writing to the specific node while the current thread is trying to delete it.
In my task I have to implement semaphores as well, But does this can give us a segmentation fault?

Correct me if i'm wrong: segmentation fault happens when we try to reach a memory which does "not exist"?

If someone could enlighten me, I would be grateful.

EDIT: debugger info:

 Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff5ff9700 (LWP 3350)]
0x00000000004011cb in operation (str=0x7ffff5ff8e00 "Q 1111 1111", atmSN=3)
    at hw4.c:175
175                     ptr->prev->next = ptr->next;


问:
ERROR in ./src/components/BasicList.js Module build failed: SyntaxError: Decorators are not officially supported
I am getting

```<code>ERROR in ./src/components/BasicList.js
Module build failed: SyntaxError: Decorators are not officially supported yet in 6.x pending a proposal update.
However, if you need to use them you can install the legacy decorators transform with:

npm install babel-plugin-transform-decorators-legacy --save-dev

and add the following line to your .babelrc file:

{
  "plugins": ["transform-decorators-legacy"]
}
</code>```

because of

```<code>import React from 'react';
// http://glortho.github.io/react-keydown/example/index.html
import keydown from 'react-keydown';

import {Grid, Row, Column} from 'react-cellblock';

import MyComponent from '../utils/MyComponent';

@keydown
export default class BasicList extends MyComponent {
</code>```

I have installed the package as asked multiple times and still confused as to why it won't work.

.babelrc:

```<code>{
  "presets": ["react", "es2015", "stage-1"],
  "plugins": ["transform-decorators-legacy"]

}
</code>```

packages:

```<code>"devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "json-loader": "^0.5.4",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^0.14.3",
    "react-cellblock": "^3.0.0",
    "react-dom": "^0.14.3",
    "react-keydown": "^1.7.3",
    "react-redux": "4.3.0",
    "react-router": "^2.8.1",
    "react-select": "^1.0.0-rc.5",
    "redux": "^3.0.4",
    "requests": "^0.1.7",
    "underscore": "^1.8.3"
  }
}
</code>```

webpack.config.js:

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};
</code>```

All the answers about this say to do what I already did. I keep restarting npm server to no avail.

答:
The problem as it appears is with your webpack.config.js file.
The correct config file should be without the key query inside the loaders, since all those have been already specified inside your .babelrc file.

The updated webpack.config.js file should be:-

```<code>module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};
</code>```

Body:
I am getting

ERROR in ./src/components/BasicList.js
Module build failed: SyntaxError: Decorators are not officially supported yet in 6.x pending a proposal update.
However, if you need to use them you can install the legacy decorators transform with:

npm install babel-plugin-transform-decorators-legacy --save-dev

and add the following line to your .babelrc file:

{
  "plugins": ["transform-decorators-legacy"]
}

because of

import React from 'react';
// http://glortho.github.io/react-keydown/example/index.html
import keydown from 'react-keydown';

import {Grid, Row, Column} from 'react-cellblock';

import MyComponent from '../utils/MyComponent';

@keydown
export default class BasicList extends MyComponent {

I have installed the package as asked multiple times and still confused as to why it won't work.

.babelrc:

{
  "presets": ["react", "es2015", "stage-1"],
  "plugins": ["transform-decorators-legacy"]

}

packages:

"devDependencies": {
    "babel-core": "^6.2.1",
    "babel-loader": "^6.2.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.1.18",
    "babel-preset-react": "^6.1.18",
    "chai": "^3.5.0",
    "chai-jquery": "^2.0.0",
    "jquery": "^2.2.1",
    "jsdom": "^8.1.0",
    "json-loader": "^0.5.4",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.0"
  },
  "dependencies": {
    "babel-preset-stage-1": "^6.1.18",
    "lodash": "^3.10.1",
    "react": "^0.14.3",
    "react-cellblock": "^3.0.0",
    "react-dom": "^0.14.3",
    "react-keydown": "^1.7.3",
    "react-redux": "4.3.0",
    "react-router": "^2.8.1",
    "react-select": "^1.0.0-rc.5",
    "redux": "^3.0.4",
    "requests": "^0.1.7",
    "underscore": "^1.8.3"
  }
}

webpack.config.js:

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['react', 'es2015', 'stage-1']
      }
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

All the answers about this say to do what I already did. I keep restarting npm server to no avail.

Body:
The problem as it appears is with your webpack.config.js file.
The correct config file should be without the key query inside the loaders, since all those have been already specified inside your .babelrc file.

The updated webpack.config.js file should be:-

module.exports = {
  entry: [
    './src/index.js'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      exclude: /node_modules/,
      loader: 'babel'
    }]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};


问:
nginx redirect httP://WWW.example to httPS://example (SSL/HTTPS and to NON-WWW)
I am trying to get

http://www.domain

https://www.domain

http:// domain

https:// domain

to all redirect to 4. https://domain

3 and 4 both end up at 4.

1 and 2 - do not end up at 4.

I also tried to do the www to non-www redirect using an s3 bucket and cloudfront, but unfortunately, this causes certificate issues.

Here is what I currently have in my nginx config:

```<code>server {
    listen 80;
    server_name www.{{ nginx_server_name }} {{ nginx_server_name }};
    return 301 https://{{ nginx_server_name }}$request_uri;
}

server {
  listen 443;
  server_name www.{{ nginx_server_name }}

  ssl on;
  charset utf-8;
  ssl_certificate     {{ certbot_output_dir }}/{{ letsencrypt_cert_filename }};
  ssl_certificate_key {{ certbot_output_dir }}/{{ letsencrypt_privkey_filename }};
  ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers         'ECDHE-..........
  ssl_prefer_server_ciphers on;

  return 301 https://{{ nginx_server_name }}$request_uri;
}

server {
    listen              443;
    server_name         {{ nginx_server_name }};
    ssl on;
    charset utf-8;

    ssl_certificate     {{ certbot_output_dir }}/{{ letsencrypt_cert_filename }};
    ssl_certificate_key {{ certbot_output_dir }}/{{ letsencrypt_privkey_filename }};

    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers         'ECDHE-..........
    ssl_prefer_server_ciphers on;
</code>```

答:
You config seems correct, but are those parameters?
Maybe this works for you:

```<code>server {
  listen 80;
  server_name www.example.com example.com;
  return 301 https://example.com$request_uri;
}
</code>```

This will forward all the http requests to www.example.com and example.com to https://example.com you should then also create a listener on https with host name www.example.com to forward the same way.
So not using the parameters, or was that because of obfuscation?

Body:
I am trying to get

http://www.domain

https://www.domain

http:// domain

https:// domain

to all redirect to 4. https://domain

3 and 4 both end up at 4.

1 and 2 - do not end up at 4.

I also tried to do the www to non-www redirect using an s3 bucket and cloudfront, but unfortunately, this causes certificate issues.

Here is what I currently have in my nginx config:

server {
    listen 80;
    server_name www.{{ nginx_server_name }} {{ nginx_server_name }};
    return 301 https://{{ nginx_server_name }}$request_uri;
}

server {
  listen 443;
  server_name www.{{ nginx_server_name }}

  ssl on;
  charset utf-8;
  ssl_certificate     {{ certbot_output_dir }}/{{ letsencrypt_cert_filename }};
  ssl_certificate_key {{ certbot_output_dir }}/{{ letsencrypt_privkey_filename }};
  ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers         'ECDHE-..........
  ssl_prefer_server_ciphers on;

  return 301 https://{{ nginx_server_name }}$request_uri;
}

server {
    listen              443;
    server_name         {{ nginx_server_name }};
    ssl on;
    charset utf-8;

    ssl_certificate     {{ certbot_output_dir }}/{{ letsencrypt_cert_filename }};
    ssl_certificate_key {{ certbot_output_dir }}/{{ letsencrypt_privkey_filename }};

    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers         'ECDHE-..........
    ssl_prefer_server_ciphers on;

Body:
You config seems correct, but are those parameters?
Maybe this works for you:

server {
  listen 80;
  server_name www.example.com example.com;
  return 301 https://example.com$request_uri;
}

This will forward all the http requests to www.example.com and example.com to https://example.com you should then also create a listener on https with host name www.example.com to forward the same way.
So not using the parameters, or was that because of obfuscation?


问:
How to check conditions without multiple if statements?
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

```<code>private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}
</code>```

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

```<code>        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }
</code>```

Is there a way to make this code less DRY? Input is appreciated.

答:
I would go this way:

First of all, you need a kind of Enumeration

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1
{
   public class MyEnumeration
   {
       #region Private Fields

       private readonly string _displayName;
       private readonly int _value;
       private readonly int _interval;
       private readonly Action _action;

       #endregion Private Fields

       #region Protected Constructors

       protected MyEnumeration()
       {
       }

       protected MyEnumeration(int value, string displayName, int interval, Action action)
       {
           _value = value;
           _displayName = displayName;
           _interval = interval;
           _action = action;
       }

       #endregion Protected Constructors

       #region Public Properties

       public string DisplayName
       {
           get { return _displayName; }
       }

       public int Value
       {
           get { return _value; }
       }

       public int Interval
       {
           get { return _interval; }
       }

       public Action Action
       {
           get { return _action; }
       }

       #endregion Public Properties

       #region Public Methods

       public static int AbsoluteDifference(MyEnumeration firstValue, MyEnumeration secondValue)
       {
           var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value);
           return absoluteDifference;
       }

       public static T FromDisplayName<T>(string displayName) where T : MyEnumeration, new()
       {
           var matchingItem = parse<T, string>(displayName, "display name", item => item.DisplayName == displayName);
           return matchingItem;
       }

       public static T FromValue<T>(int value) where T : MyEnumeration, new()
       {
           var matchingItem = parse<T, int>(value, "value", item => item.Value == value);
           return matchingItem;
       }

       public static IEnumerable<T> GetAll<T>() where T : MyEnumeration, new()
       {
           var type = typeof(T);
           var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);

           foreach (var info in fields)
           {
               var instance = new T();
               var locatedValue = info.GetValue(instance) as T;

               if (locatedValue != null)
               {
                   yield return locatedValue;
               }
           }
       }

       public int CompareTo(object other)
       {
           return Value.CompareTo(((MyEnumeration)other).Value);
       }

       public override bool Equals(object obj)
       {
           var otherValue = obj as MyEnumeration;

           if (otherValue == null)
           {
               return false;
           }

           var typeMatches = GetType().Equals(obj.GetType());
           var valueMatches = _value.Equals(otherValue.Value);

           return typeMatches && valueMatches;
       }

       public override int GetHashCode()
       {
           return _value.GetHashCode();
       }

       public override string ToString()
       {
           return DisplayName;
       }

       #endregion Public Methods

       #region Private Methods

       private static T parse<T, K>(K value, string description, Func<T, bool> predicate) where T : MyEnumeration, new()
       {
           var matchingItem = GetAll<T>().FirstOrDefault(predicate);

           if (matchingItem == null)
           {
               var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T));
               throw new ApplicationException(message);
           }

           return matchingItem;
       }

       #endregion Private Methods
   }
</code>```

}

Then you can create your own Enumeration like:

```<code>using System;

namespace ConsoleApp1
{
    internal class LevelEnum : MyEnumeration
    {
        public static readonly LevelEnum Level1 = new LevelEnum(1, "Level 1", 2000, Program.Level1);
        public static readonly LevelEnum Level2 = new LevelEnum(2, "Level 2", 3000, Program.Level2);
        public static readonly LevelEnum Level3 = new LevelEnum(3, "Level 3", 4000, Program.Level3);
        public static readonly LevelEnum Level4 = new LevelEnum(4, "Level 4", 5000, Program.Level4);
        public static readonly LevelEnum Level5 = new LevelEnum(5, "Level 5", 6000, Program.Level5);
        public static readonly LevelEnum Level6 = new LevelEnum(6, "Level 6", 7000, Program.Level6);
        public static readonly LevelEnum Level7 = new LevelEnum(7, "Level 7", 8000, Program.Level7);
        public static readonly LevelEnum Level8 = new LevelEnum(8, "Level 8", 9000, Program.Level8);

        public LevelEnum()
        {
        }

        protected LevelEnum(int value, string displayName, int interval, Action action) : base(value, displayName, interval, action)
        {
        }
    }
}
</code>```

and you can use it like:

```<code>private static void Main(string[] args)
{
    int level = 5;
    LevelEnum levelEnum = MyEnumeration.FromValue<LevelEnum>(level);

    levelDisplay.Text = levelEnum.DisplayName;
    timer = new Timer();
    timer.Interval = levelEnum.Interval;
    timer.Enabled = true;
    timer.Elapsed += levelEnum.Action;
    timer.Start();
}

internal static void Level1()
{
    // Action for Level 1
}

internal static void Level2()
{
    // Action for Level 2
}

internal static void Level3()
{
    // Action for Level 3
}
</code>```

Body:
I am working on a game for android in Xamarin, but I have two specific sections that are extremly DRY (don't repeat yourself).

The first section is when I want to change the soundtrack(audioplay) or background, where I have three different pitches for the same soundtrack based on level, and the same for background where the background canvas alternates.

For these methods the condition is based on an integer level that equals the level the player is in.

Example code

private void SetBackgrounds()
{
    if (level == 5)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpOneBackground);

    }
    else if (level == 10)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpTwoBackground);

    }
    else if (level == 15)
    {
        gameAreaCanvas.SetBackgroundResource(Resource.Drawable.LevelUpThreeBackground);

    }
}

The same goes for different parts of the code where alot is based on an integer value which is the level. Every time the player advances the level integer increments by one, and then the activity has methods that checks what the integer level is. The code is working but is very inefficient obviously, because there is a lot of duplicated code with a small tweak.

For instance a level looks like this.

        if(level == 1) {

            levelDisplay.Text = "LEVEL 1";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level1; /// DIFFERENT
            timer.Start();
        }
        ///LEVEL 2
        if (level == 2)
        {
            levelDisplay.Text = "LEVEL 2";
            timer = new Timer();
            timer.Interval = 2000; /// DIFFERENT
            timer.Enabled = true;
            timer.Elapsed += Level2; /// DIFFERENT
            timer.Start();
        }

Is there a way to make this code less DRY? Input is appreciated.

Body:
I would go this way:

First of all, you need a kind of Enumeration

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1
{
   public class MyEnumeration
   {
       #region Private Fields

       private readonly string _displayName;
       private readonly int _value;
       private readonly int _interval;
       private readonly Action _action;

       #endregion Private Fields

       #region Protected Constructors

       protected MyEnumeration()
       {
       }

       protected MyEnumeration(int value, string displayName, int interval, Action action)
       {
           _value = value;
           _displayName = displayName;
           _interval = interval;
           _action = action;
       }

       #endregion Protected Constructors

       #region Public Properties

       public string DisplayName
       {
           get { return _displayName; }
       }

       public int Value
       {
           get { return _value; }
       }

       public int Interval
       {
           get { return _interval; }
       }

       public Action Action
       {
           get { return _action; }
       }

       #endregion Public Properties

       #region Public Methods

       public static int AbsoluteDifference(MyEnumeration firstValue, MyEnumeration secondValue)
       {
           var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value);
           return absoluteDifference;
       }

       public static T FromDisplayName<T>(string displayName) where T : MyEnumeration, new()
       {
           var matchingItem = parse<T, string>(displayName, "display name", item => item.DisplayName == displayName);
           return matchingItem;
       }

       public static T FromValue<T>(int value) where T : MyEnumeration, new()
       {
           var matchingItem = parse<T, int>(value, "value", item => item.Value == value);
           return matchingItem;
       }

       public static IEnumerable<T> GetAll<T>() where T : MyEnumeration, new()
       {
           var type = typeof(T);
           var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);

           foreach (var info in fields)
           {
               var instance = new T();
               var locatedValue = info.GetValue(instance) as T;

               if (locatedValue != null)
               {
                   yield return locatedValue;
               }
           }
       }

       public int CompareTo(object other)
       {
           return Value.CompareTo(((MyEnumeration)other).Value);
       }

       public override bool Equals(object obj)
       {
           var otherValue = obj as MyEnumeration;

           if (otherValue == null)
           {
               return false;
           }

           var typeMatches = GetType().Equals(obj.GetType());
           var valueMatches = _value.Equals(otherValue.Value);

           return typeMatches && valueMatches;
       }

       public override int GetHashCode()
       {
           return _value.GetHashCode();
       }

       public override string ToString()
       {
           return DisplayName;
       }

       #endregion Public Methods

       #region Private Methods

       private static T parse<T, K>(K value, string description, Func<T, bool> predicate) where T : MyEnumeration, new()
       {
           var matchingItem = GetAll<T>().FirstOrDefault(predicate);

           if (matchingItem == null)
           {
               var message = string.Format("'{0}' is not a valid {1} in {2}", value, description, typeof(T));
               throw new ApplicationException(message);
           }

           return matchingItem;
       }

       #endregion Private Methods
   }

}

Then you can create your own Enumeration like:

using System;

namespace ConsoleApp1
{
    internal class LevelEnum : MyEnumeration
    {
        public static readonly LevelEnum Level1 = new LevelEnum(1, "Level 1", 2000, Program.Level1);
        public static readonly LevelEnum Level2 = new LevelEnum(2, "Level 2", 3000, Program.Level2);
        public static readonly LevelEnum Level3 = new LevelEnum(3, "Level 3", 4000, Program.Level3);
        public static readonly LevelEnum Level4 = new LevelEnum(4, "Level 4", 5000, Program.Level4);
        public static readonly LevelEnum Level5 = new LevelEnum(5, "Level 5", 6000, Program.Level5);
        public static readonly LevelEnum Level6 = new LevelEnum(6, "Level 6", 7000, Program.Level6);
        public static readonly LevelEnum Level7 = new LevelEnum(7, "Level 7", 8000, Program.Level7);
        public static readonly LevelEnum Level8 = new LevelEnum(8, "Level 8", 9000, Program.Level8);

        public LevelEnum()
        {
        }

        protected LevelEnum(int value, string displayName, int interval, Action action) : base(value, displayName, interval, action)
        {
        }
    }
}

and you can use it like:

private static void Main(string[] args)
{
    int level = 5;
    LevelEnum levelEnum = MyEnumeration.FromValue<LevelEnum>(level);

    levelDisplay.Text = levelEnum.DisplayName;
    timer = new Timer();
    timer.Interval = levelEnum.Interval;
    timer.Enabled = true;
    timer.Elapsed += levelEnum.Action;
    timer.Start();
}

internal static void Level1()
{
    // Action for Level 1
}

internal static void Level2()
{
    // Action for Level 2
}

internal static void Level3()
{
    // Action for Level 3
}


问:
Roslyn VSIX Extension Blows up from adding function in fix provider
I've been dealing with an issue I'm going to assume is environment specific.
I installed and reinstalled the Roslyn Templates when I add any function to the CodeFixProvider(Referenced or not).  VS blows up with an system aggregate exception when trying to open the preview window:

This is the full code fix provider the only thing modified is adding the new function

```<code>[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AggregateBugAnalyzerCodeFixProvider)), Shared]
public class AggregateBugAnalyzerCodeFixProvider : CodeFixProvider
{
    private const string title = "Make uppercase";

    public sealed override ImmutableArray<string> FixableDiagnosticIds
    {
        get { return ImmutableArray.Create(AggregateBugAnalyzerAnalyzer.DiagnosticId); }
    }

    public sealed override FixAllProvider GetFixAllProvider()
    {
        // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
        return WellKnownFixAllProviders.BatchFixer;
    }

    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
        var diagnostic = context.Diagnostics.First();
        var diagnosticSpan = diagnostic.Location.SourceSpan;

        // Find the type declaration identified by the diagnostic.
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().First();

        // Register a code action that will invoke the fix.
        context.RegisterCodeFix(
            CodeAction.Create(
                title: title,
                createChangedSolution: c => MakeUppercaseAsync(context.Document, declaration, c),
                equivalenceKey: title),
            diagnostic);
    }

    private async Task<Solution> MakeUppercaseAsync(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
    {
        // Compute new uppercase name.
        var identifierToken = typeDecl.Identifier;
        var newName = identifierToken.Text.ToUpperInvariant();

        // Get the symbol representing the type to be renamed.
        var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
        var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

        // Produce a new solution that has all references to that type renamed, including the declaration.
        var originalSolution = document.Project.Solution;
        var optionSet = originalSolution.Workspace.Options;
        var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

        // Return the new solution with the now-uppercase type name.
        return newSolution;
    }

    //Just the existance of this function causes VS to throw
    public string Blowup()
    {
        return "Why";
    }
}
</code>```

When I turn on all exception I catch this error:

Additional information: Unable to cast object of type 'System.Reflection.RuntimeMethodInfo' to type 'System.Reflection.ConstructorInfo'.

Which is presumably cause by mismatching runtimes. If I move the function into it's own class everything is fine.

Inner Exception Stack Trace

```<code>>   at Microsoft.VisualStudio.Composition.Reflection.ResolverExtensions.Resolve(ConstructorRef constructorRef)
   at Microsoft.VisualStudio.Composition.RuntimeComposition.RuntimePart.get_ImportingConstructor()
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.RuntimePartLifecycleTracker.CreateValue()
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.Create()
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.MoveNext(PartLifecycleState nextState)
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.MoveToState(PartLifecycleState requiredState)
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.GetValueReadyToExpose()
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.<>c__DisplayClass15_0.<GetExportedValueHelper>b__0()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.<>c__DisplayClass15_0.<GetExportedValueHelper>b__0()
   at Microsoft.VisualStudio.Composition.DelegateServices.<>c__DisplayClass2_0`1.<As>b__0()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Lazy`1.get_Value()
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<>c__DisplayClass24_0.<GetFixerPerLanguageMap>b__0()
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Lazy`1.get_Value()
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<AppendFixesAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<GetFixesAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionsSourceProvider.Source.<>c__DisplayClass15_1.<<GetCodeFixes>b__0>d.MoveNext()
</code>```

答:
I suspect that VS MEF cached CIL tokens from an older build of your class, and the new method is throwing off the cached tokens.

Delete the ComponentModelCache directory from AppData\Local\Microsoft\VisualStudio_your test instance_.

Body:
I've been dealing with an issue I'm going to assume is environment specific.
I installed and reinstalled the Roslyn Templates when I add any function to the CodeFixProvider(Referenced or not).  VS blows up with an system aggregate exception when trying to open the preview window:

This is the full code fix provider the only thing modified is adding the new function

[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AggregateBugAnalyzerCodeFixProvider)), Shared]
public class AggregateBugAnalyzerCodeFixProvider : CodeFixProvider
{
    private const string title = "Make uppercase";

    public sealed override ImmutableArray<string> FixableDiagnosticIds
    {
        get { return ImmutableArray.Create(AggregateBugAnalyzerAnalyzer.DiagnosticId); }
    }

    public sealed override FixAllProvider GetFixAllProvider()
    {
        // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
        return WellKnownFixAllProviders.BatchFixer;
    }

    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
        var diagnostic = context.Diagnostics.First();
        var diagnosticSpan = diagnostic.Location.SourceSpan;

        // Find the type declaration identified by the diagnostic.
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<TypeDeclarationSyntax>().First();

        // Register a code action that will invoke the fix.
        context.RegisterCodeFix(
            CodeAction.Create(
                title: title,
                createChangedSolution: c => MakeUppercaseAsync(context.Document, declaration, c),
                equivalenceKey: title),
            diagnostic);
    }

    private async Task<Solution> MakeUppercaseAsync(Document document, TypeDeclarationSyntax typeDecl, CancellationToken cancellationToken)
    {
        // Compute new uppercase name.
        var identifierToken = typeDecl.Identifier;
        var newName = identifierToken.Text.ToUpperInvariant();

        // Get the symbol representing the type to be renamed.
        var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
        var typeSymbol = semanticModel.GetDeclaredSymbol(typeDecl, cancellationToken);

        // Produce a new solution that has all references to that type renamed, including the declaration.
        var originalSolution = document.Project.Solution;
        var optionSet = originalSolution.Workspace.Options;
        var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, typeSymbol, newName, optionSet, cancellationToken).ConfigureAwait(false);

        // Return the new solution with the now-uppercase type name.
        return newSolution;
    }

    //Just the existance of this function causes VS to throw
    public string Blowup()
    {
        return "Why";
    }
}

When I turn on all exception I catch this error:

Additional information: Unable to cast object of type 'System.Reflection.RuntimeMethodInfo' to type 'System.Reflection.ConstructorInfo'.

Which is presumably cause by mismatching runtimes. If I move the function into it's own class everything is fine.

Inner Exception Stack Trace

>   at Microsoft.VisualStudio.Composition.Reflection.ResolverExtensions.Resolve(ConstructorRef constructorRef)
   at Microsoft.VisualStudio.Composition.RuntimeComposition.RuntimePart.get_ImportingConstructor()
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.RuntimePartLifecycleTracker.CreateValue()
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.Create()
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.MoveNext(PartLifecycleState nextState)
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.MoveToState(PartLifecycleState requiredState)
   at Microsoft.VisualStudio.Composition.ExportProvider.PartLifecycleTracker.GetValueReadyToExpose()
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.<>c__DisplayClass15_0.<GetExportedValueHelper>b__0()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Composition.RuntimeExportProviderFactory.RuntimeExportProvider.<>c__DisplayClass15_0.<GetExportedValueHelper>b__0()
   at Microsoft.VisualStudio.Composition.DelegateServices.<>c__DisplayClass2_0`1.<As>b__0()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Lazy`1.get_Value()
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<>c__DisplayClass24_0.<GetFixerPerLanguageMap>b__0()
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Lazy`1.get_Value()
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<AppendFixesAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.CodeFixes.CodeFixService.<GetFixesAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.Editor.Implementation.Suggestions.SuggestedActionsSourceProvider.Source.<>c__DisplayClass15_1.<<GetCodeFixes>b__0>d.MoveNext()


问:
How to insert selected data from mysql with php to another table in mysql?
Hello guys i have a problem. I dont know how to insert data from php to the database, first of all, i did selects to the database to get the data. The user choose the data in the form with the options and he sends it, but the insert doesnt work. What can be the problem?

This is the file index.php

    <?php
    session_start();
    if($_SESSION['userid'] == TRUE )

     {
    ?>

    <?php

    // Definimos nuestra zona horaria
    date_default_timezone_set("Europe/Madrid");
    include 'funciones.php';
    include 'config.php';

    // Verificamos si se ha enviado el campo con name from
    if (isset($_POST['from']))
    {

// Recibimos la fecha de inicio y la fecha final desde el form y la formateamos con la funcion _formatear

   $inicio = _formatear($_POST['from']);
   $final = _formatear($_POST['to']);
   $inicio_normal =$_POST['from'];
   $final_normal = $_POST['to'];
   $cod_falta = $_POST['coid_falta'];
   $cod_alumno =$_POST['cod_alumno'];
   $cod_profesor = $_SESSION['userid'];
   $cod_ubi = $_POST['cod_emplazamiento'];
   $cod_obs = $_POST['observacion'];

 $query="INSERT INTO castigos ('start','end','inicio_normal','final_normal','cod_falta','cod_alumno','cod_profesor','cod_emplazamiento','observaciones') VALUES ('$inicio','$final','$inicio_normal','$final_normal','$cod_falta','$cod_alumno','$cod_profesor','$cod_ubi','$cod_obs')";

$conexion->query($query) or die ("no se ha realizado la consulta");

// Obtenemos el ultimo id insetado
$im=$conexion->query("SELECT MAX(id) AS id FROM castigos");
$row = $im->fetch_row();
$id = trim($row[0]);

// para generar el link del evento
$link = "$base_url"."descripcion_evento.php?id=$id";

// y actualizamos su link
$query="UPDATE castigos SET url = '$link' WHERE id = $id";

// Ejecutamos nuestra sentencia sql
$conexion->query($query);

// redireccionamos a nuestro calendario
header("Location:$base_url");
        }

      ?>
    <form action="" method="post">

         Curso
         <select class="form-control" name="cbx_estado" id="cbx_estado">
         <option value="">Seleccionar Curso</option>
         <?php
         $query_curso = 'SELECT * FROM curso';
         $result_curso=$conexion->query($query_curso);
         while($row_curso = $result_curso->fetch_assoc())

         { ?>
          <option value="<?php echo $row_curso['cod_curso']; ?>">
          <?php echo $row_curso['curso']; ?></option>
         <?php
         }
         ?>
         </select>

         Alumno
         <select class="form-control" name="cbx_alumnos" id="cbx_alumnos"></select>

         Tipo de falta
                        <select class="form-control" name="cod_falta" id="cod_falta">
           <option value="">Seleccionar falta</option>
          <?php
           $query_falta = 'SELECT * FROM faltas';
           $result_falta = $conexion->query($query_falta);
           while ( $row_falta = $result_falta->fetch_array() )
          {
          ?>
           <option value=" <?php echo $row_falta['cod_falta']  ?> " >
           <?php echo $row_falta['falta']; ?>
           </option>

          <?php
          }
          ?>

         </select>

          Ubicación del castigo
                        <select class="form-control" name="cod_emplazamiento" id="cod_emplazamiento">
           <option value="">Seleccionar ubicación</option>
          <?php
           $query_ubi = 'SELECT * FROM emplazamiento_castigos';
           $result_ubi = $conexion->query($query_ubi);
           while ( $row_ubi = $result_ubi->fetch_array() )
          {
          ?>
           <option value=" <?php echo $row_ubi['cod_emplazamiento']  ?> " >
           <?php echo $row_ubi['emplazamiento']; ?>
           </option>

          <?php
          }
          ?>
         </select>

                        Inicio de castigo

                        <input type='text' class="form-control" readonly />

                        Final de castigo

                        <input type='text' class="form-control" readonly />

                        Tarea y observaciones
                        <textarea id="observacion" name="observacion" class="form-control" rows="1"></textarea>

              <button type="button" class="btn btn-danger" data-dismiss="modal"> Cancelar</button>
          <input type="Submit" name="enviar" value="Agregar" class="btn btn-success" >

            </form>

<?php
 } else {
  header("Location: index_log.php");
 }
  ?>```

My table name castigos.php

答:
You can do this </p>

```<code>$query="INSERT INTO castigos (start,end,inicio_normal,final_normal,cod_falta,cod_alumno,cod_profesor,cod_emplazamiento,observaciones) VALUES ('$inicio','$final','$inicio_normal','$final_normal','$cod_falta','$cod_alumno','$cod_profesor','$cod_ubi','$cod_obs')";

if ($conexion->query($query) === TRUE) {
    echo "Record Successfully<br>";
}
else
{
    echo "Error: " . $query. "<br>" . $con->error;
}
</code>```

Body:
Hello guys i have a problem. I dont know how to insert data from php to the database, first of all, i did selects to the database to get the data. The user choose the data in the form with the options and he sends it, but the insert doesnt work. What can be the problem?

This is the file index.php

    <?php
    session_start();
    if($_SESSION['userid'] == TRUE )

     {
    ?>

    <?php

    // Definimos nuestra zona horaria
    date_default_timezone_set("Europe/Madrid");
    include 'funciones.php';
    include 'config.php';

    // Verificamos si se ha enviado el campo con name from
    if (isset($_POST['from']))
    {

// Recibimos la fecha de inicio y la fecha final desde el form y la formateamos con la funcion _formatear

   $inicio = _formatear($_POST['from']);
   $final = _formatear($_POST['to']);
   $inicio_normal =$_POST['from'];
   $final_normal = $_POST['to'];
   $cod_falta = $_POST['coid_falta'];
   $cod_alumno =$_POST['cod_alumno'];
   $cod_profesor = $_SESSION['userid'];
   $cod_ubi = $_POST['cod_emplazamiento'];
   $cod_obs = $_POST['observacion'];

 $query="INSERT INTO castigos ('start','end','inicio_normal','final_normal','cod_falta','cod_alumno','cod_profesor','cod_emplazamiento','observaciones') VALUES ('$inicio','$final','$inicio_normal','$final_normal','$cod_falta','$cod_alumno','$cod_profesor','$cod_ubi','$cod_obs')";

$conexion->query($query) or die ("no se ha realizado la consulta");

// Obtenemos el ultimo id insetado
$im=$conexion->query("SELECT MAX(id) AS id FROM castigos");
$row = $im->fetch_row();
$id = trim($row[0]);

// para generar el link del evento
$link = "$base_url"."descripcion_evento.php?id=$id";

// y actualizamos su link
$query="UPDATE castigos SET url = '$link' WHERE id = $id";

// Ejecutamos nuestra sentencia sql
$conexion->query($query);

// redireccionamos a nuestro calendario
header("Location:$base_url");
        }

      ?>
    <form action="" method="post">

         Curso
         <select class="form-control" name="cbx_estado" id="cbx_estado">
         <option value="">Seleccionar Curso</option>
         <?php
         $query_curso = 'SELECT * FROM curso';
         $result_curso=$conexion->query($query_curso);
         while($row_curso = $result_curso->fetch_assoc())

         { ?>
          <option value="<?php echo $row_curso['cod_curso']; ?>">
          <?php echo $row_curso['curso']; ?></option>
         <?php
         }
         ?>
         </select>

         Alumno
         <select class="form-control" name="cbx_alumnos" id="cbx_alumnos"></select>

         Tipo de falta
                        <select class="form-control" name="cod_falta" id="cod_falta">
           <option value="">Seleccionar falta</option>
          <?php
           $query_falta = 'SELECT * FROM faltas';
           $result_falta = $conexion->query($query_falta);
           while ( $row_falta = $result_falta->fetch_array() )
          {
          ?>
           <option value=" <?php echo $row_falta['cod_falta']  ?> " >
           <?php echo $row_falta['falta']; ?>
           </option>

          <?php
          }
          ?>

         </select>

          Ubicación del castigo
                        <select class="form-control" name="cod_emplazamiento" id="cod_emplazamiento">
           <option value="">Seleccionar ubicación</option>
          <?php
           $query_ubi = 'SELECT * FROM emplazamiento_castigos';
           $result_ubi = $conexion->query($query_ubi);
           while ( $row_ubi = $result_ubi->fetch_array() )
          {
          ?>
           <option value=" <?php echo $row_ubi['cod_emplazamiento']  ?> " >
           <?php echo $row_ubi['emplazamiento']; ?>
           </option>

          <?php
          }
          ?>
         </select>

                        Inicio de castigo

                        <input type='text' class="form-control" readonly />

                        Final de castigo

                        <input type='text' class="form-control" readonly />

                        Tarea y observaciones
                        <textarea id="observacion" name="observacion" class="form-control" rows="1"></textarea>

              <button type="button" class="btn btn-danger" data-dismiss="modal"> Cancelar</button>
          <input type="Submit" name="enviar" value="Agregar" class="btn btn-success" >

            </form>

<?php
 } else {
  header("Location: index_log.php");
 }
  ?>

My table name castigos.php

Body:
You can do this

$query="INSERT INTO castigos (start,end,inicio_normal,final_normal,cod_falta,cod_alumno,cod_profesor,cod_emplazamiento,observaciones) VALUES ('$inicio','$final','$inicio_normal','$final_normal','$cod_falta','$cod_alumno','$cod_profesor','$cod_ubi','$cod_obs')";

if ($conexion->query($query) === TRUE) {
    echo "Record Successfully<br>";
}
else
{
    echo "Error: " . $query. "<br>" . $con->error;
}


问:
fullCalendar: Getting data from controller JSON
I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.

JS Code:

```<code>$(document).ready(function () {

$(".calendar").fullCalendar
    ({
        header: {
            left: 'month,basicWeek,basicDay,today',
            center: 'title',
            right: 'prev,next'
        },
        weekends: false,
        eventLimit: true,
        theme: true,
        editable: false,
        fixedWeekCount: false,
        events: function(start, end, timezone, callback)
        {$.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Calendar/GetCalendarEvents",
                dataType: 'json',
                success: function (data)
                {

                    var events = [];
                    $.each(data, function (index, value) {

                        events.push({
                            id: value['id'],
                            title: value['title'],
                            date: value['date']
                            //all data
                        });
                        console.log(value)
                    });
                    callback(events);
                },
                error: function (xhr, err) {
                    alert("ERROR! - readyState: " + xhr.readyState + "<br/>status: " + xhr.status + "<br/>responseText: " + xhr.responseText);
                }
            });

        }   });})
</code>```

Note: The above code was one of may attempts to get it working. I have tried coding it differently before.

Controller Code:

```<code>public ActionResult GetCalendarEvents()
    {
        var events = new List<VMCalendarEvents>();
        var db_events = db.PatientVisits.ToList();
        foreach(var e in db_events)
        {
            DateTime visit_start = Convert.ToDateTime(e.VisitStart);
            DateTime visit_end = Convert.ToDateTime(e.VisitEnd);

            var calEvent = new VMCalendarEvents
            {
                id = e.PatientVisitID.ToString(),
                title = "Placeholder Title" + e.PatientVisitID.ToString(),
                date = visit_start.ToShortDateString(),
                start = visit_start.ToString(),
                end = visit_end.ToString(),
                editable = true,
                allDay = false

            };
            events.Add(calEvent);
        }

        var rows = events.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);}
</code>```

Controller Code Output

JS Objects from Controller

EDIT: Problem Solved

So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a  header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd  &  MM/dd/yyyy hh:mm tt):

```<code>    $(function () {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2017-06-12',
        editable: true,
        events: '@Url.Action("GetCalendarEvents", "Calendar")',

    });

});
</code>```

I called the Controller using the URL Action command and return the JSON data as a ActionResult.

答:
Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead.
The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.

For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):

```<code>{
    $.ajax({
        url: 'example.json',
        dataType: 'json',
        success: function(doc) {
            var events = [];
            $.each(doc, function(index, element) {
                events.push({
                    title: element.title,
                    start: element.time,
        url: element.url,

                });
            });
            callback(events);
        }
    }) //ajax
    }
</code>```

And the JSON file (example.json):

```<code>    [
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]
</code>```

Body:
I am using the fullCalendar library in Visual Studio 2015. I am having trouble populating events from an AJAX command. No events are populating on the calendar. If I pass only one datetime and set allDay = true, it will populate the event. I need it to work with time as well and ave multiple events per day.

JS Code:

$(document).ready(function () {

$(".calendar").fullCalendar
    ({
        header: {
            left: 'month,basicWeek,basicDay,today',
            center: 'title',
            right: 'prev,next'
        },
        weekends: false,
        eventLimit: true,
        theme: true,
        editable: false,
        fixedWeekCount: false,
        events: function(start, end, timezone, callback)
        {$.ajax
            ({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Calendar/GetCalendarEvents",
                dataType: 'json',
                success: function (data)
                {

                    var events = [];
                    $.each(data, function (index, value) {

                        events.push({
                            id: value['id'],
                            title: value['title'],
                            date: value['date']
                            //all data
                        });
                        console.log(value)
                    });
                    callback(events);
                },
                error: function (xhr, err) {
                    alert("ERROR! - readyState: " + xhr.readyState + "
status: " + xhr.status + "
responseText: " + xhr.responseText);
                }
            });

        }   });})

Note: The above code was one of may attempts to get it working. I have tried coding it differently before.

Controller Code:

public ActionResult GetCalendarEvents()
    {
        var events = new List<VMCalendarEvents>();
        var db_events = db.PatientVisits.ToList();
        foreach(var e in db_events)
        {
            DateTime visit_start = Convert.ToDateTime(e.VisitStart);
            DateTime visit_end = Convert.ToDateTime(e.VisitEnd);

            var calEvent = new VMCalendarEvents
            {
                id = e.PatientVisitID.ToString(),
                title = "Placeholder Title" + e.PatientVisitID.ToString(),
                date = visit_start.ToShortDateString(),
                start = visit_start.ToString(),
                end = visit_end.ToString(),
                editable = true,
                allDay = false

            };
            events.Add(calEvent);
        }

        var rows = events.ToArray();
        return Json(rows, JsonRequestBehavior.AllowGet);}

Controller Code Output

JS Objects from Controller

EDIT: Problem Solved

So after some investigating I decided to use Razor in MVC to solve the problem. Instead of writing it into a seperate JS file, I put it into a  header in the html file. By implementing the code below I was able to get the objects in the date formats of (yyyy-MM-ddTHH:dd  &  MM/dd/yyyy hh:mm tt):

    $(function () {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2017-06-12',
        editable: true,
        events: '@Url.Action("GetCalendarEvents", "Calendar")',

    });

});

I called the Controller using the URL Action command and return the JSON data as a ActionResult.

Body:
Fullcalendar might not like your slashes '/' in your date fields. Try hyphens '-' instead.
The documentation (https://fullcalendar.io/docs/utilities/Moment/) is more detailed about what formats for date/time work.

For reference, here is my fullcalendar code using JSON from AJAX (note that my events do not have an end time, but this was by choice):

{
    $.ajax({
        url: 'example.json',
        dataType: 'json',
        success: function(doc) {
            var events = [];
            $.each(doc, function(index, element) {
                events.push({
                    title: element.title,
                    start: element.time,
        url: element.url,

                });
            });
            callback(events);
        }
    }) //ajax
    }

And the JSON file (example.json):

    [
{"time": "2017-06-06 09:00:00", "title": "Get It Done in June ", "url": "http://example.org"},
{"time": "2017-06-07 14:00:00", "title": "Fighting Imposter Syndrome for Dissertating Students ", "url": "http://example.com"},
{"time": "2017-06-14 14:00:00", "title": "Entering into the Academic Conversation", "url": "http://example.biz"}
]


问:
Text 2 Speech works with simulator but not real device
I use the following code:

```<code>    myUtterance = AVSpeechUtterance(string: ss2)
    myUtterance.rate = 0.4
    synth.speakUtterance(myUtterance)
</code>```

with ss2 being a valid string.

I also have an error message: imagesCategory[4437:341793] Building MacinTalk voice for asset: (null)

I tried with an ipad2 and an iPhone 5.

with the simulator it works with all.

any ideas?

Thanks!

答:
I commented out these two lines. Now it works on the real device as well as simulator. I can't tell why though.</p>

```<code>//        try audioSession.setCategory(AVAudioSessionCategoryRecord)
//        try audioSession.setMode(AVAudioSessionModeMeasurement)
</code>```

Body:
I use the following code:

    myUtterance = AVSpeechUtterance(string: ss2)
    myUtterance.rate = 0.4
    synth.speakUtterance(myUtterance)

with ss2 being a valid string.

I also have an error message: imagesCategory[4437:341793] Building MacinTalk voice for asset: (null)

I tried with an ipad2 and an iPhone 5.

with the simulator it works with all.

any ideas?

Thanks!

Body:
I commented out these two lines. Now it works on the real device as well as simulator. I can't tell why though.

//        try audioSession.setCategory(AVAudioSessionCategoryRecord)
//        try audioSession.setMode(AVAudioSessionModeMeasurement)


问:
Diversity indices by treatment groups and sites in R
I am trying to calculate the inverse Simpson's diversity index in R using vegan's diversity() function.  I would like to calculate this index for each experimental treatment.

My data looks a bit like this, where species is the species x site contingency table and env is the treatment factor x site table:

```<code>spe <- read.table(header=TRUE, text="
  S1   S2   S3   S4
  0    1    2    1
  0    1    1    0
  1    0    0    3
  0    1    0    1
  1    2    1    0
")

env <- read.table(header=TRUE, text="
  Stage
  a
  b
  c
  a
  c
")
</code>```

Ideally, I'd get a single diversity index value for each (a,b,c) treatment factor.

I know that the specnumber() function has a groups option, but I don't see anything similar for diversity and was hoping to find an easy way to do the same thing.  I've tried applying summaryBy(), aggregate(), and ddply() without any luck.

I've also tried brute force computing diversity(subset(spe, env$Stage=="a"),"simpson") for each individual env$Stagebut that still gives me a Simpson's diversity index for each site in that stage, not for the stage as a whole.

Thanks.

答:
I'm assuming your tables are joined row by row (eg. row 1 is "a 0 1 2 1"). If that's the case, maybe this is on the right track:

Make them into a single data frame:

```<code>spec_env <- data.frame(species, env)

> spec_env
  S1 S2 S3 S4 Stage
1  0  1  2  1     a
2  0  1  1  0     b
3  1  0  0  3     c
4  0  1  0  1     a
5  1  2  1  0     c
</code>```

Use split to get a list of data frames:

```<code>split_spec_env<-split(spec_env, spec_env$Stage)
</code>```

Now, if you need the mean diversity in each treatment, first use lapply to get the index for each row:

```<code>z<-lapply(split_spec_env, function(x){
  x$div<-diversity(x[,1:4], index = "invsimpson")
  return(x)
}
)

> z
$a
  S1 S2 S3 S4 Stage      div
1  0  1  2  1     a 2.666667
4  0  1  0  1     a 2.000000

$b
  S1 S2 S3 S4 Stage div
2  0  1  1  0     b   2

$c
  S1 S2 S3 S4 Stage      div
3  1  0  0  3     c 1.600000
5  1  2  1  0     c 2.666667
</code>```

Then again to get the mean index for each subset (Which I think makes more sense but depends what you need):

```<code>lapply(z, function(x){
  mean(x$div)
})
</code>```

Or if you want to take all the values from a subset and get the overall diversity within a treatment:

```<code>lapply(z, function(x){
  y <- unlist(x[,1:4])
  diversity(y, "invsimpson")
})
</code>```

Edit: I realized you may want the diversity index from the summed species within a treatment. If that's the case, use colSums:

```<code>lapply(z, function(x){
  y <- colSums(x[,1:4])
  diversity(y, "invsimpson")
})
</code>```

Body:
I am trying to calculate the inverse Simpson's diversity index in R using vegan's diversity() function.  I would like to calculate this index for each experimental treatment.

My data looks a bit like this, where species is the species x site contingency table and env is the treatment factor x site table:

spe <- read.table(header=TRUE, text="
  S1   S2   S3   S4
  0    1    2    1
  0    1    1    0
  1    0    0    3
  0    1    0    1
  1    2    1    0
")

env <- read.table(header=TRUE, text="
  Stage
  a
  b
  c
  a
  c
")

Ideally, I'd get a single diversity index value for each (a,b,c) treatment factor.

I know that the specnumber() function has a groups option, but I don't see anything similar for diversity and was hoping to find an easy way to do the same thing.  I've tried applying summaryBy(), aggregate(), and ddply() without any luck.

I've also tried brute force computing diversity(subset(spe, env$Stage=="a"),"simpson") for each individual env$Stagebut that still gives me a Simpson's diversity index for each site in that stage, not for the stage as a whole.

Thanks.

Body:
I'm assuming your tables are joined row by row (eg. row 1 is "a 0 1 2 1"). If that's the case, maybe this is on the right track:

Make them into a single data frame:

spec_env <- data.frame(species, env)

> spec_env
  S1 S2 S3 S4 Stage
1  0  1  2  1     a
2  0  1  1  0     b
3  1  0  0  3     c
4  0  1  0  1     a
5  1  2  1  0     c

Use split to get a list of data frames:

split_spec_env<-split(spec_env, spec_env$Stage)

Now, if you need the mean diversity in each treatment, first use lapply to get the index for each row:

z<-lapply(split_spec_env, function(x){
  x$div<-diversity(x[,1:4], index = "invsimpson")
  return(x)
}
)

> z
$a
  S1 S2 S3 S4 Stage      div
1  0  1  2  1     a 2.666667
4  0  1  0  1     a 2.000000

$b
  S1 S2 S3 S4 Stage div
2  0  1  1  0     b   2

$c
  S1 S2 S3 S4 Stage      div
3  1  0  0  3     c 1.600000
5  1  2  1  0     c 2.666667

Then again to get the mean index for each subset (Which I think makes more sense but depends what you need):

lapply(z, function(x){
  mean(x$div)
})

Or if you want to take all the values from a subset and get the overall diversity within a treatment:

lapply(z, function(x){
  y <- unlist(x[,1:4])
  diversity(y, "invsimpson")
})

Edit: I realized you may want the diversity index from the summed species within a treatment. If that's the case, use colSums:

lapply(z, function(x){
  y <- colSums(x[,1:4])
  diversity(y, "invsimpson")
})


问:
Can't use debugger for xamarin android project: System.IO.FileNotFoundException: Could not load file or assembly Mono.Posix
After upgrading my visual studio 2017 to 15.2v (26430.12)

Xamarin.Android SDK 7.3.1.2 (9dbc4c5)

Can't use the debugger anymore. The project builds successfully and deployment finishes but then this error happens:

Could not load file or assembly Mono.Posix

Full error message:

答:
This problem has affected two different PC's of mine. At first I first thought it was related to upgrades to VS when it occurred on my first PC. However, it has impacted my second PC after I upgraded from 23.3.0 to 25.3.1 without updating VS.

I am going to avoid 25.3.1 and revert to 23.3.0.

BTW I tried woelliJ's solution but it didn't work for me.


问:
Question about IIS working paradigm
Here is a picture I captured from < Professional IIS >

I am wondering why the web request and the resulting web content as the response have to go through the same ISAPI filters or applications in a circle fashion. I know that ISAPI applications and Filters are nothing but Win32 DLLs. This circle fashion is kind of like a function call/return manner, i.e., when the web request comes, the exported functions of ISAPI Filters are invoked, and then the Filters invoke the WWW Service, and the WWW Service invoke the exported functions of ISAPI Applicaitons, and they return all the way back reversly. So is this the root cause? (I hope you understand what I mean.)

Many thanks.

答:
Typically, in IIS, WWW service would server web content - it would map the resource to appropriate ISAPI Extension (or handler) - mapping is typically done on the basis of request resource extension. Its extension's responsibility to throw actual content (say html) that will be then returned back to browser via www service. ISAPI filters sits in between - they can modify the request before ISAPI extension/application can process it. Similarly, they can modify the response (content) generated by the application before it is returned to the browser.

I believe that following would be better resources to understand IIS Architecture

http://learn.iis.net/page.aspx/101/introduction-to-iis-7-architecture/

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/843df643-1dbb-4fb6-910d-ec1965fa9e43.mspx?mfr=true

Title: Question about IIS working paradigm


问:
Disabling form fields on select using jQuery
I have a simple booking form with different types of events. When a certain event is triggered which is called FST I want the other fields to be disabled and autofilled with timings/numbers. I have managed to work out how to get the event fields to disable but no matter which select field I use it always autofills the numbers and I can't visualize why. Any help would be great.

```<code><select id="jq-Type" name="Type">
  <option value="PET">Pre-Employment Training</option>
  <option value="FST">Functional Skills Testing</option>
  <option value="ICT">ICT Testing</option>
</select>

<script>
  $(document).on('change', '#jq-Type', function() {
    var shouldEnable = $(this).val() == 'FST';

    $("input[name='BookingLimit']:eq(0)").val('21');
    $('#jq-BookingLimit').prop('disabled', shouldEnable);
    $("select[name='StartTimeHour']:eq(0)").val('09');
    $('#jq-StartTimeHour').prop('disabled', shouldEnable);
    $("select[name='StartTimeMinute']:eq(0)").val('30');
    $('#jq-StartTimeMinute').prop('disabled', shouldEnable);
    $("select[name='EndTimeHour']:eq(0)").val('15');
    $('#jq-EndTimeHour').prop('disabled', shouldEnable);
    $("select[name='StartTimeMinute']:eq(0)").val('00');
    $('#jq-EndTimeMinute').prop('disabled', shouldEnable);
  });
</script>
</code>```

Here's a demo https://jsfiddle.net/02mv54ao/ and even though I only want the timings to change for FST it changes on any of the Type select option

答:
You are disabling the elements only if that value is selected, but you are always changing the other elements values no matter what.

Add "if" do your statement and you're good to go.

```<code>$(document).on('change', '#jq-Type', function() {
    var shouldEnable = $(this).val() == 'FST';
    if (shouldEnable){
        $("input[name='BookingLimit']:eq(0)").val('21');
        $("select[name='StartTimeHour']:eq(0)").val('09');
        $("select[name='StartTimeMinute']:eq(0)").val('30');
        $("select[name='EndTimeHour']:eq(0)").val('15');
        $("select[name='StartTimeMinute']:eq(0)").val('00');
    }
    $('#jq-BookingLimit').prop('disabled', shouldEnable);
    $('#jq-StartTimeHour').prop('disabled', shouldEnable);
    $('#jq-StartTimeMinute').prop('disabled', shouldEnable);
    $('#jq-EndTimeHour').prop('disabled', shouldEnable);
    $('#jq-EndTimeMinute').prop('disabled', shouldEnable);
});
</code>```

Body:
I have a simple booking form with different types of events. When a certain event is triggered which is called FST I want the other fields to be disabled and autofilled with timings/numbers. I have managed to work out how to get the event fields to disable but no matter which select field I use it always autofills the numbers and I can't visualize why. Any help would be great.

<select id="jq-Type" name="Type">
  <option value="PET">Pre-Employment Training</option>
  <option value="FST">Functional Skills Testing</option>
  <option value="ICT">ICT Testing</option>
</select>

Here's a demo https://jsfiddle.net/02mv54ao/ and even though I only want the timings to change for FST it changes on any of the Type select option

Body:
You are disabling the elements only if that value is selected, but you are always changing the other elements values no matter what.

Add "if" do your statement and you're good to go.

$(document).on('change', '#jq-Type', function() {
    var shouldEnable = $(this).val() == 'FST';
    if (shouldEnable){
        $("input[name='BookingLimit']:eq(0)").val('21');
        $("select[name='StartTimeHour']:eq(0)").val('09');
        $("select[name='StartTimeMinute']:eq(0)").val('30');
        $("select[name='EndTimeHour']:eq(0)").val('15');
        $("select[name='StartTimeMinute']:eq(0)").val('00');
    }
    $('#jq-BookingLimit').prop('disabled', shouldEnable);
    $('#jq-StartTimeHour').prop('disabled', shouldEnable);
    $('#jq-StartTimeMinute').prop('disabled', shouldEnable);
    $('#jq-EndTimeHour').prop('disabled', shouldEnable);
    $('#jq-EndTimeMinute').prop('disabled', shouldEnable);
});


问:
Cannot expand and substitute the contents of a variable in Bash
I am using Gitbash, GNU bash, version 4.3.46(2)-release (x86_64-pc-msys).
I am running a bash script that looks like this

CODE CHUNK 1

```<code>curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
'http://localhost:5000/api/123'
</code>```

This works fine.  Basically it posts a giant payload to an endpoint and all is well. The problem is when I attempt to substitute the url for a value from a variable, I get a curl error,

curl: (1) Protocol "'http" not supported or disabled in libcurl

CODE CHUNK 2

```<code>stuff=\'http://localhost:5000/api/123\'
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
$stuff
</code>```

If I echo $stuff immediately after the stuff=\'http://localhost:5000/api/123\', I get 'http://localhost:5000/api/123'.  This is the same value as I had hard-coded in code chunk 1, single ticks and all. There is something hiding behind the scenes in how that url is being evaluated after the variable has been expanded.  I need to get the same behavior as a hard coded url.

答:
Look closely at this error message:

curl: (1) Protocol "'http" not supported or disabled in libcurl

Notice the single-quote in front of http.
The curl command surely knows the http protocol, but not the 'http protocol!

The way you wrote it, the single-quotes are part of the value of stuff:

```<code>stuff=\'http://localhost:5000/api/123\'
</code>```

Remove those, write like this:

```<code>stuff='http://localhost:5000/api/123'
</code>```

If you have variables inside your real string,
and you want them expanded, then use double-quotes instead of single-quotes:

```<code>stuff="http://localhost:5000/api/123"
</code>```

Equally important,
when you use $stuff as a parameter of curl,
you must double-quote it.
If you just write curl $stuff,
then the shell may interpret some characters in $stuff before passing to curl.
To protect from that,
you must write curl "$stuff".

The complete command:

```<code>curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
"$stuff"
</code>```

Finally, make sure that after each \ at the end of lines,
there's nothing after the \ on each line,
the \ must be at the very end.

Body:
I am using Gitbash, GNU bash, version 4.3.46(2)-release (x86_64-pc-msys).
I am running a bash script that looks like this

CODE CHUNK 1

curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
'http://localhost:5000/api/123'

This works fine.  Basically it posts a giant payload to an endpoint and all is well. The problem is when I attempt to substitute the url for a value from a variable, I get a curl error,

curl: (1) Protocol "'http" not supported or disabled in libcurl

CODE CHUNK 2

stuff=\'http://localhost:5000/api/123\'
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
$stuff

If I echo $stuff immediately after the stuff=\'http://localhost:5000/api/123\', I get 'http://localhost:5000/api/123'.  This is the same value as I had hard-coded in code chunk 1, single ticks and all. There is something hiding behind the scenes in how that url is being evaluated after the variable has been expanded.  I need to get the same behavior as a hard coded url.

Body:
Look closely at this error message:

curl: (1) Protocol "'http" not supported or disabled in libcurl

Notice the single-quote in front of http.
The curl command surely knows the http protocol, but not the 'http protocol!

The way you wrote it, the single-quotes are part of the value of stuff:

stuff=\'http://localhost:5000/api/123\'

Remove those, write like this:

stuff='http://localhost:5000/api/123'

If you have variables inside your real string,
and you want them expanded, then use double-quotes instead of single-quotes:

stuff="http://localhost:5000/api/123"

Equally important,
when you use $stuff as a parameter of curl,
you must double-quote it.
If you just write curl $stuff,
then the shell may interpret some characters in $stuff before passing to curl.
To protect from that,
you must write curl "$stuff".

The complete command:

curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
"$stuff"

Finally, make sure that after each \ at the end of lines,
there's nothing after the \ on each line,
the \ must be at the very end.


问:
When to use header('Content-Type: application/json') in PHP
I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

OR

if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

thanks

答:
You should always set the Content-Type for any HTTP response to describe what you're serving in that response.

Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.

You should also set the Content-Type for any request to describe your POST payload.


答:
Why do you define stuff with the ' ' ?

Try it like that:

```<code>stuff="http://localhost:5000/api/123"
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
"$stuff"
</code>```

Also, don't put variables in single quotes, because bash is not available to understand them.

```<code>stuff="http://localhost:5000/api/123"
echo "$stuff"
>> http://localhost:5000/api/123
echo '$stuff'
>> $stuff
</code>```

Title: Cannot expand and substitute the contents of a variable in Bash

Body:
Why do you define stuff with the ' ' ?

Try it like that:

stuff="http://localhost:5000/api/123"
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "x-customheader:customstuff" \
   -d \
'{
  Gigantic json payload contents in here
}' \
"$stuff"

Also, don't put variables in single quotes, because bash is not available to understand them.

stuff="http://localhost:5000/api/123"
echo "$stuff"
>> http://localhost:5000/api/123
echo '$stuff'
>> $stuff


问:
PHP - how to randomly get something from array
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

```<code> $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );
</code>```

What i have tried

```<code>$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";
</code>```

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

答:
You can randomize the array order and take the first element. The code would look like this:</p>

```<code>shuffle($quizes);
</code>```

Body:
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

 $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );

What i have tried

$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

Body:
You can randomize the array order and take the first element. The code would look like this:

shuffle($quizes);