问:
load different js files for different pages or load together?
I have 3 pages of site.

Page 1: 19 kb of JS

  Page 2: 26 kb of JS

  Page 3: 10 kb of JS

  Total : 55 kb of JS

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?

答:
you should probably load them separately...

But, in order to speed things up you could do a trick : if you think that the user is staying for a bit (i donno, at least 5 sec) on your page, you could just load the script for that particular page and add the other ones remotely after the page loads. This way you force the client's browser to make a cache copy of your other - not needed at the moment - js files, and because they're being loaded after the dom object has been built, it doesn't slow your page rendering.

You will have to add an "addScript" function and make "addScript" calls when the document has finished loading.
For the first js (for the first page) it should be something like :
```
function addScript(jsUrl){
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',jsUrl);
    document.getElementsByTagName('body')[0].appendChild(s);
}
window.onload = function(){
    addScript('mySecondScript.js');
    addScript('myThirdScript.js');
}
```
The beauty is that when you load one of the other pages, the corresponding js file is loaded instantly because it is retrieved from the browser's cache.

Body:
you should probably load them separately...

But, in order to speed things up you could do a trick : if you think that the user is staying for a bit (i donno, at least 5 sec) on your page, you could just load the script for that particular page and add the other ones remotely after the page loads. This way you force the client's browser to make a cache copy of your other - not needed at the moment - js files, and because they're being loaded after the dom object has been built, it doesn't slow your page rendering.

You will have to add an "addScript" function and make "addScript" calls when the document has finished loading.
For the first js (for the first page) it should be something like :

function addScript(jsUrl){
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',jsUrl);
    document.getElementsByTagName('body')[0].appendChild(s);
}
window.onload = function(){
    addScript('mySecondScript.js');
    addScript('myThirdScript.js');
}

The beauty is that when you load one of the other pages, the corresponding js file is loaded instantly because it is retrieved from the browser's cache.


来源: stackexchange

问:
Check whether network response is coming from server or Chrome cache
In Google Chrome, how you can check which files are served from the browser cache, and which comes from the server?</p>

答:
If you can't see the size column then you may need to close this window

The size column will tell you if the response is coming from cache or over the network.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Mongoose model.save() stuck pending?
I am using mongoose to handle my schemas, with MongoDB, but when trying to save a new entry to a collection the save() method appears to be stuck, neither the then() method or the catch() method of the promise appear to be called.

Does anyone have any ideas?

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// const Promise = require('bluebird');

const config = require('./config');

const UserSchema = new Schema({
    email: { type: String, required: true, index: { unique: true } },
    name: { type: String, required: false },
    password: { type: String, required: true }
});

const User = mongoose.model('User', UserSchema);

console.log('config.database.url', config.database.url);

mongoose.Promise = global.Promise;
return mongoose.createConnection(config.database.url, {
    useMongoClient: true
})
.then((connection) => {
    const user = new User({
        email: 'someuser@somedomain.com',
        password: 'xxxxx'
    });

    const prom = user.save();

    // Displays: 'promise: Promise { <pending> }'
    console.log('promise:', prom);

    return prom
    .then((result) => {
        // Don't see this output
        console.log('result:', result);
    })
    .catch((error) => {
        // Don't see this output either
        console.log('error:', error);
    });
})
.catch((error) => {
    console.log(error);
});
</code>```

Environment: nodejs 8.9.0, node modules: Mongoose 4.13.6, mongodb 2.2.33

答:
A little more experimenting and it would appear that I need to ensure the model is tied to the connection, such that:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// const Promise = require('bluebird');

const config = require('./config');

const UserSchema = new Schema({
    email: { type: String, required: true, index: { unique: true } },
    name: { type: String, required: false },
    password: { type: String, required: true }
});

let User;

console.log('config.database.url', config.database.url);

mongoose.Promise = global.Promise;

return mongoose.createConnection(config.database.url, {
    useMongoClient: true
})
.then((connection) => {
    // associate model with connection
    User = connection.model('User', UserSchema);

    const user = new User({
        email: 'someuser@somedomain.com',
        password: 'xxxxx'
    });

    const prom = user.save();

    // Displays: 'promise: Promise { <pending> }'
    console.log('promise:', prom);

    return prom
    .then((result) => {
        // Don't see this output
        console.log('result:', result);
    })
    .catch((error) => {
        // Don't see this output either
        console.log('error:', error);
    });
})
.catch((error) => {
    console.log(error);
});
</code>```

Alternatively we should use the connect() method that will work with the model associated via mongoose.model.

For createConnection() can be used to create multiple connections, so using a 'global' model is not supported, from what I can tell.

Saying all this it would be nice if save() didn't simply block.

Note: In researching a refinement to my answer I came across the following: Queries hang when using mongoose.createConnection() vs mongoose.connect()

Title: Mongoose model.save() stuck pending?

Body:
I am using mongoose to handle my schemas, with MongoDB, but when trying to save a new entry to a collection the save() method appears to be stuck, neither the then() method or the catch() method of the promise appear to be called.

Does anyone have any ideas?

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// const Promise = require('bluebird');

const config = require('./config');

const UserSchema = new Schema({
    email: { type: String, required: true, index: { unique: true } },
    name: { type: String, required: false },
    password: { type: String, required: true }
});

const User = mongoose.model('User', UserSchema);

console.log('config.database.url', config.database.url);

mongoose.Promise = global.Promise;
return mongoose.createConnection(config.database.url, {
    useMongoClient: true
})
.then((connection) => {
    const user = new User({
        email: 'someuser@somedomain.com',
        password: 'xxxxx'
    });

    const prom = user.save();

    // Displays: 'promise: Promise { <pending> }'
    console.log('promise:', prom);

    return prom
    .then((result) => {
        // Don't see this output
        console.log('result:', result);
    })
    .catch((error) => {
        // Don't see this output either
        console.log('error:', error);
    });
})
.catch((error) => {
    console.log(error);
});

Environment: nodejs 8.9.0, node modules: Mongoose 4.13.6, mongodb 2.2.33

Body:
A little more experimenting and it would appear that I need to ensure the model is tied to the connection, such that:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// const Promise = require('bluebird');

const config = require('./config');

const UserSchema = new Schema({
    email: { type: String, required: true, index: { unique: true } },
    name: { type: String, required: false },
    password: { type: String, required: true }
});

let User;

console.log('config.database.url', config.database.url);

mongoose.Promise = global.Promise;

return mongoose.createConnection(config.database.url, {
    useMongoClient: true
})
.then((connection) => {
    // associate model with connection
    User = connection.model('User', UserSchema);

    const user = new User({
        email: 'someuser@somedomain.com',
        password: 'xxxxx'
    });

    const prom = user.save();

    // Displays: 'promise: Promise { <pending> }'
    console.log('promise:', prom);

    return prom
    .then((result) => {
        // Don't see this output
        console.log('result:', result);
    })
    .catch((error) => {
        // Don't see this output either
        console.log('error:', error);
    });
})
.catch((error) => {
    console.log(error);
});

Alternatively we should use the connect() method that will work with the model associated via mongoose.model.

For createConnection() can be used to create multiple connections, so using a 'global' model is not supported, from what I can tell.

Saying all this it would be nice if save() didn't simply block.

Note: In researching a refinement to my answer I came across the following: Queries hang when using mongoose.createConnection() vs mongoose.connect()


问:
Decompress bz2 files in 30,000 subfolders with python os walk?
I've got 30,000 folders and each folder contains 5 bz2 files of json data.

I'm trying to use os.walk() to loop through the file path and decompress each compressed file and save in the original directory.

```<code>import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for(dirpath,dirnames,files) in os.walk(path):

for filename in files:
    filepath = os.path.join(dirpath , filename)
     newfilepath = os.path.join(dirpath , filename + '.decompressed')

        with open(newfilepath , 'wb') as new_file ,
          bz2.BZ2File(filepath , 'rb') as file:

              for data in iter(lambda: file.read(100 * 1024) , b''):
                  new_file.write(data)
</code>```

I'm getting the following error running the code.

```<code>File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_compr
ession.py", line 103, in read
data = self._decompressor.decompress(rawblock, size)
OSError: Invalid data stream
</code>```

I've read that there can be an issue running the code on mac with decompressor method or am I missing something else?

答:
It looks like you might be trying to decompress your already decompressed results. You should filter them out.</p>

```<code>import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for (dirpath, dirnames, files) in os.walk(path):
    for filename in files:
        # filter out decompressed files
        if filename.endswith('.decompressed'):
            continue

        filepath = os.path.join(dirpath, filename)
        newfilepath = os.path.join(dirpath, filename + '.decompressed')

        with open(newfilepath, 'wb') as new_file,
            bz2.BZ2File(filepath, 'rb') as file:

            for data in iter(lambda: file.read(100 * 1024), b''):
                new_file.write(data)
</code>```

Body:
I've got 30,000 folders and each folder contains 5 bz2 files of json data.

I'm trying to use os.walk() to loop through the file path and decompress each compressed file and save in the original directory.

import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for(dirpath,dirnames,files) in os.walk(path):

for filename in files:
    filepath = os.path.join(dirpath , filename)
     newfilepath = os.path.join(dirpath , filename + '.decompressed')

        with open(newfilepath , 'wb') as new_file ,
          bz2.BZ2File(filepath , 'rb') as file:

              for data in iter(lambda: file.read(100 * 1024) , b''):
                  new_file.write(data)

I'm getting the following error running the code.

File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_compr
ession.py", line 103, in read
data = self._decompressor.decompress(rawblock, size)
OSError: Invalid data stream

I've read that there can be an issue running the code on mac with decompressor method or am I missing something else?

Body:
It looks like you might be trying to decompress your already decompressed results. You should filter them out.

import os
import bz2

path = "/Users/mac/PycharmProjects/OSwalk/Data"
for (dirpath, dirnames, files) in os.walk(path):
    for filename in files:
        # filter out decompressed files
        if filename.endswith('.decompressed'):
            continue

        filepath = os.path.join(dirpath, filename)
        newfilepath = os.path.join(dirpath, filename + '.decompressed')

        with open(newfilepath, 'wb') as new_file,
            bz2.BZ2File(filepath, 'rb') as file:

            for data in iter(lambda: file.read(100 * 1024), b''):
                new_file.write(data)


问:
innerRef getting completely ignored
I am running into an off issue where my innerRef prop on a component is getting totally swallowed, and never ran.

Here is what my component implementation looks like:

```<code><StyledPopOver
  innerRef={el => (this.popOverEl = el)}
  transitionState={transitionState}
  animationTiming={animationTiming}
  style={this.getAnchorPosition()}
  {...styledProps}
>
  {children}
</StyledPopOver>
</code>```

And here is what the style component definition looks like:

```<code>const StyledPopOver = styled.div`
  display: table-cell;
  transform-origin: top;
  transition-property: all;
  position: fixed;
  z-index: 9998;

  opacity: 0;
  transform: scaleY(0);

  ${props => {
    switch (props.transitionState) {
      case ENTERING:
        return css`
          opacity: 1;
          transform: scaleY(1);
          transition-duration: ${passedProps =>
            passedProps.animationTiming.enter}ms;
        `
      case ENTERED:
        return css`
          opacity: 1;
          transform: scaleY(1);
        `
      case EXITING:
        return css`
          transition-duration: ${passedProps =>
            passedProps.animationTiming.exit}ms;
        `
      default:
        return null
    }
  }};
`
</code>```

If I log the props being passed into the styled component, I can see innerRef. But if I put a log in my ref setter, it never gets called.

The only thing additionally special about this is that the component is being rendered as a child of a React 16 Portal. That said, I just tested pulling the portal out of the tree, and I get the same result.

答:
I figured this one out, and at the end of the day it is a lesson, so I figured I'd provide my solution.

It turns out that higher up in my tree, I was using "innerRef" in a way that was cascading down to children using {...styledProps}

What I learned is that innerRef should only ever be used as a prop name on a direct styled component. If not a direct styled component, it should only ever be ref (when interacting with a HTML element), or a name other than innerRef (when doing anything special about which element gets the ref handler.

Title: innerRef getting completely ignored

Body:
I am running into an off issue where my innerRef prop on a component is getting totally swallowed, and never ran.

Here is what my component implementation looks like:

And here is what the style component definition looks like:

const StyledPopOver = styled.div`
  display: table-cell;
  transform-origin: top;
  transition-property: all;
  position: fixed;
  z-index: 9998;

  opacity: 0;
  transform: scaleY(0);

  ${props => {
    switch (props.transitionState) {
      case ENTERING:
        return css`
          opacity: 1;
          transform: scaleY(1);
          transition-duration: ${passedProps =>
            passedProps.animationTiming.enter}ms;
        `
      case ENTERED:
        return css`
          opacity: 1;
          transform: scaleY(1);
        `
      case EXITING:
        return css`
          transition-duration: ${passedProps =>
            passedProps.animationTiming.exit}ms;
        `
      default:
        return null
    }
  }};
`

If I log the props being passed into the styled component, I can see innerRef. But if I put a log in my ref setter, it never gets called.

The only thing additionally special about this is that the component is being rendered as a child of a React 16 Portal. That said, I just tested pulling the portal out of the tree, and I get the same result.


问:
How do I get gradle (android studio) to put a .zip file in my app's lib/ directory?
I need to put a zip file in the lib/ directory of my app (crystax's embedded python expects it to be there), but it looks like the android studio gradle build scripts will only copy files that start with "lib" and end with ".so". I tried putting the file in assets/ and copying it at runtime but it looks like the lib/ directory isn't writable.</p>

答:
I need to put a zip file in the lib/ directory of my app.

Something like this:

```<code>task copyZipToLib(type: Copy) {
    // Copy the built zip to the lib folder
    from 'build/intermediates/dex/'
    into 'lib'
    include '*.zip'
}
</code>```

Body:
I need to put a zip file in the lib/ directory of my app.

Something like this:

task copyZipToLib(type: Copy) {
    // Copy the built zip to the lib folder
    from 'build/intermediates/dex/'
    into 'lib'
    include '*.zip'
}


问:
Need a simple Bison grammar for HTML
I've looked at the Bison help and have written this, but I'm not sure it's completely correct. Also i need an yylex() that handle Lexical Analyzer (It should be Flex tool). I know some basic things about context-free grammars. But i don't know how to implement them correctly! :(

I want a simple Bison grammar for HTML. The question is: What should change in following grammar?

```<code>%{
    #include <stdio.h>
    int yylex(void);
    int yyerror(char const *);
%}

%token NUM_TOKEN FILENAME_TOKEN COLOR_TOKEN NAME_TOKEN

/* Html Grammer follows... */
%%

/* Any html tag follow this pattern: */
EXPRESSION:
            '<' TAG CLUSER '>' INNER_EXPRESSION "</" TAG '>' ;

/* Some html tags: */
TAG:
     "a"    |
     "html" |
     "head" |
     "link" |
     "div"  |
     "input"|
     "from" |
     "title"|
     "img"  |
     "table"|
     "td"   |
     "tr"   ;

CLUSER:
       ALIGN|
       CLASS|
       ID|
       SRC|
       TEPY|
       ACTION|
       HREF|
       REL|
       /* € (Eplsilone) */
       ;

ALIGN:
      "align" '=' "left"|
      "align" '=' "right"|
      "align" '=' "center"
      ;

CLASS:
      "class" '=' NAME_TOKEN
      ;

ID:
      "id" '=' NAME_TOKEN
      ;

SRC:
      "src" '=' FILENAME_TOKEN
      ;

TEPY:
      "type" '=' CONT
      ;

ACTION:
      "action" '=' FILENAME_TOKEN
      ;

HREF:
      "href" '=' '\"#\"'|
      "href" '=' FILENAME_TOKEN
      ;

REL:
      "rel" '=' "stylesheet"|
      "rel" '=' "\"stylesheet\""
      ;

DOMIN:
      "px"|
      "mm"|
      "cm"|
      "inch"
      ;

PAS:
     "php"|
     "asp"|
     "aspx"|
     "css"
     ;

CONT:
     "button"|
     "checkbox"|
     "text"|
     "password"|
     "file"|
     "submit"
     ;

INNER_EXPRESSION:
     EXPRESSION|
     /* € (Eplsilone) */
     ;

/* Html grammer ends. */
%%
</code>```

This is Bison's output:

```<code>E:\Program Files\GnuWin32\bin>bison "E:\Dev-Cpp\HtmlBison\html.y" -o "E:\html.c"

E:\Dev-Cpp\HtmlBison\html.y: warning: 2 nonterminals useless in grammar
E:\Dev-Cpp\HtmlBison\html.y: warning: 8 rules useless in grammar
E:\\Dev-Cpp\\HtmlBison\\html.y:83.1-5: warning: nonterminal useless in grammar:
DOMIN
E:\\Dev-Cpp\\HtmlBison\\html.y:90.1-3: warning: nonterminal useless in grammar:
PAS
E:\\Dev-Cpp\\HtmlBison\\html.y:84.7-10: warning: rule useless in grammar: DOMIN:
 "px"
E:\\Dev-Cpp\\HtmlBison\\html.y:85.7-10: warning: rule useless in grammar: DOMIN:
 "mm"
E:\\Dev-Cpp\\HtmlBison\\html.y:86.7-10: warning: rule useless in grammar: DOMIN:
 "cm"
E:\\Dev-Cpp\\HtmlBison\\html.y:87.7-12: warning: rule useless in grammar: DOMIN:
 "inch"
E:\\Dev-Cpp\\HtmlBison\\html.y:91.6-10: warning: rule useless in grammar: PAS: "
php"
E:\\Dev-Cpp\\HtmlBison\\html.y:92.6-10: warning: rule useless in grammar: PAS: "
asp"
E:\\Dev-Cpp\\HtmlBison\\html.y:93.6-11: warning: rule useless in grammar: PAS: "
aspx"
E:\\Dev-Cpp\\HtmlBison\\html.y:94.6-10: warning: rule useless in grammar: PAS: "
css"
m4: cannot open `Files\GnuWin32/share/bison': No such file or directory
m4: cannot open `E:\Program': No such file or directory
m4: cannot open `Files\GnuWin32/share/bison/m4sugar/m4sugar.m4': No such file or
 directory
</code>```

It's not going to be a complete HTML parser. I just want to validate very simple HTML documents without any CSS styles or JavaScripts or ...
I also saw this.
NOTE: The Solution must be a Bison grammar!

答:
TAG should be a token that is returned from a lexer, else you will be writing cases till the cows come home.

Same goes for attributes, etc.

Title: Need a simple Bison grammar for HTML

Body:
I've looked at the Bison help and have written this, but I'm not sure it's completely correct. Also i need an yylex() that handle Lexical Analyzer (It should be Flex tool). I know some basic things about context-free grammars. But i don't know how to implement them correctly! :(

I want a simple Bison grammar for HTML. The question is: What should change in following grammar?

%{
    #include <stdio.h>
    int yylex(void);
    int yyerror(char const *);
%}

%token NUM_TOKEN FILENAME_TOKEN COLOR_TOKEN NAME_TOKEN

/* Html Grammer follows... */
%%

/* Any html tag follow this pattern: */
EXPRESSION:
            '<' TAG CLUSER '>' INNER_EXPRESSION "</" TAG '>' ;

/* Some html tags: */
TAG:
     "a"    |
     "html" |
     "head" |
     "link" |
     "div"  |
     "input"|
     "from" |
     "title"|
     "img"  |
     "table"|
     "td"   |
     "tr"   ;

CLUSER:
       ALIGN|
       CLASS|
       ID|
       SRC|
       TEPY|
       ACTION|
       HREF|
       REL|
       /* € (Eplsilone) */
       ;

ALIGN:
      "align" '=' "left"|
      "align" '=' "right"|
      "align" '=' "center"
      ;

CLASS:
      "class" '=' NAME_TOKEN
      ;

ID:
      "id" '=' NAME_TOKEN
      ;

SRC:
      "src" '=' FILENAME_TOKEN
      ;

TEPY:
      "type" '=' CONT
      ;

ACTION:
      "action" '=' FILENAME_TOKEN
      ;

HREF:
      "href" '=' '\"#\"'|
      "href" '=' FILENAME_TOKEN
      ;

REL:
      "rel" '=' "stylesheet"|
      "rel" '=' "\"stylesheet\""
      ;

DOMIN:
      "px"|
      "mm"|
      "cm"|
      "inch"
      ;

PAS:
     "php"|
     "asp"|
     "aspx"|
     "css"
     ;

CONT:
     "button"|
     "checkbox"|
     "text"|
     "password"|
     "file"|
     "submit"
     ;

INNER_EXPRESSION:
     EXPRESSION|
     /* € (Eplsilone) */
     ;

/* Html grammer ends. */
%%

This is Bison's output:

E:\Program Files\GnuWin32\bin>bison "E:\Dev-Cpp\HtmlBison\html.y" -o "E:\html.c"

E:\Dev-Cpp\HtmlBison\html.y: warning: 2 nonterminals useless in grammar
E:\Dev-Cpp\HtmlBison\html.y: warning: 8 rules useless in grammar
E:\\Dev-Cpp\\HtmlBison\\html.y:83.1-5: warning: nonterminal useless in grammar:
DOMIN
E:\\Dev-Cpp\\HtmlBison\\html.y:90.1-3: warning: nonterminal useless in grammar:
PAS
E:\\Dev-Cpp\\HtmlBison\\html.y:84.7-10: warning: rule useless in grammar: DOMIN:
 "px"
E:\\Dev-Cpp\\HtmlBison\\html.y:85.7-10: warning: rule useless in grammar: DOMIN:
 "mm"
E:\\Dev-Cpp\\HtmlBison\\html.y:86.7-10: warning: rule useless in grammar: DOMIN:
 "cm"
E:\\Dev-Cpp\\HtmlBison\\html.y:87.7-12: warning: rule useless in grammar: DOMIN:
 "inch"
E:\\Dev-Cpp\\HtmlBison\\html.y:91.6-10: warning: rule useless in grammar: PAS: "
php"
E:\\Dev-Cpp\\HtmlBison\\html.y:92.6-10: warning: rule useless in grammar: PAS: "
asp"
E:\\Dev-Cpp\\HtmlBison\\html.y:93.6-11: warning: rule useless in grammar: PAS: "
aspx"
E:\\Dev-Cpp\\HtmlBison\\html.y:94.6-10: warning: rule useless in grammar: PAS: "
css"
m4: cannot open `Files\GnuWin32/share/bison': No such file or directory
m4: cannot open `E:\Program': No such file or directory
m4: cannot open `Files\GnuWin32/share/bison/m4sugar/m4sugar.m4': No such file or
 directory

It's not going to be a complete HTML parser. I just want to validate very simple HTML documents without any CSS styles or JavaScripts or ...
I also saw this.
NOTE: The Solution must be a Bison grammar!

ContentLicense: CC BY-SA 2.5


问:
getting JSON Data with Swift 4 and Xcode 9
I've been trying to work with the below code to get my JSON data. It returns "Error after loading". I am using this JSON data in another application and it works. I'm trying to implement the new simplified method using Swift 4. The code does work to the point of the print statement "downloaded".

```<code>class MortgageRatesVC: UIViewController {
    final let url = URL (string:"http://mortgous.com/JSON/currentRatesJSON.php")

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJason()
    }

    func downloadJason () {
        guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil else {
                print("Oops Call for Help")
                return
            }

            print("downloaded")
            do
            {
                let decoder = JSONDecoder()
                let rates = try decoder.decode([LenederRates].self, from: data)
                print(rates)
            } catch {
                print("Error after loading")
            }
        }.resume()
    }
}
</code>```

Class

```<code>class LenederRates: Codable {
    let key : String
    let financial_institution : String
    let variable_rate : String
    let six_months : String
    let one_year : String
    let two_year : String
    let three_year : String
    let four_year : String
    let five_year : String
    //  let date : Date

    init(key: String, financial_institution: String, variable_rate: String, six_months: String, one_year: String, two_year: String, three_year: String, four_year: String, five_year: String) {
        self.key = key
        self.financial_institution = financial_institution
        self.variable_rate = variable_rate
        self.six_months = six_months
        self.one_year = one_year
        self.two_year = two_year
        self.three_year = three_year
        self.four_year = four_year
        self.five_year = five_year
    }
}
</code>```

答:
The problem is the missing property date in your Codable class. You need to set the decoder dateDecodingStrategy to .formatted and pass a fixed format dateFormatter. Btw I suggest changing your class for a struct, change your property names using the Swift naming convention camelCase and provide the custom CodingKeys:

```<code>struct LenederRates: Codable {
    let key: String
    let financialInstitution : String
    let variableRate: String
    let sixMonths: String
    let oneYear: String
    let twoYear: String
    let threeYear: String
    let fourYear: String
    let fiveYear: String
    let date: Date
    private enum CodingKeys: String, CodingKey {
        case key, financialInstitution = "financial_institution", variableRate = "variable_rate", sixMonths = "six_months", oneYear = "one_year", twoYear = "two_year", threeYear = "three_year", fourYear = "four_year", fiveYear = "five_year", date
    }
}
</code>```

```<code>let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
    guard let data = data else { return }
    do {
        let dateFormat = DateFormatter()
        dateFormat.locale = Locale(identifier: "en_US_POSIX")
        dateFormat.dateFormat = "yyyy-MM-dd"
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(dateFormat)
        let rates = try decoder.decode([LenederRates].self, from: data)
        print(rates)
    } catch {
        print(error)
    }
}.resume()
</code>```

Body:
I've been trying to work with the below code to get my JSON data. It returns "Error after loading". I am using this JSON data in another application and it works. I'm trying to implement the new simplified method using Swift 4. The code does work to the point of the print statement "downloaded".

class MortgageRatesVC: UIViewController {
    final let url = URL (string:"http://mortgous.com/JSON/currentRatesJSON.php")

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadJason()
    }

    func downloadJason () {
        guard let downloadURL = url else { return }
        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil else {
                print("Oops Call for Help")
                return
            }

            print("downloaded")
            do
            {
                let decoder = JSONDecoder()
                let rates = try decoder.decode([LenederRates].self, from: data)
                print(rates)
            } catch {
                print("Error after loading")
            }
        }.resume()
    }
}

Class

class LenederRates: Codable {
    let key : String
    let financial_institution : String
    let variable_rate : String
    let six_months : String
    let one_year : String
    let two_year : String
    let three_year : String
    let four_year : String
    let five_year : String
    //  let date : Date

    init(key: String, financial_institution: String, variable_rate: String, six_months: String, one_year: String, two_year: String, three_year: String, four_year: String, five_year: String) {
        self.key = key
        self.financial_institution = financial_institution
        self.variable_rate = variable_rate
        self.six_months = six_months
        self.one_year = one_year
        self.two_year = two_year
        self.three_year = three_year
        self.four_year = four_year
        self.five_year = five_year
    }
}

Body:
The problem is the missing property date in your Codable class. You need to set the decoder dateDecodingStrategy to .formatted and pass a fixed format dateFormatter. Btw I suggest changing your class for a struct, change your property names using the Swift naming convention camelCase and provide the custom CodingKeys:

struct LenederRates: Codable {
    let key: String
    let financialInstitution : String
    let variableRate: String
    let sixMonths: String
    let oneYear: String
    let twoYear: String
    let threeYear: String
    let fourYear: String
    let fiveYear: String
    let date: Date
    private enum CodingKeys: String, CodingKey {
        case key, financialInstitution = "financial_institution", variableRate = "variable_rate", sixMonths = "six_months", oneYear = "one_year", twoYear = "two_year", threeYear = "three_year", fourYear = "four_year", fiveYear = "five_year", date
    }
}

let mortgousURL = URL(string:"http://mortgous.com/JSON/currentRatesJSON.php")!
URLSession.shared.dataTask(with: mortgousURL) { data, urlResponse, error in
    guard let data = data else { return }
    do {
        let dateFormat = DateFormatter()
        dateFormat.locale = Locale(identifier: "en_US_POSIX")
        dateFormat.dateFormat = "yyyy-MM-dd"
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(dateFormat)
        let rates = try decoder.decode([LenederRates].self, from: data)
        print(rates)
    } catch {
        print(error)
    }
}.resume()


问:
Subtracting one array from another
I want to subtract one array from another .

for example I have 2 arrays.

```<code>Array
(
    [0] => 251
    [1] => 251
    [2] => 130
)

 Array
    (
        [0] => 13
        [1] => 13
        [2] => 50
    )
</code>```

The resulting array has to be

```<code>Array
    (
        [0] => 238
        [1] => 238
        [2] => 80
    )
</code>```

Any sort of help on this is appreciated .

答:
In one line $array3 = $array1 - $array2 is</p>

```<code>$array3 = array_intersect($array1, array_diff($array1, $array2));
</code>```

Title: Subtracting one array from another

Body:
I want to subtract one array from another .

for example I have 2 arrays.

Array
(
    [0] => 251
    [1] => 251
    [2] => 130
)

 Array
    (
        [0] => 13
        [1] => 13
        [2] => 50
    )

The resulting array has to be

Array
    (
        [0] => 238
        [1] => 238
        [2] => 80
    )

Any sort of help on this is appreciated .

Body:
In one line $array3 = $array1 - $array2 is

$array3 = array_intersect($array1, array_diff($array1, $array2));


问:
C# reuse method and avoid disposing on using
I would like to optionally dispose (with a using statement) an object. If the connection string is passed in the constructor, then the using must dispose and if the object SQLDataLayer is passed in the constructor, then I don't want to dispose. This is to avoid passing the SQLDataLayer object in every re-usable method, is this the right approach?

```<code>public class RepoCategory
{
    readonly string connString;
    SQLDataLayer dl = null;

    public RepoCategory(string conn_string)
    {
        this.connString = conn_string;
    }

    public RepoCategory(SQLDataLayer dl)
    {
        this.dl = dl;
    }

    //I WANT TO MAGICALLY generate using(null) if dl was passed in constructor
    //or using(dl = new SQLDataLayer(connString)) if connString was passed.
    public Category Get(int category_sid)
    {
        Category cat = null;
        using (SQLDataLayer dlDispose = (dl == null) ? new SQLDataLayer(connString) : null)
        {
            //can this be simplified/avoided?
            if (dlDispose != null)
                dl = dlDispose;
            cat = dl.GetCat();
        }
        return cat;
    }
    //I DON'T WANT TO PASS THE DL MANUALLY EVERYTIME
    public Category Get(SQLDataLayer dl, int category_sid)
    {
        Category cat = null;
        cat = dl.GetCat();
        return cat;
    }
}
</code>```

thanks!

答:
using is just short hand for

```<code>try
{
  obj = new Obj();

}
finally
{
   obj.Dispose();
}
</code>```

You can call Dispose directly if you want. Just do try / finally and in the finally go if(xxx) obj.Dispose()

Body:
I would like to optionally dispose (with a using statement) an object. If the connection string is passed in the constructor, then the using must dispose and if the object SQLDataLayer is passed in the constructor, then I don't want to dispose. This is to avoid passing the SQLDataLayer object in every re-usable method, is this the right approach?

public class RepoCategory
{
    readonly string connString;
    SQLDataLayer dl = null;

    public RepoCategory(string conn_string)
    {
        this.connString = conn_string;
    }

    public RepoCategory(SQLDataLayer dl)
    {
        this.dl = dl;
    }

    //I WANT TO MAGICALLY generate using(null) if dl was passed in constructor
    //or using(dl = new SQLDataLayer(connString)) if connString was passed.
    public Category Get(int category_sid)
    {
        Category cat = null;
        using (SQLDataLayer dlDispose = (dl == null) ? new SQLDataLayer(connString) : null)
        {
            //can this be simplified/avoided?
            if (dlDispose != null)
                dl = dlDispose;
            cat = dl.GetCat();
        }
        return cat;
    }
    //I DON'T WANT TO PASS THE DL MANUALLY EVERYTIME
    public Category Get(SQLDataLayer dl, int category_sid)
    {
        Category cat = null;
        cat = dl.GetCat();
        return cat;
    }
}

thanks!

Body:
using is just short hand for

try
{
  obj = new Obj();

}
finally
{
   obj.Dispose();
}

You can call Dispose directly if you want. Just do try / finally and in the finally go if(xxx) obj.Dispose()


问:
Soap Request Logging - Elegant solution for excluding sensitive data
I am currently working on an application that uses Apache CXF to make requests to a third party. We need to log every request that is being sent. The issue is, many of these requests contain sensitive data that cannot be logged. The data itself is usually encrypted before being sent, but we can't even log the encrypted value.

A super easy solution would be to create a "blacklist" of fields that shouldn't be logged. The problem with this is it is easy to miss a field in a constantly growing application.

What I want to do is figure out a way to "whitelist" fields that should be logged.

It seems complicated, but I can't be the only person that has ever needed to do this.

答: I've written a tool which allows for anonymize / subtree removal based on a subset of XPath expressions. I guess a more advanced approach would use a SAX filter.  </p>


问:
Type-signature vs. function equation in Haskell
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

```<code>f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))
</code>```

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)

答:
This is definitely a bit of currying. While I can't immediately find where in the documentation it explicitly states this behavior, all we have to do is check out our math a little about currying.

As we know, a function with the signature Int ->(Int -> Int) takes an Int, and returns a function that takes an Int and returns an Int. And we could just provide both of the Ints it needs to get that final int, like in your example:

```<code>f :: Int -> (Int -> Int)
f x y = x+y
</code>```

And if we provide just the first argument, we get back a function that needs another argument. The bread and butter of currying.

Simply put, currying is right-associative. In other words, Int -> (Int -> Int) is the same as Int->Int->Int, just we added parenthesis to make it more obvious that:

```<code>f 3
</code>```

Isn't missing an argument, but actually returns a function of type Int->Int.

It's kind of like back in math when you learn the associative property of addition.

```<code>3 + 2 + 1 = (3 + 2) + 1 = 3 + (2 + 1)
</code>```

The result is the same, regardless of how we put our parentheses.

Body:
I'm new to Haskell and to functional programming.  I'm reading through Real World Haskell, and I've realized I'm confused by a few examples.

Specifically this is in Chapter 9, in the section "A Domain specific language for predicates", the examples which have the w x y z parameters.

I've boiled it down to this:

Why does this code compile?

f :: Int -> (Int -> Int)
f x y = x+y

main = do
  let q = f 4 5
  putStr  (show (q))

According to the type signature, f is clearly accepting 1 parameter and returning a function.
However, it seems I can write the function equation so it will accept two parameters and return an int.
Why is this possible?  Does this mean the type signature is ignored?

Is this currying?  Is this some kind of closure?
If I understand this http://www.haskell.org/haskellwiki/Currying correctly, then it seems to be somewhat in reverse to currying as defined there - my f function is taking multiple arguments instead of a single one!

Also, can anyone answering please provide a link to some sort of Haskell documentation where this ability is stated (if possible at all).

EDIT:

After thinking about this for some time, what you two seem to be implying is that:

1) This syntax is syntactic sugar, f will always have a single parameter, no matter how many parameters are written in the equation

2) Upon application of f, the function body will (always?) be transformed into a stub (in effect, the returned function), where x is fixed to the parameter given (4), and y is a parameter.

3) Then this new function is applied to 5 which replaces y, and then the + function is evaluated.

What I was really interested in was, where exactly does it say something like "in the function equation, if you write more than one parameter, it's really syntactic sugar, and the following actually happens..." as I wrote above.
Or is that so obvious to everyone except me?

Edit II:

The real eye-opener answer was in @luqui comment below, unfortunately I don't think I can mark a comment as an answer.

It is the fact that
f x y = ...
is actually syntactic sugar for:
f = \x -> \y -> ...

And for me, everything else everyone below said follows from this.

I found a sort of source for this in the Gentle Introduction to Haskell, here: http://haskell.cs.yale.edu/tutorial/functions.html in section 3.1, called Lambda Abstractions.

In fact, the equations:

inc x                  = x+1
    add x y                = x+y

are really shorthand for:

inc                    = \x   -> x+1
    add                    = \x y -> x+y

While it doesn't use the phrase "syntactic sugar", it uses the more, uh, mathematically oriented word "shorthand", but as a programmer I read this as "sugar" :-)

Body:
This is definitely a bit of currying. While I can't immediately find where in the documentation it explicitly states this behavior, all we have to do is check out our math a little about currying.

As we know, a function with the signature Int ->(Int -> Int) takes an Int, and returns a function that takes an Int and returns an Int. And we could just provide both of the Ints it needs to get that final int, like in your example:

f :: Int -> (Int -> Int)
f x y = x+y

And if we provide just the first argument, we get back a function that needs another argument. The bread and butter of currying.

Simply put, currying is right-associative. In other words, Int -> (Int -> Int) is the same as Int->Int->Int, just we added parenthesis to make it more obvious that:

f 3

Isn't missing an argument, but actually returns a function of type Int->Int.

It's kind of like back in math when you learn the associative property of addition.

3 + 2 + 1 = (3 + 2) + 1 = 3 + (2 + 1)

The result is the same, regardless of how we put our parentheses.


问:
Check whether sanitizer like AddressSanitizer is active
I have several versions of a project checkout out and compiled. If I spot an error, I compare the versions to narrow the problem down. Sometimes I enable sanitizers like the AddressSanitizer. If I re-use an executable, I don't remember whether it was compiled with the sanitizers or not. If the executable works fine, I am not sure whether the bug is not there or whether I did not include the sanitizer in this build. So I have to reconfigure and rebuild to make sure I have the sanitizer included.

Is there a way to check whether an executable has been compiled with a sanitizer?

答:
Address sanitizer can also be compiled statically with the -static-libasan option in GCC. Statically compiling address sanitizer is the default mode in Clang.

If you compile address sanitizer statically then it is obviously not possible to use ldd to verify if your binary is sanitized or not. In this case I use nm and check if there are sanitizer symbols in the binary:

nm -an <executable> | grep asan


问:
How acceptor can add value to state and send back to initiator
I have scenario:

NodeA sends state to NodeB (State: value=100, CustomerFlag=0)

NodeB review the state/value and send approved flag along with
signature.(State: value=100, CustomerFlag=1)

Can you help me how to add that value while NodeB responding with approve/reject?

Initiator class:

```<code>    @Suspendable
    override fun call(): SignedTransaction {

        val notary = serviceHub.networkMapCache.notaryIdentities[0]

        val iouState = IOUState(iouValue, serviceHub.myInfo.legalIdentities.first(), otherParty)
        val txCommand = Command(IOUContract.Commands.Create(), iouState.participants.map { it.owningKey })
        val txBuilder = TransactionBuilder(notary).withItems(StateAndContract(iouState, IOU_CONTRACT_ID), txCommand)

        txBuilder.verify(serviceHub)
        otherPartyFlow.send(partSignedTx)
        val partSignedTx = serviceHub.signInitialTransaction(txBuilder)
        val otherPartyFlow = initiateFlow(otherParty)
        otherPartyFlow.send(partSignedTx)
        return partSignedTx
    }
}
</code>```

Acceptor class:

```<code>@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {

        val receivedData = otherPartyFlow.receive<SignedTransaction>()

        receivedData.unwrap {data -> data }
<<<<< Need help here how to add value and send back >>>>
return updatedData
}
}
</code>```

答:
You may need to rethink your flow slightly to get this to work. I would say your best bet is rather than sending a signed transaction to the acceptor, send the IOU State itself. The Acceptor class can then alter this flag in the state, and create/sign the transaction. It can then be sent back to the initiator class for it to verify the flag has been changed, sign the transaction and then commit it to the ledger.

```<code>@Suspendable
override fun call(): SignedTransaction {

    val iouState = IOUState(iouValue, serviceHub.myInfo.legalIdentities.first(), otherParty)

    val otherPartyFlow = initiateFlow(otherParty)
    otherPartyFlow.send(iouState)

    //Receieve back the signedTransaction
    val ptx = otherPartyFlow.receive<SignedTransaction>().unwrap{it}
    val stx = serviceHub.addSignature(ptx)
    //Resolve and commit to the ledger
    subFlow(ResolveTransactionsFlow(stx, otherPartyFlow))
    return subFlow(FinalityFlow(stx))
    }
}

@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val notary = serviceHub.networkMapCache.notaryIdentities[0]
        val receivedData = otherPartyFlow.receive<IOUState>().unwrap{
            //Do any state verification here
            it
        }
        receivedData.customerFlag = 1

       //Create the txn
       val txCommand = Command(IOUContract.Commands.Create(), receivedData.participants.map { it.owningKey })
       val txBuilder = TransactionBuilder(notary).withItems(StateAndContract(receivedData, IOU_CONTRACT_ID), txCommand)
       //Sign the transaction
       val partSignedTx = serviceHub.signInitialTransaction(txBuilder)
       otherPartyFlow.send(partSignedTx)
       return waitForLedgerCommit(partSignedTx.id)
}
}
</code>```

You could also look into using the signTransactionsFlow for gathering signatures rather than sending back and forth a stx as Ive done above - see https://docs.corda.net/flow-state-machines.html

Body:
I have scenario:

NodeA sends state to NodeB (State: value=100, CustomerFlag=0)

NodeB review the state/value and send approved flag along with
signature.(State: value=100, CustomerFlag=1)

Can you help me how to add that value while NodeB responding with approve/reject?

Initiator class:

    @Suspendable
    override fun call(): SignedTransaction {

        val notary = serviceHub.networkMapCache.notaryIdentities[0]

        val iouState = IOUState(iouValue, serviceHub.myInfo.legalIdentities.first(), otherParty)
        val txCommand = Command(IOUContract.Commands.Create(), iouState.participants.map { it.owningKey })
        val txBuilder = TransactionBuilder(notary).withItems(StateAndContract(iouState, IOU_CONTRACT_ID), txCommand)

        txBuilder.verify(serviceHub)
        otherPartyFlow.send(partSignedTx)
        val partSignedTx = serviceHub.signInitialTransaction(txBuilder)
        val otherPartyFlow = initiateFlow(otherParty)
        otherPartyFlow.send(partSignedTx)
        return partSignedTx
    }
}

Acceptor class:

@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {

        val receivedData = otherPartyFlow.receive<SignedTransaction>()

        receivedData.unwrap {data -> data }
<<<<< Need help here how to add value and send back >>>>
return updatedData
}
}

Body:
You may need to rethink your flow slightly to get this to work. I would say your best bet is rather than sending a signed transaction to the acceptor, send the IOU State itself. The Acceptor class can then alter this flag in the state, and create/sign the transaction. It can then be sent back to the initiator class for it to verify the flag has been changed, sign the transaction and then commit it to the ledger.

@Suspendable
override fun call(): SignedTransaction {

    val iouState = IOUState(iouValue, serviceHub.myInfo.legalIdentities.first(), otherParty)

    val otherPartyFlow = initiateFlow(otherParty)
    otherPartyFlow.send(iouState)

    //Receieve back the signedTransaction
    val ptx = otherPartyFlow.receive<SignedTransaction>().unwrap{it}
    val stx = serviceHub.addSignature(ptx)
    //Resolve and commit to the ledger
    subFlow(ResolveTransactionsFlow(stx, otherPartyFlow))
    return subFlow(FinalityFlow(stx))
    }
}

@InitiatedBy(Initiator::class)
class Acceptor(val otherPartyFlow: FlowSession) : FlowLogic<SignedTransaction>() {
    @Suspendable
    override fun call(): SignedTransaction {
        val notary = serviceHub.networkMapCache.notaryIdentities[0]
        val receivedData = otherPartyFlow.receive<IOUState>().unwrap{
            //Do any state verification here
            it
        }
        receivedData.customerFlag = 1

       //Create the txn
       val txCommand = Command(IOUContract.Commands.Create(), receivedData.participants.map { it.owningKey })
       val txBuilder = TransactionBuilder(notary).withItems(StateAndContract(receivedData, IOU_CONTRACT_ID), txCommand)
       //Sign the transaction
       val partSignedTx = serviceHub.signInitialTransaction(txBuilder)
       otherPartyFlow.send(partSignedTx)
       return waitForLedgerCommit(partSignedTx.id)
}
}

You could also look into using the signTransactionsFlow for gathering signatures rather than sending back and forth a stx as Ive done above - see https://docs.corda.net/flow-state-machines.html


问:
Generate all combination of elements in table (langage C)
i have i table of integer

```<code>int Table[]={1,2,3,....,28};
</code>```

i want to have this combination:

```<code>1 2 3 4 5 6 7 ... 28
</code>```

and after i will have this

```<code>12 13 14 15 16 17 18 19 23 24 24 .....
</code>```

until to have all combination possible without repetition (i.e 12=21)

I want combination like they are made in excel columns for example

```<code>char alp[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'
,'Q','R','S','T','U','V','W','X','Y','Z'};
</code>```

答:
Using recursion swap element with all possible following elements:

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

void swap(int* array, int i, int j)
{
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

void print_array(int *array, int len)
{
    int i;
    for (i = 0; i<len; i++ )
    {
         printf("%c ", array[i]);
    };
    printf("\n");
}

void permute(int *array, int start, int len)
{
    int i;
    if(start == len)
    {
        print_array(array, len);
        return;
    }

    permute(array, start + 1, len);

    for(i = start + 1; i < len; i++)
    {
        if(array[start] == array[i])
            continue;

        swap(array, start, i);

        permute(array, start + 1, len);
        swap(array, start, i);
    }
}

int main()
{
    // for 4 elements:
    int perm[] = {'A','B','C','D'};
    int number_of_elements = 4;

    permute(perm, 0, number_of_elements);

    return 0;
}
</code>```

OUTPUT:

```<code>A B C D
A B D C
A C B D
A C D B
A D C B
A D B C
B A C D
B A D C
B C A D
B C D A
B D C A
B D A C
C B A D
C B D A
C A B D
C A D B
C D A B
C D B A
D B C A
D B A C
D C B A
D C A B
D A C B
D A B C
</code>```

Body:
i have i table of integer

int Table[]={1,2,3,....,28};

i want to have this combination:

1 2 3 4 5 6 7 ... 28

and after i will have this

12 13 14 15 16 17 18 19 23 24 24 .....

until to have all combination possible without repetition (i.e 12=21)

I want combination like they are made in excel columns for example

char alp[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P'
,'Q','R','S','T','U','V','W','X','Y','Z'};

Body:
Using recursion swap element with all possible following elements:

#include <stdio.h>

void swap(int* array, int i, int j)
{
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

void print_array(int *array, int len)
{
    int i;
    for (i = 0; i<len; i++ )
    {
         printf("%c ", array[i]);
    };
    printf("\n");
}

void permute(int *array, int start, int len)
{
    int i;
    if(start == len)
    {
        print_array(array, len);
        return;
    }

    permute(array, start + 1, len);

    for(i = start + 1; i < len; i++)
    {
        if(array[start] == array[i])
            continue;

        swap(array, start, i);

        permute(array, start + 1, len);
        swap(array, start, i);
    }
}

int main()
{
    // for 4 elements:
    int perm[] = {'A','B','C','D'};
    int number_of_elements = 4;

    permute(perm, 0, number_of_elements);

    return 0;
}

OUTPUT:

A B C D
A B D C
A C B D
A C D B
A D C B
A D B C
B A C D
B A D C
B C A D
B C D A
B D C A
B D A C
C B A D
C B D A
C A B D
C A D B
C D A B
C D B A
D B C A
D B A C
D C B A
D C A B
D A C B
D A B C


问:
Categorical Variables Table with Percentages in R
I have a series of categorical variables that have the response options (Favorable, Unfavorable, Neutral).

I want to create a table in R that will give the list of all 10 variables in rows (one variable per row) - with the percentage response "Favorable, Unfavorable, Neutral" in the columns.  Is this possible in R?  Ideally, I would also want to be able to group this by another categorical variable (e.g. to compare how males vs. females responded to the questions differently).

答:
You'll get better answers if you provide a sample of your actual data (see this post). That said, here is a solution using dplyr:: (and reshape2::melt).

```<code># function to create a column of fake data
make_var <- function(n=100) sample(c("good","bad","ugly"), size=n, replace=TRUE)

# put ten of them together
dat <- as.data.frame(replicate(10, make_var()), stringsAsFactors=FALSE)

library("dplyr")

# then reshape to long format, group, and summarize --
dat %>% reshape2::melt(NULL) %>% group_by(variable) %>% summarize(
    good_pct = (sum(value=="good") / length(value)) * 100,
    bad_pct = (sum(value=="bad") / length(value)) * 100,
    ugly_pct = (sum(value=="ugly") / length(value)) * 100
)
</code>```

Note that to group by another column (e.g. sex), you can just say group_by(variable, sex) before you summarize (as long as sex is a column of the data, which isn't the case in this constructed example).

Body:
You'll get better answers if you provide a sample of your actual data (see this post). That said, here is a solution using dplyr:: (and reshape2::melt).

# function to create a column of fake data
make_var <- function(n=100) sample(c("good","bad","ugly"), size=n, replace=TRUE)

# put ten of them together
dat <- as.data.frame(replicate(10, make_var()), stringsAsFactors=FALSE)

library("dplyr")

# then reshape to long format, group, and summarize --
dat %>% reshape2::melt(NULL) %>% group_by(variable) %>% summarize(
    good_pct = (sum(value=="good") / length(value)) * 100,
    bad_pct = (sum(value=="bad") / length(value)) * 100,
    ugly_pct = (sum(value=="ugly") / length(value)) * 100
)

Note that to group by another column (e.g. sex), you can just say group_by(variable, sex) before you summarize (as long as sex is a column of the data, which isn't the case in this constructed example).


问:
Browser & version in prototype library?
I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.

In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.

答:
I use this over and above Prototype's browser definitions.

```<code>Object.extend(Prototype.Browser, {
    ie6: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,
    ie7: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,
    ie8: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,
    ie9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});
</code>```

Hope it helps!

OwnerDisplayName: EvilSyn

Title: Browser & version in prototype library?

LastEditorDisplayName: Cheekysoft

Body:
I use this over and above Prototype's browser definitions.

Object.extend(Prototype.Browser, {
    ie6: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,
    ie7: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,
    ie8: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,
    ie9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});

Hope it helps!


问:
shared information between components through service not working
Im having some trouble figuring this out, basically I have a headerTitleService which I want to be able to dynamically set the title in my header component but for some reason when I set the title nothing shows up? Im not getting any errors so I can seem to figure out what the problem is..

headerTitle.service.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: string) {
    this.title.next(title);
  }
}
</code>```

header.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [HeaderTitleService]
})
export class HeaderComponent implements OnInit {
  title: string;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}
</code>```

header.component.html

```<code><h1>{{title}}</h1>
</code>```

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [HeaderTitleService]
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle('hello');
  }

}
</code>```

答:
The line providers: [HeaderTitleService] in each component means that they will be given one HeaderTitleService each, rather than one between them.

To fix this remove providers: [HeaderTitleService] from your components, and place it in your module definition instead:

```<code>@NgModule({
  providers: [HeaderTitleService]
})
</code>```

Body:
Im having some trouble figuring this out, basically I have a headerTitleService which I want to be able to dynamically set the title in my header component but for some reason when I set the title nothing shows up? Im not getting any errors so I can seem to figure out what the problem is..

headerTitle.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: string) {
    this.title.next(title);
  }
}

header.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../../services/headerTitle.service'

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [HeaderTitleService]
})
export class HeaderComponent implements OnInit {
  title: string;

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.title.subscribe(updatedTitle => {
      this.title = updatedTitle;
    });
  }

}

header.component.html

{{title}}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [HeaderTitleService]
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService
  ) { }

  ngOnInit() {
    this.headerTitleService.setTitle('hello');
  }

}

Body:
The line providers: [HeaderTitleService] in each component means that they will be given one HeaderTitleService each, rather than one between them.

To fix this remove providers: [HeaderTitleService] from your components, and place it in your module definition instead:

@NgModule({
  providers: [HeaderTitleService]
})


问:
only first line of wp_enqueue_style gets executed
I'm trying to build a child theme for an existing theme someone else built. That theme uses multiple stylesheets and of course, I want the child theme to enqueue them all.

Strangely enough I noticed that that only the first line of the wp_enqueue_style() of the parent theme gets executed while the wp_enqueue_style() of the child theme does work.

I'm kinda stuck and I have no clue on how to make the child theme use all those stylesheets.

```<code>    function my_theme_enqueue_styles() {

    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
</code>```

btw: I know that those css files dont't make any sense. Tell that to the original builder.

download link of the parent theme

答:
Give first parameter a name, a unique one so in that way you can enqueue all of them.

Based on wordpress codex:

wp_enqueue_style( string $handle, string $src = '')

$handle
  (string) (Required) Name of the stylesheet. Should be unique.

```<code>function my_theme_enqueue_styles() {
    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( 'custom_login', get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( 'font_awesome', get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( 'font_dc_cash', get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( 'font_dccash', get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( 'hro_admin', get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') );
}

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
</code>```

Body:
I'm trying to build a child theme for an existing theme someone else built. That theme uses multiple stylesheets and of course, I want the child theme to enqueue them all.

Strangely enough I noticed that that only the first line of the wp_enqueue_style() of the parent theme gets executed while the wp_enqueue_style() of the child theme does work.

I'm kinda stuck and I have no clue on how to make the child theme use all those stylesheets.

    function my_theme_enqueue_styles() {

    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style',
        get_stylesheet_directory_uri() . '/style.css',
        array( $parent_style ),
        wp_get_theme()->get('Version')
    );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

btw: I know that those css files dont't make any sense. Tell that to the original builder.

download link of the parent theme

Body:
Give first parameter a name, a unique one so in that way you can enqueue all of them.

Based on wordpress codex:

wp_enqueue_style( string $handle, string $src = '')

$handle
  (string) (Required) Name of the stylesheet. Should be unique.

function my_theme_enqueue_styles() {
    //parent style
    $parent_style = 'parent-style';

    //enqueue css of the parent theme
    wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
    wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/scripts/css/bootstrap.min.css' );
    wp_enqueue_style( 'custom_login', get_template_directory_uri() . '/assets/scripts/css/custom-login.css' );
    wp_enqueue_style( 'font_awesome', get_template_directory_uri() . '/assets/scripts/css/font-awesome.min.css' );
    wp_enqueue_style( 'font_dc_cash', get_template_directory_uri() . '/assets/scripts/css/font-dc-cash.css' );
    wp_enqueue_style( 'font_dccash', get_template_directory_uri() . '/assets/scripts/css/font-dccash.css' );
    wp_enqueue_style( 'hro_admin', get_template_directory_uri() . '/assets/scripts/css/hro-admin.css' );

    //enqueue css of the child theme
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') );
}

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );


问:
How to count in multiple columns a variable
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

```<code>UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill
</code>```

I need to produce a productivity report like below

```<code>        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3
</code>```

I am not sure how to group the counts by the names that are in the data?

答:
Yeah, it has to be UNPIVOTED and then PIVOTED. Here is how we can do this in Oracle sql.</p>

```<code>SELECT *
FROM
  (SELECT name,
    status
  FROM report UNPIVOT( name FOR status IN (APPROVED AS 'APPROVED',DENIED AS 'DENIED', MOVED AS 'MOVED', PENDED AS 'PENDED'))
  ) PIVOT ( COUNT(status) FOR status   IN ('APPROVED','DENIED','MOVED','PENDED') )
ORDER BY name DESC;
</code>```

Body:
I am working on a Crystal Report and cannot figure out a way to do this in Crystal or MSSQL

I have a table with usernames that get recorded when an activity is completed in a web app like below

UID Approved    Denied  Moved   Pended
1   Tom         null    null    Bill
2   null        null    Bill    null
3   Bill        null    Tom     null
4   null        Tom     null    null
5   Tom         null    Bill    Bill
6   null        Bill    Bill    null
7   Tom         null    null    Bill

I need to produce a productivity report like below

        Approved    Denied  Moved   Pended
Tom     3           1       1       0
Bill    1           1       3       3

I am not sure how to group the counts by the names that are in the data?

Body:
Yeah, it has to be UNPIVOTED and then PIVOTED. Here is how we can do this in Oracle sql.

SELECT *
FROM
  (SELECT name,
    status
  FROM report UNPIVOT( name FOR status IN (APPROVED AS 'APPROVED',DENIED AS 'DENIED', MOVED AS 'MOVED', PENDED AS 'PENDED'))
  ) PIVOT ( COUNT(status) FOR status   IN ('APPROVED','DENIED','MOVED','PENDED') )
ORDER BY name DESC;


答:
You don't need to declare variables in a using statement.
You can make a using statement that only does anything in some circumstances:

```<code>SQLDataLayer dl = ...;
using(someCondition ? dl : null) {
    ...
}
</code>```

Title: C# reuse method and avoid disposing on using

Body:
You don't need to declare variables in a using statement.
You can make a using statement that only does anything in some circumstances:

SQLDataLayer dl = ...;
using(someCondition ? dl : null) {
    ...
}


问:
How to choose the correct left shift in bit wise operations?
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination.

For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to 001 to mark the pin as an output pin.

I have seen code that does this and I half understand it based on an explanation of another SO question.

```<code># here ra is a physical address
# the 15th to 17th bits are being
# cleared by AND-ing it with a value that is one everywhere
# except in the 15th to 17th bits
ra&=~(7<<12);
</code>```

Another example is:

```<code># this clears the 21st to 23rd bits of another address
ra&=~(7<<21);
</code>```

How do I choose the 7 and how do I choose the number of bits to shift left?

I tried this out in python to see if I can figure it out

```<code>bin((7<<21)).lstrip('-0b').zfill(32)
'00000000111000000000000000000000'
# this has 8, 9 and 10 as the bits which is wrong
</code>```

答:
The 7 (base 10) is chosen as its binary representation is 111 (7 in base 2).

As for why it's bits 8, 9 and 10 set it's because you're reading from the wrong  direction. Binary, just as normal base 10, counts right to left.

(I'd left this as a comment but reputation isn't high enough.)

Body:
I am learning bare metal programming in c++ and it often involves setting a portion of a 32 bit hardware register address to some combination.

For example for an IO pin, I can set the 15th to 17th bit in a 32 bit address to 001 to mark the pin as an output pin.

I have seen code that does this and I half understand it based on an explanation of another SO question.

# here ra is a physical address
# the 15th to 17th bits are being
# cleared by AND-ing it with a value that is one everywhere
# except in the 15th to 17th bits
ra&=~(7<<12);

Another example is:

# this clears the 21st to 23rd bits of another address
ra&=~(7<<21);

How do I choose the 7 and how do I choose the number of bits to shift left?

I tried this out in python to see if I can figure it out

bin((7<<21)).lstrip('-0b').zfill(32)
'00000000111000000000000000000000'
# this has 8, 9 and 10 as the bits which is wrong


答:
Move HeaderTitleService in providers of your module. With your implementation you receive new instance of the HeaderTitleService in each component.

Hope this helps.

Title: shared information between components through service not working


问:
Difficulties coding variables for the choices in a dictionary guessing game
I'm trying to create a guessing game where the user chooses a key within the dictionary and guesses the value of it.
I'm having a hard time trying to code the variables for the choice in order to have to guess the value.

Here is what I have so far:

```<code>def main():
    capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix',
                'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver',
                'CT' : 'Hartford', 'FL' : 'Tallahassee', 'GA' : 'Atlanta',
                'HI' : 'Honolulu', 'ID' : 'Boise', 'IL' : 'Springfield',
                'IN' : 'Indianapolis', 'IA' : 'Des Moines', 'KS' : 'Topeka'}
    print("Choose a state from the list", capitals.keys())
    choice = input('Which state would you like to guess? : ')
    choice == capitals.keys()
    guess = input('Guess the capital of the state chosen : ')
    answer = capitals.values()
    if guess == answer:
        print("Yay! You're CORRECT!")
    else:
        print("Sorry, You're INCORRECT!")

main()
</code>```

It seems that my if statement isn't being read by the program. How can I fix this?

答:
Your semantics are incorrect.  Just before your if statement, insert

```<code>print (guess, answer)
</code>```

This is basic debugging.  You'll see the problem: answer is a list of all the capitals; there's no way that raw user input can be equal to an entire list.  You need to compare against only the capital for that one state.

You'll have to make a similar check on choice, as you've made teh same mistake there.

Body:
I'm trying to create a guessing game where the user chooses a key within the dictionary and guesses the value of it.
I'm having a hard time trying to code the variables for the choice in order to have to guess the value.

Here is what I have so far:

def main():
    capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix',
                'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver',
                'CT' : 'Hartford', 'FL' : 'Tallahassee', 'GA' : 'Atlanta',
                'HI' : 'Honolulu', 'ID' : 'Boise', 'IL' : 'Springfield',
                'IN' : 'Indianapolis', 'IA' : 'Des Moines', 'KS' : 'Topeka'}
    print("Choose a state from the list", capitals.keys())
    choice = input('Which state would you like to guess? : ')
    choice == capitals.keys()
    guess = input('Guess the capital of the state chosen : ')
    answer = capitals.values()
    if guess == answer:
        print("Yay! You're CORRECT!")
    else:
        print("Sorry, You're INCORRECT!")

main()

It seems that my if statement isn't being read by the program. How can I fix this?

Body:
Your semantics are incorrect.  Just before your if statement, insert

print (guess, answer)

This is basic debugging.  You'll see the problem: answer is a list of all the capitals; there's no way that raw user input can be equal to an entire list.  You need to compare against only the capital for that one state.

You'll have to make a similar check on choice, as you've made teh same mistake there.


问:
style.css sheet on local host not saving correctly
I am building a wordpress theme on a localhost, using phpmyadmin and Ampps.

I have pasted the following into the style.css folder

```<code>    body {

    font-family: Arial;
    font-size: 15px;
    color:  #333333
    background: #f4f4f4;
    margin:0;
    padding:0;
    line-height: 1.7em;
}

header {

    background: #393939;
    color: #ffffff;
    padding: 20px 10px;

}

header h1 {

    color: #ffffff;
    margin:0;
    padding:0;
    padding-bottom: 10px;

}

a {

    color: #333333;

}

article.post {

    border-bottom: 1px #cccccc solid;
    overflow: hidden;
    padding-bottom: 20px;

}

.container {

    width:1020px;
    margin:0 auto;
    overflow: auto;

}

.main {

        margin: 15px 0;

}

footer {

    background: #393939;
    color: #ffffff;
    padding: 20px 10px;
    text-align: center;

}

article.post a.button {

    display: inline-block;
    background:#333333;
    color:white;
    padding: 10px 5px;
    margin-bottom:  10px;
    text-decoration: none;

}

.meta {

    background:#333333;
    color:white;
    padding: 5px;

}

.post-thumbnail img{

    width: 100%;
    height:auto;

.main-nav li{

    list-style: none;
    float: left;
    padding-right: 15px;

}

.main-nav {

    background: #4169E1;
    color: #ffffff;

}
</code>```

The code in my header.php folder is this:

```<code><nav class="main-nav">

        <div class="container">

            <?php
                $args = array(

                'theme_location'    => 'primary'

            );

            ?>
            <?php wp_nav_menu($args); ?>
        </div>

    </nav>
</code>```

And then the functions.php code is this:

```<code>function simple_theme_setup() {

        //Featured Image Support
        add_theme_support('post-thumbnails');

        //Menus
        register_nav_menus(array(

            'primary'   => __('Primary Menu')

        ));
    }
</code>```

I'm expecting to see the changes immediately on the site, as it has before, but this isn't occurring.

I go to "view page source" and click on the style.css link. it takes me there but the changes to the style sheet are not present.

I retried a couple of minutes later, and the changes to the stylesheet are present, but the changes have not taken effect on  the site.

I read that I may need to clear cache files so I cleared my browsing cache but that didn't do anything . Would anyone have any input on this?

EDIT: after some more digging, I'm getting the feeling it's some other style that's  overriding it that was declared earlier (based on this answer). I put the !important tags on the main-nav styles but that still didn't return anything.

答:
Fixed it, after the

```<code>.post-thumbnail img{

    width: 100%;
    height:auto;
</code>```

I forgot the last }

Thanks to all who helped look though! just a testament to how one little thing can completely mess up the whole process.

Body:
I am building a wordpress theme on a localhost, using phpmyadmin and Ampps.

I have pasted the following into the style.css folder

    body {

    font-family: Arial;
    font-size: 15px;
    color:  #333333
    background: #f4f4f4;
    margin:0;
    padding:0;
    line-height: 1.7em;
}

header {

    background: #393939;
    color: #ffffff;
    padding: 20px 10px;

}

header h1 {

    color: #ffffff;
    margin:0;
    padding:0;
    padding-bottom: 10px;

}

a {

    color: #333333;

}

article.post {

    border-bottom: 1px #cccccc solid;
    overflow: hidden;
    padding-bottom: 20px;

}

.container {

    width:1020px;
    margin:0 auto;
    overflow: auto;

}

.main {

        margin: 15px 0;

}

footer {

    background: #393939;
    color: #ffffff;
    padding: 20px 10px;
    text-align: center;

}

article.post a.button {

    display: inline-block;
    background:#333333;
    color:white;
    padding: 10px 5px;
    margin-bottom:  10px;
    text-decoration: none;

}

.meta {

    background:#333333;
    color:white;
    padding: 5px;

}

.post-thumbnail img{

    width: 100%;
    height:auto;

.main-nav li{

    list-style: none;
    float: left;
    padding-right: 15px;

}

.main-nav {

    background: #4169E1;
    color: #ffffff;

}

The code in my header.php folder is this:

            <?php
                $args = array(

                'theme_location'    => 'primary'

            );

            ?>
            <?php wp_nav_menu($args); ?>

And then the functions.php code is this:

function simple_theme_setup() {

        //Featured Image Support
        add_theme_support('post-thumbnails');

        //Menus
        register_nav_menus(array(

            'primary'   => __('Primary Menu')

        ));
    }

I'm expecting to see the changes immediately on the site, as it has before, but this isn't occurring.

I go to "view page source" and click on the style.css link. it takes me there but the changes to the style sheet are not present.

I retried a couple of minutes later, and the changes to the stylesheet are present, but the changes have not taken effect on  the site.

I read that I may need to clear cache files so I cleared my browsing cache but that didn't do anything . Would anyone have any input on this?

EDIT: after some more digging, I'm getting the feeling it's some other style that's  overriding it that was declared earlier (based on this answer). I put the !important tags on the main-nav styles but that still didn't return anything.

Body:
Fixed it, after the

.post-thumbnail img{

    width: 100%;
    height:auto;

I forgot the last }

Thanks to all who helped look though! just a testament to how one little thing can completely mess up the whole process.


问:
Zsh find permission denied - Application Saved State
Whenever I use the find command in zsh, if I have it run from the user level, it always outputs a specific permission denied message (in addition to any found paths) For example:

```<code>$ find "/Users/usr" -name "Python.gitignore"

/Users/usr/Dropbox/Programming/Git/gitignore/Python.gitignore
find: /Users/usr/Library/Saved Application State/com.bitrock.appinstaller.savedState: Permission denied
</code>```

But if it's run on any subdirectory of /Users/usr (except Users/usr/Library) it works as expected:

```<code>$ find "/Users/usr/Dropbox" -name "Python.gitignore"

/Users/vivekjha/Dropbox/Programming/Git/gitignore/Python.gitignore
</code>```

What is a "Saved Application State" and how can I prevent this error message from outputting when running find?

答:
And alternative to find would be to use zsh globbing. The following will most likely return the results you want.

```<code>$ print -l /Users/usr/**/Python.gitignore(N)
</code>```

Body:
Whenever I use the find command in zsh, if I have it run from the user level, it always outputs a specific permission denied message (in addition to any found paths) For example:

$ find "/Users/usr" -name "Python.gitignore"

/Users/usr/Dropbox/Programming/Git/gitignore/Python.gitignore
find: /Users/usr/Library/Saved Application State/com.bitrock.appinstaller.savedState: Permission denied

But if it's run on any subdirectory of /Users/usr (except Users/usr/Library) it works as expected:

$ find "/Users/usr/Dropbox" -name "Python.gitignore"

/Users/vivekjha/Dropbox/Programming/Git/gitignore/Python.gitignore

What is a "Saved Application State" and how can I prevent this error message from outputting when running find?

Body:
And alternative to find would be to use zsh globbing. The following will most likely return the results you want.

$ print -l /Users/usr/**/Python.gitignore(N)


问:
Count all entries of child tables in single query
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

```<code>MainTable
  |--Child1
  |--Child2
</code>```

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.

答:
Something like this should work:</p>

```<code>SELECT m.IdMain,
       COUNT(c1.id),
       COUNT(c2.id)
FROM MainTable m
LEFT OUTER JOIN Child1 c1
  ON c1.id = m.IdMain
LEFT OUTER JOIN Child2 c2
  ON c2.id = m.IdMain
WHERE m.IdMain = SomeNumber
GROUP BY m.IdMain;
</code>```

Body:
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

MainTable
  |--Child1
  |--Child2

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.

Body:
Something like this should work:

SELECT m.IdMain,
       COUNT(c1.id),
       COUNT(c2.id)
FROM MainTable m
LEFT OUTER JOIN Child1 c1
  ON c1.id = m.IdMain
LEFT OUTER JOIN Child2 c2
  ON c2.id = m.IdMain
WHERE m.IdMain = SomeNumber
GROUP BY m.IdMain;


问:
Eliminate 300ms delay on click events in mobile Safari
I've read that  mobile Safari has a 300ms delay on click events from the time the link/button is clicked to the time the event fires. The reason for the delay is to wait to see if the user intends to double-click, but from a UX perspective waiting 300ms is often undesirable.

One solution to eliminate this 300ms delay is to use jQuery Mobile "tap" handling. Unfortunately I'm not familiar with this framework and don't want to load some big framework if all I need is a line or two of code applying touchend in the right way.

Like many sites, my site has many click events like this:

```<code>$("button.submitBtn").on('click', function (e) {
  $.ajaxSubmit({... //ajax form submisssion
});

$("a.ajax").on('click', function (e) {
  $.ajax({... //ajax page loading
});

$("button.modal").on('click', function (e) {
      //show/hide modal dialog
});
</code>```

and what I'd like to do is to get rid of the 300ms delay on ALL those click events using a single code snippet like this:

```<code>$("a, button").on('tap', function (e) {
 $(this).trigger('click');
 e.preventDefault();
});
</code>```

Is that a bad/good idea?

答:
In jQuery you can bind "touchend" event, witch trigger code inmediatly after tap (is like a keydown in keyboard). Tested on current Chrome and Firefox tablet versions. Don't forget "click" also, for your touch screen laptops and desktop devices.

jQuery('.yourElements').bind('click touchend',function(event){

    event.stopPropagation();
    event.preventDefault();

 // everything else
});```

Body:
I've read that  mobile Safari has a 300ms delay on click events from the time the link/button is clicked to the time the event fires. The reason for the delay is to wait to see if the user intends to double-click, but from a UX perspective waiting 300ms is often undesirable.

One solution to eliminate this 300ms delay is to use jQuery Mobile "tap" handling. Unfortunately I'm not familiar with this framework and don't want to load some big framework if all I need is a line or two of code applying touchend in the right way.

Like many sites, my site has many click events like this:

$("button.submitBtn").on('click', function (e) {
  $.ajaxSubmit({... //ajax form submisssion
});

$("a.ajax").on('click', function (e) {
  $.ajax({... //ajax page loading
});

$("button.modal").on('click', function (e) {
      //show/hide modal dialog
});

and what I'd like to do is to get rid of the 300ms delay on ALL those click events using a single code snippet like this:

$("a, button").on('tap', function (e) {
 $(this).trigger('click');
 e.preventDefault();
});

Is that a bad/good idea?


问:
Error when cloning git "shallow" repository
I'm getting the following error when issuing the command git clone --bare /path/to/repo:

fatal: attempt to fetch/clone from a shallow repository

First, what is a shallow repository and why doesn't it let me clone it?

答:
A shallow repository is a repository which does not contain the full history.

See the git-clone manpage:

--depth

Create a shallow clone with a history truncated to the specified
  number of revisions. A shallow
  repository has a number of limitations
  (you cannot clone or fetch from it,
  nor push from nor into it), but is
  adequate if you are only interested in
  the recent history of a large project
  with a long history, and would want to
  send in fixes as patches.


问:
Mouseover with an image and a caption in Aframe
I would like to display an image along with a caption when the mouse move over an image in Aframe.</p>

答:
you'll want to add the mouseenter eventlistener to the object.

HTML

```<code><img alt="img" id="img" src="myimg"/>
</code>```

.

Javascript

```<code>window.onload = function(){
  var img = document.getElementById("img");
  img.addEventListener("mouseenter", function(){
      //your code to show image and text here
  });
}
</code>```

You can ofcourse swap out the HTML for basicly anything in aframe and it would work as long as you keep the id.

Body:
you'll want to add the mouseenter eventlistener to the object.

HTML

<img alt="img" id="img" src="myimg"/>

.

Javascript

window.onload = function(){
  var img = document.getElementById("img");
  img.addEventListener("mouseenter", function(){
      //your code to show image and text here
  });
}

You can ofcourse swap out the HTML for basicly anything in aframe and it would work as long as you keep the id.


问:
Assign ranks based on multiple conditions
I have identified some duplicates in my data (based on V1,V2,V3,V4), however as it is getting difficult to manually review too many records, I would like to assign ranks based on a few conditions:

if V5,V6 match - rank -1

if V7,V8 match - rank -2

and so on. how can this be achieved?

T1

```<code>ID |   V1 |  V2 |  V5   | V6 | CreatedDate
---| ---  | ---    ---   --- ----------
1  |   A  |  US |  1984 | QR | 01-AUG-2017
2  |   B  |  FR |  1991 | TY | 01-JAN-2017
3  |   C  |  AU |  1989 | GH | 25-SEP-2017
4  |   B  |  FR |  1995 | BN | 01-AUG-2017
5  |   A  |  US |  1984 | QR | 30-MAR-2016
6  |   C  |  AU |  1999 | MK | 14-JUN-2015
</code>```

T2

```<code>ID | V3    | V7
---| ---    ---
1  | Apple   D12
1  | Kiwi    S45
2  | Pear    T23
3  | Banana  U78
4  | Pear    T23
5  | Apple   D12
6  | Banana  P90
</code>```

T3

```<code>ID | V4      V8
---|  ---    ---
1  | Spinach A678
1  | Beets   V902
2  | Celery  T456
3  | Radish  Y675
4  | Celery  T456
5  | Spinach G890
6  | Celery  F567
6  | Radish  R453

1 A US Apple Spinach 1984 QR D12 A678 1
5 A US Apple Spinach 1984 QR D12 G890 1
2 B FR Pear  Celery  1991 TY T23 T456 2
4 B FR Pear  Celery  1995 BN T23 T456 2
</code>```

答:
Looks like your basic problem is just regarding T1. T2 and T3 is just additional information.

So because your example data isnt clear I will focus only on T1.

Here you join T1 with itself and see if exist same value on the columns.

```<code>SELECT TA.*, TB.*,
       CASE WHEN TA.V5 = TB.V5  AND TA.V6 = TB.V6
            THEN 'rank -1'
            WHEN TA.V7 = TB.V7  AND TA.V8 = TB.V7
            THEN 'rank -2'
       END as ranking
FROM T1 as TA
JOIN T1 as TB
  ON TA.ID < TB.ID
 AND (  (TA.V5 = TB.V5  AND TA.V6 = TB.V6)
     OR (TA.V7 = TB.V7  AND TA.V8 = TB.V7)
     )
</code>```

Body:
I have identified some duplicates in my data (based on V1,V2,V3,V4), however as it is getting difficult to manually review too many records, I would like to assign ranks based on a few conditions:

if V5,V6 match - rank -1

if V7,V8 match - rank -2

and so on. how can this be achieved?

T1

ID |   V1 |  V2 |  V5   | V6 | CreatedDate
---| ---  | ---    ---   --- ----------
1  |   A  |  US |  1984 | QR | 01-AUG-2017
2  |   B  |  FR |  1991 | TY | 01-JAN-2017
3  |   C  |  AU |  1989 | GH | 25-SEP-2017
4  |   B  |  FR |  1995 | BN | 01-AUG-2017
5  |   A  |  US |  1984 | QR | 30-MAR-2016
6  |   C  |  AU |  1999 | MK | 14-JUN-2015

T2

ID | V3    | V7
---| ---    ---
1  | Apple   D12
1  | Kiwi    S45
2  | Pear    T23
3  | Banana  U78
4  | Pear    T23
5  | Apple   D12
6  | Banana  P90

T3

ID | V4      V8
---|  ---    ---
1  | Spinach A678
1  | Beets   V902
2  | Celery  T456
3  | Radish  Y675
4  | Celery  T456
5  | Spinach G890
6  | Celery  F567
6  | Radish  R453

1 A US Apple Spinach 1984 QR D12 A678 1
5 A US Apple Spinach 1984 QR D12 G890 1
2 B FR Pear  Celery  1991 TY T23 T456 2
4 B FR Pear  Celery  1995 BN T23 T456 2

Body:
Looks like your basic problem is just regarding T1. T2 and T3 is just additional information.

So because your example data isnt clear I will focus only on T1.

Here you join T1 with itself and see if exist same value on the columns.

SELECT TA.*, TB.*,
       CASE WHEN TA.V5 = TB.V5  AND TA.V6 = TB.V6
            THEN 'rank -1'
            WHEN TA.V7 = TB.V7  AND TA.V8 = TB.V7
            THEN 'rank -2'
       END as ranking
FROM T1 as TA
JOIN T1 as TB
  ON TA.ID < TB.ID
 AND (  (TA.V5 = TB.V5  AND TA.V6 = TB.V6)
     OR (TA.V7 = TB.V7  AND TA.V8 = TB.V7)
     )


问:
Azure pre-compiled Functions not available to Logic Apps
We are utilising visual studio 2017 and azure precompiled functions in VB.NET. All functions run successfully locally using the func.exe CLI tool. We can publish the Function App to Azure where we can see and test within the portal.

The problem exists when we try to use the functions as part of a logic app. We can add an action selecting Azure Functions and can see our function app, but none of the underlying functions are available/missing.

What am i missing?

Edit
I am using http triggers and web hooks.

Edit
It was indeed the custom routes

答: Only functions of type 'Generic Web Hooks' are supported by Logic Apps. You don't state what type you are using, but if you are using 'http trigger' functions, that could be the problem.</p>