问:
Rails 5 rendering extra spaces in check_box_tag labels
I really cannot find a fix for this, I'm sure you can direct me to a solution.
I want to have a line of check boxes one for each day of the week to schedule training sessions on selected week days, the code in my controller is:

```<code># GET /eventos/forma_prog
def forma_prog
  @entrenadores = User.all
  @dias = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"]
end
</code>```

My form code is:

```<code><div class="well">
  <%= label_tag :dias %>
  <div class="form-group checkbox-inline">
    <% @dias.each do |day| %>
      <%= day %><%= check_box_tag 'dias[]', day, checked = false %>
    <% end %>
  </div>
</div>
</code>```

the HTML generated is this:

```<code><div class="form-group checkbox-inline">
"
                                                 Dom"
<input type="checkbox" name="dias[]" id="dias_" value="Dom">
"
                                                 Lun"
<input type="checkbox" name="dias[]" id="dias_" value="Lun">
"
                                                 Mar"
<input type="checkbox" name="dias[]" id="dias_" value="Mar">
</code>```

and so on. Don't need to tell you the too many extra spaces Rails is generating in the string are ruining my sanity and my form,

the question is how can I avoid/get rid of those unwanted spaces?

I'm using Rails-Bootstrap, this is the style code I get from the browser's  (Chrome) developer tools for that element:

```<code> .checkbox-inline {
        position: relative;
        padding-left: 20px;
        margin-bottom: 0;
        vertical-align: middle;
        font-weight: normal;
        cursor: pointer;
   }
  custom.self-d93…ss?body=1:3933
 .form-group {
        margin-bottom: 15px;
   }
</code>```

As I am trying to solve this, I did chage the form code to:

```<code><div class="well">
  Dias
  <div class="form-group checkbox-inline">
    <% @dias.each do |day| %>
      <%= label_tag day, day, class: "checkbox-inline" %><%= check_box_tag 'dias[]', day, checked = false %>
    <% end %>
  </div>
</div>
</code>```

Still not working...

答:
Thanks to Gerry's comments I found the solution to my problem, it is in the CSS so I did change the code to:

```<code><div class="well">
    <% @dias.each_with_index do |day, index| %>
      <%= label_tag day, day, class: "checkbox-inline nopadding"; %>
      <%= check_box_tag 'dias[]', index, checked = false, class: "nopadding" %>  |
    <% end %>
</div>
</code>```

and then defined the .nopadding class in my custom.scss file like this:

```<code>.nopadding {
   padding: 1px !important;
   margin: 3px !important;
   width: inherit;
 }
</code>```

Thank you =)

Body:
I really cannot find a fix for this, I'm sure you can direct me to a solution.
I want to have a line of check boxes one for each day of the week to schedule training sessions on selected week days, the code in my controller is:

# GET /eventos/forma_prog
def forma_prog
  @entrenadores = User.all
  @dias = ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"]
end

My form code is:

  <%= label_tag :dias %>

    <% @dias.each do |day| %>
      <%= day %><%= check_box_tag 'dias[]', day, checked = false %>
    <% end %>

the HTML generated is this:

"
                                                 Dom"
<input type="checkbox" name="dias[]" id="dias_" value="Dom">
"
                                                 Lun"
<input type="checkbox" name="dias[]" id="dias_" value="Lun">
"
                                                 Mar"
<input type="checkbox" name="dias[]" id="dias_" value="Mar">

and so on. Don't need to tell you the too many extra spaces Rails is generating in the string are ruining my sanity and my form,

the question is how can I avoid/get rid of those unwanted spaces?

I'm using Rails-Bootstrap, this is the style code I get from the browser's  (Chrome) developer tools for that element:

 .checkbox-inline {
        position: relative;
        padding-left: 20px;
        margin-bottom: 0;
        vertical-align: middle;
        font-weight: normal;
        cursor: pointer;
   }
  custom.self-d93…ss?body=1:3933
 .form-group {
        margin-bottom: 15px;
   }

As I am trying to solve this, I did chage the form code to:

  Dias

    <% @dias.each do |day| %>
      <%= label_tag day, day, class: "checkbox-inline" %><%= check_box_tag 'dias[]', day, checked = false %>
    <% end %>

Still not working...

Body:
Thanks to Gerry's comments I found the solution to my problem, it is in the CSS so I did change the code to:

<div class="well">
    <% @dias.each_with_index do |day, index| %>
      <%= label_tag day, day, class: "checkbox-inline nopadding"; %>
      <%= check_box_tag 'dias[]', index, checked = false, class: "nopadding" %>  |
    <% end %>
</div>

and then defined the .nopadding class in my custom.scss file like this:

.nopadding {
   padding: 1px !important;
   margin: 3px !important;
   width: inherit;
 }

Thank you =)


来源: stackexchange

问:
Split function gives 'Subscript out of range' error inside loop
The code snippet below is attempting to look at the contents of a column of cells. Each cell is formatted: "X.XX_-_X.XX". For example: 5.66 - 13.44. The code is meant to take each cell, convert each of the strings to a double, compare them to some other numbers and then repeat for the next cell.

```<code>Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace, MinSpace As Double
Dim MinMax() As String

Set PC = Workbooks("RFQ_Worksheet").Worksheets("Press Choice")

For i = 7 To 52
    MinMax = Split(PC.Cells(i, 8), " - ", 2)
    MaxSpace = CDbl(MinMax(1))
    MinSpace = CDbl(MinMax(0))
    If MaxSpace > 10.3 Then
        'Do some stuff
    End If
Next i

End Sub
</code>```

The line containing MaxSpace = CDbl(MinMax(1)) gives a 'Subscript out of range' error. However, when I replace PC.Cells(i, 8) with PC.Cells(7, 8), the code runs fine.

What am I missing here?

答:
Basically, you are hitting cells in your loop that don't have the delimiter.

Fix:

```<code>Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace As Double  'you didn't declare it properly
Dim MinSpace As Double
Dim MinMax() As String
Dim r As Range

Set PC = ThisWorkbook.Worksheets("Press Choice")

For i = 7 To 52
    Set r = PC.Cells(i, 8)
    If InStr(r, " - ") <> 0 Then
        MinMax = Split(PC.Cells(i, 8), " - ", 2)
        MaxSpace = CDbl(MinMax(1))
        MinSpace = CDbl(MinMax(0))
        '... etc
    End If
Next i

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The code snippet below is attempting to look at the contents of a column of cells. Each cell is formatted: "X.XX_-_X.XX". For example: 5.66 - 13.44. The code is meant to take each cell, convert each of the strings to a double, compare them to some other numbers and then repeat for the next cell.

Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace, MinSpace As Double
Dim MinMax() As String

Set PC = Workbooks("RFQ_Worksheet").Worksheets("Press Choice")

For i = 7 To 52
    MinMax = Split(PC.Cells(i, 8), " - ", 2)
    MaxSpace = CDbl(MinMax(1))
    MinSpace = CDbl(MinMax(0))
    If MaxSpace > 10.3 Then
        'Do some stuff
    End If
Next i

End Sub

The line containing MaxSpace = CDbl(MinMax(1)) gives a 'Subscript out of range' error. However, when I replace PC.Cells(i, 8) with PC.Cells(7, 8), the code runs fine.

What am I missing here?

Body:
Basically, you are hitting cells in your loop that don't have the delimiter.

Fix:

Sub Test()
Dim PC As Worksheet
Dim i As Integer
Dim MaxSpace As Double  'you didn't declare it properly
Dim MinSpace As Double
Dim MinMax() As String
Dim r As Range

Set PC = ThisWorkbook.Worksheets("Press Choice")

For i = 7 To 52
    Set r = PC.Cells(i, 8)
    If InStr(r, " - ") <> 0 Then
        MinMax = Split(PC.Cells(i, 8), " - ", 2)
        MaxSpace = CDbl(MinMax(1))
        MinSpace = CDbl(MinMax(0))
        '... etc
    End If
Next i

End Sub


问:
RESTful service using express and typescript - this undefined for Response.send()
Appears that "this" is undefined inside of a express.Response.send() method. Is there a way to still send a member of my Router?

my-router.ts:

```<code>import { Router, Request, Response, NextFunction } from 'express';
import { MyTsObject } from "../my-ts-object";

export class MyRouter {
    router: Router;
    myTsObject: MyTsObject;

    constructor() {
        this.myTsObject = new MyTsObject();
        this.router = Router();
        this.init();
    }

    public getData(req: Request, res: Response, next: NextFunction){
        res.send(JSON.stringify(this.myTsObject)); // runtime error here:
        // TypeError: Cannot read property 'myTsObject' of undefined
    }

    init() {
        this.router.get('/', this.getData);
    }
}
</code>```

app.ts:

```<code>import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { MyRouter } from "./routes/my-router";

class App {
    public express: express.Application;

    constructor() {
        this.express = express();
        this.middleware();
        this.routes();
    }

    private middleware(): void {
        this.express.use(logger('dev'));
        this.express.use(bodyParser.json());
        this.express.use(bodyParser.urlencoded({ extended: false}));
    }

    private routes(): void {
        this.express.use('/', new MyRouter().router);
    }

}

export default new App().express;
</code>```

index.ts:

```<code>import * as  http from 'http';
import * as debug from 'debug';

import App from './app';

debug('ts-express:server');

const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);

const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

....
</code>```

See the my-router.ts file for the runtime error that is occurring when I hit the url in a browser.  I'm assuming 'this' in that context is not referring to the MyRouter object. Is there still a way to get a reference to the myTsObject from inside the send() method? Is there a better way to do all this?

答:
You can bind the context of your getData method to MyRouter in your init method:

```<code>init() {
    this.router.get('/', this.getData.bind(this));
}
</code>```

Alternatively you could pass an anonymous function to router.get that achieves the same thing:

```<code>init() {
    this.router.get('/', (req: Request, res: Response, next: NextFunction) => this.getData(req, res, next));
}
</code>```

Body:
Appears that "this" is undefined inside of a express.Response.send() method. Is there a way to still send a member of my Router?

my-router.ts:

import { Router, Request, Response, NextFunction } from 'express';
import { MyTsObject } from "../my-ts-object";

export class MyRouter {
    router: Router;
    myTsObject: MyTsObject;

    constructor() {
        this.myTsObject = new MyTsObject();
        this.router = Router();
        this.init();
    }

    public getData(req: Request, res: Response, next: NextFunction){
        res.send(JSON.stringify(this.myTsObject)); // runtime error here:
        // TypeError: Cannot read property 'myTsObject' of undefined
    }

    init() {
        this.router.get('/', this.getData);
    }
}

app.ts:

import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { MyRouter } from "./routes/my-router";

class App {
    public express: express.Application;

    constructor() {
        this.express = express();
        this.middleware();
        this.routes();
    }

    private middleware(): void {
        this.express.use(logger('dev'));
        this.express.use(bodyParser.json());
        this.express.use(bodyParser.urlencoded({ extended: false}));
    }

    private routes(): void {
        this.express.use('/', new MyRouter().router);
    }

}

export default new App().express;

index.ts:

import * as  http from 'http';
import * as debug from 'debug';

import App from './app';

debug('ts-express:server');

const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);

const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

....

See the my-router.ts file for the runtime error that is occurring when I hit the url in a browser.  I'm assuming 'this' in that context is not referring to the MyRouter object. Is there still a way to get a reference to the myTsObject from inside the send() method? Is there a better way to do all this?

Body:
You can bind the context of your getData method to MyRouter in your init method:

init() {
    this.router.get('/', this.getData.bind(this));
}

Alternatively you could pass an anonymous function to router.get that achieves the same thing:

init() {
    this.router.get('/', (req: Request, res: Response, next: NextFunction) => this.getData(req, res, next));
}


问:
Making sure the user enters a particular file type
I have a JFileChooser (not shown here) that takes a users file Input. I would like to make sure the user enters only a .txt file. Is there a function available that allows this to be verified with JFileChooser or another possible solution. I considered the following:

```<code>if (selectedFile != null && selectedFile.getName().endsWith(".txt")){
    //action
} else {
    JOptionPane.showMessageDialog(null, "You have not selected a .txt file. Please choose a correct file type to continue.);
}
</code>```

However, if it is possible, I would like for it to be the case that even if the file does not explicitly end with .txt in the name, it will still be accepted but it must still be a text file.

答:
Answer, how to detect if a file is actually .txt file you can use Apache Tika library for that

```<code>public static void main(String[] sss) {

        try {
        //  System.out.println(ContainsMedia(new File("D:\\test")));

            Tika tika = new Tika();
            String contentTypeDetected = "";
            File dir = new File("D:\\test");
            for (String dir2 : dir.list()) {
                try {

                    contentTypeDetected = tika.detect(new File(dir,dir2));
                    System.out.println(contentTypeDetected);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>```

output:text/plain
even though the file in that directory is text file but i renamed it to .exe file and .rar file but the apache tikka tell the truth
for download here is the link of jar add it to your classpath after downloading Apache tikka homepage

Secondly if you want him to choose only txt file type you can do

```<code>fileChooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                String name = f.getName().toLowerCase();
                return name.endsWith(".txt")
                        ;
            }

            @Override
            public String getDescription() {
                return "only text file";
            }
        });
</code>```

Body:
I have a JFileChooser (not shown here) that takes a users file Input. I would like to make sure the user enters only a .txt file. Is there a function available that allows this to be verified with JFileChooser or another possible solution. I considered the following:

if (selectedFile != null && selectedFile.getName().endsWith(".txt")){
    //action
} else {
    JOptionPane.showMessageDialog(null, "You have not selected a .txt file. Please choose a correct file type to continue.);
}

However, if it is possible, I would like for it to be the case that even if the file does not explicitly end with .txt in the name, it will still be accepted but it must still be a text file.

Body:
Answer, how to detect if a file is actually .txt file you can use Apache Tika library for that

public static void main(String[] sss) {

        try {
        //  System.out.println(ContainsMedia(new File("D:\\test")));

            Tika tika = new Tika();
            String contentTypeDetected = "";
            File dir = new File("D:\\test");
            for (String dir2 : dir.list()) {
                try {

                    contentTypeDetected = tika.detect(new File(dir,dir2));
                    System.out.println(contentTypeDetected);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

output:text/plain
even though the file in that directory is text file but i renamed it to .exe file and .rar file but the apache tikka tell the truth
for download here is the link of jar add it to your classpath after downloading Apache tikka homepage

Secondly if you want him to choose only txt file type you can do

fileChooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                String name = f.getName().toLowerCase();
                return name.endsWith(".txt")
                        ;
            }

            @Override
            public String getDescription() {
                return "only text file";
            }
        });


问:
Finding a specified pattern in the data-- Hive
My table has data as below

```<code>Column
--------
1122 52
1122 62
1122 82
1122 12
112222
1122442
</code>```

I need to find the count of those numbers which has spaces in MIDDLE in a pattern Hive.

Please help me out in getting the count with explanation if possible.

答:
Use like and count(*):

```<code>select count(*)
from t
where column like '% %';
</code>```

Body:
My table has data as below

Column
--------
1122 52
1122 62
1122 82
1122 12
112222
1122442

I need to find the count of those numbers which has spaces in MIDDLE in a pattern Hive.

Please help me out in getting the count with explanation if possible.

Body:
Use like and count(*):

select count(*)
from t
where column like '% %';


答:
Yes it is possible.

The JFileChooser provides everything you need.

For example:

```<code>    jfc.setAcceptAllFileFilterUsed(false);

    jfc.setFileFilter(new FileFilter()
    {
        @Override
        public String getDescription()
        { return "*" + fileExtension; }

        @Override
        public boolean accept(File f)
        {
            return f.isDirectory() || f.getName().toLowerCase().endsWith(fileExtension));
        }
    });
</code>```

(jfc is the JFileChooser object, created before.)

This is a really simple example.

As you can see, you have to add a new FileFilter to solve your problem.

This Object got a method called "accept", which just returns a boolean value

(whether it is a "valid file" or not.)

But you should check the Java Documentation about it for all the possibilities.

Or use these tutorials provided by Oracle:

http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Btw. you cannot ensure that the chosen file containts just text.

You would have to check this afterwards.

Good luck!

(It wont be that hard to achieve ;D)

Title: Making sure the user enters a particular file type

Body:
Yes it is possible.

The JFileChooser provides everything you need.

For example:

    jfc.setAcceptAllFileFilterUsed(false);

    jfc.setFileFilter(new FileFilter()
    {
        @Override
        public String getDescription()
        { return "*" + fileExtension; }

        @Override
        public boolean accept(File f)
        {
            return f.isDirectory() || f.getName().toLowerCase().endsWith(fileExtension));
        }
    });

(jfc is the JFileChooser object, created before.)

This is a really simple example.

As you can see, you have to add a new FileFilter to solve your problem.

This Object got a method called "accept", which just returns a boolean value

(whether it is a "valid file" or not.)

But you should check the Java Documentation about it for all the possibilities.

Or use these tutorials provided by Oracle:

http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Btw. you cannot ensure that the chosen file containts just text.

You would have to check this afterwards.

Good luck!

(It wont be that hard to achieve ;D)


问:
Testing already deployed ember app with ember-cli
I'm aware that ember-cli can be used write unit, integration and acceptance tests for apps with default test-runners: QUnit and PhantomJS.
I want to write acceptance tests for a remote website using ember-cli . I was able to write basic test cases for a local app created using:

```<code>ember new <login-test-repo>
ember generate acceptance-test login-test
</code>```

I'm able to fill in, click and run tests on the local app, but when I change the rootURL of in the environment as I need a remote website to be tested, ember-cli adds "/" at the start to the remote website URL and tests fail with error:

```<code>The URL "/https://my-website.com" did not match any routes in your application
</code>```

I'm pretty new to testing front-end apps with ember-cli. I've tested the same workflow with selenium where I can scrap and run acceptance tests for the webpage easily.

Any help on setting up ember-cli routes for remote webpage would be of great help. Thanks.

答:
I don't want to be prophet of doom, but it is just not meant to test remote websites using Ember CLI tooling. First, you can see in your config different configuration for tests, develop and production environments. One of key things is:

```<code>ENV.APP.rootElement = '#ember-testing';
</code>```

And application is rendered into that element. Also the application is closed after each acceptance test, then booted again, initializers are fired. It works because start-app test helper is called:

```<code>import Ember from 'ember';
import Application from '../../app';
import Router from '../../router';
import config from '../../config/environment';

export default function startApp(attrs) {
  let application;

  let attributes = Ember.merge({}, config.APP);
  attributes = Ember.merge(attributes, attrs); // use defaults, but you can override;

  Ember.run(function() {
    application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
  });

  return application;
}
</code>```

You don't have any of these things remotely. Also, how would you expect your tests to get this remote website? Via IFRAME - I seriously doubt there's any logic in Ember CLI tooling to make it work. :)

The standard I'm familiar with is remote websites are tested via Selenium, for example, by QA or developers. Separate Ember CLI test suite is maintained by developers.

Body:
I'm aware that ember-cli can be used write unit, integration and acceptance tests for apps with default test-runners: QUnit and PhantomJS.
I want to write acceptance tests for a remote website using ember-cli . I was able to write basic test cases for a local app created using:

ember new <login-test-repo>
ember generate acceptance-test login-test

I'm able to fill in, click and run tests on the local app, but when I change the rootURL of in the environment as I need a remote website to be tested, ember-cli adds "/" at the start to the remote website URL and tests fail with error:

The URL "/https://my-website.com" did not match any routes in your application

I'm pretty new to testing front-end apps with ember-cli. I've tested the same workflow with selenium where I can scrap and run acceptance tests for the webpage easily.

Any help on setting up ember-cli routes for remote webpage would be of great help. Thanks.

Body:
I don't want to be prophet of doom, but it is just not meant to test remote websites using Ember CLI tooling. First, you can see in your config different configuration for tests, develop and production environments. One of key things is:

ENV.APP.rootElement = '#ember-testing';

And application is rendered into that element. Also the application is closed after each acceptance test, then booted again, initializers are fired. It works because start-app test helper is called:

import Ember from 'ember';
import Application from '../../app';
import Router from '../../router';
import config from '../../config/environment';

export default function startApp(attrs) {
  let application;

  let attributes = Ember.merge({}, config.APP);
  attributes = Ember.merge(attributes, attrs); // use defaults, but you can override;

  Ember.run(function() {
    application = Application.create(attributes);
    application.setupForTesting();
    application.injectTestHelpers();
  });

  return application;
}

You don't have any of these things remotely. Also, how would you expect your tests to get this remote website? Via IFRAME - I seriously doubt there's any logic in Ember CLI tooling to make it work. :)

The standard I'm familiar with is remote websites are tested via Selenium, for example, by QA or developers. Separate Ember CLI test suite is maintained by developers.


问:
SPARQL Type Conversion?
I have the following SPARQL query:

```<code>PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#>
PREFIX dtp: <http://dtp-126.sncs.abdn.ac.uk#>
PREFIX dbp: <http://dbpedia.org/resource/>
SELECT ?value ?time WHERE {
    dtp:CD7514 ssn:madeObservation ?observation .
    ?observation ssn:observedProperty ?property .
    ?property ssn:hasValue <http://dbpedia.org/resource/Temperature> .
    ?observation ssn:observationResult ?observationValue .
    ?observationValue ssn:hasValue ?value .
    ?observationValue ssn:observationSamplingTime ?time
    FILTER(?time > 1291908000)
}
</code>```

Which, in a nutshell, is selecting all temperature sensor observations from a sensor, dtp:CD7514, and filtering out values less than the given timestamp.

However, adding the filter constraint returns 0 results (when there are observations that match this time region!)

Is it possible that ?time is a varchar/text/String data type and therefore the comparison can't be done? If so, is it possible to do the conversion within SPARQL?

答: The solution to this was merely to add quotes around the timestamp.</p>

ContentLicense: CC BY-SA 2.5

Title: SPARQL Type Conversion?

Body:
I have the following SPARQL query:

PREFIX ssn: <http://purl.oclc.org/NET/ssnx/ssn#>
PREFIX dtp: <http://dtp-126.sncs.abdn.ac.uk#>
PREFIX dbp: <http://dbpedia.org/resource/>
SELECT ?value ?time WHERE {
    dtp:CD7514 ssn:madeObservation ?observation .
    ?observation ssn:observedProperty ?property .
    ?property ssn:hasValue <http://dbpedia.org/resource/Temperature> .
    ?observation ssn:observationResult ?observationValue .
    ?observationValue ssn:hasValue ?value .
    ?observationValue ssn:observationSamplingTime ?time
    FILTER(?time > 1291908000)
}

Which, in a nutshell, is selecting all temperature sensor observations from a sensor, dtp:CD7514, and filtering out values less than the given timestamp.

However, adding the filter constraint returns 0 results (when there are observations that match this time region!)

Is it possible that ?time is a varchar/text/String data type and therefore the comparison can't be done? If so, is it possible to do the conversion within SPARQL?


问:
ionic 2 serve ignores changes in html
I am starting an ionic2 project, and running into trouble with seeing changes in code reflect to the browser.

Description of the phenomenon:

At some point I  see all of what I expect to see in the browser. For example, a single page whose .html is

```<code>{{text}}
</code>```

and text field in the .ts contains "hola".

The output is obviously hola.

Then, I either can change the .html to

```<code>Hello World!
</code>```

Or the text field in the .ts to "mundo"

Since ionic serve is running in the background, I see the browser update itself after I save the change in the code.

However, it always updates to the same old hola.

Doesn't matter how many times I refresh, save, change. I can even delete all contents of both .html and .ts files, and still the browser would show the old state.

things I tried that don't work:

clearing cache from chrome

restarting ionic serve

saving any and all files again

refreshing browser.

It is very frustrating to work like this, as this problem comes and goes, and I have no clear method to even bypass it.

Any suggestions?

I run windows 10, and this happens both in chrome and firefox.

my package.json:

```<code>{
  "name": "saperli",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/core": "3.10.2",
    "@ionic-native/splash-screen": "3.10.2",
    "@ionic-native/status-bar": "3.10.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.7",
    "@ionic/cli-plugin-ionic-angular": "1.3.0",
    "typescript": "2.3.3"
  },
  "description": "An Ionic project"
}
</code>```

答: This happened to me and I had to switch to using Google Chrome Icognito mode. Caching of javascript seemed to mess things up in development.</p>

Title: ionic 2 serve ignores changes in html

Body:
I am starting an ionic2 project, and running into trouble with seeing changes in code reflect to the browser.

Description of the phenomenon:

At some point I  see all of what I expect to see in the browser. For example, a single page whose .html is

{{text}}

and text field in the .ts contains "hola".

The output is obviously hola.

Then, I either can change the .html to

Hello World!

Or the text field in the .ts to "mundo"

Since ionic serve is running in the background, I see the browser update itself after I save the change in the code.

However, it always updates to the same old hola.

Doesn't matter how many times I refresh, save, change. I can even delete all contents of both .html and .ts files, and still the browser would show the old state.

things I tried that don't work:

clearing cache from chrome

restarting ionic serve

saving any and all files again

refreshing browser.

It is very frustrating to work like this, as this problem comes and goes, and I have no clear method to even bypass it.

Any suggestions?

I run windows 10, and this happens both in chrome and firefox.

my package.json:

{
  "name": "saperli",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.2",
    "@angular/compiler": "4.1.2",
    "@angular/compiler-cli": "4.1.2",
    "@angular/core": "4.1.2",
    "@angular/forms": "4.1.2",
    "@angular/http": "4.1.2",
    "@angular/platform-browser": "4.1.2",
    "@angular/platform-browser-dynamic": "4.1.2",
    "@ionic-native/core": "3.10.2",
    "@ionic-native/splash-screen": "3.10.2",
    "@ionic-native/status-bar": "3.10.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.11"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.3.7",
    "@ionic/cli-plugin-ionic-angular": "1.3.0",
    "typescript": "2.3.3"
  },
  "description": "An Ionic project"
}


问:
Close responsive menu
I have a response menu which works great. However, I want the menu to be closed when the visitor clicks on an item in my menu. At this moment, the menu closes only when the visitor clicks on the 'button_menu'. The menu must stay open if someone clicks on 'submenu-button'. How can I do this?

```<code>    <script>
(function($) {
$.fn.menumaker = function(options) {
 var cssmenu = $(this), settings = $.extend({
   format: "dropdown",
   sticky: false
 }, options);
 return this.each(function() {
   $(this).find(".button_menu").on('click', function(){
     $(this).toggleClass('menu-opened');
     var mainmenu = $(this).next('ul');
     if (mainmenu.hasClass('open')) {
       mainmenu.slideToggle().removeClass('open');
     }
     else {
       mainmenu.slideToggle().addClass('open');
       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }
     }
   });
   cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
     cssmenu.find(".has-sub").prepend('<span class="submenu-button"></span>');
     cssmenu.find('.submenu-button').on('click', function() {
       $(this).toggleClass('submenu-opened');
       if ($(this).siblings('ul').hasClass('open')) {
         $(this).siblings('ul').removeClass('open').slideToggle();
       }
       else {
         $(this).siblings('ul').addClass('open').slideToggle();
       }
     });
   };
   if (settings.format === 'multitoggle') multiTg();
   else cssmenu.addClass('dropdown');
   if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
  var mediasize = 1000;
     if ($( window ).width() > mediasize) {
       cssmenu.find('ul').show();
     }
     if ($(window).width() <= mediasize) {
       cssmenu.find('ul').hide().removeClass('open');
     }
   };
   resizeFix();
   return $(window).on('resize', resizeFix);
 });
  };
})(jQuery);

(function($){
$(document).ready(function(){
$("#cssmenu").menumaker({
   format: "multitoggle"
});
});
})(jQuery);
</script>
</code>```

HTML:

```<code><header>
            <nav id="cssmenu">
                <div class="logo">
                    <a href="http://www. .com">
                    <img alt="" src="images/logo.png"></a> </div>
                <div id="head-mobile">
                </div>
                <div class="button_menu">
                </div>
                <ul id="myTopnav" class="navigation">
                    <li class="active" data-slide="1">
                    <a onclick="myFunction()">HOME</a></li>
                    <li data-slide="2"><a onclick="myFunction()">PRODUCTS</a>
                    <ul>
                        <li>
                        <a onclick="window.location.href='http://www.'">
                        ROTARY STAGES</a></li>
                        <li>
                        <a onclick="window.location.href='http://www.'">
                        LINEAR STAGES</a></li>
                        <li>
                        <a onclick="window.location.href='http://www.'">
                        MULTI-DOF STAGES</a></li>
                        <li>
                        <a onclick="window.location.href='http://www.'">
                        DRIVERS</a></li>
                    </ul>
                    </li>
                    <li data-slide="4"><a onclick="myFunction()">TRADE FAIRS</a></li>
                    <li data-slide="6"><a onclick="myFunction()">COMPANY</a></li>
                    <li data-slide="16"><a onclick="myFunction()">TECHNOLOGY</a></li>
                    <li data-slide="8"><a onclick="myFunction()">CAREERS</a></li>
                    <li data-slide="10"><a onclick="myFunction()">CONTACT</a></li>
                </ul>
            </nav>
        </header>
</code>```

答:
You can simply attach the click event to the ul within your .menumaker, and check whether the original target of the click was within a .submenu-button to determine whether to close:

return this.each(function() {
   $(this).find(".button_menu").on('click', function(){
     // Your current button event remains the same
   }).next('ul').on('click.checkToClose', function(e) {
       var target = e.originalEvent.target;
       if ($(target).closest('.submenu-button').length === 0) {
           $(this).slideToggle().removeClass('open');
       }
   });
   // ...
});```
</div>
</div>
</p>

<p>Or, if you'd like to close only if a menu link has been clicked, it can be even more brief:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>return this.each(function() {
   // ...
   var mainmenu = $(this).find(".button_menu").next('ul');
   mainmenu.on('click.checkToClose', 'a', function(e) {
       if ($(this).closest('.submenu-button').length === 0) {
           mainmenu.slideToggle().removeClass('open');
       }
   });
   // ...
});</code>```

ContentLicense: CC BY-SA 4.0

Title: Close responsive menu

Body:
I have a response menu which works great. However, I want the menu to be closed when the visitor clicks on an item in my menu. At this moment, the menu closes only when the visitor clicks on the 'button_menu'. The menu must stay open if someone clicks on 'submenu-button'. How can I do this?

HTML:

                    HOME

PRODUCTS

                        ROTARY STAGES

                        LINEAR STAGES

                        MULTI-DOF STAGES

                        DRIVERS

TRADE FAIRS

COMPANY

TECHNOLOGY

CAREERS

CONTACT

Body:
You can simply attach the click event to the ul within your .menumaker, and check whether the original target of the click was within a .submenu-button to determine whether to close:

return this.each(function() {
   $(this).find(".button_menu").on('click', function(){
     // Your current button event remains the same
   }).next('ul').on('click.checkToClose', function(e) {
       var target = e.originalEvent.target;
       if ($(target).closest('.submenu-button').length === 0) {
           $(this).slideToggle().removeClass('open');
       }
   });
   // ...
});

Or, if you'd like to close only if a menu link has been clicked, it can be even more brief:

return this.each(function() {
   // ...
   var mainmenu = $(this).find(".button_menu").next('ul');
   mainmenu.on('click.checkToClose', 'a', function(e) {
       if ($(this).closest('.submenu-button').length === 0) {
           mainmenu.slideToggle().removeClass('open');
       }
   });
   // ...
});


问:
VS 2017 RC generating an 0x8000ffff error when trying to debug xUnit tests
I'm trying to debug my .NET Core xUnit tests in VS 2017 RC. I run my tests via the Test Explorer window. While right-clicking a test and selecting Run Selected Tests works fine, selecting Debug Selected Tests does not:

I'm at a loss at how to get past this. I have tried restarting VS, doing a clean build, removing the .vs/ folder, and even updating to a newer build of VS 2017. However, nothing so far has worked. Does anyone have suggestions for how I can work around this? Thanks!

edit: My project has a Git repo here, so if you want to you're free to clone it and see if you can repro for yourself. The test assembly is in src/BasicCompiler.Tests/.

答:
Try running Visual Studio as an administrator, it might resolve the issue.  </p>

<p>In case you don't know how:
Right click on the application icon, right click on the applications name and select Run as Administrator.  </p>

Body:
Try running Visual Studio as an administrator, it might resolve the issue.

In case you don't know how:
Right click on the application icon, right click on the applications name and select Run as Administrator.


问:
Can I use array.prototype.reduce() to process two arrays at once?
I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:

```<code>var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131
</code>```

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.

My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].

Is there some nice solution to this using the reduce() function?

答:
You may do as follows with pure JS;

var arr1 = [2, 3, 4, 5, 6],
    arr2 = [5, 10, 4, 9, 5],
  result = arr1.reduce((r,c,i) => (r.sum = r.sum ? r.sum + c * r[i] : c * r[i], r), arr2.slice()).sum;
console.log(result);```

I .slice() arr2 in order to not mutate it with a state variable yet you may still do without slicing if you will not apply a for in loop to arr2 afterwards or such...

Body:
I have two arrays of same length and I would like to somehow process them both at once with the reduce method. Something like:

var arr1 = [2, 3, 4, 5, 6];
var arr2 = [5, 10, 4, 9, 5];
var productSum = arr1.reduce(function(sumOfProducts, item, secondArrayItem) {
    /* here I would like to multiply item from arr1 by the item from arr2 at the same index */
    return sumOfProducts + item * secondArrayItem;
}, 0, arr2)
console.log(productSum);  // 131

An option would of course be to access the correct item from arr2 using currentIndex, but that solution is ugly as I am accessing a variable outside of the scope of the function.

My specific use case is that I have an array with resources like var resources = [2, 5, 4, 6, 2] and I want to check if each item is higher than corresponding resource cost in another array like var cost = [3, 1, 0, 0, 1].

Is there some nice solution to this using the reduce() function?

Body:
You may do as follows with pure JS;

var arr1 = [2, 3, 4, 5, 6],
    arr2 = [5, 10, 4, 9, 5],
  result = arr1.reduce((r,c,i) => (r.sum = r.sum ? r.sum + c * r[i] : c * r[i], r), arr2.slice()).sum;
console.log(result);

I .slice() arr2 in order to not mutate it with a state variable yet you may still do without slicing if you will not apply a for in loop to arr2 afterwards or such...


问:
Add integrity checks to csv files with php
I have to generate large csv files that export data from database with some minimal processing of the raw data.

The file is downloaded to the user, writing chunks with putcsv. My problem is that the download can stop before is done and the user won't notice that the csv if truncated.

Question:  is there a way to add integrity hints to cvsfile so the user can check if the file contains all the data was supposed to contain?

One solution would be to add at the last line count of all records and the client should check that, but is seems more like a hack

答:
The CSV specification doesn't leave room for any sort of file integrity check. So if you are hoping to so something that a CSV parser will pick up on automatically, you can't. Part of the issue is that there isn't really a CSV specification, and in my experience different parsers have slightly different definitions of what CSV means. Either way, there is no integrity check built into the CSV "specification" that you can expect any CSV parser to  automatically notice. Adding something to the end would give the end user a chance to verify the file themselves, but then again I doubt anyone would actually bother checking.

One possible option would be to send the content length along with the file. Then the browser may detect an interrupted download when the total content doesn't match what it was told to expect. The exact behavior there probably varies from browser to browser though, and you would have to run some tests to see if that is actually helpful.

However, that also requires you to know the length of the file before hand, which means building it all in memory, measuring the size, and then dumping to the browser. That has some disadvantages itself, including the fact that you are limited by the size of your memory (although you can mitigate that with php://temp). Also, the download won't start until the file is fully built, and depending on how long that takes it might result in more cancelations if the user thinks the download is frozen.

A completely different solution would be to write the file contents to disk (in the background) and then email the user with a download link when the file is built. This way they aren't waiting on your download script, and the actual download will simply be a simple file download managed directly by your web server, which will be much faster and less prone to errors.


问:
UIScrollView contentInset not working
I'm having a problem with contentInset not working for a UIScrollView to work with a keyboard popup. It kind of works: for some reason I need large numbers (maybe above the view's height?) for it to do anything, despite all documentation of contentInset showing small numbers like 40.0 (e.g. for a bar), or the keyboard height.

I've reproduced the problem on a brand new application by the following steps:

Create new single view application using Xcode new project

On storyboard, drag in a scrollview, filling full view size

On storyboard, drag in a button, at the very bottom of the screen (inside the scrollview)

Link the scrollview to a new property in the ViewController

Link button to a method in the ViewController

Make the button's pressed method set the contentInset

Here is the code for the ViewController:

```<code>@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end

@implementation ViewController
- (IBAction)button:(id)sender {
    self.scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 600, 0.0);
}
@end
</code>```

What am I missing / why do I need large numbers?

答: In my case, I just forgot to connect the ScrollView in the Interface Builder...</p>

Title: UIScrollView contentInset not working

Body:
I'm having a problem with contentInset not working for a UIScrollView to work with a keyboard popup. It kind of works: for some reason I need large numbers (maybe above the view's height?) for it to do anything, despite all documentation of contentInset showing small numbers like 40.0 (e.g. for a bar), or the keyboard height.

I've reproduced the problem on a brand new application by the following steps:

Create new single view application using Xcode new project

On storyboard, drag in a scrollview, filling full view size

On storyboard, drag in a button, at the very bottom of the screen (inside the scrollview)

Link the scrollview to a new property in the ViewController

Link button to a method in the ViewController

Make the button's pressed method set the contentInset

Here is the code for the ViewController:

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end

@implementation ViewController
- (IBAction)button:(id)sender {
    self.scrollView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 600, 0.0);
}
@end

What am I missing / why do I need large numbers?


问:
Worst & Best Player based on PPG
I'm trying to output the best and worst players based on their points-per-game.

My issue is with calculating worstPlayer. I don't know how to keep track of bestPPG relative to my other if-statement, or else I feel that I have the right idea. I've tried this for 2 days, no luck.

By the way, I'm not trying to use functions, just conditional statements, unless I have to? Then why not. Also, ignore the unnecessary use of headers, learning via tutorials at the moment.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main() {
    int i;
    int player[5] = {58, 66, 68, 71, 87};
    int goals[5] = {26, 39, 25, 29, 31};
    int gamesPlayed[5] = {30,30,28,30,26};
    float ppg[5];
    float bestPPG = 0.0;
    float worstPPG = 0.0;
    int bestPlayer;
    int worstPlayer;

    for(i=0; i<5; i++) {

        ppg[i] = (float)goals[i] / (float)gamesPlayed[i];
        printf("%d \t %d \t %d \t %.2f \n",player[i],goals[i],
gamesPlayed[i],ppg[i]);

        if ( ppg[i] > bestPPG ) {

            if(bestPPG == 0.0)
            {
                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            if (ppg[i] < worstPPG)
            {

                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            bestPPG = ppg[i];
            bestPlayer = player[i];

        }

        if ( ppg[i] < bestPPG )
        {
            if ( ppg[i] < worstPPG ) {

                worstPPG = ppg[i];
                worstPlayer = ppg[i];
            }
        }

    }

    printf("\nThe best player is: %d \n", bestPlayer);
    printf("The worst player is: %d \n", worstPlayer);

    return 0;

}
</code>```

Thank you!

答:
First of all, you have this error:

```<code>worstPlayer = ppg[i];
</code>```

where it should be:

```<code>worstPlayer = player[i];
</code>```

Secondly, after fixing that, then even though your conditional statements are working they can be simplified a lot:

```<code>    if (i == 0) { // Initialize
        worstPPG = bestPPG = ppg[0];
        worstPlayer = bestPlayer = player[0];
    } else if ( ppg[i] > bestPPG ) {
        bestPPG = ppg[i];
        bestPlayer = player[i];
    } else if ( ppg[i] < worstPPG ) {
        worstPPG = ppg[i];
        worstPlayer = player[i];
    }
</code>```

Title: Worst & Best Player based on PPG

Body:
I'm trying to output the best and worst players based on their points-per-game.

My issue is with calculating worstPlayer. I don't know how to keep track of bestPPG relative to my other if-statement, or else I feel that I have the right idea. I've tried this for 2 days, no luck.

By the way, I'm not trying to use functions, just conditional statements, unless I have to? Then why not. Also, ignore the unnecessary use of headers, learning via tutorials at the moment.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main() {
    int i;
    int player[5] = {58, 66, 68, 71, 87};
    int goals[5] = {26, 39, 25, 29, 31};
    int gamesPlayed[5] = {30,30,28,30,26};
    float ppg[5];
    float bestPPG = 0.0;
    float worstPPG = 0.0;
    int bestPlayer;
    int worstPlayer;

    for(i=0; i<5; i++) {

        ppg[i] = (float)goals[i] / (float)gamesPlayed[i];
        printf("%d \t %d \t %d \t %.2f \n",player[i],goals[i],
gamesPlayed[i],ppg[i]);

        if ( ppg[i] > bestPPG ) {

            if(bestPPG == 0.0)
            {
                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            if (ppg[i] < worstPPG)
            {

                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            bestPPG = ppg[i];
            bestPlayer = player[i];

        }

        if ( ppg[i] < bestPPG )
        {
            if ( ppg[i] < worstPPG ) {

                worstPPG = ppg[i];
                worstPlayer = ppg[i];
            }
        }

    }

    printf("\nThe best player is: %d \n", bestPlayer);
    printf("The worst player is: %d \n", worstPlayer);

    return 0;

}

Thank you!

Body:
First of all, you have this error:

worstPlayer = ppg[i];

where it should be:

worstPlayer = player[i];

Secondly, after fixing that, then even though your conditional statements are working they can be simplified a lot:

    if (i == 0) { // Initialize
        worstPPG = bestPPG = ppg[0];
        worstPlayer = bestPlayer = player[0];
    } else if ( ppg[i] > bestPPG ) {
        bestPPG = ppg[i];
        bestPlayer = player[i];
    } else if ( ppg[i] < worstPPG ) {
        worstPPG = ppg[i];
        worstPlayer = player[i];
    }


问:
Choose an item in navigation bar and then it leads to showing a text in the page
I am a beginner. I am trying to learn JavaScript, HTML and CSS simultaneously. I have written a test code which has a navigation bar and I would like that a paragraph of text will pop out in the page when I click on any of the items in the menu bar. I have written the following code but it doesn't work.
index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="index.css">
  <script type="text/javascript" charset="utf-8" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--creating a navigation bar-->
<nav id="MyNavBar" class="navbar navbar-default">
    <div class="container-fluid">
 <ul id="details" class="nav navbar-nav">

<li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
        Links
        <b class="caret"></b>
    </a>
    <ul id="subdetails" class="dropdown-menu">
        <li><a href="Something">Something</a></li>
        <li><a href="Others">Another thing</a></li>
    </ul>
</li>
</ul>
</div>
</nav>
<div class="background-image"></div>
<section id="content">

</section>
<script type="text/javascript" charset="utf-8">
            $(document).ready(function(){

                $('#MyNavBar ul li a').click(function(){
                    $('#content').load('details.html #' + $(this).attr('href'));
                    return false;
                });

            });
</script>
</body>
</html>
</code>```

index.css

```<code>body {
  font-family: "Serif";
}

.background-image {
  background: url("https://pbs.twimg.com/media/CXAOHDfWMAU2Zmi.jpg");
  background-size: cover;
  position: fixed;
  background-repeat: no-repeat;
  -webkit-filter:blur(3px) grayscale(50%);
  -ms-filter:blur(3px) grayscale(50%);
  filter:blur(3px) grayscale(50%);
  width:100%;
  height:100%;
}
.dropdown {
    position: relative;
    display: inline-block;
    font-family: Lobster;
}

.dropdown-menu {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    padding: 12px 16px;
    z-index: 1;
}
.dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0;
 }
#MyNavBar {
   background-color:goldenrod;
}
#details {
   background-color:goldenrod;
}
#subdetails {
    background-color: gold;
}
</code>```

details.html

```<code><!DOCTYPE html>
<html>
<body>
<div id="Others">
    <h2>This is Another thing</h2>
    <p>This is a paragraph of textual information about <b>Another thing</b> that will blow your mind.</p>
</div>
<div id="Something">
    <h2>This is Something</h2>
    <p>This is a paragraph of textual information about <b>Something</b> that will blow your mind.</p>
</div>
</body>
</html>
</code>```

How can I make my code to show a text based on selection of an item in the menu?

答:
Change this code:

```<code>$('#content').load('details.html #' + $(this).attr('href'));
</code>```

To this:

```<code>$('#content').load('details.html');
</code>```

Then when you click on the "Links" element:

```<code><a href="#" class="dropdown-toggle" data-toggle="dropdown">
    Links
    <b class="caret"></b>
</a>
</code>```

It should load the content of details.html inside your section

Body:
I am a beginner. I am trying to learn JavaScript, HTML and CSS simultaneously. I have written a test code which has a navigation bar and I would like that a paragraph of text will pop out in the page when I click on any of the items in the menu bar. I have written the following code but it doesn't work.
index.html

<!DOCTYPE html>

  <meta charset="utf-8">
  <link rel="stylesheet" href="index.css">

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Links

Something

Another thing

index.css

body {
  font-family: "Serif";
}

.background-image {
  background: url("https://pbs.twimg.com/media/CXAOHDfWMAU2Zmi.jpg");
  background-size: cover;
  position: fixed;
  background-repeat: no-repeat;
  -webkit-filter:blur(3px) grayscale(50%);
  -ms-filter:blur(3px) grayscale(50%);
  filter:blur(3px) grayscale(50%);
  width:100%;
  height:100%;
}
.dropdown {
    position: relative;
    display: inline-block;
    font-family: Lobster;
}

.dropdown-menu {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    padding: 12px 16px;
    z-index: 1;
}
.dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0;
 }
#MyNavBar {
   background-color:goldenrod;
}
#details {
   background-color:goldenrod;
}
#subdetails {
    background-color: gold;
}

details.html

<!DOCTYPE html>

This is Another thing

This is a paragraph of textual information about Another thing that will blow your mind.

This is Something

This is a paragraph of textual information about Something that will blow your mind.

How can I make my code to show a text based on selection of an item in the menu?

Body:
Change this code:

$('#content').load('details.html #' + $(this).attr('href'));

To this:

$('#content').load('details.html');

Then when you click on the "Links" element:

<a href="#" class="dropdown-toggle" data-toggle="dropdown">
    Links
    <b class="caret"></b>
</a>

It should load the content of details.html inside your section


问:
Conditional join in SQL depending on a column value
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

```<code>proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;
</code>```

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

答:
Don't use case.  Just express the logic booleanly"

```<code>proc sql;
create table test as
    select A.*, A.PPNG_RVNE * B.perc_ress as variable1, A.P_RVNE    * B.perc_ress as variable2
    from tableA A left join
         tableB B
         on A.cod_cia = B.cod_cia and
            (A.cod_cia = 1 and A.cod_agrup_produto = B.cod_agrup_produto) or
            (A.cod_cia <> 1 and A.projeto = B.projeto);
</code>```

Note:  This uses <> 1.  If cod_cia could be NULL you need to take that into account.  Also note that this factors out the first condition.

Body:
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

Body:
Don't use case.  Just express the logic booleanly"

proc sql;
create table test as
    select A.*, A.PPNG_RVNE * B.perc_ress as variable1, A.P_RVNE    * B.perc_ress as variable2
    from tableA A left join
         tableB B
         on A.cod_cia = B.cod_cia and
            (A.cod_cia = 1 and A.cod_agrup_produto = B.cod_agrup_produto) or
            (A.cod_cia <> 1 and A.projeto = B.projeto);

Note:  This uses <> 1.  If cod_cia could be NULL you need to take that into account.  Also note that this factors out the first condition.


问:
yii2. query with like condition
In my yii2 application i need something like this:

```<code>SELECT * FROM customers WHERE first_name||' '||last_name ILIKE '%Nick%' ORDER BY "id";
</code>```

This query gets customers with concatinated first_name and last_name like 'Nick'.

In my yii1 application I can use CDBCriteria next way:

```<code>$criteria = new CDbCriteria;
        $criteria->addSearchCondition(
            "first_name||' '||last_name",
            'Nick',
            true,
            'and',
            'ILIKE'
        );

$criteria->order = 't.id asc';
</code>```

And this works fine.

In yii2 I tried:

```<code>$a = \common\models\Customer::find()
        ->filterWhere(['ILIKE', "first_name||' '||last_name", 'Nick'])
        ->orderBy(['id' => SORT_ASC])
        ->all();
</code>```

And got exception column does not exist, and sql was:

```<code>SELECT * FROM "customers" WHERE "first_name||' '||last_name" ILIKE '%Nick%' ORDER BY "id"
</code>```

Using \yii\db\Expression doesnt change situation.

答:
This is one of many ways to do it:</p>

```<code>$customers = \common\models\Customer::find()
        ->select('*')
        ->where(['like','concat(first_name,\' \', last_name)','Nick N'])
        ->orderBy(['id' => SORT_ASC])
        ->all();
</code>```

Title: yii2. query with like condition

Body:
In my yii2 application i need something like this:

SELECT * FROM customers WHERE first_name||' '||last_name ILIKE '%Nick%' ORDER BY "id";

This query gets customers with concatinated first_name and last_name like 'Nick'.

In my yii1 application I can use CDBCriteria next way:

$criteria = new CDbCriteria;
        $criteria->addSearchCondition(
            "first_name||' '||last_name",
            'Nick',
            true,
            'and',
            'ILIKE'
        );

$criteria->order = 't.id asc';

And this works fine.

In yii2 I tried:

$a = \common\models\Customer::find()
        ->filterWhere(['ILIKE', "first_name||' '||last_name", 'Nick'])
        ->orderBy(['id' => SORT_ASC])
        ->all();

And got exception column does not exist, and sql was:

SELECT * FROM "customers" WHERE "first_name||' '||last_name" ILIKE '%Nick%' ORDER BY "id"

Using \yii\db\Expression doesnt change situation.

Body:
This is one of many ways to do it:

$customers = \common\models\Customer::find()
        ->select('*')
        ->where(['like','concat(first_name,\' \', last_name)','Nick N'])
        ->orderBy(['id' => SORT_ASC])
        ->all();


问:
How to return function with img.onload?
I am currently building an application, in which a user can upload several images and work with them simultaneously. Since some processes performed poorly due to large image files, I want to resize them, before the user gets them.

In my resizer() function I try to resize using canvas. It works, but since the 'canvas.toDataURL()' is inside the img.onload function, I don't know how to return the value and parse it to the handleFiles() function.

Also...I tried some cases in which I got some code from the handleFiles() - like:

```<code>var preview = document.getElementById("img"+count);
var surface = document.getElementById("cubface"+count);
var count = counterImg();
preview.src =  resizer(e.target.result, count);
surface.src = resizer(e.target.result, count);
</code>```

And put them in the end of the img.onload function like

```<code>var preview = document.getElementById("img"+number);
var surface = document.getElementById("cubface"+number);
preview.src = canvas.toDataURL;
surface.src = canvas.toDataURL;
</code>```

I got the resize, but I got only the last image from the loop to be processed.

So the questions are:

In the resizer() function, how to return the canvas.toDataURL value which is in img.onload?

Why does the loop cover only the last instance and not every image and how to solve that?

Full code:

JavaScript:

```<code>function resizer(base64, number){

    // Max size for thumbnail
    if(typeof(maxWidth) === 'undefined')  maxWidth = 1200;
    if(typeof(maxHeight) === 'undefined')  maxHeight = 1200;

    var img = new Image();
    img.src = base64;

    // Create and initialize two canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");

    img.onload = function() {

        // Determine new ratio based on max size
        var ratio = 1;
        if (img.width > maxWidth)
            ratio = maxWidth / img.width;
        else if (img.height > maxHeight)
            ratio = maxHeight / img.height;

        // Draw original image in second canvas
        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
        copyContext.drawImage(img, 0, 0);

        // Copy and resize second canvas to first canvas
        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

        return canvas.toDataURL();

    };

    return img.onload;

}

function handleFiles(files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var count = counterImg();
        var preview = document.getElementById("img"+count);
        var surface = document.getElementById("cubface"+count);

        var reader = new FileReader();
        reader.onload =  (function (preview, surface) {
            return function (e) {
                var newimage = resizer(e.target.result, count);
                preview.src =  newimage;
                surface.src = newimage;
                $('#image-cropper'+count).cropit('imageSrc', e.target.result);
            }
        })(preview, surface);
        reader.readAsDataURL(file);
    }
}
</code>```

答:
The variable count is not scoped properly.

There's a delay between the time you declare the function and the time you use it, therefore, each execution ends up with the same value. So the jquery selector will always return the same element. Which explains why only the last image is modified.

Here's a jsfiddle that demonstrate the execution.

https://jsfiddle.net/Lc6bngv5/1/

To fix this, simply pass count to the function that encapsulate your preview and surface :

```<code>    reader.onload =  (function (preview, surface, count) {
        return function (e) {
            var newimage = resizer(e.target.result, count);
            preview.src =  newimage;
            surface.src = newimage;
            $('#image-cropper'+count).cropit('imageSrc', e.target.result);
        }
    })(preview, surface, count);
</code>```

For the second question :

The resize function returns a function. It does not return the result of that function. To get the url properly, I would use a callback function :

```<code>reader.onload =  (function (preview, surface, count) {
    return function (e) {
        var newimage = resizer(e.target.result, count, function(url){
            preview.src =  url;
            surface.src = url;
            $('#image-cropper'+count).cropit('imageSrc', e.target.result);
        });
    }
})(preview, surface, count);
</code>```

And you would have to do the following changes in resize :

```<code>function resizer(base64, number, cb){
    ...
    img.onload = function() {
        ...
        // return canvas.toDataURL();
        cb(canvas.toDataURL());
    };
}
</code>```

Title: How to return function with img.onload?

Body:
I am currently building an application, in which a user can upload several images and work with them simultaneously. Since some processes performed poorly due to large image files, I want to resize them, before the user gets them.

In my resizer() function I try to resize using canvas. It works, but since the 'canvas.toDataURL()' is inside the img.onload function, I don't know how to return the value and parse it to the handleFiles() function.

Also...I tried some cases in which I got some code from the handleFiles() - like:

var preview = document.getElementById("img"+count);
var surface = document.getElementById("cubface"+count);
var count = counterImg();
preview.src =  resizer(e.target.result, count);
surface.src = resizer(e.target.result, count);

And put them in the end of the img.onload function like

var preview = document.getElementById("img"+number);
var surface = document.getElementById("cubface"+number);
preview.src = canvas.toDataURL;
surface.src = canvas.toDataURL;

I got the resize, but I got only the last image from the loop to be processed.

So the questions are:

In the resizer() function, how to return the canvas.toDataURL value which is in img.onload?

Why does the loop cover only the last instance and not every image and how to solve that?

Full code:

JavaScript:

function resizer(base64, number){

    // Max size for thumbnail
    if(typeof(maxWidth) === 'undefined')  maxWidth = 1200;
    if(typeof(maxHeight) === 'undefined')  maxHeight = 1200;

    var img = new Image();
    img.src = base64;

    // Create and initialize two canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var canvasCopy = document.createElement("canvas");
    var copyContext = canvasCopy.getContext("2d");

    img.onload = function() {

        // Determine new ratio based on max size
        var ratio = 1;
        if (img.width > maxWidth)
            ratio = maxWidth / img.width;
        else if (img.height > maxHeight)
            ratio = maxHeight / img.height;

        // Draw original image in second canvas
        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
        copyContext.drawImage(img, 0, 0);

        // Copy and resize second canvas to first canvas
        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);

        return canvas.toDataURL();

    };

    return img.onload;

}

function handleFiles(files) {
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var count = counterImg();
        var preview = document.getElementById("img"+count);
        var surface = document.getElementById("cubface"+count);

        var reader = new FileReader();
        reader.onload =  (function (preview, surface) {
            return function (e) {
                var newimage = resizer(e.target.result, count);
                preview.src =  newimage;
                surface.src = newimage;
                $('#image-cropper'+count).cropit('imageSrc', e.target.result);
            }
        })(preview, surface);
        reader.readAsDataURL(file);
    }
}

Body:
The variable count is not scoped properly.

There's a delay between the time you declare the function and the time you use it, therefore, each execution ends up with the same value. So the jquery selector will always return the same element. Which explains why only the last image is modified.

Here's a jsfiddle that demonstrate the execution.

https://jsfiddle.net/Lc6bngv5/1/

To fix this, simply pass count to the function that encapsulate your preview and surface :

    reader.onload =  (function (preview, surface, count) {
        return function (e) {
            var newimage = resizer(e.target.result, count);
            preview.src =  newimage;
            surface.src = newimage;
            $('#image-cropper'+count).cropit('imageSrc', e.target.result);
        }
    })(preview, surface, count);

For the second question :

The resize function returns a function. It does not return the result of that function. To get the url properly, I would use a callback function :

reader.onload =  (function (preview, surface, count) {
    return function (e) {
        var newimage = resizer(e.target.result, count, function(url){
            preview.src =  url;
            surface.src = url;
            $('#image-cropper'+count).cropit('imageSrc', e.target.result);
        });
    }
})(preview, surface, count);

And you would have to do the following changes in resize :

function resizer(base64, number, cb){
    ...
    img.onload = function() {
        ...
        // return canvas.toDataURL();
        cb(canvas.toDataURL());
    };
}


问:
Testing Ember Mixin - as Controller
I basically have Mixin:

```<code>export default Ember.Mixin.create({}};
</code>```

I use it like this:

```<code>export default Ember.Controller.extend(EditControllerMixin, {...});
</code>```

Everything works fine in application.

However what I want to do and not sure how to go about is to write tests something like this:

```<code>const ctrl = Ember.Controller.extend(MyMixin, {...}).create();
ctrl.actions.someAction();
// assert if behaving as expected
</code>```

The problem is that currently I have trouble with injections as needs: [...] does not take effect, since I am creating controller dynamically, so I guess no Ember container is present, that's why. Also this.get() does not work. So I basically want to create dynamic controller and integrate it into Ember runtime. Hoping for some complete examples.

Thanks.

答:
Please, don't do that. Test mixin separately to what's possible (without trying to get needs working).

To test needs - create Controller Unit Tests and in tests needs include each controller you need.

But:

needs in controllers is deprecated - Ember.inject.controller() is new syntax.

Creating dependencies between controllers is bad (and hard to test - as you've seen) - why not creating a service which is easily testable? Service should be also easily tested even when included in mixin :)

Title: Testing Ember Mixin - as Controller

Body:
I basically have Mixin:

export default Ember.Mixin.create({}};

I use it like this:

export default Ember.Controller.extend(EditControllerMixin, {...});

Everything works fine in application.

However what I want to do and not sure how to go about is to write tests something like this:

const ctrl = Ember.Controller.extend(MyMixin, {...}).create();
ctrl.actions.someAction();
// assert if behaving as expected

The problem is that currently I have trouble with injections as needs: [...] does not take effect, since I am creating controller dynamically, so I guess no Ember container is present, that's why. Also this.get() does not work. So I basically want to create dynamic controller and integrate it into Ember runtime. Hoping for some complete examples.

Thanks.


问:
how to print results of sqlite3 on html using flask_sqlalchemy
Good Day fellow developers. I have been googling for hours and reading documents for a while but i cant seem to print the contents of allmodels into the html file

```<code>#python file
@app.route('/models')
#@login_required
def models():
    allmodels = Modeldb.query.all() #THIS RETURNS A LIST FORM SQLITE3
    return render_template('models.html', allmodels=allmodels)
</code>```

here is the html file

```<code><html>
<head>

<body class = "body">

<body>
<h1> HELLOO </h1>

{% for models in allmodels %}
<p> {{ models }} </p>
{% endfor %}

</body>

</head>
</html>
</code>```

and it outputs

 HELLOO
<main.Modeldb object at 0xb5db0bcc>

<main.Modeldb object at 0xb5db0c8c>

<main.Modeldb object at 0xb5db0c0c>

<main.Modeldb object at 0xb5db0ccc>

<main.Modeldb object at 0xb5db0d0c>

<main.Modeldb object at 0xb5db0d4c>

<main.Modeldb object at 0xb5db0d8c>

I know im close. or maybe not. :) thanks in advance and more energy to you guys ;))))

答:
Glad you figured it out :). Not able to comment yet, so adding this post with alternative syntax:</p>

```<code>{% for models in allmodels %}
    {{models.column_name_here}}
    {{models.column2_name_here}}
{% endfor %}
</code>```

Body:
Good Day fellow developers. I have been googling for hours and reading documents for a while but i cant seem to print the contents of allmodels into the html file

#python file
@app.route('/models')
#@login_required
def models():
    allmodels = Modeldb.query.all() #THIS RETURNS A LIST FORM SQLITE3
    return render_template('models.html', allmodels=allmodels)

here is the html file

 HELLOO

{% for models in allmodels %}

 {{ models }}

{% endfor %}

and it outputs

 HELLOO
<main.Modeldb object at 0xb5db0bcc>

<main.Modeldb object at 0xb5db0c8c>

<main.Modeldb object at 0xb5db0c0c>

<main.Modeldb object at 0xb5db0ccc>

<main.Modeldb object at 0xb5db0d0c>

<main.Modeldb object at 0xb5db0d4c>

<main.Modeldb object at 0xb5db0d8c>

I know im close. or maybe not. :) thanks in advance and more energy to you guys ;))))

Body:
Glad you figured it out :). Not able to comment yet, so adding this post with alternative syntax:

{% for models in allmodels %}
    {{models.column_name_here}}
    {{models.column2_name_here}}
{% endfor %}


问:
spring-security & jersey: no automatic redirection to the login site
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

```<code>@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>
</code>```

context:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>
</code>```

Thank you!

答:
This was a problem with spring-security 3.0.3.
After switching to spring-security 3.0.5 everything works as expected.</p>

Body:
I ran into the following problem using spring-security 3.0.3 with jersey 1.2:

when i annotate my Jersey Resources with the @Secured or @PreAuthorize Annotations, spring-security does not autoredirect the user-agent to the login page as i want it to. Only the AuthenticationCredentialsNotFoundException gets thrown and a HTTP 500 gets returned to the user-agent instead of a redirection to spring-security's form login page.
Does anyone know why this problem occurs?

Resource:

@Path("/event")
@Component
public class EventResource extends AbstractBaseResource {

     @Resource(name = "eventService")
     private EventService eventService;

     public void setEventService(EventService eventService) {
         this.eventService = eventService;
     }

 @GET
 @Path("/view/{id}")
 @Produces(MediaType.TEXT_HTML)
 @PreAuthorize("hasRole('ROLE_USER')")
 public Viewable viewEvent(@PathParam("id") long id) throws UnsupportedEncodingException, URISyntaxException{
            ...
        }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_3_0.xsd"
    version="3.0">
    <filter>
        <filter-name>jersey</filter-name>
        <filter-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>/(static|images|js|css|(WEB-INF/views))/.*</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
            <param-value>/WEB-INF/views/</param-value>
        </init-param>
    </filter>

    <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

    <filter-mapping>
        <filter-name>jersey</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

    [...]
</web-app>

context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="..." />
 <context:mbean-export/>

    <security:http auto-config="true" >
     <security:form-login/>
     <security:logout/>
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider ref="..." />
    </security:authentication-manager>

 <security:global-method-security pre-post-annotations="enabled" />

    [...]
</beans>

Thank you!


问:
Render multiple templates inside a component template in Angular
I'm trying to build a component which can make a draggle partition between two templates. Kind of like replicating two adjoining resizable frames. I'm thinking that my component will accept two template inputs and then render a div around them as well as a div in between them which acts as the partition slider. Here's what I think the implementation would look like:

<template #frameOne>content of the first template</template>
<template #frameTwo>content of the second template</template>
<split-component [frameOne]="frameOne" [frameTwo]="frameTwo"><split-component>
```

<p>Where the component selector is 'split-component' and the two inputs for the templates are 'frameOne' and 'frameTwo'. I can't find anywhere in the documentation or in any examples how to include a template from outside a component inside of the component template.</p>

<p>Here's my starting component:
</p>

```import { Component, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';
@Component({
  selector: 'split-component',
  templateUrl: './split.component.html',
  styleUrls: ['./split.component.scss']
})
export class SplitComponent implements OnInit {
  @Input() firstFrame: TemplateRef<any>;
  @Input() secondFrame: TemplateRef<any>;
}
```

<p>And the template for it:</p>

<pre class="lang-html prettyprint-override"><code><div class="split">
  <div class="frame1">{{firstFrame}}</div>
  <div class="divider-bar">
    <div class="handle">:::</div>
  </div>
  <div class="frame2">{{secondFrame}}</div>
</div>
</code>```

Of course {{firstFrame}} won't work but is there something else that would?

UPDATE

I added this to my component:

@ViewChild("frame1", {read: ViewContainerRef}) frame1: ViewContainerRef;
@ViewChild("frame2", {read: ViewContainerRef}) frame2: ViewContainerRef;

ngAfterViewInit(): void {
  this.frame1.createEmbeddedView(this.firstFrame);
  this.frame2.createEmbeddedView(this.secondFrame);
}
```

<p>And changed my template to this:</p>

<pre class="lang-html prettyprint-override"><code><div class="split">
  <div class="frame1" #frame1></div>
  <div class="divider-bar">
    <div class="handle">:::</div>
  </div>
  <div class="frame2" #frame2></div>
</div>
</code>```

But it added the content of the template beside the frame div instead of inside...

答: I've updated the question with my solution. There might be a way to do this with the Renderer as well but I've stopped working on it. I'd be interested in a more eligant solution. </p>

Body:
I'm trying to build a component which can make a draggle partition between two templates. Kind of like replicating two adjoining resizable frames. I'm thinking that my component will accept two template inputs and then render a div around them as well as a div in between them which acts as the partition slider. Here's what I think the implementation would look like:

<template #frameOne>content of the first template</template>
<template #frameTwo>content of the second template</template>
<split-component [frameOne]="frameOne" [frameTwo]="frameTwo"><split-component>

Where the component selector is 'split-component' and the two inputs for the templates are 'frameOne' and 'frameTwo'. I can't find anywhere in the documentation or in any examples how to include a template from outside a component inside of the component template.

Here's my starting component:

import { Component, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';
@Component({
  selector: 'split-component',
  templateUrl: './split.component.html',
  styleUrls: ['./split.component.scss']
})
export class SplitComponent implements OnInit {
  @Input() firstFrame: TemplateRef<any>;
  @Input() secondFrame: TemplateRef<any>;
}

And the template for it:

{{firstFrame}}

:::

{{secondFrame}}

Of course {{firstFrame}} won't work but is there something else that would?

UPDATE

I added this to my component:

@ViewChild("frame1", {read: ViewContainerRef}) frame1: ViewContainerRef;
@ViewChild("frame2", {read: ViewContainerRef}) frame2: ViewContainerRef;

ngAfterViewInit(): void {
  this.frame1.createEmbeddedView(this.firstFrame);
  this.frame2.createEmbeddedView(this.secondFrame);
}

And changed my template to this:

:::

But it added the content of the template beside the frame div instead of inside...


问:
How to use switch operator and best way to iterate string and detect symbols
How to implement this logic with switch operator instead of large if/else?

```<code>   type token =
  | DOT
  | OPEN_BRACKET
  | SYMBOL;

let dot_code = ".".[0] |> Char.code;
let open_bracket_code = "{".[0] |> Char.code;

let char_to_token symbol :token => {
  let code = Char.code symbol;
  let c =
    if (code === dot_code) {
      DOT
    } else if (code === open_bracket_code) {
      OPEN_BRACKET
    } else {
      SYMBOL
    };
  c
};

String.iter
  (
    fun symbol => {
      let c = char_to_token symbol;
      switch c {
      | DOT => print_string " DOT "
      | OPEN_BRACKET => print_string " OPEN_BRACKET "
      | SYMBOL => print_char symbol
      }
    }
  )
  "a.s {";
</code>```

Or what is the best way to iterate string and detect symbols like . and { ?

答:
First, instead of ".".[0] |> Char.code, try '.' |> Char.code. Reason/OCaml has character literals. In this case, since it's a single pipe, Char.code '.' is encouraged.

Second, I'd personally use a switch in char_to_token too:

```<code>let char_to_token symbol :token =>
  switch symbol {
  | '.' => DOT
  | '{' => OPEN_BRACKET
  | _ => SYMBOL
  };
</code>```

Which obviates the need for the above let dot_code = ... in the first place. The benefit of using switch, as you might have guessed, is that it's more efficient. See the compiled-to-js code here. Same thing happens for native compilation.

The rest looks good! Btw since you've told me (in discord) that you've just started Reason, I'd say this is pretty simple and keep it this way! When you get more proficient, I sense that you might want a real parser here or try GADT (http://mads-hartmann.com/ocaml/2015/01/05/gadt-ocaml.html).

Body:
How to implement this logic with switch operator instead of large if/else?

   type token =
  | DOT
  | OPEN_BRACKET
  | SYMBOL;

let dot_code = ".".[0] |> Char.code;
let open_bracket_code = "{".[0] |> Char.code;

let char_to_token symbol :token => {
  let code = Char.code symbol;
  let c =
    if (code === dot_code) {
      DOT
    } else if (code === open_bracket_code) {
      OPEN_BRACKET
    } else {
      SYMBOL
    };
  c
};

String.iter
  (
    fun symbol => {
      let c = char_to_token symbol;
      switch c {
      | DOT => print_string " DOT "
      | OPEN_BRACKET => print_string " OPEN_BRACKET "
      | SYMBOL => print_char symbol
      }
    }
  )
  "a.s {";

Or what is the best way to iterate string and detect symbols like . and { ?

Body:
First, instead of ".".[0] |> Char.code, try '.' |> Char.code. Reason/OCaml has character literals. In this case, since it's a single pipe, Char.code '.' is encouraged.

Second, I'd personally use a switch in char_to_token too:

let char_to_token symbol :token =>
  switch symbol {
  | '.' => DOT
  | '{' => OPEN_BRACKET
  | _ => SYMBOL
  };

Which obviates the need for the above let dot_code = ... in the first place. The benefit of using switch, as you might have guessed, is that it's more efficient. See the compiled-to-js code here. Same thing happens for native compilation.

The rest looks good! Btw since you've told me (in discord) that you've just started Reason, I'd say this is pretty simple and keep it this way! When you get more proficient, I sense that you might want a real parser here or try GADT (http://mads-hartmann.com/ocaml/2015/01/05/gadt-ocaml.html).


问:
C# Mysql Error Check if token Exist
Okay, so I want to check if the token exist. I do this and I get this
ERROR:  Unknown column 'WhatEverTokenIType' in 'where clause'
Ik the token doesn't exist i just want it to print that to the console as I have it below.   </p>

```<code>    public static async Task RedeemToken(CommandEventArgs e, string Token) {

        try {
            var Channel = e.Server.FindChannels("tokens").FirstOrDefault();
            var User = e.User;

            string Connection = "datasource=myip;port=3306;database=somedb;username=someuser;password=somepass;";
            string Query = "SELECT * FROM Tokens WHERE token = " + Token;

            MySqlConnection conn = new MySqlConnection(Connection);
            MySqlCommand cmd = new MySqlCommand(Query, conn);
            MySqlDataReader reader = null;

            conn.Open();
            reader = cmd.ExecuteReader();
            int tokenExist = (int)cmd.ExecuteScalar();
            if (tokenExist > 0) {
                Console.WriteLine("Token Exist");
            } else {
                Console.WriteLine("Token Doesn't Exist");
            }
            while (reader.Read()) {
            }
            conn.Close();
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
</code>```

答:
Your SQL would be something like SELECT * FROM Tokens WHERE token = someToken - that's treating someToken as a column name, not a value.

You should use parameterized SQL instead of building the SQL dynamically, e.g.

```<code>// Include the parameter name (@token) in the SQL...
string query = "SELECT * FROM Tokens WHERE token = @token";

// Then populate the parameter *value* in the parameter collection.
// Change the parameter type to match the token column, obviously.
cmd.Parameters.Add("@token", MySqlDbType.VarChar).Value = token;
</code>```

Additionally, you should:

Use using statements to ensure you close connections, commands etc properly

Follow .NET and C# naming conventions, where parameters, local variables etc start with a lower case letter.

Use asynchronous calls within an async method - currently the calling method is still going to block while you execute the query.

Not call ExecuteScalar() in your code - you're already calling ExecuteReader(), and your query doesn't return a scalar value, so why would you call it?

Title: C# Mysql Error Check if token Exist

Body:
Okay, so I want to check if the token exist. I do this and I get this
ERROR:  Unknown column 'WhatEverTokenIType' in 'where clause'
Ik the token doesn't exist i just want it to print that to the console as I have it below.

    public static async Task RedeemToken(CommandEventArgs e, string Token) {

        try {
            var Channel = e.Server.FindChannels("tokens").FirstOrDefault();
            var User = e.User;

            string Connection = "datasource=myip;port=3306;database=somedb;username=someuser;password=somepass;";
            string Query = "SELECT * FROM Tokens WHERE token = " + Token;

            MySqlConnection conn = new MySqlConnection(Connection);
            MySqlCommand cmd = new MySqlCommand(Query, conn);
            MySqlDataReader reader = null;

            conn.Open();
            reader = cmd.ExecuteReader();
            int tokenExist = (int)cmd.ExecuteScalar();
            if (tokenExist > 0) {
                Console.WriteLine("Token Exist");
            } else {
                Console.WriteLine("Token Doesn't Exist");
            }
            while (reader.Read()) {
            }
            conn.Close();
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }

Body:
Your SQL would be something like SELECT * FROM Tokens WHERE token = someToken - that's treating someToken as a column name, not a value.

You should use parameterized SQL instead of building the SQL dynamically, e.g.

// Include the parameter name (@token) in the SQL...
string query = "SELECT * FROM Tokens WHERE token = @token";

// Then populate the parameter *value* in the parameter collection.
// Change the parameter type to match the token column, obviously.
cmd.Parameters.Add("@token", MySqlDbType.VarChar).Value = token;

Additionally, you should:

Use using statements to ensure you close connections, commands etc properly

Follow .NET and C# naming conventions, where parameters, local variables etc start with a lower case letter.

Use asynchronous calls within an async method - currently the calling method is still going to block while you execute the query.

Not call ExecuteScalar() in your code - you're already calling ExecuteReader(), and your query doesn't return a scalar value, so why would you call it?


问:
How to create python bytes object from long hex string?
I have a long sequence of hex digits in a string, such as

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes.  Is there a builtin way to convert this to a bytes object in python 2.6/3?

答:
```<code>result = bytes.fromhex(some_hex_string)
</code>```

OwnerDisplayName: recursive

Body: result = bytes.fromhex(some_hex_string)

OwnerDisplayName: vili

LastEditorDisplayName: vili