问:
Ember not setting hasMany relationship attribute after retrieving data
Foreward: There are a lot of firsts in this project, such as building my first API, first time using JSON API, first time using Ember, first time posting on SO, etc.

I'm trying to access an 'authors' hasMany attribute in my template containing the latest updates. What I access it in the template, however, nothing is returned. The models are being saved correctly, but the relationship is not being set it appears, as the length of the DS.PromiseManyArray on latest.contentAuthors is 0 while the promise is fulfilled ({ _length: 0, isFulfilled: true, isRejected: false }).

I'm using Ember 3.10 (with CLI). I have full control over my backend (LAMP running ExpressionEngine 5) and am serving API requests through a custom built plugin, though I'm not sure that matters too much as this seems to largely be a frontend problem from what I can discern.

Route

```<code>import Route from '@ember/routing/route';

export default Route.extend({
    model(){
        let latest = this.store.peekAll('latest');
        if (latest.length < 2){
            latest = this.store.query('latest', { limit: 2, include: "people" });
        }
        return latest;
    }
});
</code>```

Base Model

```<code>import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
    title: DS.attr()
});
</code>```

Latest Model

Edit: Removed redundant property that's not in original code

```<code>import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    blurb: DS.attr(),
    contentAuthors: DS.hasMany('person')
});
</code>```

Person Model

Edit: Removed redundant property that's not in original code

```<code>import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    latest: DS.hasMany('latest')
});
</code>```

Template

{{#each this.model as |latest|}}

{{latest.title}}

    {{#each latest.contentAuthors as |author|}}

{{author.title}}

    {{else}}

Can't find author(s)

    {{/each}}

{{latest.blurb}}

{{/each}}
```

<p>Data sent from server<br>
<strong>Edit:</strong> Checked this against a JSON API validator to find the original was non-conforming. I've updated my backend but this didn't solve the problem. This is now conforming according to that validator.</p>

```{
    "data": [{
        "id": "3161",
        "type": "latest",
        "attributes": {
            "title": "Amazing Video 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/video\/3161"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": "1",
                    "type": "people"
                }]
            }
        }
    }, {
        "id": "2573",
        "type": "latest",
        "attributes": {
            "title": "Amazing Article 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/white_papers_insights\/2573"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": "1",
                    "type": "people"
                }, {
                    "id": "52",
                    "type": "people"
                }]
            }
        }
    }],
    "links": {
        "self": "https:\/\/cms.example.com\/api\/v1\/latest?include=people&limit=2"
    },
    "included": [{
        "id": "1",
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Author"
        }
    }, {
        "id": "52",
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/52",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Co-Author"
        }
    }]
}
```

To reiterate, the relationship model is saving and is viewable in Ember Inspector, but the actual link/relationship is not being set.

Update: I've tried renaming types and query parameters to no avail, checking to see if inflection had anything to do with the dropped relationship.

答:
The relationship in your model is named contentAuthors but in your payload you name it people.

So instead of this:

```<code>"people": {
  "data": [{
    "id": "1",
    "type": "people"
  }]
}
</code>```

do this:

```<code>"contentAuthors": {
  "data": [{
    "id": "1",
    "type": "people"
  }]
}
</code>```

If you have contentAuthors: DS.hasMany('person') in your model.

sidenote: latest is not a good model name. A model name should always be a noun, or at least end in one.

Body:
Foreward: There are a lot of firsts in this project, such as building my first API, first time using JSON API, first time using Ember, first time posting on SO, etc.

I'm trying to access an 'authors' hasMany attribute in my template containing the latest updates. What I access it in the template, however, nothing is returned. The models are being saved correctly, but the relationship is not being set it appears, as the length of the DS.PromiseManyArray on latest.contentAuthors is 0 while the promise is fulfilled ({ _length: 0, isFulfilled: true, isRejected: false }).

I'm using Ember 3.10 (with CLI). I have full control over my backend (LAMP running ExpressionEngine 5) and am serving API requests through a custom built plugin, though I'm not sure that matters too much as this seems to largely be a frontend problem from what I can discern.

Route

import Route from '@ember/routing/route';

export default Route.extend({
    model(){
        let latest = this.store.peekAll('latest');
        if (latest.length < 2){
            latest = this.store.query('latest', { limit: 2, include: "people" });
        }
        return latest;
    }
});

Base Model

import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
    title: DS.attr()
});

Latest Model

Edit: Removed redundant property that's not in original code

import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    blurb: DS.attr(),
    contentAuthors: DS.hasMany('person')
});

Person Model

Edit: Removed redundant property that's not in original code

import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';

export default ExpressionEngineBase.extend({
    latest: DS.hasMany('latest')
});

Template

{{#each this.model as |latest|}}

{{latest.title}}

    {{#each latest.contentAuthors as |author|}}

{{author.title}}

    {{else}}

Can't find author(s)

    {{/each}}

{{latest.blurb}}

{{/each}}

Data sent from server

Edit: Checked this against a JSON API validator to find the original was non-conforming. I've updated my backend but this didn't solve the problem. This is now conforming according to that validator.

{
    "data": [{
        "id": "3161",
        "type": "latest",
        "attributes": {
            "title": "Amazing Video 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/video\/3161"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": "1",
                    "type": "people"
                }]
            }
        }
    }, {
        "id": "2573",
        "type": "latest",
        "attributes": {
            "title": "Amazing Article 1"
        },
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/white_papers_insights\/2573"
        },
        "relationships": {
            "people": {
                "data": [{
                    "id": "1",
                    "type": "people"
                }, {
                    "id": "52",
                    "type": "people"
                }]
            }
        }
    }],
    "links": {
        "self": "https:\/\/cms.example.com\/api\/v1\/latest?include=people&limit=2"
    },
    "included": [{
        "id": "1",
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Author"
        }
    }, {
        "id": "52",
        "type": "people",
        "links": {
            "self": "https:\/\/cms.example.com\/api\/v1\/people\/52",
            "channel": "https:\/\/cms.example.com\/api\/v1\/people"
        },
        "attributes": {
            "title": "Great Co-Author"
        }
    }]
}

To reiterate, the relationship model is saving and is viewable in Ember Inspector, but the actual link/relationship is not being set.

Update: I've tried renaming types and query parameters to no avail, checking to see if inflection had anything to do with the dropped relationship.

Body:
The relationship in your model is named contentAuthors but in your payload you name it people.

So instead of this:

"people": {
  "data": [{
    "id": "1",
    "type": "people"
  }]
}

do this:

"contentAuthors": {
  "data": [{
    "id": "1",
    "type": "people"
  }]
}

If you have contentAuthors: DS.hasMany('person') in your model.

sidenote: latest is not a good model name. A model name should always be a noun, or at least end in one.


来源: stackexchange

问:
grouping of elements of same type together in an array in O(1) Space and O(n) time
This is a problem from Elements of programming interviews book.

Question:

Given an array of n objects with keys that takes on of four values, reorder the array so that the objects that have the same type appear together. Use O(1) additional space and O(n) time.

I am unable to conceive an idea for more than three groups(Dutch National flag problem). Any help would be really appreciated.

For example a[6]={1,2,3,4,3,1}; Then the result should be {1,1,2,3,3,4} or in any order, only the grouping of numbers matters( ie, the result need not be in ascending order)

答:
To make flag with same color to come together, we could have a pointer variable and swap all those elements that have the current flag to the left and repeat this for each subsequent flag. In the end, we would have all 4 flags grouped together. Space complexity is O(1) and time complexity is O(number of flags * n). Since the flags for your case is 4, it will be O(4 * n) = O(n).

```<code>#include <iostream>
using namespace std;

int main() {

    int a[] = {1,2,3,4,3,1,2,3,3,4};
    int size = sizeof(a) / sizeof(int);
    int ptr = 0;

    for(int flag=1;flag <= 4;++flag){
        for(int i=ptr;i<size;++i){
            if(a[i] == flag){
                swap(a[i],a[ptr++]);
            }
        }
    }

    for(int i=0;i<size;++i){
        cout<<a[i]<<" ";
    }

}
</code>```

Update:

For Independent of the number of groups, you can use a trie data structure. Trie would be composed of binary representation of each number with the last bit node holding the count value of occurrence for that group's element.

Since we could represent integers in 32 bits, the space occupied by trie would be less and wouldn't grow with respect to the number of groups.

As a result, space complexity would be O(1). Time complexity would be O(n + log(max_number) * n).

ContentLicense: CC BY-SA 4.0

Body:
To make flag with same color to come together, we could have a pointer variable and swap all those elements that have the current flag to the left and repeat this for each subsequent flag. In the end, we would have all 4 flags grouped together. Space complexity is O(1) and time complexity is O(number of flags * n). Since the flags for your case is 4, it will be O(4 * n) = O(n).

#include <iostream>
using namespace std;

int main() {

    int a[] = {1,2,3,4,3,1,2,3,3,4};
    int size = sizeof(a) / sizeof(int);
    int ptr = 0;

    for(int flag=1;flag <= 4;++flag){
        for(int i=ptr;i<size;++i){
            if(a[i] == flag){
                swap(a[i],a[ptr++]);
            }
        }
    }

    for(int i=0;i<size;++i){
        cout<<a[i]<<" ";
    }

}

Update:

For Independent of the number of groups, you can use a trie data structure. Trie would be composed of binary representation of each number with the last bit node holding the count value of occurrence for that group's element.

Since we could represent integers in 32 bits, the space occupied by trie would be less and wouldn't grow with respect to the number of groups.

As a result, space complexity would be O(1). Time complexity would be O(n + log(max_number) * n).


问:
aspx and htm files with identical code behave differently
I have two pages with identical code.  One has an aspx extension, one htm.  In Firefox they display exactly the same.  In IE8, my dropdown menus appear layered beneath the content...but only on the aspx page.  There's a slight positioning discrepancy in IE8 between the two as well.  Again, identical code, and pointing to the same css and js files...how is this even possible?

http://webdev.craftonhills.edu/Admissions_and_Financial%20Aid.aspx

http://thelionscall.com/temp/menutest/

I really need to get this working in the aspx file.  Thanks.

答:
One of the pages has a FORM tag and a div with a hidden input in it that the other doesn't.

IE will render default padding/margin on a form tag, when many other browsers will not.

I suggest using a good CSS reset.

ContentLicense: CC BY-SA 3.0


问:
Hadoop Format NameNode after installation - Error: command not found (UBUNTO)
Hello i have just installed Hadoop and cant format namenode
i am working with Ubunto

and its supposed to be quite simple but i get this error : "command not found"

```<code>barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ ls -ltr
total 76
-rwxr-xr-x 1 root root  1462   2 23:08 stop-all.sh
-rw-r--r-- 1 root root  1770   2 23:08 stop-all.cmd
-rwxr-xr-x 1 root root  1471   2 23:08 start-all.sh
-rw-r--r-- 1 root root  1779   2 23:08 start-all.cmd
-rwxr-xr-x 1 root root  2145   2 23:08 slaves.sh
-rwxr-xr-x 1 root root  1776   2 23:08 rcc
-rwxr-xr-x 1 root root  1360   2 23:08 hadoop-daemons.sh
-rwxr-xr-x 1 root root  6452   2 23:08 hadoop-daemon.sh
-rw-r--r-- 1 root root 11179   2 23:08 hadoop-config.sh
-rw-r--r-- 1 root root  8023   2 23:08 hadoop-config.cmd
-rw-r--r-- 1 root root  8298   2 23:08 hadoop.cmd
-rwxr-xr-x 1 root root  5479   2 23:08 hadoop

barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ sudo hadoop namenode -format
sudo: hadoop: command not found

barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ hadoop namenode -format
hadoop: command not found
</code>```

what do i need to do to format my name node ?

答:
I faced the similar problem and while checking all the Hadoop configurations, my bashrc profile details had issues.

```<code>export HADOOP_HOME=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME

export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin
export HADOOP_INSTALL=$HADOOP_HOME
</code>```

I had done a typo for my bin

Please check $ echo $PATH

Body:
Hello i have just installed Hadoop and cant format namenode
i am working with Ubunto

and its supposed to be quite simple but i get this error : "command not found"

barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ ls -ltr
total 76
-rwxr-xr-x 1 root root  1462   2 23:08 stop-all.sh
-rw-r--r-- 1 root root  1770   2 23:08 stop-all.cmd
-rwxr-xr-x 1 root root  1471   2 23:08 start-all.sh
-rw-r--r-- 1 root root  1779   2 23:08 start-all.cmd
-rwxr-xr-x 1 root root  2145   2 23:08 slaves.sh
-rwxr-xr-x 1 root root  1776   2 23:08 rcc
-rwxr-xr-x 1 root root  1360   2 23:08 hadoop-daemons.sh
-rwxr-xr-x 1 root root  6452   2 23:08 hadoop-daemon.sh
-rw-r--r-- 1 root root 11179   2 23:08 hadoop-config.sh
-rw-r--r-- 1 root root  8023   2 23:08 hadoop-config.cmd
-rw-r--r-- 1 root root  8298   2 23:08 hadoop.cmd
-rwxr-xr-x 1 root root  5479   2 23:08 hadoop

barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ sudo hadoop namenode -format
sudo: hadoop: command not found

barak@barak-VirtualBox:/usr/local/hadoop/hadoop-common-project/hadoop-common/src/main/bin$ hadoop namenode -format
hadoop: command not found

what do i need to do to format my name node ?

Body:
I faced the similar problem and while checking all the Hadoop configurations, my bashrc profile details had issues.

export HADOOP_HOME=/usr/local/hadoop
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME

export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin
export HADOOP_INSTALL=$HADOOP_HOME

I had done a typo for my bin

Please check $ echo $PATH


问:
Kubectl get svc command throws Access Denied error
Using AWS CLI and typing the command Kubectl get svc

throws the below error "An error occurred (AccessDenied) when calling the AssumeRole operation: Access denied"

Can anyone provide directions on what could be causing this error?

答: The issue was EKS Cluster was created with a different IAM role compared to Kubectl. Upon resolving the access credentials, kubectl was able to connect to Control Plane API Servers.</p>


问:
Stretching content to fit desktop page using css
How do I stretch this content to fit full page width in desktop?

Html:

```<code><div class="entry-content">
<blockquote class="wp-embedded-content" data-secret="paBu4nyBJV">.
<p>. <a href="https://tbwdrawingprize.artopps.co.uk/online-
entry/">Online Entry</a></p></blockquote>
<p><iframe title="“Online Entry” — TBW Drawing
Prize" class="wp-embedded-content" sandbox="allow-scripts"
security="restricted" style="position: absolute; clip: rect(1px,
1px, 1px, 1px);" src="https://tbwdrawingprize.artopps.co.uk/online-
entry/embed/#?secret=paBu4nyBJV" data-secret="paBu4nyBJV"
width="600" height="338" frameborder="0" marginwidth="0"
marginheight="0" scrolling="no"></iframe></p>
<p> </p>
<p><embed style="width: 500px; height: 300px;"
</code>```

https://adsler.co.uk/adsler-blog/

答:
If you are referring to the iframe - the width is set to 600px in the width attribute.
If you replace it to 100% it will fill the width of the parent.

```<code><iframe title="“Online Entry” — TBW Drawing
Prize" class="wp-embedded-content" sandbox="allow-scripts"
security="restricted" style="position: absolute; clip: rect(1px,
1px, 1px, 1px);" src="https://tbwdrawingprize.artopps.co.uk/online-
entry/embed/#?secret=paBu4nyBJV" data-secret="paBu4nyBJV"
width="100%" height="338" frameborder="0" marginwidth="0"
marginheight="0" scrolling="no"></iframe>
</code>```

If you want to make the change universal to all of the iframe and embed tags, try the  following css

```<code>iframe, embed {
  width: 100% !important
}
</code>```

Body:
How do I stretch this content to fit full page width in desktop?

Html:

.

. Online Entry

<embed style="width: 500px; height: 300px;"

https://adsler.co.uk/adsler-blog/

Body:
If you are referring to the iframe - the width is set to 600px in the width attribute.
If you replace it to 100% it will fill the width of the parent.

<iframe title="&#8220;Online Entry&#8221; &#8212; TBW Drawing
Prize" class="wp-embedded-content" sandbox="allow-scripts"
security="restricted" style="position: absolute; clip: rect(1px,
1px, 1px, 1px);" src="https://tbwdrawingprize.artopps.co.uk/online-
entry/embed/#?secret=paBu4nyBJV" data-secret="paBu4nyBJV"
width="100%" height="338" frameborder="0" marginwidth="0"
marginheight="0" scrolling="no"></iframe>

If you want to make the change universal to all of the iframe and embed tags, try the  following css

iframe, embed {
  width: 100% !important
}


问:
Google Colab having problems with Drive folders containing lots of files
I have imported several folders from Drive onto Google Colab. The smaller folders work fine when listing directories, but when I try to list the directories in the larger folders, Colab gives me an error.

I am aware that there are other ways of listing directories, but this same issue is causing problems further down the line when I try to access the files for training.

I am using this to import the files:

```<code>from google.colab import drive
drive.mount('/content/drive')
</code>```

And then describing the folders as follows:

```<code>TRAIN = '../content/drive/My Drive/train/'
TEST = '../content/drive/My Drive/test/'
</code>```

When I try to do the following:

```<code>print(os.listdir(TEST))
print(os.listdir(TRAIN))
</code>```

TEST prints fine. It has circa 8000 files (all images).

TRAIN prints some times, others it doesn't! It has circa 32,000 files (all images too).
It prints this when I try to run it:

```<code>OSError: [Errno 5] Input/output error: '../content/drive/My Drive/train/'
</code>```

Does anyone know how to fix this in Google colab?

I've found that if after importing the files I wait for a while and then run the prints, it runs, suggesting that Colab takes a while to process the files from Drive even after the cell importing stops running.

答:
```<code>OSError: [Errno 5] Input/output error: '../content/drive/My Drive/train/'
</code>```

reason is google colab can't read file tree as '../content/drive/My Drive/train/'
so, change it as 'content/drive/My Drive/train/'.(or give full path based on your present working directory)

Body:
I have imported several folders from Drive onto Google Colab. The smaller folders work fine when listing directories, but when I try to list the directories in the larger folders, Colab gives me an error.

I am aware that there are other ways of listing directories, but this same issue is causing problems further down the line when I try to access the files for training.

I am using this to import the files:

from google.colab import drive
drive.mount('/content/drive')

And then describing the folders as follows:

TRAIN = '../content/drive/My Drive/train/'
TEST = '../content/drive/My Drive/test/'

When I try to do the following:

print(os.listdir(TEST))
print(os.listdir(TRAIN))

TEST prints fine. It has circa 8000 files (all images).

TRAIN prints some times, others it doesn't! It has circa 32,000 files (all images too).
It prints this when I try to run it:

OSError: [Errno 5] Input/output error: '../content/drive/My Drive/train/'

Does anyone know how to fix this in Google colab?

I've found that if after importing the files I wait for a while and then run the prints, it runs, suggesting that Colab takes a while to process the files from Drive even after the cell importing stops running.

Body:
OSError: [Errno 5] Input/output error: '../content/drive/My Drive/train/'

reason is google colab can't read file tree as '../content/drive/My Drive/train/'
so, change it as 'content/drive/My Drive/train/'.(or give full path based on your present working directory)


问:
How to optimize search algorithm
I have 4 dropdown multi-select filters in row.

Which need to render and on every selected option.
I need to add that selected option in new array and update that current array -> object.property.selected = false/true.

I am searching trough array of objects, and one property of every object have array of objects.

You can found code example on this code-pen: https://codepen.io/nikolatrajkovicits/pen/JqpWOX?editors=0012

Here is how that array looks:

```<code>export const getFiltersList = () => [
  {
    title: 'Taxonomy',
    options: [
      {
        id: 0,
        name: 'Competitions',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 1,
        name: 'Events',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 2,
        name: 'Data',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 3,
        name: 'Organisations',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 4,
        name: 'Players',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 5,
        name: 'Teams',
        selected: false,
        key: 'Taxonomy'
      }
    ]
  },
  {
    title: 'Source',
    options: [
      {
        id: 0,
        name: 'Facebook',
        selected: false,
        key: 'Source'
      },
      {
        id: 1,
        name: 'Twitter',
        selected: false,
        key: 'Source'
      },
      {
        id: 2,
        name: 'Instagram',
        selected: false,
        key: 'Source'
      },
      {
        id: 3,
        name: 'Websites',
        selected: false,
        key: 'Source'
      }
    ]
  },
  {
    title: 'Timeframe',
    options: [
      {
        id: 0,
        name: 'Past hour',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 1,
        name: 'Past 24 hours',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 2,
        name: 'Past week',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 3,
        name: 'Past month',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 4,
        name: 'Past year',
        selected: false,
        key: 'Timeframe'
      }
    ]
  },
  {
    title: 'Location',
    options: [
      {
        id: 0,
        name: 'Location 1',
        selected: false,
        key: 'Location'
      },
      {
        id: 1,
        name: 'Location 2',
        selected: false,
        key: 'Location'
      },
      {
        id: 2,
        name: 'Location 3',
        selected: false,
        key: 'Location'
      },
      {
        id: 3,
        name: 'Location 4',
        selected: false,
        key: 'Location'
      }
    ]
  }
];

</code>```

Here is algorithm:

```<code>selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;
    const tempFilters = filtersList;
    const tempSelected = selectedFilters;
    const i = tempSelected.length;

    tempFilters.forEach((filter) => {
      if (filter.title === key) {
        filter.options.forEach((option) => {
          if (option.id === id) {
            option.selected = !option.selected;
            const isFilterExist = tempSelected.filter(
              (selectedFilter) => selectedFilter.name === option.name
            );
            if (!isFilterExist.length) {
              const selectedItem = { name: option.name, key, id };
              tempSelected[i] = selectedItem;
            }
          }
        });
      }
    });
    this.setState({
      filtersList: tempFilters,
      selectedFilters: tempSelected
    });
  };

</code>```

On code pen you can found version which is in pure javascript code.

How to make better cleaner faster search algo?

Any advice article, tutorial, comment?

答:
First of all these two are unnecessary:

```<code>const tempFilters = filtersList;
const tempSelected = selectedFilters;
</code>```

The variables are references to the exact same objects and you already have variables for those. You can simply use filtersList and selectedFilters instead of tempFilters and tempSelected respectively.

```<code>tempFilters.forEach((filter) => {
      if (filter.title === key) {`
</code>```

Since the entirety of the .forEach is the if, then this suggests you need to use .filter instead.

```<code>tempFilters.filter((filter) => filter.title === key)`
</code>```

Same here, when you get inside the if

```<code>filter.options.forEach((option) => {
  if (option.id === id) {
</code>```

you can simplify to

```<code>filter.options.filter((option) => option.id === id)
</code>```

Continuing on, this line is a waste

```<code>const isFilterExist = tempSelected.filter(
    (selectedFilter) => selectedFilter.name === option.name
);
</code>```

No need to run .filter on the entire array, when all you're interested in is if there are any items that match the predicate or not. Use .some instead which directly gives you a boolean:

```<code>const isFilterExist = tempSelected.some(
    (selectedFilter) => selectedFilter.name === option.name
);
</code>```

Also, since you are always inverting the boolean, it's a bit simpler to just find the opposite - if a filter doesn't exist - invert the predicate and use .every to get that. The reasoning is that some of the element match but you want the opposite which is logically that every of the elements match the exact opposite of the predicate. Finally, I've changed the name to use has to sound a bit more natural.

```<code>const hasNoFilter = tempSelected.every(
    (selectedFilter) => selectedFilter.name !== option.name
);
</code>```

So, as a start, the code can be re-written into the following:

```<code>selectFilter = ({ id, key }) => {
  const { filtersList, selectedFilters } = this.state;
  const i = selectedFilters.length;

  filtersList
    .filter((filter) => filter.title === key)
    .forEach(filter => {
      filter.options
        .filter((option) => option.id === id)
        .forEach(option => {
          option.selected = !option.selected;
          const hasNoFilter = tempSelected.every(
            (selectedFilter) => selectedFilter.name !== option.name
          );

          if (hasNoFilter) {
            const selectedItem = { name: option.name, key, id };
            selectedFilters[i] = selectedItem;
          }
        });
    });
  this.setState({
    filtersList,
    selectedFilters
  });
};
</code>```

This makes it a bit easier to reason about the code.

It seems like you have filters with unique titles and options with unique IDs within those, which means that the combination of title + ID would also be unique.

With that in mind, you are interested in a single value not, any number of them, thus you don't need to do all the looping. You can use .find to fetch the values you are interested in which then makes the entire code easier to read:

```<code>selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;

    const filter = filtersList.find((filter) => filter.title === key);

    const option = filter.options.find((option) => option.id === id)

    option.selected = !option.selected;
    const hasNoFilter = tempSelected.every(
      (selectedFilter) => selectedFilter.name !== option.name
    );
    if (hasNoFilter) {
      const selectedItem = { name: option.name, key, id };
      selectedFilters.push(selectedItem);
    }

    this.setState({
      filtersList,
      selectedFilters
    });
  };
}
</code>```

As a consequence of this code only working with a single item, you don't need the line
const i = selectedFilters.length; because you are going to make a single insertion in the array. Previously, the line selectedFilters[i] = selectedItem; enclosed in a all the loops suggested you would insert multiple values but all in the same position, so as to leave only the last one. A simple .push is enough to append to the end.

Title: How to optimize search algorithm

Body:
I have 4 dropdown multi-select filters in row.

Which need to render and on every selected option.
I need to add that selected option in new array and update that current array -> object.property.selected = false/true.

I am searching trough array of objects, and one property of every object have array of objects.

You can found code example on this code-pen: https://codepen.io/nikolatrajkovicits/pen/JqpWOX?editors=0012

Here is how that array looks:

export const getFiltersList = () => [
  {
    title: 'Taxonomy',
    options: [
      {
        id: 0,
        name: 'Competitions',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 1,
        name: 'Events',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 2,
        name: 'Data',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 3,
        name: 'Organisations',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 4,
        name: 'Players',
        selected: false,
        key: 'Taxonomy'
      },
      {
        id: 5,
        name: 'Teams',
        selected: false,
        key: 'Taxonomy'
      }
    ]
  },
  {
    title: 'Source',
    options: [
      {
        id: 0,
        name: 'Facebook',
        selected: false,
        key: 'Source'
      },
      {
        id: 1,
        name: 'Twitter',
        selected: false,
        key: 'Source'
      },
      {
        id: 2,
        name: 'Instagram',
        selected: false,
        key: 'Source'
      },
      {
        id: 3,
        name: 'Websites',
        selected: false,
        key: 'Source'
      }
    ]
  },
  {
    title: 'Timeframe',
    options: [
      {
        id: 0,
        name: 'Past hour',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 1,
        name: 'Past 24 hours',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 2,
        name: 'Past week',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 3,
        name: 'Past month',
        selected: false,
        key: 'Timeframe'
      },
      {
        id: 4,
        name: 'Past year',
        selected: false,
        key: 'Timeframe'
      }
    ]
  },
  {
    title: 'Location',
    options: [
      {
        id: 0,
        name: 'Location 1',
        selected: false,
        key: 'Location'
      },
      {
        id: 1,
        name: 'Location 2',
        selected: false,
        key: 'Location'
      },
      {
        id: 2,
        name: 'Location 3',
        selected: false,
        key: 'Location'
      },
      {
        id: 3,
        name: 'Location 4',
        selected: false,
        key: 'Location'
      }
    ]
  }
];

Here is algorithm:

selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;
    const tempFilters = filtersList;
    const tempSelected = selectedFilters;
    const i = tempSelected.length;

    tempFilters.forEach((filter) => {
      if (filter.title === key) {
        filter.options.forEach((option) => {
          if (option.id === id) {
            option.selected = !option.selected;
            const isFilterExist = tempSelected.filter(
              (selectedFilter) => selectedFilter.name === option.name
            );
            if (!isFilterExist.length) {
              const selectedItem = { name: option.name, key, id };
              tempSelected[i] = selectedItem;
            }
          }
        });
      }
    });
    this.setState({
      filtersList: tempFilters,
      selectedFilters: tempSelected
    });
  };

On code pen you can found version which is in pure javascript code.

How to make better cleaner faster search algo?

Any advice article, tutorial, comment?

Body:
First of all these two are unnecessary:

const tempFilters = filtersList;
const tempSelected = selectedFilters;

The variables are references to the exact same objects and you already have variables for those. You can simply use filtersList and selectedFilters instead of tempFilters and tempSelected respectively.

tempFilters.forEach((filter) => {
      if (filter.title === key) {`

Since the entirety of the .forEach is the if, then this suggests you need to use .filter instead.

tempFilters.filter((filter) => filter.title === key)`

Same here, when you get inside the if

filter.options.forEach((option) => {
  if (option.id === id) {

you can simplify to

filter.options.filter((option) => option.id === id)

Continuing on, this line is a waste

const isFilterExist = tempSelected.filter(
    (selectedFilter) => selectedFilter.name === option.name
);

No need to run .filter on the entire array, when all you're interested in is if there are any items that match the predicate or not. Use .some instead which directly gives you a boolean:

const isFilterExist = tempSelected.some(
    (selectedFilter) => selectedFilter.name === option.name
);

Also, since you are always inverting the boolean, it's a bit simpler to just find the opposite - if a filter doesn't exist - invert the predicate and use .every to get that. The reasoning is that some of the element match but you want the opposite which is logically that every of the elements match the exact opposite of the predicate. Finally, I've changed the name to use has to sound a bit more natural.

const hasNoFilter = tempSelected.every(
    (selectedFilter) => selectedFilter.name !== option.name
);

So, as a start, the code can be re-written into the following:

selectFilter = ({ id, key }) => {
  const { filtersList, selectedFilters } = this.state;
  const i = selectedFilters.length;

  filtersList
    .filter((filter) => filter.title === key)
    .forEach(filter => {
      filter.options
        .filter((option) => option.id === id)
        .forEach(option => {
          option.selected = !option.selected;
          const hasNoFilter = tempSelected.every(
            (selectedFilter) => selectedFilter.name !== option.name
          );

          if (hasNoFilter) {
            const selectedItem = { name: option.name, key, id };
            selectedFilters[i] = selectedItem;
          }
        });
    });
  this.setState({
    filtersList,
    selectedFilters
  });
};

This makes it a bit easier to reason about the code.

It seems like you have filters with unique titles and options with unique IDs within those, which means that the combination of title + ID would also be unique.

With that in mind, you are interested in a single value not, any number of them, thus you don't need to do all the looping. You can use .find to fetch the values you are interested in which then makes the entire code easier to read:

selectFilter = ({ id, key }) => {
    const { filtersList, selectedFilters } = this.state;

    const filter = filtersList.find((filter) => filter.title === key);

    const option = filter.options.find((option) => option.id === id)

    option.selected = !option.selected;
    const hasNoFilter = tempSelected.every(
      (selectedFilter) => selectedFilter.name !== option.name
    );
    if (hasNoFilter) {
      const selectedItem = { name: option.name, key, id };
      selectedFilters.push(selectedItem);
    }

    this.setState({
      filtersList,
      selectedFilters
    });
  };
}

As a consequence of this code only working with a single item, you don't need the line
const i = selectedFilters.length; because you are going to make a single insertion in the array. Previously, the line selectedFilters[i] = selectedItem; enclosed in a all the loops suggested you would insert multiple values but all in the same position, so as to leave only the last one. A simple .push is enough to append to the end.


问:
eslint why does my plugin show Definition for rule was not found?
my plugin

@bluelovers/eslint-plugin
https://github.com/bluelovers/ws-node-bluelovers/tree/master/packages/eslint-plugin

my base config
https://github.com/bluelovers/ws-node-bluelovers/blob/master/packages/eslintrc/.eslintrc.json

runtime user config

```<code>{
  "extends": [
    "bluelovers"
  ]
}
</code>```

i can type in user repo

```<code>eslint --print-config .
</code>```

this can show config and didn't error, i also see my plugin config inside the list

```<code>   "@bluelovers/no-irregular-whitespace": [
      "error",
      {
        "skipComments": true,
        "skipStrings": false,
        "skipTemplates": false,
        "skipRegExps": false,
        "ignores": [
          "　"
        ]
      }
    ],

</code>```

but when i type eslint index.ts, it show error

```<code>   1:1   error    Definition for rule '@bluelovers/no-irregular-whitespace' was not found  @bluelovers/no-irregular-whitespace
</code>```

index.ts

```<code>export const r = /[ \t\uFEFF\xA0　]+$/;

const IRREGULAR_WHITESPACE = /[\f\v               　]+/mgu;
</code>```

how can i fix this??

答:
I think the key missing piece is no "plugins" section in config.

Why are you extending from "bluelovers"? Do you have a shared config published? It seems like you're working on a plugin, not a config.

You're then using a rule "@bluelovers/no-irregular-whitespace", with a leading @.

If your plugin is published as "@bluelovers/eslint-plugin", you should try something like this:

```<code>{
    "plugins": ["@bluelovers"],
    "extends": ["@bluelovers"], // Assuming you have @bluelovers/eslint-config published, otherwise this might look different or could be skipped
    "rules": {
        "@bluelovers/no-irregular-whitespace": ["error"]
    }
}
</code>```

Body:
my plugin

@bluelovers/eslint-plugin
https://github.com/bluelovers/ws-node-bluelovers/tree/master/packages/eslint-plugin

my base config
https://github.com/bluelovers/ws-node-bluelovers/blob/master/packages/eslintrc/.eslintrc.json

runtime user config

{
  "extends": [
    "bluelovers"
  ]
}

i can type in user repo

eslint --print-config .

this can show config and didn't error, i also see my plugin config inside the list

   "@bluelovers/no-irregular-whitespace": [
      "error",
      {
        "skipComments": true,
        "skipStrings": false,
        "skipTemplates": false,
        "skipRegExps": false,
        "ignores": [
          "　"
        ]
      }
    ],

but when i type eslint index.ts, it show error

   1:1   error    Definition for rule '@bluelovers/no-irregular-whitespace' was not found  @bluelovers/no-irregular-whitespace

index.ts

export const r = /[ \t\uFEFF\xA0　]+$/;

const IRREGULAR_WHITESPACE = /[\f\v               　]+/mgu;

how can i fix this??

Body:
I think the key missing piece is no "plugins" section in config.

Why are you extending from "bluelovers"? Do you have a shared config published? It seems like you're working on a plugin, not a config.

You're then using a rule "@bluelovers/no-irregular-whitespace", with a leading @.

If your plugin is published as "@bluelovers/eslint-plugin", you should try something like this:

{
    "plugins": ["@bluelovers"],
    "extends": ["@bluelovers"], // Assuming you have @bluelovers/eslint-config published, otherwise this might look different or could be skipped
    "rules": {
        "@bluelovers/no-irregular-whitespace": ["error"]
    }
}


问:
learn python the hard way exercise 35 help
for some reason when the game reaches gold room it doesn't work right. when i enter any number i get the death message 'man, learn to type a number'

thanks

```<code>from sys import exit

def gold_room():
    print 'this room is full of gold, how much do you take?'

    next = raw_input('> ')
    if '0' in next or '1' in next:
        how_much = int(next)
    else:
        dead('man, learn how to type a number')

    if how_much < 50:
        print 'nice! your not too greedy. you win!'
        exit(0)
    else:
        dead('you greedy bastard!')

def bear_room():
    print 'there is a bear here.'
    print 'the bear has a bunch of honey'
    print 'the fat bear is in fromt of another door'
    print 'how are you going to move the bear?'
    bear_moved = False

    while True:
        next = raw_input('> ')

        if next == 'take honey':
            dead('the bear looks at you then pimp slaps you in the face')
        elif next == 'taunt bear' and not bear_moved:
            print 'the bear has moved from the door now. you can go through.'
            bear_moved = True
        elif next == 'taunt bear' and bear_moved:
            dead('the bear gets pissed off and chews your crotch off')
        elif next == 'open door' and bear_moved:
            gold_room()
        else:
            print 'i have no idea what that means.'

def bolofumps_room():
    print 'here you see the great evil bolofump'
    print 'he, it whatever stares at you and you go insane'
    print 'do you flee for your life or eat your head?'

    next = raw_input('> ')
    if 'flee' in next:
        start()
    elif 'head' in next:
        dead('well, that was tasty!')
    else:
        bolofumps_room()

def dead(why):
    print why, 'good job!'
    exit(0)

def start():
    print 'you are in a dark room'
    print 'there is a door to your left and right'
    print 'which one do you take?'

    next = raw_input('> ')

    if next == 'left':
        bear_room()
    elif next == 'right':
        bolofumps_room()
    else:
        dead('you stumble around the room until you starve to death')

start()
</code>```

EDIT: typing one works, but 2 does not

答:
I could be missing something but this is how I changed it. Less code and runs good.</p>

```<code>Def gold_room():
       Print("This room is full of gold. How much do you take?")

       choice = input('  ')
       next = int(choice)
       If next > 50:
            dead("Man, learn to type a number.")
       else:
             print("your not greedy. Good job!")
             exit(0)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
for some reason when the game reaches gold room it doesn't work right. when i enter any number i get the death message 'man, learn to type a number'

thanks

from sys import exit

def gold_room():
    print 'this room is full of gold, how much do you take?'

    next = raw_input('> ')
    if '0' in next or '1' in next:
        how_much = int(next)
    else:
        dead('man, learn how to type a number')

    if how_much < 50:
        print 'nice! your not too greedy. you win!'
        exit(0)
    else:
        dead('you greedy bastard!')

def bear_room():
    print 'there is a bear here.'
    print 'the bear has a bunch of honey'
    print 'the fat bear is in fromt of another door'
    print 'how are you going to move the bear?'
    bear_moved = False

    while True:
        next = raw_input('> ')

        if next == 'take honey':
            dead('the bear looks at you then pimp slaps you in the face')
        elif next == 'taunt bear' and not bear_moved:
            print 'the bear has moved from the door now. you can go through.'
            bear_moved = True
        elif next == 'taunt bear' and bear_moved:
            dead('the bear gets pissed off and chews your crotch off')
        elif next == 'open door' and bear_moved:
            gold_room()
        else:
            print 'i have no idea what that means.'

def bolofumps_room():
    print 'here you see the great evil bolofump'
    print 'he, it whatever stares at you and you go insane'
    print 'do you flee for your life or eat your head?'

    next = raw_input('> ')
    if 'flee' in next:
        start()
    elif 'head' in next:
        dead('well, that was tasty!')
    else:
        bolofumps_room()

def dead(why):
    print why, 'good job!'
    exit(0)

def start():
    print 'you are in a dark room'
    print 'there is a door to your left and right'
    print 'which one do you take?'

    next = raw_input('> ')

    if next == 'left':
        bear_room()
    elif next == 'right':
        bolofumps_room()
    else:
        dead('you stumble around the room until you starve to death')

start()

EDIT: typing one works, but 2 does not

Body:
I could be missing something but this is how I changed it. Less code and runs good.

Def gold_room():
       Print("This room is full of gold. How much do you take?")

       choice = input('  ')
       next = int(choice)
       If next > 50:
            dead("Man, learn to type a number.")
       else:
             print("your not greedy. Good job!")
             exit(0)


问:
In Angular 7, why HttpClient.post is getting executed twice even if subscribed only once?
Only once I am subscribed to this observable from HttpClient.post. However, post request is getting executed twice, and thus adding same record twice. Note that all debug log statement shows, that only successful response from subscribe function is being printed (and executed) twice.

```<code>  addTemplate(template) {
      console.log('In addTemplate');
      let authHeaders = new HttpHeaders();
      authHeaders = authHeaders.set('Authorization', 'Bearer ' + localStorage.getItem('id_token'));
      authHeaders = authHeaders.set('Content-Type', 'application/json');
      const httpOptions = {
        headers: authHeaders,
        observe: 'body' as 'body',
        responseType: 'json' as 'json'
      };
      console.log('^^^^^ addTemplate  Service Header  = ', httpOptions);

      this.httpClient.post<any>(this.constants.URL + 'addTemplate', JSON.stringify(template),
        {headers: authHeaders}).pipe().subscribe(
        (response) => {  console.log ('Added Template Successfully -->', response)},
        (error) => { console.error('Got an Error while adding Template ->', error) }
      );
   }
</code>```

Above function is called from here:

```<code> saveTemplate(){
      const saveTemplate : ITemplate = Object.assign({}, this.templateForm.value);
      console.log('Adding new Template with name -->', saveTemplate.name);
      this.templateService.addTemplate(saveTemplate);
  }
</code>```

Here's the image of browser console:

Here's the image of browser's Network tab:

As you can see HttpClient.post call to addTemplate REST API is being called twice. Even if post call is subscribed only once and there is no other place it's being called from. Call log

```<code>  console.log('^^^^^ addTemplate  Service Header  = ', httpOptions);
</code>```

in addTemplate function in service is executed once but log (response) => {  console.log ('Added Template Successfully -->', response)},  is executed twice.

I did try changing call to httpClient.post to use share()  and publishLast().refCount() but nothing worked. Maybe I didn't do it right.

Using Angular 7.2 with rxjs 6.5.2 and rxjs/compat (Yes, I do have some legacy code that needs to upgrade to latest)

答:
It was my mistake. The form was calling saveTemplate() as well as button... So it was being called twice.

```<code><form [formGroup]="templateForm" autocomplete="off" novalidate (ngSubmit)="saveTemplate()">
</code>```

Button:

```<code>          <button mat-button mat-raised-button color="primary"
              type="submit" (click)="saveTemplate()" [disabled]="templateForm.pristine">Save
</code>```

Thanks @CaptainFindus, @Alexander Staroselsky and all for your help

Body:
Only once I am subscribed to this observable from HttpClient.post. However, post request is getting executed twice, and thus adding same record twice. Note that all debug log statement shows, that only successful response from subscribe function is being printed (and executed) twice.

  addTemplate(template) {
      console.log('In addTemplate');
      let authHeaders = new HttpHeaders();
      authHeaders = authHeaders.set('Authorization', 'Bearer ' + localStorage.getItem('id_token'));
      authHeaders = authHeaders.set('Content-Type', 'application/json');
      const httpOptions = {
        headers: authHeaders,
        observe: 'body' as 'body',
        responseType: 'json' as 'json'
      };
      console.log('^^^^^ addTemplate  Service Header  = ', httpOptions);

      this.httpClient.post<any>(this.constants.URL + 'addTemplate', JSON.stringify(template),
        {headers: authHeaders}).pipe().subscribe(
        (response) => {  console.log ('Added Template Successfully -->', response)},
        (error) => { console.error('Got an Error while adding Template ->', error) }
      );
   }

Above function is called from here:

 saveTemplate(){
      const saveTemplate : ITemplate = Object.assign({}, this.templateForm.value);
      console.log('Adding new Template with name -->', saveTemplate.name);
      this.templateService.addTemplate(saveTemplate);
  }

Here's the image of browser console:

Here's the image of browser's Network tab:

As you can see HttpClient.post call to addTemplate REST API is being called twice. Even if post call is subscribed only once and there is no other place it's being called from. Call log

  console.log('^^^^^ addTemplate  Service Header  = ', httpOptions);

in addTemplate function in service is executed once but log (response) => {  console.log ('Added Template Successfully -->', response)},  is executed twice.

I did try changing call to httpClient.post to use share()  and publishLast().refCount() but nothing worked. Maybe I didn't do it right.

Using Angular 7.2 with rxjs 6.5.2 and rxjs/compat (Yes, I do have some legacy code that needs to upgrade to latest)

Body:
It was my mistake. The form was calling saveTemplate() as well as button... So it was being called twice.

<form [formGroup]="templateForm" autocomplete="off" novalidate (ngSubmit)="saveTemplate()">

Button:

          <button mat-button mat-raised-button color="primary"
              type="submit" (click)="saveTemplate()" [disabled]="templateForm.pristine">Save

Thanks @CaptainFindus, @Alexander Staroselsky and all for your help


问:
XSL - Remove non breaking space
In my XSL implementation (2.0), I tried using the below statement to remove all the spaces & non breaking spaces  within a text node. It works for spaces only but not for non breaking spaces whose ASCII codes are,                                etc. I am using SAXON processor for execution.

Current XSL code:

```<code>translate(normalize-space($text-nodes[1]),  ' ' , '' ))
</code>```

How can I have them removed. Please share your thoughts.

答:
Those codes are Unicode, not ASCII (for the most part), so you should probably use the replace function with a regex containing the Unicode separator character class:

```<code>replace($text-nodes[1], '\p{Z}+', '')
</code>```

In more detail:

The regex \p{Z}+ matches one or more characters that are in the "separator" category in Unicode. \p{} is the category escape sequence, which matches a single character in the category specified within the curly braces. Z specifies the "separator" category (which includes various kinds of whitespace). + means "match the preceding regex one or more times". The replace function returns a version of its first argument with all non-overlapping substrings matching its second argument replaced with its third argument. So this returns a version of $text-nodes[1] with all sequences of separator characters replaced with the empty string, i.e. removed.

Title: XSL - Remove non breaking space

Body:
In my XSL implementation (2.0), I tried using the below statement to remove all the spaces & non breaking spaces  within a text node. It works for spaces only but not for non breaking spaces whose ASCII codes are,                                etc. I am using SAXON processor for execution.

Current XSL code:

translate(normalize-space($text-nodes[1]),  ' ' , '' ))

How can I have them removed. Please share your thoughts.

Body:
Those codes are Unicode, not ASCII (for the most part), so you should probably use the replace function with a regex containing the Unicode separator character class:

replace($text-nodes[1], '\p{Z}+', '')

In more detail:

The regex \p{Z}+ matches one or more characters that are in the "separator" category in Unicode. \p{} is the category escape sequence, which matches a single character in the category specified within the curly braces. Z specifies the "separator" category (which includes various kinds of whitespace). + means "match the preceding regex one or more times". The replace function returns a version of its first argument with all non-overlapping substrings matching its second argument replaced with its third argument. So this returns a version of $text-nodes[1] with all sequences of separator characters replaced with the empty string, i.e. removed.


问:
Django "ValueError: embedded null byte"
I just installed Django and changed the DATABASES from sqlite3 to mysql in settings.py, but when I runserver, "ValueError: embedded null byte" occurs occasionally.
What should I do?

Python 3.6.1

Django version 2.2.1

```<code>(myproject) bash-3.2$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute
    super().execute(*args, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle
    self.run(**options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 577, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 562, in start_django
    reloader.run(django_main_thread)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 280, in run
    self.run_loop()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 286, in run_loop
    next(ticker)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 326, in tick
    for filepath, mtime in self.snapshot_files():
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 342, in snapshot_files
    for file in self.watched_files():
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 241, in watched_files
    yield from iter_all_python_module_files()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files
    return iter_modules_and_files(modules, frozenset(_error_files))
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 132, in iter_modules_and_files
    results.add(path.resolve().absolute())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 1122, in resolve
    s = self._flavour.resolve(self, strict=strict)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 349, in resolve
    return _resolve(base, str(path)) or sep
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 331, in _resolve
    target = accessor.readlink(newpath)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 443, in readlink
    return os.readlink(path)
ValueError: embedded null byte
</code>```

答:
this is my mysql setting.

```<code> DATABASES = {
       'default': {
         'ENGINE': 'django.db.backends.mysql',
         'NAME': 'novoair',
         'USER': 'root',
         'PASSWORD': 'root@123',
         'HOST': 'localhost',
         'PORT': '3306',
     },
 }
</code>```

user name password host port set to your according

Title: Django "ValueError: embedded null byte"

Body:
I just installed Django and changed the DATABASES from sqlite3 to mysql in settings.py, but when I runserver, "ValueError: embedded null byte" occurs occasionally.
What should I do?

Python 3.6.1

Django version 2.2.1

(myproject) bash-3.2$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute
    super().execute(*args, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle
    self.run(**options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run
    autoreload.run_with_reloader(self.inner_run, **options)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 577, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 562, in start_django
    reloader.run(django_main_thread)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 280, in run
    self.run_loop()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 286, in run_loop
    next(ticker)
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 326, in tick
    for filepath, mtime in self.snapshot_files():
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 342, in snapshot_files
    for file in self.watched_files():
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 241, in watched_files
    yield from iter_all_python_module_files()
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files
    return iter_modules_and_files(modules, frozenset(_error_files))
  File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 132, in iter_modules_and_files
    results.add(path.resolve().absolute())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 1122, in resolve
    s = self._flavour.resolve(self, strict=strict)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 349, in resolve
    return _resolve(base, str(path)) or sep
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 331, in _resolve
    target = accessor.readlink(newpath)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/pathlib.py", line 443, in readlink
    return os.readlink(path)
ValueError: embedded null byte

Body:
this is my mysql setting.

 DATABASES = {
       'default': {
         'ENGINE': 'django.db.backends.mysql',
         'NAME': 'novoair',
         'USER': 'root',
         'PASSWORD': 'root@123',
         'HOST': 'localhost',
         'PORT': '3306',
     },
 }

user name password host port set to your according


答:
If I'm not misunderstanding your problem, you should just set width to 100%. I tried to edit it on the link you posted and it seems to fit the width of the screen well.</p>

```<code><div class="entry-content">
<blockquote class="wp-embedded-content" data-secret="paBu4nyBJV">.
<p>. <a href="https://tbwdrawingprize.artopps.co.uk/online-
entry/">Online Entry</a></p></blockquote>
<p><iframe title="“Online Entry” — TBW Drawing
Prize" class="wp-embedded-content" sandbox="allow-scripts"
security="restricted" style="position: absolute; clip: rect(1px,
1px, 1px, 1px);" src="https://tbwdrawingprize.artopps.co.uk/online-
entry/embed/#?secret=paBu4nyBJV" data-secret="paBu4nyBJV"
width="100%" height="338" frameborder="0" marginwidth="0"
marginheight="0" scrolling="no"></iframe></p>
<p> </p>
<p><embed style="width: 100%; height: 300px;"
</code>```

Title: Stretching content to fit desktop page using css

Body:
If I'm not misunderstanding your problem, you should just set width to 100%. I tried to edit it on the link you posted and it seems to fit the width of the screen well.

<div class="entry-content">
<blockquote class="wp-embedded-content" data-secret="paBu4nyBJV">.
<p>. <a href="https://tbwdrawingprize.artopps.co.uk/online-
entry/">Online Entry</a></p></blockquote>
<p><iframe title="&#8220;Online Entry&#8221; &#8212; TBW Drawing
Prize" class="wp-embedded-content" sandbox="allow-scripts"
security="restricted" style="position: absolute; clip: rect(1px,
1px, 1px, 1px);" src="https://tbwdrawingprize.artopps.co.uk/online-
entry/embed/#?secret=paBu4nyBJV" data-secret="paBu4nyBJV"
width="100%" height="338" frameborder="0" marginwidth="0"
marginheight="0" scrolling="no"></iframe></p>
<p>&nbsp;</p>
<p><embed style="width: 100%; height: 300px;"


问:
Error Number: 1066 Not unique table/alias: 'tb_perumahan' in codeigniter
So I want to make a website that selling houses, but when I tried to join two tables with a filter but it came to this error...

I've tried to swap the tables but it still error.

$this->db->select('*');
      $this->db->from('tb_rumah');
      $this->db->join('tb_perumahan', 'tb_perumahan.id_perumahan = tb_rumah.id_perumahan');
      $perumahan = $this->db->get_where('tb_perumahan', ['id_perumahan' => $id_rumah])->row_array();
```

So, can anyone help me solve this error?

答:
By using a get_where() method after a join(), you are selecting from the same table twice, and using the same name for each, which I suppose you're not intend to.

Try to change the get_where() method to where() and change it's parameters :

```<code>$this->db->select('*');
$this->db->from('tb_rumah');
$this->db->join('tb_perumahan', 'tb_perumahan.id_perumahan = tb_rumah.id_perumahan');
$perumahan = $this->db->where('tb_perumahan.id_perumahan', $id_rumah)->row_array();
</code>```

Body:
So I want to make a website that selling houses, but when I tried to join two tables with a filter but it came to this error...

I've tried to swap the tables but it still error.

$this->db->select('*');
      $this->db->from('tb_rumah');
      $this->db->join('tb_perumahan', 'tb_perumahan.id_perumahan = tb_rumah.id_perumahan');
      $perumahan = $this->db->get_where('tb_perumahan', ['id_perumahan' => $id_rumah])->row_array();

So, can anyone help me solve this error?

Body:
By using a get_where() method after a join(), you are selecting from the same table twice, and using the same name for each, which I suppose you're not intend to.

Try to change the get_where() method to where() and change it's parameters :

$this->db->select('*');
$this->db->from('tb_rumah');
$this->db->join('tb_perumahan', 'tb_perumahan.id_perumahan = tb_rumah.id_perumahan');
$perumahan = $this->db->where('tb_perumahan.id_perumahan', $id_rumah)->row_array();


问:
Ember : debounce called multiple times on scroll event listener
I added a debounce method inside a scroll event listener. Something like this.

```<code>$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});
</code>```

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.

答:
Your problem is that you pass an anonymous function to debounce:

```<code>debounce(this, ()=> {
  console.log('debounce called);
},1000);
</code>```

this is problematic because you recreate this function every time when you cann debounce! So you never call debounce twice with the same function, which is necessary for it to do anything different from a setTimeout.

So you should create/save this function to somewhere and then call it like

```<code>debounce(this, this.doSomething, 1000);
</code>```

Make sure you always pass exactly the same function. Just because 2 functions do the same thing does not mean its the same function instance.

Body:
I added a debounce method inside a scroll event listener. Something like this.

$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});

When I do the scroll on $group the debounce is also called the same number of times the scroll event called. I don't know where is the loophole in this thing.

For example, if 5 times the scroll event printed then debounce called is also called 5 times.

This is the link for ember debounce documentation.

Body:
Your problem is that you pass an anonymous function to debounce:

debounce(this, ()=> {
  console.log('debounce called);
},1000);

this is problematic because you recreate this function every time when you cann debounce! So you never call debounce twice with the same function, which is necessary for it to do anything different from a setTimeout.

So you should create/save this function to somewhere and then call it like

debounce(this, this.doSomething, 1000);

Make sure you always pass exactly the same function. Just because 2 functions do the same thing does not mean its the same function instance.


问:
Maven build no main manifest attribute
I'm building a small app with Maven that has dependencies and is an executable jar file.

Here is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        com.company.Main
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

The build completes with no issues but when executing the jar it writes

no main manifest attribute, in local maven repo / my jar.

I sought aid at the docs and Baeldung too to no avail.

I seek assistance to make the jar include its dependencies and is executable at the same time.

Edit:

I updated my pom to use the jar and the dependencies plugins instead of the assembly. Here is the updated pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.company.Main
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                ${project.build.directory}/libs
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

But I get a NoClassDefFoundError when running it:

C:\Users\myusername\Documents\Commands>call java -jar
  D:.m2\repository\com\company\site-downloader\1.0.0\site-downloader-1.0.0.jar
  -9gag https://9gag.com/gag/arGEvRX?ref C:\Users\myusername\Documents\sites\data\android Error: A JNI error
  has occurred, please check your installation and try again Exception
  in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/WebDriver
          at java.lang.Class.getDeclaredMethods0(Native Method)
          at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
          at java.lang.Class.privateGetMethodRecursive(Unknown Source)
          at java.lang.Class.getMethod0(Unknown Source)
          at java.lang.Class.getMethod(Unknown Source)
          at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
          at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by: java.lang.ClassNotFoundException:
  org.openqa.selenium.WebDriver
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          ... 7 more

答:
To create an executable jar, you have to use the following maven jar plugin. I provide below the code snippet.

```<code><plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                your main class
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
</code>```

For more details, refer below the github link to get an idea of how to create executable/runnable jar.

https://github.com/debjava/runnableJar

As per docs, Maven Assembly Plugin for Maven is primarily intended to
  allow users to aggregate the project output along with its
  dependencies, modules, site documentation, and other files into a
  single distributable archive.

Refer below the details of Maven Assembly plugin.
http://maven.apache.org/plugins/maven-assembly-plugin/

Title: Maven build no main manifest attribute

Body:
I'm building a small app with Maven that has dependencies and is an executable jar file.

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        com.company.Main
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

The build completes with no issues but when executing the jar it writes

no main manifest attribute, in local maven repo / my jar.

I sought aid at the docs and Baeldung too to no avail.

I seek assistance to make the jar include its dependencies and is executable at the same time.

Edit:

I updated my pom to use the jar and the dependencies plugins instead of the assembly. Here is the updated pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company</groupId>
    <artifactId>site-downloader</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>com.company.siteripper</groupId>
            <artifactId>common-interfaces</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                com.company.Main
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                ${project.build.directory}/libs
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

But I get a NoClassDefFoundError when running it:

C:\Users\myusername\Documents\Commands>call java -jar
  D:.m2\repository\com\company\site-downloader\1.0.0\site-downloader-1.0.0.jar
  -9gag https://9gag.com/gag/arGEvRX?ref C:\Users\myusername\Documents\sites\data\android Error: A JNI error
  has occurred, please check your installation and try again Exception
  in thread "main" java.lang.NoClassDefFoundError:
  org/openqa/selenium/WebDriver
          at java.lang.Class.getDeclaredMethods0(Native Method)
          at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
          at java.lang.Class.privateGetMethodRecursive(Unknown Source)
          at java.lang.Class.getMethod0(Unknown Source)
          at java.lang.Class.getMethod(Unknown Source)
          at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
          at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by: java.lang.ClassNotFoundException:
  org.openqa.selenium.WebDriver
          at java.net.URLClassLoader.findClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
          at java.lang.ClassLoader.loadClass(Unknown Source)
          ... 7 more

Body:
To create an executable jar, you have to use the following maven jar plugin. I provide below the code snippet.

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>
                                your main class
                            </mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

For more details, refer below the github link to get an idea of how to create executable/runnable jar.

https://github.com/debjava/runnableJar

As per docs, Maven Assembly Plugin for Maven is primarily intended to
  allow users to aggregate the project output along with its
  dependencies, modules, site documentation, and other files into a
  single distributable archive.

Refer below the details of Maven Assembly plugin.
http://maven.apache.org/plugins/maven-assembly-plugin/


问:
How to check if the system has enough resources for another thread?
I'm writing a c++ function for merge sort using multithreading with the #include <thread> library and i don't know how to limit the number of threads such that the programs doesn't crash.

I tried putting the declaration of a the new thread in a try block but then i have run out of scope. The following is the code of the MergeSort function

```<code>vector < int > V;

// st == left margin of interval
// dr == right margin of interval
void MergeSort( int st, int dr ) {

    static int limit = 0;

    int mid = ( st + dr ) / 2;

    if ( st >= dr ) {
        return ;
    }

    if ( limit > 200 ) {   // i tried to manually limit the number of threads
        MergeSort( st, mid );
        MergeSort( mid + 1, dr );
        Merge( st, dr );                  // this merge the 2 sub arrays
        return ;
    }

    thread t1 { MergeSort, st, mid };
    thread t2 { MergeSort, mid + 1, dr };

    limit += 2;

    t1.join();
    t2.join();

    limit -= 2;

    Merge( st, dr );

}
</code>```

答:
I suspect that due to the following two bugs, your program is spawning far more than 200 threads.

First, your program is undefined behavior, since you are changing limit from different threads at the same time without any synchronization mechanism, which is illegal. The easiest way to avoid this is to use atomic:

static std::atomic<int> limit = 0;
```

Second, you should do the limit updating before you spawn the new threads. Otherwise, the new threads might themselves spawn new threads, and so on, and so on, before you ever run limit += 2 in any of them. In general the order in which different threads run in C++ is not guaranteed.

Body:
I'm writing a c++ function for merge sort using multithreading with the #include <thread> library and i don't know how to limit the number of threads such that the programs doesn't crash.

I tried putting the declaration of a the new thread in a try block but then i have run out of scope. The following is the code of the MergeSort function

vector < int > V;

// st == left margin of interval
// dr == right margin of interval
void MergeSort( int st, int dr ) {

    static int limit = 0;

    int mid = ( st + dr ) / 2;

    if ( st >= dr ) {
        return ;
    }

    if ( limit > 200 ) {   // i tried to manually limit the number of threads
        MergeSort( st, mid );
        MergeSort( mid + 1, dr );
        Merge( st, dr );                  // this merge the 2 sub arrays
        return ;
    }

    thread t1 { MergeSort, st, mid };
    thread t2 { MergeSort, mid + 1, dr };

    limit += 2;

    t1.join();
    t2.join();

    limit -= 2;

    Merge( st, dr );

}

Body:
I suspect that due to the following two bugs, your program is spawning far more than 200 threads.

First, your program is undefined behavior, since you are changing limit from different threads at the same time without any synchronization mechanism, which is illegal. The easiest way to avoid this is to use atomic:

static std::atomic<int> limit = 0;

Second, you should do the limit updating before you spawn the new threads. Otherwise, the new threads might themselves spawn new threads, and so on, and so on, before you ever run limit += 2 in any of them. In general the order in which different threads run in C++ is not guaranteed.


问:
jQuery override form submit not working when submit called by javascript on a element
I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?

答:
This worked for me:

Make a dummy button, hide the real submit with the name submit,

and then:

```<code>$("#mySubmit").click(function(){
    $("#submit").trigger("click"); });
</code>```

set an event handler on your dummy to trigger click on the form submit button. let the browser figure out how to submit the form... This way you don't need to preventDefault on the form submit which is where the trouble starts.

This seemed to work around the problem.

LastEditorDisplayName: JasonBunting

Body:
This worked for me:

Make a dummy button, hide the real submit with the name submit,

and then:

$("#mySubmit").click(function(){
    $("#submit").trigger("click"); });

set an event handler on your dummy to trigger click on the form submit button. let the browser figure out how to submit the form... This way you don't need to preventDefault on the form submit which is where the trouble starts.

This seemed to work around the problem.


问:
How to include storage service account key in function
I'm trying to include service account key into my storage function to be able to get long lived signed url by following out of date example here

https://github.com/firebase/functions-samples/blob/b404482342906ee1b46dddb4c75667685ab098a1/generate-thumbnail/functions/index.js#L21

I have downloaded my key from IAM which is in JSON format. I have tried to save it right next to my function

-functions/storage/resizeProfileImg.js

-functions/storage/service-account-credentials.json

-functions/index.js

-functions/admin.js

where resizeProfileImg.js is my function and call it like this

```<code>const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: './service-account-credentials.json'})
</code>```

but after deployment when the function is triggered then I get an error

Error: ENOENT: no such file or directory, open '/srv/service-account-credentials.json'

I have even tried to add it in constant like this

```<code>const serviceAccountCredentials = require('./accountKey/service-account-credentials.json')

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: serviceAccountCredentials})
</code>```

but then I get an error

TypeError: Path must be a string. Received { type: 'service_account',...

Any idea how to do this properly

答:
In Cloud Functions, the current directory . isn't where your source file is located.  It's where the functions folder was deployed.  Since your credentials file is in a subdirectory called "storage", you will need to use that in the path.

```<code>const serviceAccountCredentials = require('./storage/service-account-credentials.json')
</code>```

Body:
I'm trying to include service account key into my storage function to be able to get long lived signed url by following out of date example here

https://github.com/firebase/functions-samples/blob/b404482342906ee1b46dddb4c75667685ab098a1/generate-thumbnail/functions/index.js#L21

I have downloaded my key from IAM which is in JSON format. I have tried to save it right next to my function

-functions/storage/resizeProfileImg.js

-functions/storage/service-account-credentials.json

-functions/index.js

-functions/admin.js

where resizeProfileImg.js is my function and call it like this

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: './service-account-credentials.json'})

but after deployment when the function is triggered then I get an error

Error: ENOENT: no such file or directory, open '/srv/service-account-credentials.json'

I have even tried to add it in constant like this

const serviceAccountCredentials = require('./accountKey/service-account-credentials.json')

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({ projectId: projectId ,keyFilename: serviceAccountCredentials})

but then I get an error

TypeError: Path must be a string. Received { type: 'service_account',...

Any idea how to do this properly

Body:
In Cloud Functions, the current directory . isn't where your source file is located.  It's where the functions folder was deployed.  Since your credentials file is in a subdirectory called "storage", you will need to use that in the path.

const serviceAccountCredentials = require('./storage/service-account-credentials.json')


问:
how to tell org-mode to embed my css file on HTML export?
What's the best way to instruct org-mode to embed all the css from my stylesheet into a single HTML file, rather than including a link to it as it does by default?</p>

答:
There is another solution for that.

In your org file, you can use #+SETUPFILE: file, that enables additional in-buffer settings:

```<code>#+SETUPFILE: style.css.org
</code>```

And in the file style.css.org, you can have:

```<code>#+OPTIONS: org-html-head-include-default-style:nil

#+HTML_HEAD: <style type="text/css">
#+HTML_HEAD:   ...your CSS here...
#+HTML_HEAD: </style>
</code>```

The content of style.css.org is:

org-html-head-include-default-style:nil tells to not use the default style.

...your CSS here... is to be replaced by your CSS code. Every line must be prefixed with #+HTML_HEAD:.

The advantage of this solution is that you can have a style.css.org per file. I personally use the trick to have one style.css.org per directory of org files.

Credit goes to  Paul Provost.

Note that single line CSS is much more performance efficient here than multiple lines CSS.

Body:
There is another solution for that.

In your org file, you can use #+SETUPFILE: file, that enables additional in-buffer settings:

#+SETUPFILE: style.css.org

And in the file style.css.org, you can have:

#+OPTIONS: org-html-head-include-default-style:nil

#+HTML_HEAD: <style type="text/css">
#+HTML_HEAD:   ...your CSS here...
#+HTML_HEAD: </style>

The content of style.css.org is:

org-html-head-include-default-style:nil tells to not use the default style.

...your CSS here... is to be replaced by your CSS code. Every line must be prefixed with #+HTML_HEAD:.

The advantage of this solution is that you can have a style.css.org per file. I personally use the trick to have one style.css.org per directory of org files.

Credit goes to  Paul Provost.

Note that single line CSS is much more performance efficient here than multiple lines CSS.