问:
Iterate over PDO::FETCH_GROUP array to output results by category
I am sure this is a very simple problem that I seem unable to get my head around. I want to display a list of links grouped on screen into their respective categories. I'm using bootstrap and the idea is to have each link category outputted in its own column with the links under the heading:

For example:

---Cat 1 ------- Cat 2 ---

---Link 1 ------ Link 3 ---

---Link 2 ------ Link 4 ---

I have two tables:

The first 'links' has the columns linkId, categoryId, linkTitle, linkDescription, linkUrl etc.

The second 'linkcategories' has the columns categoryId, categoryTitle, categoryDescription etc.

I am using PDO and using the following to get the data from the database:

```<code>public function getLinkCategories() {
  $this->db->query('SELECT categoryTitle, linkTitle, linkDescription, linkUrl
                    FROM link
                    INNER JOIN linkcategories ON linkCategories.categoryId = link.categoryId
                    WHERE link.marked_for_delete != 1');
  $results = $this->db->resultSetGrouped();
  return $results;
}
</code>```

I am then using the code below to pass the results back, spcifically I read that I should use PDO::FETCH_GROUP so that I can return rows into a nested array, where indexes will be unique values from the first column, and values will be arrays similar to ones returned by regular fetchAll(). So using:

```<code>//get results set as array of objects - grouped
public function resultSetGrouped() {
  $this->execute();
  return $this->statement->fetchAll(PDO::FETCH_GROUP);
}
</code>```

My page is loaded with the following and I pass the data to the view:

```<code>public function index() {
  //get the links
  $links = $this->linkModel->getLinkCategories();
  $pageData = ['title' => 'Links • BM Intranet'];
  $data = ['pageData' => $pageData, 'linkCategories' => $links];
  $this->view('links/index', $data);
}
</code>```

I think I should be able to use a foreach loop to display the results on the page but can't get my head around naming the right parts. This is what is returned in $data.

```<code>Array
(
[pageData] => Array
    (
        [title] => Links • Intranet
    )

[linkCategories] => Array
    (
        [Unsorted] => Array //Unsorted is the category name
            (
                [0] => Array
                    (
                        [linkTitle] => a link title
                        [0] => a link title
                        [linkDescription] => This is an example of a link you can store. This is the external website
                        [1] => This is an example of a link you can store. This is the external website
                        [linkUrl] => https://www.asbcdef.co.uk/
                        [2] => https://www.abcdef.co.uk/
                    )

                [1] => Array
                    (
                        [linkTitle] => People
                        [0] => People
                        [linkDescription] => This is another link
                        [1] => This is another link
                        [linkUrl] => https://www.efgjk.co.uk/people/
                        [2] => https://www.efgjk.co.uk/people/
                    )

            )

    )

)
</code>```

So the bit I am stuck on is taking the returned results above and making it display on the page like...

---Cat 1 ------- Cat 2 ---

---Link 1 ------ Link 3 ---

---Link 2 ------ Link 4 ---

I have so far...

```<code>foreach($data as $link) : ?>
<div class="col-lg-6 col-md-12 mb-5">
<div class="row">
  <div class="col lead border-bottom mb-2">
    <i class="fas fa-folder text-secondary"></i> <?php echo $link->linkCategories; ?>
  </div>
</div>
<div class="row">
  <div class="col">
    <a target="_blank" class="text-danger" href="<?php echo $category->url; ?>"><?php echo $category->linkTitle; ?></a>
    <span class="float-right text-secondary">Hits: <?php echo $category->hits; ?></span>
    <p mt-0>
      <?php echo $category->linkDescription; ?>
    </p>
  </div>
</div>
</code>```

But this is not working as the properties are incorrect.

So it looks like I can use $link[0]['linkTitle'] to get the data from the array - so could foreach through that I think. What I don't know how to do now is get the category name (which equals - Unsorted - in this case) and have the links related to it underneath

答:
Based on your current data groupings, in order to iterate over the groups and retrieve the category names, you would need to implement three foreach($array as $index => $values) iterations.

$data = array(
    'pageData' => array(
        'title' => 'Links • Intranet',
    ),
    'linkCategories' => array(
        'Unsorted' => array(
            array(
                'linkTitle' => 'a link title',
                0 => 'a link title',
                'linkDescription' => 'This is an example of a link you can store. This is the external website',
                1 => 'This is an example of a link you can store. This is the external website',
                'linkUrl' => 'https://www.asbcdef.co.uk/',
                2 => 'https://www.abcdef.co.uk/',
            ),
            array(
              'linkTitle' => 'People',
                0 => 'People',
                'linkDescription' => 'This is another link',
                1 => 'This is another link',
                'linkUrl' => 'https://www.efgjk.co.uk/people/',
                2 => 'https://www.efgjk.co.uk/people/',
            ),
        ),
        'Cat 2' => array(
            array(
              'linkTitle' => 'People',
                0 => 'People',
                'linkDescription' => 'This is another link',
                1 => 'This is another link',
                'linkUrl' => 'https://www.efgjk.co.uk/people/',
                2 => 'https://www.efgjk.co.uk/people/',
            ),
        )
    ),
);
```

<h2>Simple Iteration https://3v4l.org/KGcuv</h2>

<p>As I am not aware how the <code>$data['pageData']</code> array is expected in your desired output, I have omitted it's iteration by iterating over the linkCategories directly, using <code>$data['linkCategories']</code>. I have also added an additional group, <code>Cat 2</code> to demonstrate multiple <code>categoryTitle</code> groupings.</p>

<pre class="lang-php prettyprint-override"><code>foreach ($data['linkCategories'] as $category => $links) {
    echo $category;
    foreach ($links as $link) {
        echo $link['linkTitle'];
    }
}
</code>```

Result

```<code>Unsorted
a link title
People

Cat 2
People
</code>```

Bootstrap Markup Iteration https://3v4l.org/Du4YR

For displaying each grouping as a separate column in bootstrap, you would need to alter the simple iteration with your desired markup, by utilizing the row and col-**-** classes to suit your desired appearance.
To produce a two-column listing I have used col-6, but you can change the grid sizes as desired.

```<code><div class="row">
<?php foreach ($data['linkCategories'] as $category => $links) { ?>
    <div class="col-6">
    <div class="h6"><?php echo $category; ?></div>
    <?php foreach ($links as $link) { ?>
        <div class="row">
            <div class="col">
                <p>
                <a target="_blank" class="text-danger" href="<?php echo $link['linkUrl'] ?>"><?php echo $link['linkTitle']; ?></a>
                </p>
                 <p><?php echo $link['linkDescription']; ?></p>
             </div>
        </div>
    <?php } ?>
    </div>
<?php } ?>
</div>
</code>```

Result https://jsfiddle.net/sayudjp0/

Unsorted

          a link title

This is an example of a link you can store. This is the external website

          People

This is another link

Cat 2

          People

This is another link

```

Body:
I am sure this is a very simple problem that I seem unable to get my head around. I want to display a list of links grouped on screen into their respective categories. I'm using bootstrap and the idea is to have each link category outputted in its own column with the links under the heading:

For example:

---Cat 1 ------- Cat 2 ---

---Link 1 ------ Link 3 ---

---Link 2 ------ Link 4 ---

I have two tables:

The first 'links' has the columns linkId, categoryId, linkTitle, linkDescription, linkUrl etc.

The second 'linkcategories' has the columns categoryId, categoryTitle, categoryDescription etc.

I am using PDO and using the following to get the data from the database:

public function getLinkCategories() {
  $this->db->query('SELECT categoryTitle, linkTitle, linkDescription, linkUrl
                    FROM link
                    INNER JOIN linkcategories ON linkCategories.categoryId = link.categoryId
                    WHERE link.marked_for_delete != 1');
  $results = $this->db->resultSetGrouped();
  return $results;
}

I am then using the code below to pass the results back, spcifically I read that I should use PDO::FETCH_GROUP so that I can return rows into a nested array, where indexes will be unique values from the first column, and values will be arrays similar to ones returned by regular fetchAll(). So using:

//get results set as array of objects - grouped
public function resultSetGrouped() {
  $this->execute();
  return $this->statement->fetchAll(PDO::FETCH_GROUP);
}

My page is loaded with the following and I pass the data to the view:

public function index() {
  //get the links
  $links = $this->linkModel->getLinkCategories();
  $pageData = ['title' => 'Links • BM Intranet'];
  $data = ['pageData' => $pageData, 'linkCategories' => $links];
  $this->view('links/index', $data);
}

I think I should be able to use a foreach loop to display the results on the page but can't get my head around naming the right parts. This is what is returned in $data.

Array
(
[pageData] => Array
    (
        [title] => Links • Intranet
    )

[linkCategories] => Array
    (
        [Unsorted] => Array //Unsorted is the category name
            (
                [0] => Array
                    (
                        [linkTitle] => a link title
                        [0] => a link title
                        [linkDescription] => This is an example of a link you can store. This is the external website
                        [1] => This is an example of a link you can store. This is the external website
                        [linkUrl] => https://www.asbcdef.co.uk/
                        [2] => https://www.abcdef.co.uk/
                    )

                [1] => Array
                    (
                        [linkTitle] => People
                        [0] => People
                        [linkDescription] => This is another link
                        [1] => This is another link
                        [linkUrl] => https://www.efgjk.co.uk/people/
                        [2] => https://www.efgjk.co.uk/people/
                    )

            )

    )

)

So the bit I am stuck on is taking the returned results above and making it display on the page like...

---Cat 1 ------- Cat 2 ---

---Link 1 ------ Link 3 ---

---Link 2 ------ Link 4 ---

I have so far...

foreach($data as $link) : ?>

     <?php echo $link->linkCategories; ?>

    <a target="_blank" class="text-danger" href="<?php echo $category->url; ?>"><?php echo $category->linkTitle; ?>
    Hits: <?php echo $category->hits; ?>

      <?php echo $category->linkDescription; ?>

But this is not working as the properties are incorrect.

So it looks like I can use $link[0]['linkTitle'] to get the data from the array - so could foreach through that I think. What I don't know how to do now is get the category name (which equals - Unsorted - in this case) and have the links related to it underneath

Body:
Based on your current data groupings, in order to iterate over the groups and retrieve the category names, you would need to implement three foreach($array as $index => $values) iterations.

$data = array(
    'pageData' => array(
        'title' => 'Links • Intranet',
    ),
    'linkCategories' => array(
        'Unsorted' => array(
            array(
                'linkTitle' => 'a link title',
                0 => 'a link title',
                'linkDescription' => 'This is an example of a link you can store. This is the external website',
                1 => 'This is an example of a link you can store. This is the external website',
                'linkUrl' => 'https://www.asbcdef.co.uk/',
                2 => 'https://www.abcdef.co.uk/',
            ),
            array(
              'linkTitle' => 'People',
                0 => 'People',
                'linkDescription' => 'This is another link',
                1 => 'This is another link',
                'linkUrl' => 'https://www.efgjk.co.uk/people/',
                2 => 'https://www.efgjk.co.uk/people/',
            ),
        ),
        'Cat 2' => array(
            array(
              'linkTitle' => 'People',
                0 => 'People',
                'linkDescription' => 'This is another link',
                1 => 'This is another link',
                'linkUrl' => 'https://www.efgjk.co.uk/people/',
                2 => 'https://www.efgjk.co.uk/people/',
            ),
        )
    ),
);

Simple Iteration https://3v4l.org/KGcuv

As I am not aware how the $data['pageData'] array is expected in your desired output, I have omitted it's iteration by iterating over the linkCategories directly, using $data['linkCategories']. I have also added an additional group, Cat 2 to demonstrate multiple categoryTitle groupings.

foreach ($data['linkCategories'] as $category => $links) {
    echo $category;
    foreach ($links as $link) {
        echo $link['linkTitle'];
    }
}

Result

Unsorted
a link title
People

Cat 2
People

Bootstrap Markup Iteration https://3v4l.org/Du4YR

For displaying each grouping as a separate column in bootstrap, you would need to alter the simple iteration with your desired markup, by utilizing the row and col-**-** classes to suit your desired appearance.
To produce a two-column listing I have used col-6, but you can change the grid sizes as desired.

<div class="row">
<?php foreach ($data['linkCategories'] as $category => $links) { ?>
    <div class="col-6">
    <div class="h6"><?php echo $category; ?></div>
    <?php foreach ($links as $link) { ?>
        <div class="row">
            <div class="col">
                <p>
                <a target="_blank" class="text-danger" href="<?php echo $link['linkUrl'] ?>"><?php echo $link['linkTitle']; ?></a>
                </p>
                 <p><?php echo $link['linkDescription']; ?></p>
             </div>
        </div>
    <?php } ?>
    </div>
<?php } ?>
</div>

Result https://jsfiddle.net/sayudjp0/

<div class="row">
  <div class="col-6">
    <div class="h6">Unsorted</div>
    <div class="row">
      <div class="col">
        <p>
          <a target="_blank" class="text-danger" href="https://www.asbcdef.co.uk/">a link title</a>
        </p>
        <p>This is an example of a link you can store. This is the external website</p>
      </div>
    </div>
    <div class="row">
      <div class="col">
        <p>
          <a target="_blank" class="text-danger" href="https://www.efgjk.co.uk/people/">People</a>
        </p>
        <p>This is another link</p>
      </div>
    </div>
  </div>
  <div class="col-6">
    <div class="h6">Cat 2</div>
    <div class="row">
      <div class="col">
        <p>
          <a target="_blank" class="text-danger" href="https://www.efgjk.co.uk/people/">People</a>
        </p>
        <p>This is another link</p>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
How to automatically zip files with Node.js and npm
Is there a way to automatically zip certain files at the build time with Node.js and npm?

For example, I have a project, that file structure looks like this:

```<code>Project/
--lib/
--node_modules/
--test/
--index.js
--package.json
</code>```

I want to be able to zip lib folder, certain modules from node_modules and index.js into some zip archive to upload it on the AWS Lambda, for example. I do not need test folder or test Node.js modules (mocha and chai) to be zipped. I have even created a bash script for generating zip file, but is there a way to automatically execute this script, when 'npm install' is called?

This should be a standard problem and it should have a standard solution, but I was unable to discover such.

UPDATE

thanks to michael, decided to use gulp. This is my script, in case some one else will need it for AWS Lambda:

```<code>var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var merge = require('merge-stream');

gulp.task('clean', function () {
    var build = gulp.src('build', {read: false})
        .pipe(clean());
    var dist = gulp.src('dist', {read: false})
        .pipe(clean());

    return merge(build, dist);
});

gulp.task('build', function() {
    var index = gulp.src('index.js')
        .pipe(gulp.dest('build'));
    var lib = gulp.src('lib/**')
        .pipe(gulp.dest('build/lib'));
    var async = gulp.src('node_modules/async/**')
        .pipe(gulp.dest('build/node_modules/async'));
    var collections = gulp.src('node_modules/collections/**')
        .pipe(gulp.dest('build/node_modules/collections'));
    var underscore = gulp.src('node_modules/underscore/**')
        .pipe(gulp.dest('build/node_modules/underscore'));
    var util = gulp.src('node_modules/util/**')
        .pipe(gulp.dest('build/node_modules/util'));
    var xml2js = gulp.src('node_modules/xml2js/**')
        .pipe(gulp.dest('build/node_modules/xml2js'));

    return merge(index, lib, async, collections, underscore, util, xml2js);
});

gulp.task('zip', ['build'], function() {
    return gulp.src('build/*')
        .pipe(zip('archive.zip'))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['zip']);
</code>```

答:
npm-pack-zip worked for me.

```<code>npm install --save-dev npm-pack-zip
</code>```

To publish the whole lambda using aws I used this node script in package.json:

```<code>    "publish": "npm-pack-zip && aws lambda update-function-code --function-name %npm_package_name% --zip-file fileb://%npm_package_name%.zip && rm %npm_package_name%.zip"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to automatically zip certain files at the build time with Node.js and npm?

For example, I have a project, that file structure looks like this:

Project/
--lib/
--node_modules/
--test/
--index.js
--package.json

I want to be able to zip lib folder, certain modules from node_modules and index.js into some zip archive to upload it on the AWS Lambda, for example. I do not need test folder or test Node.js modules (mocha and chai) to be zipped. I have even created a bash script for generating zip file, but is there a way to automatically execute this script, when 'npm install' is called?

This should be a standard problem and it should have a standard solution, but I was unable to discover such.

UPDATE

thanks to michael, decided to use gulp. This is my script, in case some one else will need it for AWS Lambda:

var gulp = require('gulp');
var clean = require('gulp-clean');
var zip = require('gulp-zip');
var merge = require('merge-stream');

gulp.task('clean', function () {
    var build = gulp.src('build', {read: false})
        .pipe(clean());
    var dist = gulp.src('dist', {read: false})
        .pipe(clean());

    return merge(build, dist);
});

gulp.task('build', function() {
    var index = gulp.src('index.js')
        .pipe(gulp.dest('build'));
    var lib = gulp.src('lib/**')
        .pipe(gulp.dest('build/lib'));
    var async = gulp.src('node_modules/async/**')
        .pipe(gulp.dest('build/node_modules/async'));
    var collections = gulp.src('node_modules/collections/**')
        .pipe(gulp.dest('build/node_modules/collections'));
    var underscore = gulp.src('node_modules/underscore/**')
        .pipe(gulp.dest('build/node_modules/underscore'));
    var util = gulp.src('node_modules/util/**')
        .pipe(gulp.dest('build/node_modules/util'));
    var xml2js = gulp.src('node_modules/xml2js/**')
        .pipe(gulp.dest('build/node_modules/xml2js'));

    return merge(index, lib, async, collections, underscore, util, xml2js);
});

gulp.task('zip', ['build'], function() {
    return gulp.src('build/*')
        .pipe(zip('archive.zip'))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['zip']);

Body:
npm-pack-zip worked for me.

npm install --save-dev npm-pack-zip

To publish the whole lambda using aws I used this node script in package.json:

    "publish": "npm-pack-zip && aws lambda update-function-code --function-name %npm_package_name% --zip-file fileb://%npm_package_name%.zip && rm %npm_package_name%.zip"


问:
How to fill dictionaries values by using the for loop?
I have three lists, each contains a unique ID of the employee. For example,

```<code>bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
</code>```

The number of references of employee ID shows, how many issues were solved by the employee. For example, employee with ID=1 solved 1 bug, 4 tasks and 0 subtasks. I want to create a dictionary, which has the next structure: keys are IDs of employees and values are list of size 3, each value of list shows how much bugs, tasks and subtasks employee with ID = something solved. For example, in my case I have to obtain the next dictionary:

```<code>all_employees = {1:[1, 4, 0], 2:[1, 1, 0], 3:[1, 0, 0], 4:[5, 0, 0], 5:[1, 0, 0], 6:[1, 0, 1], \
                 7:[1, 0, 1], 8:[3, 0, 6], 9:[0, 1, 0], 10:[0, 0, 1], 11:[0, 0, 3]}
</code>```

This is my code:

```<code>from collections import defaultdict, Counter
bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
all_issues = bug + task + subtask
all_emlpoyees = dict.fromkeys(all_issues, [0, 0, 0])
bug_d = dict(Counter(bug))
task_d = dict(Counter(task))
subtask_d = dict(Counter(subtask))
for i in all_employees.keys():
    try:
        print("value = ", bug_d[i])
        print ("key = ", i)

        all_employees[i][0] = bug_d[i]
    except Exception as e:
        pass
print (all_assignees)
</code>```

In my opinion, this code should produce the same dictionary, as mentioned above, but only with one, first, non-zero value at its lists, but my output looks like:

```<code>{1: [3, 0, 0], 2: [3, 0, 0], 3: [3, 0, 0], 4: [3, 0, 0], 5: [3, 0, 0], 6: [3, 0, 0], 7: [3, 0, 0], 8: [3, 0, 0], 9: [3, 0, 0], 10: [3, 0, 0], 11: [3, 0, 0]}
</code>```

in spite of two prints at the for loop shows correct values.
Any ideas, what am I doing wrong?

Thanks for help, issue solved.

答:
You can use a Counter to count from each of the list and then create a dictionary.<br>
This avoids counting the number of tasks for each employee.  </p>

```<code>>>> c1, c2, c3 = Counter(bug), Counter(task), Counter(subtask)
>>> d={}
>>> for employee in set(c1)|set(c2)|set(c3):
...     d[employee] = [c1[employee], c2[employee], c3[employee]]
...
>>> d
{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}
</code>```

Body:
I have three lists, each contains a unique ID of the employee. For example,

bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]

The number of references of employee ID shows, how many issues were solved by the employee. For example, employee with ID=1 solved 1 bug, 4 tasks and 0 subtasks. I want to create a dictionary, which has the next structure: keys are IDs of employees and values are list of size 3, each value of list shows how much bugs, tasks and subtasks employee with ID = something solved. For example, in my case I have to obtain the next dictionary:

all_employees = {1:[1, 4, 0], 2:[1, 1, 0], 3:[1, 0, 0], 4:[5, 0, 0], 5:[1, 0, 0], 6:[1, 0, 1], \
                 7:[1, 0, 1], 8:[3, 0, 6], 9:[0, 1, 0], 10:[0, 0, 1], 11:[0, 0, 3]}

This is my code:

from collections import defaultdict, Counter
bug = [1,2,3,4,4,4,4,4,5,6,7,8,8,8]
task = [1,1,1,1,2,9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8 ,8 , 8, 6]
all_issues = bug + task + subtask
all_emlpoyees = dict.fromkeys(all_issues, [0, 0, 0])
bug_d = dict(Counter(bug))
task_d = dict(Counter(task))
subtask_d = dict(Counter(subtask))
for i in all_employees.keys():
    try:
        print("value = ", bug_d[i])
        print ("key = ", i)

        all_employees[i][0] = bug_d[i]
    except Exception as e:
        pass
print (all_assignees)

In my opinion, this code should produce the same dictionary, as mentioned above, but only with one, first, non-zero value at its lists, but my output looks like:

{1: [3, 0, 0], 2: [3, 0, 0], 3: [3, 0, 0], 4: [3, 0, 0], 5: [3, 0, 0], 6: [3, 0, 0], 7: [3, 0, 0], 8: [3, 0, 0], 9: [3, 0, 0], 10: [3, 0, 0], 11: [3, 0, 0]}

in spite of two prints at the for loop shows correct values.
Any ideas, what am I doing wrong?

Thanks for help, issue solved.

Body:
You can use a Counter to count from each of the list and then create a dictionary.

This avoids counting the number of tasks for each employee.

>>> c1, c2, c3 = Counter(bug), Counter(task), Counter(subtask)
>>> d={}
>>> for employee in set(c1)|set(c2)|set(c3):
...     d[employee] = [c1[employee], c2[employee], c3[employee]]
...
>>> d
{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}


问:
Defining analogue (similar) colors
I want to do a program that take the color from a image, and than give me the analogue colors...,
but I don't know how I can use the color taken from the image because it doesn't give me the colors like the object...

I tried to make like this:

```<code>from PIL import Image

img = Image.open("C:/Marco/programas/orange2.jpg").convert("P")

colors = []

for cor_rgb in img.getpalette():
    if cor_rgb not in colors:
        colors.append(cor_rgb)
c = Image.Image.getdata(img)

print(c)
print (colors)
</code>```

Can anybody help me please?

答:
Documentation for getpalette shows that it gives it as flat list [R,G,B, ... ]. Using numpy.array you could reshape it to array [ [R,G,B], [...], ...] and get unique elements

```<code>from PIL import Image
import numpy

img = Image.open("image.jpg").convert("P")

colors = numpy.array(img.getpalette())
colors = colors.reshape((-1,3))
colors = numpy.unique(colors, axis=0)

print(colors)
</code>```

Example result

```<code>[[  0   0   0]
 [  0   0  51]
 [  0   0 102]
 [  0   0 153]
 [  0   0 204]
 [  0   0 255]
 [  0  51   0]
 [  0  51  51]
 [  0  51 102]
 [  0  51 153]
 [  0  51 204]
 [  0  51 255]
 [  0 102   0]
 [  0 102  51]
 [  0 102 102]
 [  0 102 153]
 [  0 102 204]
 [  0 102 255]
</code>```

But I don't know how to define "analogue colors"

Title: Defining analogue (similar) colors

Body:
I want to do a program that take the color from a image, and than give me the analogue colors...,
but I don't know how I can use the color taken from the image because it doesn't give me the colors like the object...

I tried to make like this:

from PIL import Image

img = Image.open("C:/Marco/programas/orange2.jpg").convert("P")

colors = []

for cor_rgb in img.getpalette():
    if cor_rgb not in colors:
        colors.append(cor_rgb)
c = Image.Image.getdata(img)

print(c)
print (colors)

Can anybody help me please?

Body:
Documentation for getpalette shows that it gives it as flat list [R,G,B, ... ]. Using numpy.array you could reshape it to array [ [R,G,B], [...], ...] and get unique elements

from PIL import Image
import numpy

img = Image.open("image.jpg").convert("P")

colors = numpy.array(img.getpalette())
colors = colors.reshape((-1,3))
colors = numpy.unique(colors, axis=0)

print(colors)

Example result

[[  0   0   0]
 [  0   0  51]
 [  0   0 102]
 [  0   0 153]
 [  0   0 204]
 [  0   0 255]
 [  0  51   0]
 [  0  51  51]
 [  0  51 102]
 [  0  51 153]
 [  0  51 204]
 [  0  51 255]
 [  0 102   0]
 [  0 102  51]
 [  0 102 102]
 [  0 102 153]
 [  0 102 204]
 [  0 102 255]

But I don't know how to define "analogue colors"


问:
How to properly call Powershell script from Batch script (fix a bug)
My script in batch main.bat should call other script in Powershell 07-PermissionsChecking.ps1, but it opens the mouse properties instead and I have no idea why it does that.

When I execute 07-PermissionsChecking.ps1 directly from Powershell, it works fine as expected. This code tries to open folders in shared-drive, and tries to create files in order to verify read & write access permissions for the user.

Can someone help to make it work calling from main.bat?

EDIT: After I rename a function previously named as "main" to "myfunction" the error changed to:

```<code>"-myfunction : The term 'myfunction' is not recognizer as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."
</code>```

main.bat:

```<code>Powershell -command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser"
Powershell -noexit "& ""Y:\02 - Installations\Batch files\07-PermissionsChecking.ps1"""
</code>```

07-PermissionsChecking.ps1:

```<code>clear
$error.Clear()

$AvailableProjectsPath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\AccessCtrl"
$WorkspacePath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\Workspace\AccessCtrl"
$WorkInProgressPath = "\\Abrrec01fscp030\swc$\HIL\Work In Progress\AccessCtrl"

$currentDate = (Get-Date).ToString('MM/dd/yyyy')
$currentTime = (Get-Date).ToString('HH:mm:sstt')

$text = ""

myfunction

function myfunction{
    if (Test-Connection -ComputerName Abrrec01fscp030 -Quiet -Count 1){

        CheckAccessStatus $AvailableProjectsPath
        CheckAccessStatus $WorkspacePath
        CheckAccessStatus $WorkInProgressPath

    }
    else
    {
        Write-Host "Make sure you are connected to FIATAUTO network"
    }
}

function CheckAccessStatus{

    Param ([string]$path)

    if(CheckReadAccessStatus $path)
    {
        if(CheckWriteAccessStatus $path)
        {
            $AccessStatus = "R/W";

        } else
        {
            $AccessStatus = "R";
        }
    } else
    {
        $AccessStatus = "-RW";
    }

    $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,$AccessStatus"
    Write-Host $toPrint
    add-content -path "$PSScriptRoot\$env:UserName.txt" -value "$toPrint"
}

function CheckReadAccessStatus {

    Param ([string]$path)

    $readAccessStatus = [bool]1 #0: No read access. 1: read access.

    try {

        $error.Clear()
        ii $path -ErrorAction "Stop"

        $shell = New-Object -ComObject Shell.Application
        Start-Sleep -Seconds 1
        $window = $shell.Windows() | Where-Object { $_.LocationURL -like "$(([uri]$path).AbsoluteUri)*" }
        $window | ForEach-Object { $_.Quit() }

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $readAccessStatus = [bool]0

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $readAccessStatus
}

function CheckWriteAccessStatus {

    Param ([string]$path)

    $writeAccessStatus = [bool]1 #0: No write access. 1: write access.

    try {

        $error.Clear()
       $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,3"
        add-content -path "$path\$env:UserName.txt" -value "$toPrint"

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $writeAccessStatus = [bool]0

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $writeAccessStatus
}
</code>```

答:
Reason behind mouse properties opening is because windows have a main.cpl command that opens mouse properties. Can you change the name of your function from main to something else? main after $text="" is what's opening your mouse properties since you are running it from cmd line

Move the functions above your actual code. When you define your functions after you run your commands, the compiler will not know anything about the functions. Compiler has to read in the functions first and after that it will know to execute them when called by name.

```<code>TryMe

Function TryMe {
  Write-output "Hello"
}
</code>```

Above will fail because TryMe is defined after the execution.

Correct way

```<code>Function TryMe {
  Write-output "Hello"
}

TryMe # Writes Hello successfully.
</code>```

Move all the actual code you have after the function declarations.

Body:
My script in batch main.bat should call other script in Powershell 07-PermissionsChecking.ps1, but it opens the mouse properties instead and I have no idea why it does that.

When I execute 07-PermissionsChecking.ps1 directly from Powershell, it works fine as expected. This code tries to open folders in shared-drive, and tries to create files in order to verify read & write access permissions for the user.

Can someone help to make it work calling from main.bat?

EDIT: After I rename a function previously named as "main" to "myfunction" the error changed to:

"-myfunction : The term 'myfunction' is not recognizer as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

main.bat:

Powershell -command "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser"
Powershell -noexit "& ""Y:\02 - Installations\Batch files\07-PermissionsChecking.ps1"""

07-PermissionsChecking.ps1:

clear
$error.Clear()

$AvailableProjectsPath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\AccessCtrl"
$WorkspacePath = "\\Abrrec01fscp030\swc$\HIL\Available Projects\Workspace\AccessCtrl"
$WorkInProgressPath = "\\Abrrec01fscp030\swc$\HIL\Work In Progress\AccessCtrl"

$currentDate = (Get-Date).ToString('MM/dd/yyyy')
$currentTime = (Get-Date).ToString('HH:mm:sstt')

$text = ""

myfunction

function myfunction{
    if (Test-Connection -ComputerName Abrrec01fscp030 -Quiet -Count 1){

        CheckAccessStatus $AvailableProjectsPath
        CheckAccessStatus $WorkspacePath
        CheckAccessStatus $WorkInProgressPath

    }
    else
    {
        Write-Host "Make sure you are connected to FIATAUTO network"
    }
}

function CheckAccessStatus{

    Param ([string]$path)

    if(CheckReadAccessStatus $path)
    {
        if(CheckWriteAccessStatus $path)
        {
            $AccessStatus = "R/W";

        } else
        {
            $AccessStatus = "R";
        }
    } else
    {
        $AccessStatus = "-RW";
    }

    $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,$AccessStatus"
    Write-Host $toPrint
    add-content -path "$PSScriptRoot\$env:UserName.txt" -value "$toPrint"
}

function CheckReadAccessStatus {

    Param ([string]$path)

    $readAccessStatus = [bool]1 #0: No read access. 1: read access.

    try {

        $error.Clear()
        ii $path -ErrorAction "Stop"

        $shell = New-Object -ComObject Shell.Application
        Start-Sleep -Seconds 1
        $window = $shell.Windows() | Where-Object { $_.LocationURL -like "$(([uri]$path).AbsoluteUri)*" }
        $window | ForEach-Object { $_.Quit() }

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $readAccessStatus = [bool]0

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $readAccessStatus
}

function CheckWriteAccessStatus {

    Param ([string]$path)

    $writeAccessStatus = [bool]1 #0: No write access. 1: write access.

    try {

        $error.Clear()
       $toPrint = "$env:UserName,$env:ComputerName,$currentDate,$currentTime,$path,3"
        add-content -path "$path\$env:UserName.txt" -value "$toPrint"

    }

    catch [System.UnauthorizedAccessException]{ #$Error[0].Exception.GetType().FullName

        $writeAccessStatus = [bool]0

    }

    $ErrorActionPreference = "Continue"; #Reset the error action pref to default
    return $writeAccessStatus
}

Body:
Reason behind mouse properties opening is because windows have a main.cpl command that opens mouse properties. Can you change the name of your function from main to something else? main after $text="" is what's opening your mouse properties since you are running it from cmd line

Move the functions above your actual code. When you define your functions after you run your commands, the compiler will not know anything about the functions. Compiler has to read in the functions first and after that it will know to execute them when called by name.

TryMe

Function TryMe {
  Write-output "Hello"
}

Above will fail because TryMe is defined after the execution.

Correct way

Function TryMe {
  Write-output "Hello"
}

TryMe # Writes Hello successfully.

Move all the actual code you have after the function declarations.


答:
The required output can be achieved using following piece of code.

```<code>bug = [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8]
task = [1, 1, 1, 1, 2, 9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8, 8, 8, 6]

# first create a set of all employee id , no repeats
all_employees = set(bug + task + subtask)

# loop over each id and find the count of bug, task, sub_task and append it in the dict
final_dict = {}
for id in all_employees:
    final_dict[id] = [bug.count(id), task.count(id), subtask.count(id)]

print(final_dict)
</code>```

Output :

```<code>{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}
</code>```

Title: How to fill dictionaries values by using the for loop?

Body:
The required output can be achieved using following piece of code.

bug = [1, 2, 3, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8]
task = [1, 1, 1, 1, 2, 9]
subtask = [10, 11, 11, 11, 8, 8, 8, 8, 8, 8, 6]

# first create a set of all employee id , no repeats
all_employees = set(bug + task + subtask)

# loop over each id and find the count of bug, task, sub_task and append it in the dict
final_dict = {}
for id in all_employees:
    final_dict[id] = [bug.count(id), task.count(id), subtask.count(id)]

print(final_dict)

Output :

{1: [1, 4, 0], 2: [1, 1, 0], 3: [1, 0, 0], 4: [5, 0, 0], 5: [1, 0, 0], 6: [1, 0, 1], 7: [1, 0, 0], 8: [3, 0, 6], 9: [0, 1, 0], 10: [0, 0, 1], 11: [0, 0, 3]}


问:
Function for adjusted Rsquare on test data?
w.r.t  R/Rstudio  I know there is RMSE and R2 function which i can leverage to calculate RMSE and Rsquare on test data.  Is there a similar function for adjusted R square on test data?</p>

答:
You can compute the Adjusted R-squared for any model by simply ... adjusting R-squared.
The formula is available from Wikipedia.

AdjR2 = 1 - (1 - R2) * (n-1) / (n-k-1)

  where n = number of points

  and   k = number of variables in the model

Here is a simple example:

```<code>library(MASS)
data(Boston)

LM <- lm(medv~., data=Boston)
R2 = summary(LM)$r.squared
R2
dim(Boston)

summary(LM)$adj.r.squared
[1] 0.7337897

1 - (1 - R2)*(dim(Boston)[1]-1)/(dim(Boston)[1]-dim(Boston)[2])
[1] 0.7337897
</code>```

Body:
You can compute the Adjusted R-squared for any model by simply ... adjusting R-squared.
The formula is available from Wikipedia.

AdjR2 = 1 - (1 - R2) * (n-1) / (n-k-1)

  where n = number of points

  and   k = number of variables in the model

Here is a simple example:

library(MASS)
data(Boston)

LM <- lm(medv~., data=Boston)
R2 = summary(LM)$r.squared
R2
dim(Boston)

summary(LM)$adj.r.squared
[1] 0.7337897

1 - (1 - R2)*(dim(Boston)[1]-1)/(dim(Boston)[1]-dim(Boston)[2])
[1] 0.7337897


问:
Android - how to ensure that checked radiobutton in ScrollView will be visible on screen?
I have RadioGroup with 19 RadioButtons in a ScrollView in DialogPreference. There are visible only around first 7 of RadioButtons in dialog. All is working fine, only one question. How to ensure that checked RadioButton will be always visible on screen after bind the dialog? How to scroll in ScrollView programmatically to show hidden checked RadioButton ?

Thank you for your help or suggestions.

答:
This is what worked for me.</p>

```<code>final Scrollview scrollview = findViewById(R.id.myScrollView);
final RadioGroup rg = findViewById(R.id.myRadioGroup);
int position = //checked position

    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.scrollTo(0, rg.getChildAt(position).getTop());
        }
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is what worked for me.

final Scrollview scrollview = findViewById(R.id.myScrollView);
final RadioGroup rg = findViewById(R.id.myRadioGroup);
int position = //checked position

    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.scrollTo(0, rg.getChildAt(position).getTop());
        }
    });


问:
Why are browser requests not going through my proxy server?
I tried writing a simple proxy in node.js today with a basic HTTP server, I realized in Firefox when I reload the proxy, I can see a request.  However, when I load any page, it doesn't seem to be going through my proxy.  I can curl the server, and it works fine. But why is the browser not using my proxy?

The code just looks like:

```<code>var http = require('http');

var listener = function(request, response) {
  console.log('hi');

  response.write("200");
  response.end();
};

var server = http.createServer(listener);
server.listen(8000, undefined, function() {
  console.log('Server has started on 8000');
});
</code>```

I'm just looking for something that changes the header of the request, though a reverse proxy would also be cool.

Edit: This is how I'm pointing my browser to my proxy. In Firefox, preferences -> advanced -> Network -> Settings

I tried to setting the HTTP Proxy under "Manual proxy configuration" to 127.0.0.1:8000 - that seems to do something, cuz all my pages fail to load, but I don't see any activity on my proxy server.

I also tried to just put 127.0.0.1:8000 under "Automatic proxy configuration URL" which sends a request when I just configure it, but nothing is proxied afterwards. I'm wonder what kind of response the "automatic" configuration is looking for...

答:
To use Charles to capture traffic to localhost you need to use http://localhost./ (yes, with a dot on the end).

See the documentation here:
http://www.charlesproxy.com/documentation/faqs/localhost-traffic-doesnt-appear-in-charles

Body:
I tried writing a simple proxy in node.js today with a basic HTTP server, I realized in Firefox when I reload the proxy, I can see a request.  However, when I load any page, it doesn't seem to be going through my proxy.  I can curl the server, and it works fine. But why is the browser not using my proxy?

The code just looks like:

var http = require('http');

var listener = function(request, response) {
  console.log('hi');

  response.write("200");
  response.end();
};

var server = http.createServer(listener);
server.listen(8000, undefined, function() {
  console.log('Server has started on 8000');
});

I'm just looking for something that changes the header of the request, though a reverse proxy would also be cool.

Edit: This is how I'm pointing my browser to my proxy. In Firefox, preferences -> advanced -> Network -> Settings

I tried to setting the HTTP Proxy under "Manual proxy configuration" to 127.0.0.1:8000 - that seems to do something, cuz all my pages fail to load, but I don't see any activity on my proxy server.

I also tried to just put 127.0.0.1:8000 under "Automatic proxy configuration URL" which sends a request when I just configure it, but nothing is proxied afterwards. I'm wonder what kind of response the "automatic" configuration is looking for...


问:
How to start new svn repo from exisiting svn repo
I pulled the SVN project to my machine and edited it.

From this modified version, I want to start new repository.

For example, I have this structure,

```<code>Parent
  |-Foo
</code>```

I pulled Foo project, modified and named it as Bar.

Final structure,

```<code>Parent
  |-Foo
  |-Bar
</code>```

How can I push this one without affecting the original project?
(I haven't push any changes to original project(Foo).)

答:
Easy Way

If you want to commit the whole WC as monorepo and lost relation to original Foo-repo (The Bad Idea, if you want to maintain and sync changes some time longer, than "just now")

Create new fresh empty SVN-repo

Relocate WC to new URL

Commit

Better Way

If you want to have modular structure and easy incorporate changes from upstream-repo later

Create new fresh empty SVN-repo

Relocate WC to new URL

Convert existing WC into "WC + pegged externals" (Foo dir, namely)

Commit

Body:
I pulled the SVN project to my machine and edited it.

From this modified version, I want to start new repository.

For example, I have this structure,

Parent
  |-Foo

I pulled Foo project, modified and named it as Bar.

Final structure,

Parent
  |-Foo
  |-Bar

How can I push this one without affecting the original project?
(I haven't push any changes to original project(Foo).)


问:
Email doesn't get sent with Gmail smtp using Nodejs
I'm trying to send an email (Gmail) smtp using nodejs but I'm getting the error:

My email and password is correct I'm using the nodemailer for sending the mail. This is my code :

```<code>    //send email to confirme gain
    var smtpTransport = nodemailer.createTransport({
        service : 'Gmail',
        host: 'smtp.gmail.com',
        port: 587,
        secure: false,
        auth : {
            user : config.supportemail,
            pass : config.gmailPSW
        }
    });
    var mailOptions = {
        to : gain.emailAccount,
        from : config.supportemail,
        subject : "FATBOAR : Vous avez gagné ! ",
        text : "Félicitations ! \n \n Votre compte : "+gain.emailAccount+" a bien gagné : "+gain.libelleGain+" grace à votre ticket de caisse N°: "+gain.numTicket+". \n \n Présentez-vous à notre équipe Fatboar avec ce mail ou avec l'application Fatboar pour récupérer votre gain. \n \n Nous vous remercions pour votre visite et espérons vous revoir très prochainement pour plus de cadeau. \n \n P.S : Vous avez participé automatiquement au tirage au sort pour gagner une voiture Range Rover Evoque. \n \n Bonne chance et à bientôt ! \n \n L'équipe FATBOAR"
    }
    smtpTransport.sendMail(mailOptions,function(err){
        if(err){
            res.status(400);
            resultats = {
                "success": false,
                "message": 'Error :5 '+ err,
                "result": ''
            }
            res.json(resultats);
        }
        else{
            res.status(200);
            resultats = {
                "success": true,
                "message": "SUCCESS",
                "result": gain
            }
            res.json(resultats);
        }
    });
</code>```

And this is my .env file :

```<code>#GMAIL
SECRETKEY="xxxx......="
GMAILPSW="XXXXX"
SUPPORTEMAIL="xXX.XxXXXxXXxxXx@gmail.com"
</code>```

I allowed access to less secured app, and activated two-step validation.
With all that it gives nothing.

答:
if you have activated the two factor authentication
please check this guide:

https://galleryserverpro.com/use-gmail-as-your-smtp-server-even-when-using-2-factor-authentication-2-step-verification/

Maybe you need to use the "google app password" instead.

More official informations are here:
https://support.google.com/mail/answer/185833?hl=en

Maybe thats help :)

Body:
I'm trying to send an email (Gmail) smtp using nodejs but I'm getting the error:

My email and password is correct I'm using the nodemailer for sending the mail. This is my code :

    //send email to confirme gain
    var smtpTransport = nodemailer.createTransport({
        service : 'Gmail',
        host: 'smtp.gmail.com',
        port: 587,
        secure: false,
        auth : {
            user : config.supportemail,
            pass : config.gmailPSW
        }
    });
    var mailOptions = {
        to : gain.emailAccount,
        from : config.supportemail,
        subject : "FATBOAR : Vous avez gagné ! ",
        text : "Félicitations ! \n \n Votre compte : "+gain.emailAccount+" a bien gagné : "+gain.libelleGain+" grace à votre ticket de caisse N°: "+gain.numTicket+". \n \n Présentez-vous à notre équipe Fatboar avec ce mail ou avec l'application Fatboar pour récupérer votre gain. \n \n Nous vous remercions pour votre visite et espérons vous revoir très prochainement pour plus de cadeau. \n \n P.S : Vous avez participé automatiquement au tirage au sort pour gagner une voiture Range Rover Evoque. \n \n Bonne chance et à bientôt ! \n \n L'équipe FATBOAR"
    }
    smtpTransport.sendMail(mailOptions,function(err){
        if(err){
            res.status(400);
            resultats = {
                "success": false,
                "message": 'Error :5 '+ err,
                "result": ''
            }
            res.json(resultats);
        }
        else{
            res.status(200);
            resultats = {
                "success": true,
                "message": "SUCCESS",
                "result": gain
            }
            res.json(resultats);
        }
    });

And this is my .env file :

#GMAIL
SECRETKEY="xxxx......="
GMAILPSW="XXXXX"
SUPPORTEMAIL="xXX.XxXXXxXXxxXx@gmail.com"

I allowed access to less secured app, and activated two-step validation.
With all that it gives nothing.


问:
How to change a text in JSON that has quotes in it?
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

```<code>import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)
</code>```

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

```<code>replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""
</code>```

How I replace a text containing quotes on JSON using Python?

答:
If we know what key the value ArmReoriented is attached to, we can do this the right way, processing your content structured data rather than as a string:

```<code>import json, copy

def hideReorientedArm(obj):
    if isinstance(obj, dict):
        if obj.get("LastEvent") == "ArmReoriented" and obj.get("visible") is True:
            obj["visible"] = False
    return obj

def walk(obj, updateFn):
    if isinstance(obj, list):
        obj = [walk(elem, updateFn) for elem in obj]
    elif isinstance(obj, dict):
        obj = {k: walk(v, updateFn) for k, v in obj.items()}
    return updateFn(obj)

with open(mycodepath, 'r') as file:
    data = json.load(file)
    data = walk(data, hideReorientedArm)
</code>```

See this running at https://ideone.com/Zr6546

Even if you don't know the name of the specific key having that value, you can still search all of them if that's necessary for some reason, replacing the shorter hideReorientedArm definition above with something more like the following:

```<code>def hideReorientedArm(obj):
    if isinstance(obj, dict):
        if obj.get("visible") is True:
            foundArmReoriented = False
            for (k,v) in obj.items():
                if v == "ArmReoriented":
                    foundArmReoriented = True
                    break
            if foundArmReoriented:
                obj["visible"] = False
    return obj
</code>```

...see this version running at https://ideone.com/z34Mx1

Body:
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""

How I replace a text containing quotes on JSON using Python?

Body:
If we know what key the value ArmReoriented is attached to, we can do this the right way, processing your content structured data rather than as a string:

import json, copy

def hideReorientedArm(obj):
    if isinstance(obj, dict):
        if obj.get("LastEvent") == "ArmReoriented" and obj.get("visible") is True:
            obj["visible"] = False
    return obj

def walk(obj, updateFn):
    if isinstance(obj, list):
        obj = [walk(elem, updateFn) for elem in obj]
    elif isinstance(obj, dict):
        obj = {k: walk(v, updateFn) for k, v in obj.items()}
    return updateFn(obj)

with open(mycodepath, 'r') as file:
    data = json.load(file)
    data = walk(data, hideReorientedArm)

See this running at https://ideone.com/Zr6546

Even if you don't know the name of the specific key having that value, you can still search all of them if that's necessary for some reason, replacing the shorter hideReorientedArm definition above with something more like the following:

def hideReorientedArm(obj):
    if isinstance(obj, dict):
        if obj.get("visible") is True:
            foundArmReoriented = False
            for (k,v) in obj.items():
                if v == "ArmReoriented":
                    foundArmReoriented = True
                    break
            if foundArmReoriented:
                obj["visible"] = False
    return obj

...see this version running at https://ideone.com/z34Mx1


问:
overlay discrete and continuous layer in ggplot - surprised that layer order matters
consider the following example dataset:

library(dplyr)
library(ggplot2)

d = mtcars %>%
 as_tibble(rownames = "name") %>%
 mutate(wt.cat = cut(wt, seq(1.5, 5.5, by = 1))) %>%
 group_by(wt.cat) %>%
 summarize(
   Mean = mean(mpg),
   Min = min(mpg),
   Max = max(mpg)
 )
```

<p>Say I want to plot points for the "mean" value of each category in <code>wt.cat</code> and a ribbon showing the range. This works:</p>

```ggplot(d, aes(x = wt.cat)) +
  geom_point(aes(y= Mean)) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")
```

<p><img src="https://i.stack.imgur.com/OMAgA.png" alt="example 1"></p>

<p>But the points are masked by the ribbon. However, if I change the order of the layers so that the points are plotted on top of the ribbon, I get an error:</p>

<pre class="lang-r prettyprint-override"><code>ggplot(d, aes(x = wt.cat)) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue") +
  geom_point(aes(y= Mean))
## Error: Discrete value supplied to continuous scale
</code>```

So even though I'm specifying the discrete axis as the "default" aesthetic, it gets overridden by the specification of the first plotted layer. The only way I can find around this is to plot a dummy point layer first:

ggplot(d, aes(x = wt.cat)) +
  geom_point(aes(y= Mean), shape = NA) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue") +
  geom_point(aes(y= Mean))
## Warning message:
## Removed 4 rows containing missing values (geom_point).
```

Is there a more "proper" or correct way of combining discrete and continuous layers? Is there a solution that doesn't require creating a dummy layer?

答:
would something like this be a solution?

```<code>d %>% {
  ggplot(., aes(x = wt.cat)) +
    scale_x_discrete(labels = levels(.$wt.cat)) +
    geom_ribbon(aes(x =as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")  +
    geom_point(aes(y=Mean))
}
</code>```

I just learned you can wrap a pipe with { } and then reference the entire data frame with .

As camille said, the issue is that geom_ribbon requires a continuous scale because it plots area across values relating to the adjacent position. I believe the scale gets converted to continuous when geom_ribbon is added, but the labels are maintained.

Hope this helps

As per my reply -- the following works just as well if you want ggplot2 to handle all the labeling

```<code>d %>%
      ggplot(aes(x = wt.cat)) +
        scale_x_discrete() +
        geom_ribbon(aes(x =as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")  +
        geom_point(aes(y=Mean))
</code>```

Body:
consider the following example dataset:

library(dplyr)
library(ggplot2)

d = mtcars %>%
 as_tibble(rownames = "name") %>%
 mutate(wt.cat = cut(wt, seq(1.5, 5.5, by = 1))) %>%
 group_by(wt.cat) %>%
 summarize(
   Mean = mean(mpg),
   Min = min(mpg),
   Max = max(mpg)
 )

Say I want to plot points for the "mean" value of each category in wt.cat and a ribbon showing the range. This works:

ggplot(d, aes(x = wt.cat)) +
  geom_point(aes(y= Mean)) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")

But the points are masked by the ribbon. However, if I change the order of the layers so that the points are plotted on top of the ribbon, I get an error:

ggplot(d, aes(x = wt.cat)) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue") +
  geom_point(aes(y= Mean))
## Error: Discrete value supplied to continuous scale

So even though I'm specifying the discrete axis as the "default" aesthetic, it gets overridden by the specification of the first plotted layer. The only way I can find around this is to plot a dummy point layer first:

ggplot(d, aes(x = wt.cat)) +
  geom_point(aes(y= Mean), shape = NA) +
  geom_ribbon(aes(x = as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue") +
  geom_point(aes(y= Mean))
## Warning message:
## Removed 4 rows containing missing values (geom_point).

Is there a more "proper" or correct way of combining discrete and continuous layers? Is there a solution that doesn't require creating a dummy layer?

Body:
would something like this be a solution?

d %>% {
  ggplot(., aes(x = wt.cat)) +
    scale_x_discrete(labels = levels(.$wt.cat)) +
    geom_ribbon(aes(x =as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")  +
    geom_point(aes(y=Mean))
}

I just learned you can wrap a pipe with { } and then reference the entire data frame with .

As camille said, the issue is that geom_ribbon requires a continuous scale because it plots area across values relating to the adjacent position. I believe the scale gets converted to continuous when geom_ribbon is added, but the labels are maintained.

Hope this helps

As per my reply -- the following works just as well if you want ggplot2 to handle all the labeling

d %>%
      ggplot(aes(x = wt.cat)) +
        scale_x_discrete() +
        geom_ribbon(aes(x =as.numeric(wt.cat), ymin = Min, ymax = Max), fill = "blue")  +
        geom_point(aes(y=Mean))


问:
AWS Glue cannot create database from crawler: permission denied
I am trying to use an AWS Glue crawler on an S3 bucket to populate a Glue database. I run the Create Crawler wizard, select my datasource (the S3 bucket with the avro files), have it create the IAM role, and run it, and I get the following error:

```<code>Database does not exist or principal is not authorized to create tables. (Database name: zzz-db, Table name: avroavro_all) (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: 78fc18e4-c383-11e9-a86f-736a16f57a42). For more information, see Setting up IAM Permissions in the Developer Guide (http://docs.aws.amazon.com/glue/latest/dg/getting-started-access.html).
</code>```

I tried to create this table in a new blank database (as opposed to an existing one with tables), I tried prefixing the names, I tried sourcing different schemas, and I tried using an existing role with Admin access. I though the latter would work, but I keep getting the same error, and have no idea why.

To be explicit, the service role I created has several policies I assume a premissive enough to create tables:

The logs are vanilla:

```<code>
19:52:52
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Running Start Crawl for Crawler avro
19:53:22
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Classification complete, writing results to database zzz-db
19:53:22
[10cb3191-9785-49dc-8935-fb02dcbd69a3] INFO : Crawler configured with SchemaChangePolicy {"UpdateBehavior":"UPDATE_IN_DATABASE","DeleteBehavior":"DEPRECATE_IN_DATABASE"}.
19:53:34
[10cb3191-9785-49dc-8935-fb02dcbd69a3] ERROR : Insufficient Lake Formation permission(s) on s3://zzz-data/avro-all/ (Database name: zzz-db, Table name: avroavro_all) (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: 31481e7e-c384-11e9-a6e1-e78dc8223fae). For more information, see Setting up IAM Permissions in the Developer Guide (http://docs.aws.amazon.com/glu
19:54:44
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Crawler has finished running and is in state READY
</code>```

答:
I had to add the custom role I created for Glue to the "Data lake Administrators" grantees:

(Note: just saying this solves the crawler's denied access. There may be something with lesser privileges to do...)

Body:
I am trying to use an AWS Glue crawler on an S3 bucket to populate a Glue database. I run the Create Crawler wizard, select my datasource (the S3 bucket with the avro files), have it create the IAM role, and run it, and I get the following error:

Database does not exist or principal is not authorized to create tables. (Database name: zzz-db, Table name: avroavro_all) (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: 78fc18e4-c383-11e9-a86f-736a16f57a42). For more information, see Setting up IAM Permissions in the Developer Guide (http://docs.aws.amazon.com/glue/latest/dg/getting-started-access.html).

I tried to create this table in a new blank database (as opposed to an existing one with tables), I tried prefixing the names, I tried sourcing different schemas, and I tried using an existing role with Admin access. I though the latter would work, but I keep getting the same error, and have no idea why.

To be explicit, the service role I created has several policies I assume a premissive enough to create tables:

The logs are vanilla:


19:52:52
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Running Start Crawl for Crawler avro
19:53:22
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Classification complete, writing results to database zzz-db
19:53:22
[10cb3191-9785-49dc-8935-fb02dcbd69a3] INFO : Crawler configured with SchemaChangePolicy {"UpdateBehavior":"UPDATE_IN_DATABASE","DeleteBehavior":"DEPRECATE_IN_DATABASE"}.
19:53:34
[10cb3191-9785-49dc-8935-fb02dcbd69a3] ERROR : Insufficient Lake Formation permission(s) on s3://zzz-data/avro-all/ (Database name: zzz-db, Table name: avroavro_all) (Service: AWSGlue; Status Code: 400; Error Code: AccessDeniedException; Request ID: 31481e7e-c384-11e9-a6e1-e78dc8223fae). For more information, see Setting up IAM Permissions in the Developer Guide (http://docs.aws.amazon.com/glu
19:54:44
[10cb3191-9785-49dc-8935-fb02dcbd69a3] BENCHMARK : Crawler has finished running and is in state READY


问:
Native Java method to prepend a LinkedList to another?
I have two LinkedLists in Java and I would like to prepend all elements of one list to another. Is there a native way to do this in O(1) time? I know all that needs to be done is set the last pointer of the first list to the first of the second list, but there doesn't seem to be a native method to do this.

Also, to add to the complexity of this, I need a way to prepend the list to another one and not append it. I have list A and B, and I need all elements of B to be prepended to list A. I can't just add the elements of A to the end of B because I want to list A to be modified.

Is there a way to do this without having to implement my own LinkedList?

答:
There is no predefined method to do it in O(1) time. You can however do it in O(N) using LinkedList.add(index, Collection) method by using 0 index:

```<code>LinkedList<Integer> source = new LinkedList<>();
source.add(1);
source.add(2);
LinkedList<Integer> target = new LinkedList<>();
target.add(3);
target.add(4);

target.addAll(0, source);
System.out.println(target); // [1, 2, 3, 4]
</code>```

Above is O(source N) because addAll will iterate over data in the collection parameter.

Body:
There is no predefined method to do it in O(1) time. You can however do it in O(N) using LinkedList.add(index, Collection) method by using 0 index:

LinkedList<Integer> source = new LinkedList<>();
source.add(1);
source.add(2);
LinkedList<Integer> target = new LinkedList<>();
target.add(3);
target.add(4);

target.addAll(0, source);
System.out.println(target); // [1, 2, 3, 4]

Above is O(source N) because addAll will iterate over data in the collection parameter.


问:
Json Jackson Custom attribute field
I would like to customize the attribute labels during Rest API and POJO process. Essentially, I would like to call POST request with attribute A. But, when we store the value in DynamoDB, we want the attribute to be B. Then, when we call the GET request, we would want it to present with attribute A. Should I use @JsonDeserilize?

Calling POST request with input -

```<code>{
    "foo": "foo",
    "bar": "bar",
    "A": "ownTest"

}
</code>```

Store in the DB with

```<code>{
    "foo": "foo",
    "bar": "bar",
    "**B**": "ownTest"

}
</code>```

Calling GET request Output -

```<code>{
    "foo": "foo",
    "bar": "bar",
    "A": "ownTest"

}
</code>```

My entity class -

```<code>public class Test implements Serializable, IEntity<Test> {

    @Key
    @JsonProperty("foo")
    private String foo;

    @JsonProperty("bar")
    private String bar;

    private String B;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public Test withFoo(String foo){
        this.setFoo(foo);
        return this;
    }

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public Test withBar(String bar){
        this.setBar(bar);
        return this;
    }

    @JsonGetter("A")
    @JsonAlias({"B"})
    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public Test withB(String b){
        this.setB(b);
        return this;
    }
</code>```

I have tried custom deserializer but no luck. Please help!

Thanks!

答:
Have you tried JsonView?
example: https://www.baeldung.com/jackson-json-view-annotation</p>

Title: Json Jackson Custom attribute field

Body:
I would like to customize the attribute labels during Rest API and POJO process. Essentially, I would like to call POST request with attribute A. But, when we store the value in DynamoDB, we want the attribute to be B. Then, when we call the GET request, we would want it to present with attribute A. Should I use @JsonDeserilize?

Calling POST request with input -

{
    "foo": "foo",
    "bar": "bar",
    "A": "ownTest"

}

Store in the DB with

{
    "foo": "foo",
    "bar": "bar",
    "**B**": "ownTest"

}

Calling GET request Output -

{
    "foo": "foo",
    "bar": "bar",
    "A": "ownTest"

}

My entity class -

public class Test implements Serializable, IEntity<Test> {

    @Key
    @JsonProperty("foo")
    private String foo;

    @JsonProperty("bar")
    private String bar;

    private String B;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    public Test withFoo(String foo){
        this.setFoo(foo);
        return this;
    }

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

    public Test withBar(String bar){
        this.setBar(bar);
        return this;
    }

    @JsonGetter("A")
    @JsonAlias({"B"})
    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public Test withB(String b){
        this.setB(b);
        return this;
    }

I have tried custom deserializer but no luck. Please help!

Thanks!


问:
Hide any div or text when ion-menu is opened in Ionic 5 using Angular
I want to hide the toolbar .custom-nav-link div when the ionic side menu will open and again show this when the side menu is closed.
How to detect and apply conditions in HTML based on ion-menu is open or close?

```<code><ion-toolbar>
  <div class="containers">
    <div class="logo" >
      <h4>My Toolbar</h4>
    </div>

    <div class="custom-nav-link" slot="end">
      <nav class="desktop-nav">
        <ul class="nav-list">
          <li *ngFor="let p of buttonLinks">
            <a href="">{{p.title}}</a>
          </li>
        </ul>
      </nav>
    </div>

    <div class="">
      <ion-buttons slot="start">
        <ion-menu-button menu="userMenu">
          <ion-icon name="apps"></ion-icon>
        </ion-menu-button>
      </ion-buttons>
    </div>

  </div>
</ion-toolbar>
</code>```

答:
Try this:

```<code>import { MenuController } from '@ionic/angular';

public isMenuOpen: boolean = false;

constructor(public menuCtrl:MenuController){}

ngOnInit() {   // or on click of menu button
    this.menuCtrl.isOpen('userMenu').then(res => {
        this.isMenuOpen = res;
    })
}
</code>```

and html

```<code><div *ngIf="!isMenuOpen" class="custom-nav-link" slot="end">
  <nav class="desktop-nav">
    <ul class="nav-list">
      <li *ngFor="let p of buttonLinks">
        <a href="">{{p.title}}</a>
      </li>
    </ul>
  </nav>
</div>

<div class="">
  <ion-buttons slot="start">
    <ion-menu-button menu="userMenu">
      <ion-icon name="apps"></ion-icon>
    </ion-menu-button>
  </ion-buttons>
</div>
</code>```

Body:
I want to hide the toolbar .custom-nav-link div when the ionic side menu will open and again show this when the side menu is closed.
How to detect and apply conditions in HTML based on ion-menu is open or close?

<ion-toolbar>

My Toolbar

            {{p.title}}

      <ion-buttons slot="start">
        <ion-menu-button menu="userMenu">
          <ion-icon name="apps"></ion-icon>
        </ion-menu-button>
      </ion-buttons>

</ion-toolbar>

Body:
Try this:

import { MenuController } from '@ionic/angular';

public isMenuOpen: boolean = false;

constructor(public menuCtrl:MenuController){}

ngOnInit() {   // or on click of menu button
    this.menuCtrl.isOpen('userMenu').then(res => {
        this.isMenuOpen = res;
    })
}

and html

<div *ngIf="!isMenuOpen" class="custom-nav-link" slot="end">
  <nav class="desktop-nav">
    <ul class="nav-list">
      <li *ngFor="let p of buttonLinks">
        <a href="">{{p.title}}</a>
      </li>
    </ul>
  </nav>
</div>

<div class="">
  <ion-buttons slot="start">
    <ion-menu-button menu="userMenu">
      <ion-icon name="apps"></ion-icon>
    </ion-menu-button>
  </ion-buttons>
</div>


问:
How to configure services.yaml when i have submodules?
i'm just trying to create a subdirectory structure for my system, i've already readed the documentation, courses and youtube vids, but nothing works, every time i got the error anytime i add something

my Directory Structure

src -> Base -> Offer -> src -> Offer or Users -> repository -> UsersRepository.php

src -> Entity -> UserEntity.php

src -> Admin -> Offer -> src -> Offer or Users -> controller -> OfferController.php

src -> Admin -> Offer -> src -> Offer or Users -> service -> OfferService.php

```<code>#services.yaml

# my controller
App\Offer\Offer\Controller\:
    resource: '../src/Web/Offer/src/Offer/Controller'
    tags: ['controller.service_arguments']

# default service
offer.service:
    class: App\Offer\Offer\Service\OfferService
    public: true
App\Offer\Offer\Service\OfferService: '@offer.service'

# default repository
offer.repo:
    class: App\Base\Offer\Offer\Repository\UsersRepository
    public: true

App\Base\Offer\Offer\Repository\UsersRepository: '@offer.repo'
</code>```

in my controller

```<code><?php
namespace App\Offer\Offer\Controller;
use App\Base\Offer\Offer\Repository\UsersRepository;
use App\Offer\Offer\Service\OfferService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class OfferController extends AbstractController
{

    /**
     * @Route("/web/offer", name="offer_list")
     */
    public function index(OfferService $service,UsersRepository $repo)
    {
        # can i do this ?
        #$a = new OfferService();
        #$a = $this->get('offer.service');

        $b = $service->OfferTester();

        $c = $repo->findAll();

        return new Response(
           '{"success":"'.$c.'"}'
        );
    }
}
</code>```

in my repo

```<code>namespace App\Base\Offer\Offer\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */

class UsersRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

}
</code>```

has any way to keep it simple or dynamic ? im almost giving up, thanks in advice :)

答:
If you need to specify services configuration like you are doing you just missed class definition:

```<code>App\Base\Offer\Offer\Repository\UsersRepository:
    public: false

# default repository
offer.repo:
    class: App\Base\Offer\Offer\Repository\UsersRepository
    public: true

</code>```

But to make it clear, symfony preconize this way to configure services
https://symfony.com/doc/current/service_container.html#importing-many-services-at-once-with-resource :

```<code>services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
</code>```

PS: for symfony 3 or above.

Body:
i'm just trying to create a subdirectory structure for my system, i've already readed the documentation, courses and youtube vids, but nothing works, every time i got the error anytime i add something

my Directory Structure

src -> Base -> Offer -> src -> Offer or Users -> repository -> UsersRepository.php

src -> Entity -> UserEntity.php

src -> Admin -> Offer -> src -> Offer or Users -> controller -> OfferController.php

src -> Admin -> Offer -> src -> Offer or Users -> service -> OfferService.php

#services.yaml

# my controller
App\Offer\Offer\Controller\:
    resource: '../src/Web/Offer/src/Offer/Controller'
    tags: ['controller.service_arguments']

# default service
offer.service:
    class: App\Offer\Offer\Service\OfferService
    public: true
App\Offer\Offer\Service\OfferService: '@offer.service'

# default repository
offer.repo:
    class: App\Base\Offer\Offer\Repository\UsersRepository
    public: true

App\Base\Offer\Offer\Repository\UsersRepository: '@offer.repo'

in my controller

<?php
namespace App\Offer\Offer\Controller;
use App\Base\Offer\Offer\Repository\UsersRepository;
use App\Offer\Offer\Service\OfferService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class OfferController extends AbstractController
{

    /**
     * @Route("/web/offer", name="offer_list")
     */
    public function index(OfferService $service,UsersRepository $repo)
    {
        # can i do this ?
        #$a = new OfferService();
        #$a = $this->get('offer.service');

        $b = $service->OfferTester();

        $c = $repo->findAll();

        return new Response(
           '{"success":"'.$c.'"}'
        );
    }
}

in my repo

namespace App\Base\Offer\Offer\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */

class UsersRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

}

has any way to keep it simple or dynamic ? im almost giving up, thanks in advice :)

Body:
If you need to specify services configuration like you are doing you just missed class definition:

App\Base\Offer\Offer\Repository\UsersRepository:
    public: false

# default repository
offer.repo:
    class: App\Base\Offer\Offer\Repository\UsersRepository
    public: true

But to make it clear, symfony preconize this way to configure services
https://symfony.com/doc/current/service_container.html#importing-many-services-at-once-with-resource :

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

PS: for symfony 3 or above.


问:
Create record for another model when account is created?
I have a multi-tenant application. When an account is created, the account belongs to an owner and also creates a user record for the owner. This owner can invite other users through a memberships join table. All users except for account owners have memberships to the account.

For users with memberships (not owners of accounts) the account/users/:id show page shows up. I would like the same for account owners, but am receiving the following error message:

```<code>ActiveRecord::RecordNotFound in Accounts::UsersController#show
Couldn't find User with 'id'=2 [WHERE "memberships"."account_id" = $1]

def show
  @user = current_account.users.find(params[:id])
end
</code>```

I can add a membership to the owner user in the admin panel and this error goes away, however I would like to add the membership to the owner/user when they create their account.

Any ideas?

Adding @account.memberships.build(user_id: current_user, account_id: current_account) before if @account.save in the accounts controller below does not seem to work.

controllers

user.rb

```<code>module Accounts
  class UsersController < Accounts::BaseController
    before_action :authorize_owner!, only: [:edit, :show, :update, :destroy]

    def show
      @user = current_account.users.find(params[:id])
    end

    def destroy
      user = User.find(params[:id])
      current_account.users.delete(user)
      flash[:notice] = "#{user.email} has been removed from this account."
      redirect_to users_path
    end
  end
end
</code>```

accounts_controller.rb

```<code>class AccountsController < ApplicationController
  def new
    @account = Account.new
    @account.build_owner
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      sign_in(@account.owner)
      flash[:notice] = "Your account has been created."
      redirect_to root_url(subdomain: @account.subdomain)
    else
      flash.now[:alert] = "Sorry, your account could not be created."
      render :new
    end
  end

  private

    def account_params
      params.require(:account).permit(:name, :subdomain,
        { owner_attributes: [:email, :password, :password_confirmation
        ]}
      )
    end
end
</code>```

Models

user.rb

```<code>class User < ApplicationRecord
  has_many :memberships
  has_many :accounts, through: :memberships

  def owned_accounts
    Account.where(owner: self)
  end

  def all_accounts
    owned_accounts + accounts
  end
end
</code>```

account.rb

```<code>class Account < ApplicationRecord
  belongs_to :owner, class_name: "User"
  accepts_nested_attributes_for :owner

  validates :subdomain, presence: true, uniqueness: true

  has_many :memberships
  has_many :users, through: :memberships
end
</code>```

membership.rb

```<code>class Membership < ApplicationRecord
  belongs_to :account
  belongs_to :user
end
</code>```

答:
Have you tried callback after_create?
If it works, you will need to figure it on client and admin create an account, self assigning (admin) against on create assigning (client).

```<code># models/account.rb
  after_create do
    self.memberships.create(user_id: self.owner, account_id: self.id)
  end
</code>```

Body:
I have a multi-tenant application. When an account is created, the account belongs to an owner and also creates a user record for the owner. This owner can invite other users through a memberships join table. All users except for account owners have memberships to the account.

For users with memberships (not owners of accounts) the account/users/:id show page shows up. I would like the same for account owners, but am receiving the following error message:

ActiveRecord::RecordNotFound in Accounts::UsersController#show
Couldn't find User with 'id'=2 [WHERE "memberships"."account_id" = $1]

def show
  @user = current_account.users.find(params[:id])
end

I can add a membership to the owner user in the admin panel and this error goes away, however I would like to add the membership to the owner/user when they create their account.

Any ideas?

Adding @account.memberships.build(user_id: current_user, account_id: current_account) before if @account.save in the accounts controller below does not seem to work.

controllers

user.rb

module Accounts
  class UsersController < Accounts::BaseController
    before_action :authorize_owner!, only: [:edit, :show, :update, :destroy]

    def show
      @user = current_account.users.find(params[:id])
    end

    def destroy
      user = User.find(params[:id])
      current_account.users.delete(user)
      flash[:notice] = "#{user.email} has been removed from this account."
      redirect_to users_path
    end
  end
end

accounts_controller.rb

class AccountsController < ApplicationController
  def new
    @account = Account.new
    @account.build_owner
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      sign_in(@account.owner)
      flash[:notice] = "Your account has been created."
      redirect_to root_url(subdomain: @account.subdomain)
    else
      flash.now[:alert] = "Sorry, your account could not be created."
      render :new
    end
  end

  private

    def account_params
      params.require(:account).permit(:name, :subdomain,
        { owner_attributes: [:email, :password, :password_confirmation
        ]}
      )
    end
end

Models

user.rb

class User < ApplicationRecord
  has_many :memberships
  has_many :accounts, through: :memberships

  def owned_accounts
    Account.where(owner: self)
  end

  def all_accounts
    owned_accounts + accounts
  end
end

account.rb

class Account < ApplicationRecord
  belongs_to :owner, class_name: "User"
  accepts_nested_attributes_for :owner

  validates :subdomain, presence: true, uniqueness: true

  has_many :memberships
  has_many :users, through: :memberships
end

membership.rb

class Membership < ApplicationRecord
  belongs_to :account
  belongs_to :user
end

Body:
Have you tried callback after_create?
If it works, you will need to figure it on client and admin create an account, self assigning (admin) against on create assigning (client).

# models/account.rb
  after_create do
    self.memberships.create(user_id: self.owner, account_id: self.id)
  end


问:
How do I add a variable as a column value in a result set?
I have a variable that loops through values from a CSV file. As the loop returns result sets for each value I have in the CSV, I also want that value (the variable) returned in the result set. I tried to add my variable, $user, in my Select statement, but it just shows in the column header and my value is either blank or {}.

Here's the loop code:

$users = Get-Content C:\AD\ad_groups.txt

ForEach ($User in $users)
{
    Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,$user
}
```

答:
You likely need to use what's called a calculated property. In place of $User, try the following hash table as a property value. "Name" can be shortened to "N" and "Expression to "E" (without the double quotes as seen here), if you feel it's necessary/preferred.</p>

```<code>@{Name='User';Expression={$User}}
</code>```

Body:
You likely need to use what's called a calculated property. In place of $User, try the following hash table as a property value. "Name" can be shortened to "N" and "Expression to "E" (without the double quotes as seen here), if you feel it's necessary/preferred.

@{Name='User';Expression={$User}}


问:
WCF Service Reference creates second class
I am creating a service reference to a WCF service using VS2008 but the generated reference file has 2 classes defined representing the same object.  Any ideas why this would be?  See result below - THView and THView1 were generated while I'm expecting only THView.</p>

```<code>[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="THView", Namespace="http://schemas.datacontract.org/2004/07/CH.BusinessServices.Model")]
[System.SerializableAttribute()]
public partial class THView : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="THView", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class THView1 : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
</code>```

答:
The issue is that you are refreshing the reference when you already have information in the app.config, to fix this, delete the app.config information before refreshing the proxy, or recreate the proxy to a different file

Thanks,
Sebastian

ContentLicense: CC BY-SA 2.5

Body:
I am creating a service reference to a WCF service using VS2008 but the generated reference file has 2 classes defined representing the same object.  Any ideas why this would be?  See result below - THView and THView1 were generated while I'm expecting only THView.

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="THView", Namespace="http://schemas.datacontract.org/2004/07/CH.BusinessServices.Model")]
[System.SerializableAttribute()]
public partial class THView : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="THView", Namespace="http://tempuri.org/")]
[System.SerializableAttribute()]
public partial class THView1 : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {


问:
iOS fetch healthkit data combining multiple devices
I have an application that collects healthkit data from iOS.
It sends the data to my application like this:

```<code> {
      "header": {
        "id": "18018B64-850A-4F3A-9D21-4FF0C99762D6",
        "creation_date_time": "2020-01-15T14:15:00.000+01:00",
        "schema_id": {
          "namespace": "omh",
          "name": "step-count",
          "version": "1.0"
        }
      },
      "source": {
        "operating_system_version": "13.3.0",
        "bundle_identifier": "com.garmin.connect.mobile",
        "product_type": "iPhone10,4",
        "name": "Connect",
        "version": "20"
      },
      "device": null,
      "body": {
        "step_count": 888,
        "effective_time_frame": {
          "time_interval": {
            "start_date_time": "2020-01-15T14:15:00.000+01:00",
            "end_date_time": "2020-01-15T14:29:59.000+01:00"
          }
        }
      }
    },
</code>```

I want the separate data, because my app shows its own aggregations (day, month, today, etc) and I want to do this as I wish on server side, so I don't have access to the users phone. The users phone sends new measurements to the server as they are available in the background.

But, the issue is that I also receive measurements that are from iPhone iteself, or another device collecting stepcounts.

I could filter the incoming data for one device, but that means that if we turn off the watch, we miss data. Healthkit does collect iPhone data, so in the Health app you do see stepcounts.

I actually want to see the data that is in the healthkit app, so I get updated constantly.

Short question: I don't want to have to think about the device, I just want the HK value as it changes. Is this possible?

答: The way to reproduce the aggregates shown in Health on iOS is to use  HKStatisticsCollectionQuery rather than uploading individual samples and then attempting to compute the values for charts yourself. It's unlikely that you will be able to reproduce the logic that HKStatisticsCollectionQuery uses to combine overlapping data, so it is much more straightforward to use the query directly.

Body:
I have an application that collects healthkit data from iOS.
It sends the data to my application like this:

 {
      "header": {
        "id": "18018B64-850A-4F3A-9D21-4FF0C99762D6",
        "creation_date_time": "2020-01-15T14:15:00.000+01:00",
        "schema_id": {
          "namespace": "omh",
          "name": "step-count",
          "version": "1.0"
        }
      },
      "source": {
        "operating_system_version": "13.3.0",
        "bundle_identifier": "com.garmin.connect.mobile",
        "product_type": "iPhone10,4",
        "name": "Connect",
        "version": "20"
      },
      "device": null,
      "body": {
        "step_count": 888,
        "effective_time_frame": {
          "time_interval": {
            "start_date_time": "2020-01-15T14:15:00.000+01:00",
            "end_date_time": "2020-01-15T14:29:59.000+01:00"
          }
        }
      }
    },

I want the separate data, because my app shows its own aggregations (day, month, today, etc) and I want to do this as I wish on server side, so I don't have access to the users phone. The users phone sends new measurements to the server as they are available in the background.

But, the issue is that I also receive measurements that are from iPhone iteself, or another device collecting stepcounts.

I could filter the incoming data for one device, but that means that if we turn off the watch, we miss data. Healthkit does collect iPhone data, so in the Health app you do see stepcounts.

I actually want to see the data that is in the healthkit app, so I get updated constantly.

Short question: I don't want to have to think about the device, I just want the HK value as it changes. Is this possible?


问:
Why does an IP header need to have source address?
What is the use of source address in IP header? Isn't network layer only concerned with forwarding packets to the destination address using the routing table?</p>

答:
How would you send a confirmation if you don't know where you should send it to?

Protocols like TCP and ICMP need that.

Those protocols don't need to transmit the source address if it is stored in the IP header.

For example, TCP does not explizitly store the source address but the source (and destination) port. It is also easier to read if the source and destination address are transmitted one after another and not in different headers.

Nearly every protocol needs the source address in any case.

Lots of high-level protocols like HTTP need to send content back to the user who originally sent the packet(s).

Those protocols would have to send the senders IP too.

The source address is also needed if the packet can't be transmitted and an error response is sent back.


答:
You could use a calculated property like this:</p>

```<code>$userList = Get-Content C:\AD\ad_groups.txt
ForEach ($User in $userList) {
    Get-ADGroupMember -Identity $user -Server MyServerName |
        Select-Object name, SamAccountName, @{Name='user';Expression={$User}}
}
</code>```

Title: How do I add a variable as a column value in a result set?

Body:
I have a variable that loops through values from a CSV file. As the loop returns result sets for each value I have in the CSV, I also want that value (the variable) returned in the result set. I tried to add my variable, $user, in my Select statement, but it just shows in the column header and my value is either blank or {}.

Here's the loop code:

$users = Get-Content C:\AD\ad_groups.txt

ForEach ($User in $users)
{
    Get-ADGroupMember -Identity $user  -Server MyServerName| Select name,SamAccountName,$user
}

Body:
You could use a calculated property like this:

$userList = Get-Content C:\AD\ad_groups.txt
ForEach ($User in $userList) {
    Get-ADGroupMember -Identity $user -Server MyServerName |
        Select-Object name, SamAccountName, @{Name='user';Expression={$User}}
}


问:
Best way to split data of varying length into columns
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

```<code>Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615
</code>```

Desired Output

```<code>Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615
</code>```

答:
A sed solution is also possible, which looks pretty much like the vim one, except that it has no fancy stuff (e.g. no \d in place of [0-9]):

```<code>sed 's/ \([0-9]\+-[0-9]\+\) \([0-9]\+-[0-9]\+\) \([0-9]\+-[0-9]\+\)$/; \1; \2; \3/' yourfile
</code>```

Analogously, however, you can simplify it by means of the -E option

```<code>sed -E 's/ ([0-9]+-[0-9]+) ([0-9]+-[0-9]+) ([0-9]+-[0-9]+)$/; \1; \2; \3/' yourfile
</code>```

Body:
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615

Desired Output

Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615

Body:
A sed solution is also possible, which looks pretty much like the vim one, except that it has no fancy stuff (e.g. no \d in place of [0-9]):

sed 's/ \([0-9]\+-[0-9]\+\) \([0-9]\+-[0-9]\+\) \([0-9]\+-[0-9]\+\)$/; \1; \2; \3/' yourfile

Analogously, however, you can simplify it by means of the -E option

sed -E 's/ ([0-9]+-[0-9]+) ([0-9]+-[0-9]+) ([0-9]+-[0-9]+)$/; \1; \2; \3/' yourfile