问:
Get hours difference between two dates in Moment Js
I'm able to get the difference between two dates using MomentJs as follows:

```<code>moment(end.diff(startTime)).format("m[m] s[s]")
</code>```

However, I also want to display the hour when applicable (only when >= 60 minutes have passed).

However, when I try to retrieve the duration hours using the following:

```<code>var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();
</code>```

it is returning the current hour and not the number of hours between the two dates.

How do I get the difference in hours between two Moments?

答:
```<code> calcDifferential(from, to) {
      const fromTime = this.$moment(from, 'hh:mm:ss')
      const toTime = this.$moment(to, 'hh:mm:ss')
      const ms = toTime.diff(fromTime)
      const d = this.$moment.duration(ms)
      const s = d.format()
      return s
    }
</code>```

Body:
I'm able to get the difference between two dates using MomentJs as follows:

moment(end.diff(startTime)).format("m[m] s[s]")

However, I also want to display the hour when applicable (only when >= 60 minutes have passed).

However, when I try to retrieve the duration hours using the following:

var duration = moment.duration(end.diff(startTime));
var hours = duration.hours();

it is returning the current hour and not the number of hours between the two dates.

How do I get the difference in hours between two Moments?


来源: stackexchange

问:
How to validate an array without keys in Laravel/Lumen
For testing, I want to use the validator method to validate the size and minimum size of this passwordsArray:

```<code>    array:9 [
      0 => "password 0"
      1 => "password 1"
      2 => "password 2"
      3 => "password 3"
      4 => "password 4"
      5 => "password 5"
    ]
</code>```

I'm trying something like:

```<code>$validator = Validator::make($passwordsArray, [
            'passwordsArray' => 'required|min:6',
        ]);

        if( $validator->passes() ){
            $this->assertTrue(true);

        }else{

            $this->assertTrue(false);
        }
</code>```

I'm getting this error:

Failed asserting that false is true.

Help is appreciated, thanks :)

答:
Your $passwordsArray needs to have an element named passwordsArray which unless you've omitted from your example, it does not appear to have.

```<code>$passwordsArray= [
    'passwordsArray' => [
        'password 0',
        'password 1',
        'password 2',
        'password 3',
        'password 4',
        'password 5',
    ]
];

$validator = Validator::make($passwordsArray, [
    'passwordsArray' => ['required', 'min:6']
]);

if ($validator->fails()) {
    dd('Failed validation');
}

dd('Passed validation');
</code>```

Working example here

ContentLicense: CC BY-SA 4.0

Body:
For testing, I want to use the validator method to validate the size and minimum size of this passwordsArray:

    array:9 [
      0 => "password 0"
      1 => "password 1"
      2 => "password 2"
      3 => "password 3"
      4 => "password 4"
      5 => "password 5"
    ]

I'm trying something like:

$validator = Validator::make($passwordsArray, [
            'passwordsArray' => 'required|min:6',
        ]);

        if( $validator->passes() ){
            $this->assertTrue(true);

        }else{

            $this->assertTrue(false);
        }

I'm getting this error:

Failed asserting that false is true.

Help is appreciated, thanks :)

Body:
Your $passwordsArray needs to have an element named passwordsArray which unless you've omitted from your example, it does not appear to have.

$passwordsArray= [
    'passwordsArray' => [
        'password 0',
        'password 1',
        'password 2',
        'password 3',
        'password 4',
        'password 5',
    ]
];

$validator = Validator::make($passwordsArray, [
    'passwordsArray' => ['required', 'min:6']
]);

if ($validator->fails()) {
    dd('Failed validation');
}

dd('Passed validation');

Working example here


问:
How to insert a column value by comparing columns from two data frames in pandas
I am trying to compare two columns from two different dataframes and insert a new column in second dataframe from the first one.

I have two data frames df1 and df2. I would like to compare ID column from df1 and df2 and insert filename in df2 .

```<code>df1:

ID   Date         filename          col2
1    20220207     data1.csv         AAA
2    20220207     data2.csv         BBB
3    20220207     data2.csv         CCC

df2:
ID  Date        col1
1   20220207    123XER
2   20220207    234FGY
3   20220207    000GGG

Result
df2:
ID  Date        col1       filename
1   20220207    123XER     data1.csv
2   20220207    234FGY     data2.csv
3   20220207    000GGG     data2.csv
</code>```

I tried with below code

```<code>df2['FileName']=np.where(df1['ID'].equals(df2['ID']), df1['filename'], '')
</code>```

It throws below error.

```<code>Length of values (1863) does not match length of index (1862)
</code>```

Can anyone please help me with this logic?

答:
```<code>df2['FileName'] = np.where(df1['ID'] == df2['ID'], df1['filename'], None)
</code>```

Body:
I am trying to compare two columns from two different dataframes and insert a new column in second dataframe from the first one.

I have two data frames df1 and df2. I would like to compare ID column from df1 and df2 and insert filename in df2 .

df1:

ID   Date         filename          col2
1    20220207     data1.csv         AAA
2    20220207     data2.csv         BBB
3    20220207     data2.csv         CCC

df2:
ID  Date        col1
1   20220207    123XER
2   20220207    234FGY
3   20220207    000GGG

Result
df2:
ID  Date        col1       filename
1   20220207    123XER     data1.csv
2   20220207    234FGY     data2.csv
3   20220207    000GGG     data2.csv

I tried with below code

df2['FileName']=np.where(df1['ID'].equals(df2['ID']), df1['filename'], '')

It throws below error.

Length of values (1863) does not match length of index (1862)

Can anyone please help me with this logic?


问:
Best way to store date/time in mongodb
I've seen using strings, integer timestamps and mongo datetime objects. </p>

答:
I figured when you use pymongo, MongoDB will store the native Python datetime object as a Date field. This Date field in MongoDB could facilitate date-related queries later (e.g. querying intervals). Therefore, a code like this would work in Python

```<code>from datetime import datetime

datetime_now = datetime.utcnow()
new_doc = db.content.insert_one({"updated": datetime_now})
</code>```

After this, I can see in my database a field like the following (I am using Mongo Compass to view my db). Note how it is not stored as a string (no quotation) and it shows Date as the field type.

Regarding javascript usage, this should also work there. As long as you have the +00:00 (UTC in my case) or Z at the end of your date, Javascript should be able to read the date properly with timezone information.

ContentLicense: CC BY-SA 3.0

Title: Best way to store date/time in mongodb

Body:
I figured when you use pymongo, MongoDB will store the native Python datetime object as a Date field. This Date field in MongoDB could facilitate date-related queries later (e.g. querying intervals). Therefore, a code like this would work in Python

from datetime import datetime

datetime_now = datetime.utcnow()
new_doc = db.content.insert_one({"updated": datetime_now})

After this, I can see in my database a field like the following (I am using Mongo Compass to view my db). Note how it is not stored as a string (no quotation) and it shows Date as the field type.

Regarding javascript usage, this should also work there. As long as you have the +00:00 (UTC in my case) or Z at the end of your date, Javascript should be able to read the date properly with timezone information.


问:
how to use asp.net mvc with those one-page html templates?
I'm new to web development and I decided to try Asp.Net MVC3.

I purchased this one-page template (http://amatyr4n.com/themeforest/freshlr/#home) to use in my first site but I dont know how to proceed in terms of views.

So my question is:

Should I have a single view or should I separate each page (about, portfolio, services, etc.) into a separate view?

Thanks

答:
You're going to want to place most of the common template content in a shared layout file, and the page-specific content in individual views that use the layout file as a base. There's a good basic introduction of the concept on Scott Guthrie's blog here:

http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx

Edited to add:

Since the template you bought is designed to contain all of the site's static content in one file, then you could get away with one view. If, however, you want to begin adding more pages that work in the same way, you'll eventually want to extract out the common template content into a shared layout as described in Scott's blog post.


问:
mySQL How to alter column to have foreign key?
I want to alter a column in one of my tables to that it references another column in another table. I've tried to introduce a foreign key the following ways:

ALTER TABLE `table` ALTER COLUMN `id_l` int NOT NULL, foreign key (`id_l`) references table_b(`id_l`);

ALTER TABLE `table` CHANGE `id_l` `id_l` int NOT NULL, foreign key (`id_l`) references table_b(`id_l`);

I am thrown a syntax error.

A work around is to delete the table and create a new one with the desired reference (this works) but I want to change this table as it is, not to transfer the data. How do I do this?

MySQL Server 5.6.17

答:
I had problem with other answers. and after some research I find this answer</p>
```<code>ALTER TABLE `TABLE_NAME`
ADD COLUMN `COLUMN_NAME` BIGINT(20) UNSIGNED NULL DEFAULT NULL AFTER
`AFTER_COLUMN_NAME`,
ADD FOREIGN KEY `FOREIGN_RELATION_NAME`(`COLUMN_NAME`) REFERENCES
`FOREIGN_TABLE`(`FOREIGN_COLUMN`)  ON UPDATE SET NULL ON DELETE SET NULL
</code>```

Body:
I had problem with other answers. and after some research I find this answer

ALTER TABLE `TABLE_NAME`
ADD COLUMN `COLUMN_NAME` BIGINT(20) UNSIGNED NULL DEFAULT NULL AFTER
`AFTER_COLUMN_NAME`,
ADD FOREIGN KEY `FOREIGN_RELATION_NAME`(`COLUMN_NAME`) REFERENCES
`FOREIGN_TABLE`(`FOREIGN_COLUMN`)  ON UPDATE SET NULL ON DELETE SET NULL


问:
How can I make Bootstrap 5 grids responsive to smartphones?
I have a projects section part of my portfolio. I alternate between description on left/image on right to image on left/description on right. I have been painstakingly trying to make this responsive, but I cannot think of what to do to fix this. I want the image on top and the text below on every project when viewed on a smartphone.

This is the HTML for the projects section:

```<code><section id="projects">
        <div class="container">
          <div class="row projects">
              <h1>My Projects</h1>
            <div class="col project-desc-left">
              <h2>Tindog</h2>
                <p>An landing page for the Tindog app. A twist on a typical dating app. Created with Bootstrap 5 and HTML/CSS utilizing Bootstrap grids.</p>
                <i class="fab fa-html5"></i> <i class="fab fa-css3-alt"></i> <i class="fab fa-bootstrap"></i><br>
                <a class="btn button primary-button mr-4 live-site-btn" href="https://kiannaamaya.github.io/TinDog-WebDevBootcamp/" role="button" target="_blank">Live Site</a>
                <a class="btn button secondary-button mr-4 github-btn" href="https://github.com/kiannaamaya/TinDog-WebDevBootcamp" role="button" target="_blank">Github Repo</a>            </div>
            <div class="col col-lg-6 col-sm-12 project-img-right">
              <img class="project-img" src="assets/tindog.png"/>
            </div>
          </div>
          <div class="row projects">
            <div class="col">
              <img class="project-img" src="assets/nftcard.png"/>
            </div>
            <div class="col project-desc-right">
              <h2>NFT Preview Card</h2>
                <p>An preview card page created with HTML/CSS.</p>
                <i class="fab fa-html5"></i> <i class="fab fa-css3-alt"></i> <br>
                <a class="btn button primary-button mr-4 live-site-btn" href="https://kiannaamaya.github.io/nft-preview-card-component-main/" role="button" target="_blank">Live Site</a>
          <a class="btn button secondary-button mr-4 github-btn" href="https://github.com/kiannaamaya/nft-preview-card-component-main" role="button" target="_blank">Github Repo</a>            </div>
          </div>
          <div class="row projects">
            <div class="col project-desc-left">
              <h2>3-Card Column</h2>
                <p>A preview card of vehicle options created with HTML/CSS.</p>
                <i class="fab fa-html5"></i> <i class="fab fa-css3-alt"></i> </i><br>
                <a class="btn button primary-button mr-4 live-site-btn" href="https://kiannaamaya.github.io/3-column-preview-card-component-main/" role="button" target="_blank">Live Site</a>
                <a class="btn button secondary-button mr-4 github-btn" href="https://github.com/kiannaamaya/3-column-preview-card-component-main" role="button" target="_blank">Github Repo</a>
            </div>
            <div class="col project-img-right">
              <img class="project-img" src="assets/3colcard.png"/>
            </div>
          </div>
        </div>
      </section>
</code>```

I used Bootstrap 5 and I tried to use col-xs-12 but it didn't look right and it also completely messed up the desktop view. The laptop view looks exactly how I want it to look, it's just every other sizing that it completely wrong.

This is the CSS:

```<code>/* Projects */

    #projects {
        width: 100%;
    }

    #projects h1 {
        text-align: center;
    }

    .projects {
        margin-left: 0;

    }

    .project-img{
        width: 300px;
    }

    .project-desc-left {
        margin: 5rem;
        width: 320px;
    }

    .project-desc-right {

    }
}

</code>```

I have been trying to tweak the code for days, but I have barely made any progress.

This is the laptop view of the projects section

This is the mobile view of the projects section

答:
You should be able to do it using Bootstrap 5 Column Ordering without adding any extra CSS. You can add these classes to your Col's and they will appear on the page in the order given no matter their physical place in your HTML.

General useage.

```<code>.order-1
.order-2
.order-3
.order-4
.order-5
</code>```

Ordering according to screen size. In this exammple, the Column will show 1st on SM screens, it will show second on MD screens and third on LG screens.

```<code>.order-sm-1
.order-md-2
.order-lg-3 etc etc etc
</code>```

You can also specify items to be unordered or ordered-first and ordered-last. Here are the docs for everything here....

https://getbootstrap.com/docs/5.0/layout/columns/#order-classes

Body:
I have a projects section part of my portfolio. I alternate between description on left/image on right to image on left/description on right. I have been painstakingly trying to make this responsive, but I cannot think of what to do to fix this. I want the image on top and the text below on every project when viewed on a smartphone.

This is the HTML for the projects section:

My Projects

Tindog

An landing page for the Tindog app. A twist on a typical dating app. Created with Bootstrap 5 and HTML/CSS utilizing Bootstrap grids.

                Live Site
                Github Repo

NFT Preview Card

An preview card page created with HTML/CSS.

                Live Site
          Github Repo

3-Card Column

A preview card of vehicle options created with HTML/CSS.

                Live Site
                Github Repo

I used Bootstrap 5 and I tried to use col-xs-12 but it didn't look right and it also completely messed up the desktop view. The laptop view looks exactly how I want it to look, it's just every other sizing that it completely wrong.

This is the CSS:

/* Projects */

    #projects {
        width: 100%;
    }

    #projects h1 {
        text-align: center;
    }

    .projects {
        margin-left: 0;

    }

    .project-img{
        width: 300px;
    }

    .project-desc-left {
        margin: 5rem;
        width: 320px;
    }

    .project-desc-right {

    }
}

I have been trying to tweak the code for days, but I have barely made any progress.

This is the laptop view of the projects section

This is the mobile view of the projects section

Body:
You should be able to do it using Bootstrap 5 Column Ordering without adding any extra CSS. You can add these classes to your Col's and they will appear on the page in the order given no matter their physical place in your HTML.

General useage.

.order-1
.order-2
.order-3
.order-4
.order-5

Ordering according to screen size. In this exammple, the Column will show 1st on SM screens, it will show second on MD screens and third on LG screens.

.order-sm-1
.order-md-2
.order-lg-3 etc etc etc

You can also specify items to be unordered or ordered-first and ordered-last. Here are the docs for everything here....

https://getbootstrap.com/docs/5.0/layout/columns/#order-classes


问:
Iterating over data to display inputs renders data multiple times
I am trying to create a custom component that iterates over an array of data and display for each item an input field type radio with its according label, it works but for some reason the data is displayed three times, instead of just once for each field and I cant figure out why, I just want to render just three inputs, why does this behavior occur, am I missing something? Here is my code:

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Tooltip } from '@progress/kendo-react-tooltip';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { RadioGroup, RadioButton } from '@progress/kendo-react-inputs';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);

const data = [
  {
    label: 'Female',
    value: 'female',
  },
  {
    label: 'Male',
    value: 'male',
  },
  {
    label: 'Other',
    value: 'other',
  },
];

const emailValidator = (value) =>
  emailRegex.test(value) ? '' : 'Please enter a valid email.';

const EmailInput = (fieldRenderProps) => {
  const { validationMessage, visited, ...others } = fieldRenderProps;
  return (
    <div>
      <Input {...others} />
      {visited && validationMessage && <Error>{validationMessage}</Error>}
    </div>
  );
};

const Component = () => {
  return (
    <>
      {data.map((item, index) => {
        return (
          <p>
            <input
              name="group1"
              type="radio"
              value={item.value}
              label={item.label}
              key={index}
            />
            <label>{item.label}</label>
          </p>
        );
      })}
    </>
  );
};

const App = () => {
  const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
  const tooltip = React.useRef(null);

  return (
    <Form
      onSubmit={handleSubmit}
      render={(formRenderProps) => (
        <FormElement
          style={{
            maxWidth: 650,
          }}
        >
          <fieldset className={'k-form-fieldset'}>
            <legend className={'k-form-legend'}>
              Please fill in the fields:
            </legend>
            <div className="mb-3">
              <Field
                name={'firstName'}
                component={Input}
                label={'First name'}
              />
            </div>

            <div className="mb-3">
              <Field name={'lastName'} component={Input} label={'Last name'} />
            </div>

            <div className="mb-3">
              <Field
                name={'email'}
                type={'email'}
                component={EmailInput}
                label={'Email'}
                validator={emailValidator}
              />
            </div>
          </fieldset>

          <div
            onMouseOver={(event) =>
              tooltip.current && tooltip.current.handleMouseOver(event)
            }
            onMouseOut={(event) =>
              tooltip.current && tooltip.current.handleMouseOut(event)
            }
          >
            <RadioGroup data={data} item={Component} />
            <Tooltip
              ref={tooltip}
              anchorElement="target"
              position="right"
              openDelay={300}
              parentTitle={true}
            />
          </div>

          <div className="k-form-buttons">
            <button
              type={'submit'}
              className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
              disabled={!formRenderProps.allowSubmit}
            >
              Submit
            </button>
          </div>
        </FormElement>
      )}
    />
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));
</code>```

and here is an example:

https://stackblitz.com/edit/react-rfb1ux-jpqvwy?file=app/main.jsx

答:
```<code> <RadioGroup  data={[1]} item={Component} />
</code>```

RadioGroup assumes that Component element is to be rendered over data array ... so it renders like this -->

```<code>data.map(val=><Component />)
here size of data array is 3 .
</code>```

or

```<code> <Component />
</code>```

Body:
I am trying to create a custom component that iterates over an array of data and display for each item an input field type radio with its according label, it works but for some reason the data is displayed three times, instead of just once for each field and I cant figure out why, I just want to render just three inputs, why does this behavior occur, am I missing something? Here is my code:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Tooltip } from '@progress/kendo-react-tooltip';
import { Form, Field, FormElement } from '@progress/kendo-react-form';
import { RadioGroup, RadioButton } from '@progress/kendo-react-inputs';
import { Error } from '@progress/kendo-react-labels';
import { Input } from '@progress/kendo-react-inputs';
const emailRegex = new RegExp(/\S+@\S+\.\S+/);

const data = [
  {
    label: 'Female',
    value: 'female',
  },
  {
    label: 'Male',
    value: 'male',
  },
  {
    label: 'Other',
    value: 'other',
  },
];

const emailValidator = (value) =>
  emailRegex.test(value) ? '' : 'Please enter a valid email.';

const EmailInput = (fieldRenderProps) => {
  const { validationMessage, visited, ...others } = fieldRenderProps;
  return (

      <Input {...others} />
      {visited && validationMessage && <Error>{validationMessage}</Error>}

  );
};

const Component = () => {
  return (
    <>
      {data.map((item, index) => {
        return (

            <input
              name="group1"
              type="radio"
              value={item.value}
              label={item.label}
              key={index}
            />
            {item.label}

        );
      })}
    </>
  );
};

const App = () => {
  const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
  const tooltip = React.useRef(null);

  return (
    <Form
      onSubmit={handleSubmit}
      render={(formRenderProps) => (
        <FormElement
          style={{
            maxWidth: 650,
          }}
        >
          <fieldset className={'k-form-fieldset'}>
            <legend className={'k-form-legend'}>
              Please fill in the fields:
            </legend>

              <Field
                name={'firstName'}
                component={Input}
                label={'First name'}
              />

              <Field name={'lastName'} component={Input} label={'Last name'} />

              <Field
                name={'email'}
                type={'email'}
                component={EmailInput}
                label={'Email'}
                validator={emailValidator}
              />

          </fieldset>

              tooltip.current && tooltip.current.handleMouseOver(event)
            }
            onMouseOut={(event) =>
              tooltip.current && tooltip.current.handleMouseOut(event)
            }
          >
            <RadioGroup data={data} item={Component} />
            <Tooltip
              ref={tooltip}
              anchorElement="target"
              position="right"
              openDelay={300}
              parentTitle={true}
            />

            <button
              type={'submit'}
              className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
              disabled={!formRenderProps.allowSubmit}
            >
              Submit
            </button>

        </FormElement>
      )}
    />
  );
};

ReactDOM.render(<App />, document.querySelector('my-app'));

and here is an example:

https://stackblitz.com/edit/react-rfb1ux-jpqvwy?file=app/main.jsx

Body:
 <RadioGroup  data={[1]} item={Component} />

RadioGroup assumes that Component element is to be rendered over data array ... so it renders like this -->

data.map(val=><Component />)
here size of data array is 3 .

or

 <Component />


问:
Can't serve Angular 6 on Windows 10
I'm having a problem serving an Angular 6 project in a PC with Windows 10.
I have the Angular CLI installed with version 11.2.18 and the ng command works, but when running ng serve it throws this error about an RxJs operator:

Cannot find module '../operators/refCount'

I have no problem running npm install and I can serve the project without problems in a Mac with the same CLI version.

These are the dependencies of the project:

```<code>"dependencies": {
    "@angular/animations": "6.1.8",
    "@angular/cdk": "6.4.7",
    "@angular/common": "6.1.0",
    "@angular/compiler": "6.1.0",
    "@angular/core": "6.1.0",
    "@angular/forms": "6.1.0",
    "@angular/http": "6.1.0",
    "@angular/material": "6.4.7",
    "@angular/platform-browser": "6.1.0",
    "@angular/platform-browser-dynamic": "6.1.0",
    "@angular/router": "6.1.0",
    "@ngx-translate/core": "9.1.1",
    "@ngx-translate/http-loader": "2.0.1",
    "core-js": "2.5.4",
    "material-tooltip": "1.0.1",
    "ngx-bootstrap": "3.0.1",
    "ngx-color-picker": "6.7.0",
    "ngx-drag-drop": "1.1.0",
    "rxjs": "6.2.2",
    "rxjs-compat": "6.2.2",
    "xlsx": "0.14.0",
    "zone.js": "~0.8.26"
  },
"devDependencies": {
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.2",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~2.9.2"
  }
</code>```

Any ideas of what's wrong?

答: Try running npm install rxjs@6.2.2 --save-dev.

Title: Can't serve Angular 6 on Windows 10

Body:
I'm having a problem serving an Angular 6 project in a PC with Windows 10.
I have the Angular CLI installed with version 11.2.18 and the ng command works, but when running ng serve it throws this error about an RxJs operator:

Cannot find module '../operators/refCount'

I have no problem running npm install and I can serve the project without problems in a Mac with the same CLI version.

These are the dependencies of the project:

"dependencies": {
    "@angular/animations": "6.1.8",
    "@angular/cdk": "6.4.7",
    "@angular/common": "6.1.0",
    "@angular/compiler": "6.1.0",
    "@angular/core": "6.1.0",
    "@angular/forms": "6.1.0",
    "@angular/http": "6.1.0",
    "@angular/material": "6.4.7",
    "@angular/platform-browser": "6.1.0",
    "@angular/platform-browser-dynamic": "6.1.0",
    "@angular/router": "6.1.0",
    "@ngx-translate/core": "9.1.1",
    "@ngx-translate/http-loader": "2.0.1",
    "core-js": "2.5.4",
    "material-tooltip": "1.0.1",
    "ngx-bootstrap": "3.0.1",
    "ngx-color-picker": "6.7.0",
    "ngx-drag-drop": "1.1.0",
    "rxjs": "6.2.2",
    "rxjs-compat": "6.2.2",
    "xlsx": "0.14.0",
    "zone.js": "~0.8.26"
  },
"devDependencies": {
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.2",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~2.9.2"
  }

Any ideas of what's wrong?


问:
How to install only required fonts from Font Awesome?
I would to use a couple of icons from Font Awesome.

I see that we can download the entire font-awesome directory and use simple code like  and use fa-camera-retro to display the icons.

Is it possible for me to download only the fonts I will be using?

For the above example if I am using only , fa-camera-retro, I would like to reduce the directory size by only using the files related to this icon.

答:
I'd like to propose an alternative solution since there're only a few answers provided here.
I faced the same issue and found that the easiest solution was to simply use the svg version. Make sure to provide a height or width dimension though!

```
<pre class="lang-css prettyprint-override"><code>.my-fa-icon {
  width: 1rem; /** Required */
}
</code>```

I know it's not exactly what the question demands, but it's simple & works well.

Body:
I'd like to propose an alternative solution since there're only a few answers provided here.
I faced the same issue and found that the easiest solution was to simply use the svg version. Make sure to provide a height or width dimension though!

<img class="my-fa-icon" src="/assets/css/fontawesome-free-svgs/brands/facebook-f.svg">

.my-fa-icon {
  width: 1rem; /** Required */
}

I know it's not exactly what the question demands, but it's simple & works well.


答:
Radio Group will do the mapping for you. Try changing Component to:

```<code>const Component = (props) => {
  return (
    <p>
      <input
        name="group1"
        type="radio"
        value={props.children.props.value}
        label={props.children.props.label}
        key={props.children.props.label}
      />
      <label>{props.children.props.label}</label>
    </p>
  );
};
</code>```

This will then map out the items for you.

Title: Iterating over data to display inputs renders data multiple times

Body:
Radio Group will do the mapping for you. Try changing Component to:

const Component = (props) => {
  return (
    <p>
      <input
        name="group1"
        type="radio"
        value={props.children.props.value}
        label={props.children.props.label}
        key={props.children.props.label}
      />
      <label>{props.children.props.label}</label>
    </p>
  );
};

This will then map out the items for you.


问:
How to get winform fullpath?
I have a winform and its fullpath is C:\test.exe

How do I get the winform fullpath at run time? For example, the user may move the winform to other places. Thanks.

答:
This information is part of the My namespace.  The directory path can be found via
My.Application.Info.DirectoryPath</p>

Title: How to get winform fullpath?


问:
How do I use Powershell to chain Invoke Command?
I have the list of commands to be invoke in my PC to a server

Start the cmd.exe as Administrator

Logon to PPP database with dbmcli.exe

Run the backup history command to show the last backup

```<code>Invoke-Command -Session $session -ScriptBlock {echo "backup_history_list -l DAT -c START,STOP,LABEL,ACTION,RC -Inverted" | Start-Process cmd -Verb runAs | C:\sapdb\clients\DatabaseStudio\pgm\dbmcli.exe -d PPP -n localhost -u "CONTROL,Testing123"}
</code>```

Does not work.

Error:

```<code>The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
    + CategoryInfo          : InvalidArgument: (backup_history_...ON,RC -Inverted:PSObject) [Start-Process], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.StartProcessCommand
    + PSComputerName        : localhost
</code>```

答:
To use multiple commands in one line use Semicolon (;) after each complete command. Your command will be like this:

```<code>Invoke-Command -Session $session -ScriptBlock {echo "backup_history_list -l DAT -c START,STOP,LABEL,ACTION,RC -Inverted" ; Start-Process cmd -Verb runAs | C:\sapdb\clients\DatabaseStudio\pgm\dbmcli.exe -d PPP -n localhost -u "CONTROL,Testing123"}
</code>```

Here I am shortly describing some of the Operator of Powershell:

Semicolon (;) Operator: It allows you to execute many instructions in first command success or failure.

command1 ; command2 ; command3 [; command4 ...]

OR (||) Operator: Only the command after || will run if the command before || failed to execute.

```<code>command1 || command2 || command3 [|| command4 ...]
</code>```

AND (&&) Operator:If anyone left of an operator fails then all other commands located right of the operator won't be executed.

```<code>command1 && command2 && command3 [&& command4 ...]
</code>```

 Pipeline (|) Operator:
This | is called pipeline operator. If you want to use the output of one command as the input of another command then you can use the pipe (|) operator.

```<code>command1 | command2 | command3
</code>```

Body:
I have the list of commands to be invoke in my PC to a server

Start the cmd.exe as Administrator

Logon to PPP database with dbmcli.exe

Run the backup history command to show the last backup

Invoke-Command -Session $session -ScriptBlock {echo "backup_history_list -l DAT -c START,STOP,LABEL,ACTION,RC -Inverted" | Start-Process cmd -Verb runAs | C:\sapdb\clients\DatabaseStudio\pgm\dbmcli.exe -d PPP -n localhost -u "CONTROL,Testing123"}

Does not work.

Error:

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
    + CategoryInfo          : InvalidArgument: (backup_history_...ON,RC -Inverted:PSObject) [Start-Process], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.StartProcessCommand
    + PSComputerName        : localhost

Body:
To use multiple commands in one line use Semicolon (;) after each complete command. Your command will be like this:

Invoke-Command -Session $session -ScriptBlock {echo "backup_history_list -l DAT -c START,STOP,LABEL,ACTION,RC -Inverted" ; Start-Process cmd -Verb runAs | C:\sapdb\clients\DatabaseStudio\pgm\dbmcli.exe -d PPP -n localhost -u "CONTROL,Testing123"}

Here I am shortly describing some of the Operator of Powershell:

Semicolon (;) Operator: It allows you to execute many instructions in first command success or failure.

command1 ; command2 ; command3 [; command4 ...]

OR (||) Operator: Only the command after || will run if the command before || failed to execute.

command1 || command2 || command3 [|| command4 ...]

AND (&&) Operator:If anyone left of an operator fails then all other commands located right of the operator won't be executed.

command1 && command2 && command3 [&& command4 ...]

 Pipeline (|) Operator:
This | is called pipeline operator. If you want to use the output of one command as the input of another command then you can use the pipe (|) operator.

command1 | command2 | command3


问:
How to get Image Url from local Json file in React.js
I want to be able to display images from a local folder by getting the URL from JSON file. So far I've tried :

src={require(blog.imUrl)}
src={blog.imgUrl}
src={require(${blog.imgUrl})}

Errors i am getting when I use require :

Error: Cannot find module '../../images/safe-image.jpeg'

```<code>import { useHistory } from 'react-router-dom';
import { Col, Row, Container, Image } from 'react-bootstrap';
import blogArticles from './blog.json';
import './BlogCard.css';

export default function BlogCard() {
  const history = useHistory();

  function handleClick() {
    history.push('/`${blog.id}`');
  }

  return blogArticles.map((blog) => {
    return (
      <Container key={blog.id} className="blogContainer">
        <Row>
          <Col xs={6} md={6} lg={8}>
            <h3 className="blogTitle">{blog.title}</h3>
            <span className="blogBody">{blog.body.substring(0, 250)}...</span>
            <button onClick={handleClick} className="readMoreButton">
              Read More
            </button>
          </Col>
          <Col xs={4} md={4} lg={3} className="imageContainer">
            <Image src={require(blog.imgUrl)} roundedCircle />
          </Col>
        </Row>
      </Container>
    );
  });
}```

Here is my JSON File structure :

{
    "id": 3,
    "title": "abc",
    "body": "abcdefg",
    "author": "as",
    "imgUrl": "../../images/leon-biss.jpg"
}

```

答:
Simply react works by rendering jsx so At first always try to maintain javascript or variables before return or render so js works properly in react app . You can try this method and keep your images in public folder.
1.

import { Col, Row, Container, Image } from 'react-bootstrap';
import img from '../path

export default function BlogCard() {

  return (
    <Image src={img} roundedCircle />
  );
});
```

Body:
I want to be able to display images from a local folder by getting the URL from JSON file. So far I've tried :

src={require(blog.imUrl)}
src={blog.imgUrl}
src={require(${blog.imgUrl})}

Errors i am getting when I use require :

Error: Cannot find module '../../images/safe-image.jpeg'

import { useHistory } from 'react-router-dom';
import { Col, Row, Container, Image } from 'react-bootstrap';
import blogArticles from './blog.json';
import './BlogCard.css';

export default function BlogCard() {
  const history = useHistory();

  function handleClick() {
    history.push('/`${blog.id}`');
  }

  return blogArticles.map((blog) => {
    return (
      <Container key={blog.id} className="blogContainer">
        <Row>
          <Col xs={6} md={6} lg={8}>

{blog.title}

            {blog.body.substring(0, 250)}...
            <button onClick={handleClick} className="readMoreButton">
              Read More
            </button>
          </Col>
          <Col xs={4} md={4} lg={3} className="imageContainer">
            <Image src={require(blog.imgUrl)} roundedCircle />
          </Col>
        </Row>
      </Container>
    );
  });
}```

Here is my JSON File structure :

{
    "id": 3,
    "title": "abc",
    "body": "abcdefg",
    "author": "as",
    "imgUrl": "../../images/leon-biss.jpg"
}


问:
Accessing cell text when using the GridView of a ListView in WPF
I am really struggling with the WPF ListView at the moment, I imagine a missing something really dumb but after a couple of hours of googling I though I had better ask.

I am trying to access the text contents of individual cells in a ListView which has been created with a GridView thus:

```<code><ListView Name="MyListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Foo" DisplayMemberBinding="{Binding Foo}"/>
            <GridViewColumn Header="Bar" DisplayMemberBinding="{Binding Bar}"/>
        </GridView>
    </ListView.View>
</ListView>
</code>```

I am adding to the list view as so:

```<code>var foobars = new ObservableCollection<Foobar>();
foobars.Add(new Foobar { Foo = "Hello", Bar = "world" });
MyListView.ItemsSource = foobars;
</code>```

Now I would like to grab the word "world" from the second column of the first row. If this was WinForms I would type:

```<code>var word = (string)(((ListViewItem)MyListView.Items[0]).SubItems[1]);
</code>```

I can't find any way to do this in WPF! I realize I could do:

```<code>var word = ((Foobar)MyListView.Items[0]).Bar;
</code>```

But in my real application the text which appears in the ListView has been through one of a couple of ValueConverters based on which column it is in, and so is not the same as the text in the binding object. I just need to grab the text which is being displayed to the user, not the underlying data object.

Do any of the code gurus here have any advice??

Cheers,

Gavin

答:
Ok, found a ugly way to do this. Here is the code to get "world" from the first row, second column cell:

```<code>var columns = ((GridView) MyListView.View).Columns;
var foobar = (Foobar)MyListView.Items[0];
var result = (string)DataBinder.Eval(foobar, (Binding) columns[0].DisplayMemberBinding);
</code>```

This is using a helper class (thanks to http://social.expression.microsoft.com/Forums/en-US/wpf/thread/315d2442-b978-4e5f-89cd-1004a51f390d/ you saved alot of my hair from being pulled):

```<code>public class DataBinder
{
    private static readonly DependencyProperty BindingEvalProperty = DependencyProperty.RegisterAttached(
        "BindingEval",
        typeof(Object),
        typeof(DependencyObject),
        new UIPropertyMetadata(null));

    public static Object Eval(Object data, Binding binding)
    {
        var newbinding = new Binding {Path = binding.Path, Converter = binding.Converter, Source = data};
        var evalobj = new DependencyObject();
        BindingOperations.SetBinding(evalobj, BindingEvalProperty, newbinding);
        return evalobj.GetValue(BindingEvalProperty);
    }
}
</code>```

So this is grabbing the binding object from the second column and evaluating it against the data object associated with the first row the same way the underlying GridView code would be. This will work for my application, but if anyone has a neater solution please feel free to post an answer!

Body:
I am really struggling with the WPF ListView at the moment, I imagine a missing something really dumb but after a couple of hours of googling I though I had better ask.

I am trying to access the text contents of individual cells in a ListView which has been created with a GridView thus:

<ListView Name="MyListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Foo" DisplayMemberBinding="{Binding Foo}"/>
            <GridViewColumn Header="Bar" DisplayMemberBinding="{Binding Bar}"/>
        </GridView>
    </ListView.View>
</ListView>

I am adding to the list view as so:

var foobars = new ObservableCollection<Foobar>();
foobars.Add(new Foobar { Foo = "Hello", Bar = "world" });
MyListView.ItemsSource = foobars;

Now I would like to grab the word "world" from the second column of the first row. If this was WinForms I would type:

var word = (string)(((ListViewItem)MyListView.Items[0]).SubItems[1]);

I can't find any way to do this in WPF! I realize I could do:

var word = ((Foobar)MyListView.Items[0]).Bar;

But in my real application the text which appears in the ListView has been through one of a couple of ValueConverters based on which column it is in, and so is not the same as the text in the binding object. I just need to grab the text which is being displayed to the user, not the underlying data object.

Do any of the code gurus here have any advice??

Cheers,

Gavin

Body:
Ok, found a ugly way to do this. Here is the code to get "world" from the first row, second column cell:

var columns = ((GridView) MyListView.View).Columns;
var foobar = (Foobar)MyListView.Items[0];
var result = (string)DataBinder.Eval(foobar, (Binding) columns[0].DisplayMemberBinding);

This is using a helper class (thanks to http://social.expression.microsoft.com/Forums/en-US/wpf/thread/315d2442-b978-4e5f-89cd-1004a51f390d/ you saved alot of my hair from being pulled):

public class DataBinder
{
    private static readonly DependencyProperty BindingEvalProperty = DependencyProperty.RegisterAttached(
        "BindingEval",
        typeof(Object),
        typeof(DependencyObject),
        new UIPropertyMetadata(null));

    public static Object Eval(Object data, Binding binding)
    {
        var newbinding = new Binding {Path = binding.Path, Converter = binding.Converter, Source = data};
        var evalobj = new DependencyObject();
        BindingOperations.SetBinding(evalobj, BindingEvalProperty, newbinding);
        return evalobj.GetValue(BindingEvalProperty);
    }
}

So this is grabbing the binding object from the second column and evaluating it against the data object associated with the first row the same way the underlying GridView code would be. This will work for my application, but if anyone has a neater solution please feel free to post an answer!


问:
Slowness after migrating to Grails 5.1.1 - time spent on GrailsControllerUrlMappingInfo
Recently, we migrated our backend APIs from Grails 3 to Grails 5.1.1
Together with it we also upgraded java version to 11. Everything is running on Docker. Otherwise, nothing else has changed.

After the migration, we are now facing performance issues. But it's a weird one.

First, we got some results from NewRelic:

NewRelic is showing that org.grails.web.mapping.mvc.GrailsControllerUrlMappingInfo is to blame. There is nothing else underneath it that is slow.
Digging a bit deeper, we found an article (from a while ago) which claims that NewRelic is not instrumenting Grails very well.

At this point, we were trying to reproduce the issues locally and we did. Created a simple function that wraps whatever we need with a timer to measure how long things taking to execute:

```<code>def withExecutionTimeLog(Closure closure) {
        Long start = System.currentTimeMillis()
        def result = closure()
        log.warn "Execution time -> ${System.currentTimeMillis() - start} ms"

        result
    }
</code>```

And as an example, used it for one of the slowest endpoints:

This is a controller (the highest(ish) point under our control)

```<code>def create(Long workspaceId, Long projectId) {
        withExecutionTimeLog {
            canUpdateProject(projectId) {
                withExceptionsHandling {
                    CecUtilization utilization =
                            cecUtilizationService.create(workspaceId, projectId, getCurrentUser())

                    [utilization: utilization]
                }
            }
        }
    }
</code>```

So, in this case, the timer function wraps everything including the DB calls, all the way to view rendering.

And here is the result:

The full request cycle takes 524ms (out of which 432ms is server-side:

From that little execution time logger I've got 161ms

Given all of that, it looks like NewRelic is kinda right. Something else is wasting cycles. The biggest question is WHAT?

How can I profile that? Maybe someone came across a similar situation.
How can I resolve it?

On another note, since we have all the possible monitoring tools in place, I can tell for sure that the servers are not doing much (including the DB). The allocated heap size is up to 3G.
Usually, the first request to the same endpoint takes much longer, and the consecutive ones are much better but still slow.

UPDATE

Decided to dig deeper. Hooked up the Async Profiler and I think my original assumptions were proved true.

The class loader seems to be the one causing the performance issues. This also explains the slowness of the first request (of any type), while subsequent ones start working faster. But, if I do the same call in another 4-5 minutes, it loads the classes again and is slow.

So, unless I am mistaken, the issue here is the class loader. I am blaming TomcatEmbeddedWebappClassLoader for this.

Now, the biggest question is how do I fix that in Grails? I am running a war file in prod -> java -Dgrails.env=prod -Xms1500m -Xmx3000m -jar app.war

I found this post that is somewhat in the same direction, but I am not sure how to wire it in, in Grails.

UPDATE #2

Looking for the class loader solution brought me to this issue. The proposed solution is for Spring. I am wondering what is the way to solve that for grails.

答:
In the link https://github.com/spring-projects/spring-boot/issues/16471 has the following report:

"It's quite low priority as the problem can be avoided by using .jar packaging rather than .war packaging or, I believe, by switching to another embedded container. As things stand, we have no plans to tackle this in the 2.x timeframe."

So I ran the command './gradlew bootJar'.

And I did the test with siege and the first request was from 1.62 seconds to 0.47 seconds

Body:
Recently, we migrated our backend APIs from Grails 3 to Grails 5.1.1
Together with it we also upgraded java version to 11. Everything is running on Docker. Otherwise, nothing else has changed.

After the migration, we are now facing performance issues. But it's a weird one.

First, we got some results from NewRelic:

NewRelic is showing that org.grails.web.mapping.mvc.GrailsControllerUrlMappingInfo is to blame. There is nothing else underneath it that is slow.
Digging a bit deeper, we found an article (from a while ago) which claims that NewRelic is not instrumenting Grails very well.

At this point, we were trying to reproduce the issues locally and we did. Created a simple function that wraps whatever we need with a timer to measure how long things taking to execute:

def withExecutionTimeLog(Closure closure) {
        Long start = System.currentTimeMillis()
        def result = closure()
        log.warn "Execution time -> ${System.currentTimeMillis() - start} ms"

        result
    }

And as an example, used it for one of the slowest endpoints:

This is a controller (the highest(ish) point under our control)

def create(Long workspaceId, Long projectId) {
        withExecutionTimeLog {
            canUpdateProject(projectId) {
                withExceptionsHandling {
                    CecUtilization utilization =
                            cecUtilizationService.create(workspaceId, projectId, getCurrentUser())

                    [utilization: utilization]
                }
            }
        }
    }

So, in this case, the timer function wraps everything including the DB calls, all the way to view rendering.

And here is the result:

The full request cycle takes 524ms (out of which 432ms is server-side:

From that little execution time logger I've got 161ms

Given all of that, it looks like NewRelic is kinda right. Something else is wasting cycles. The biggest question is WHAT?

How can I profile that? Maybe someone came across a similar situation.
How can I resolve it?

On another note, since we have all the possible monitoring tools in place, I can tell for sure that the servers are not doing much (including the DB). The allocated heap size is up to 3G.
Usually, the first request to the same endpoint takes much longer, and the consecutive ones are much better but still slow.

UPDATE

Decided to dig deeper. Hooked up the Async Profiler and I think my original assumptions were proved true.

The class loader seems to be the one causing the performance issues. This also explains the slowness of the first request (of any type), while subsequent ones start working faster. But, if I do the same call in another 4-5 minutes, it loads the classes again and is slow.

So, unless I am mistaken, the issue here is the class loader. I am blaming TomcatEmbeddedWebappClassLoader for this.

Now, the biggest question is how do I fix that in Grails? I am running a war file in prod -> java -Dgrails.env=prod -Xms1500m -Xmx3000m -jar app.war

I found this post that is somewhat in the same direction, but I am not sure how to wire it in, in Grails.

UPDATE #2

Looking for the class loader solution brought me to this issue. The proposed solution is for Spring. I am wondering what is the way to solve that for grails.


问:
Google Chrome Path in Windows 10
Google repeatedly changed the path to the .exe of Chrome. Sometimes it's hidden in %APPDATA%, in Version 35/36 they changed the path back to program files. There are also differencies across the Windows versions.

Where is Google Chrome located in Windows 10?

答:
To find the location of Google, type the following command...

chrome://version

And then look for Command Line on the left side of the screen.

Title: Google Chrome Path in Windows 10


问:
How to randomly reshuffle letters in words
I am trying to make a word scrambler in R. So i have put some words in a collection and tried to use strsplit() to split the letters of each word in the collection.

But I don't understand how to jumble the letters of a word and merge them to one word in R Tool. Does anyone know how can I solve this?

This is what I have done
enter image description here

答:
Once you've split the words, you can use sample() to rescramble the letters, and then paste0() with collapse="", to concatenate back into a 'word'

```<code>lapply(words, function(x) paste0(sample(strsplit(x, split="")[[1]]), collapse=""))

</code>```

Body:
Once you've split the words, you can use sample() to rescramble the letters, and then paste0() with collapse="", to concatenate back into a 'word'

lapply(words, function(x) paste0(sample(strsplit(x, split="")[[1]]), collapse=""))


问:
How to create a persistant state for Pinia + Quasar?
I'm using Pinia for state managment, and I want the state to persist when the page is refeshed.

I'm aware of two options:

Use a plugin. Vuex has a vuex-persistedstate plugin for this, and Pinia has a similar plugin but it's still under development.

Use local storage. Luckily Quasar has a LocalStorage plugin which would be nice to use here. But I'm not sure how to integrate it with Pinia, thus the reason for this post.

I found a nice tutorial doing something similar with Pinia + Vueuse.

And I tried adapting it to my needs with Pinia + TypeScript + Quasar LocalStorage Plugin as per below:

```<code>import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
import { LocalStorage } from 'quasar';

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> };

export const useUserStore = defineStore('user', {
  state: () => ({
    // user: {} as CreateMutable<User>, // This was my previous non-persistent state
    user: LocalStorage.set('user', {}) as unknown as CreateMutable<User>, // This is my attempt at using LocalStorage persistent state
  }),
  actions: {
    setUser(userData: User) {
      this.user = userData;
    },
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData;
    },
  },
});
</code>```

Unfortunately it doesn't work.

The state does not persist on page refresh.

Any ideas on how to make this work?

答:
To initialize the user state with Local Storage data, use Quasar's LocalStorage.getItem(), and default to an empty object:

export const useUserStore = defineStore('user', {
  state: () => ({
    user: (LocalStorage.getItem('user') || {}) as CreateMutable<User>,
  }),
  ⋮
```
<p>In the <code>setUser</code> action, call <code>LocalStorage.set()</code> to save the user data to Local Storage.</p>
<p>Since <code>user</code> is an object, clone the object instead of directly assigning it, so that the store does not unnecessarily retain a reference to external objects. If <code>userData</code> has nested properties, you can use Quasar's <code>extend</code> to deep-copy the object:</p>
<pre class="lang-js prettyprint-override"><code>import { extend, LocalStorage } from 'quasar'

export const useUserStore = defineStore('user', {
  ⋮
  actions: {
    setUser(userData: User) {
      const copyOfData = { ...userData }
      // or...
      const copyOfData = extend(true /* deep */, {}, userData)

      LocalStorage.set('user', copyOfData)
      this.user = copyOfData
    },
  }
})
</code>```

demo

Body:
I'm using Pinia for state managment, and I want the state to persist when the page is refeshed.

I'm aware of two options:

Use a plugin. Vuex has a vuex-persistedstate plugin for this, and Pinia has a similar plugin but it's still under development.

Use local storage. Luckily Quasar has a LocalStorage plugin which would be nice to use here. But I'm not sure how to integrate it with Pinia, thus the reason for this post.

I found a nice tutorial doing something similar with Pinia + Vueuse.

And I tried adapting it to my needs with Pinia + TypeScript + Quasar LocalStorage Plugin as per below:

import { User } from 'firebase/auth';
import { defineStore } from 'pinia';
import { LocalStorage } from 'quasar';

type CreateMutable<T> = { -readonly [P in keyof T]: CreateMutable<T[P]> };

export const useUserStore = defineStore('user', {
  state: () => ({
    // user: {} as CreateMutable<User>, // This was my previous non-persistent state
    user: LocalStorage.set('user', {}) as unknown as CreateMutable<User>, // This is my attempt at using LocalStorage persistent state
  }),
  actions: {
    setUser(userData: User) {
      this.user = userData;
    },
    setPhotoURL(photoURLData: string | null) {
      this.user.photoURL = photoURLData;
    },
  },
});

Unfortunately it doesn't work.

The state does not persist on page refresh.

Any ideas on how to make this work?

Body:
To initialize the user state with Local Storage data, use Quasar's LocalStorage.getItem(), and default to an empty object:

export const useUserStore = defineStore('user', {
  state: () => ({
    user: (LocalStorage.getItem('user') || {}) as CreateMutable<User>,
  }),
  ⋮

In the setUser action, call LocalStorage.set() to save the user data to Local Storage.

Since user is an object, clone the object instead of directly assigning it, so that the store does not unnecessarily retain a reference to external objects. If userData has nested properties, you can use Quasar's extend to deep-copy the object:

import { extend, LocalStorage } from 'quasar'

export const useUserStore = defineStore('user', {
  ⋮
  actions: {
    setUser(userData: User) {
      const copyOfData = { ...userData }
      // or...
      const copyOfData = extend(true /* deep */, {}, userData)

      LocalStorage.set('user', copyOfData)
      this.user = copyOfData
    },
  }
})

demo


问:
How to use ActiveAdmin on models using has_many through association?
I am using ActiveAdmin gem in my project.

I have 2 models using has_many through association. The database schema looks exactly the same as the example in RailsGuide. http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

(source: rubyonrails.org)

How can I use ActiveAdmin to ...

show appointment date of each patient in physicians page?

edit appointment date of each patient in physicians page?

Thanks all. :)

答:
For 1)

```<code>show do
  panel "Patients" do
    table_for physician.appointments do
      column "name" do |appointment|
        appointment.patient.name
      end
      column :appointment_date
    end
  end
end
</code>```

For 2)

```<code>form do |f|
  f.inputs "Details" do # physician's fields
    f.input :name
  end

  f.has_many :appointments do |app_f|
    app_f.inputs "Appointments" do
      if !app_f.object.nil?
        # show the destroy checkbox only if it is an existing appointment
        # else, there's already dynamic JS to add / remove new appointments
        app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
      end

      app_f.input :patient # it should automatically generate a drop-down select to choose from your existing patients
      app_f.input :appointment_date
    end
  end
end
</code>```

Body:
For 1)

show do
  panel "Patients" do
    table_for physician.appointments do
      column "name" do |appointment|
        appointment.patient.name
      end
      column :appointment_date
    end
  end
end

For 2)

form do |f|
  f.inputs "Details" do # physician's fields
    f.input :name
  end

  f.has_many :appointments do |app_f|
    app_f.inputs "Appointments" do
      if !app_f.object.nil?
        # show the destroy checkbox only if it is an existing appointment
        # else, there's already dynamic JS to add / remove new appointments
        app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
      end

      app_f.input :patient # it should automatically generate a drop-down select to choose from your existing patients
      app_f.input :appointment_date
    end
  end
end


问:
Object Oriented Programming, not getting filtered by the if and else// and
So currently studying OOP, I have encountered a problem regarding why the numbers are not getting filtered by my range in the if and else statements, and also one more thing on the last part of the code there should be something with the lines of "public String showDetails()" but I don't know what is inside of it.</p>
```<code>    package com.xble.department.domain

public class Person
{
    private String name;
    private int EmpNo;
    private int age;

    public Person()
    {

    }
    public Person(String n, int en, int a)
    {
        name = n;

        if((en < 0) && (en >= 1) && (en <= 999999))
            en = 0;
        else
            EmpNo = en;

        if((a < 0) && (a >= 1) && (a <= 65))
            a = 0;
        else
            age = a;
    }

    public void setName(String n)
    {
        name=n;
    }

    public void setEmpNo(int en)
    {
            if((en < 0) && (en >= 1) && (en <= 999999))
                en = 0;
            else
                EmpNo = en;
    }

    public void setAge(int a)
    {
            if((a < 0) && (a >= 1) && (a <= 65))
                a = 0;
            else
                age = a;
    }

    public String getName()
    {
        return name;
    }

    public int getEmpNo()
    {
        return EmpNo;
    }

    public int getAge()
    {
        return age;
    }

    //public String showDetails()

}
</code>```

答:
Here's your problem:

(en < 0) && (en >= 1)
```

This can never be true. For any given int value of en, it can not be below 0 and above or equal 1. This same condition is repeated in all the if statements.

Regarding the showDtails() method it looks like there should be some logic that returns a string, presumably with the details of this Person.

Body:
So currently studying OOP, I have encountered a problem regarding why the numbers are not getting filtered by my range in the if and else statements, and also one more thing on the last part of the code there should be something with the lines of "public String showDetails()" but I don't know what is inside of it.

    package com.xble.department.domain

public class Person
{
    private String name;
    private int EmpNo;
    private int age;

    public Person()
    {

    }
    public Person(String n, int en, int a)
    {
        name = n;

        if((en < 0) && (en >= 1) && (en <= 999999))
            en = 0;
        else
            EmpNo = en;

        if((a < 0) && (a >= 1) && (a <= 65))
            a = 0;
        else
            age = a;
    }

    public void setName(String n)
    {
        name=n;
    }

    public void setEmpNo(int en)
    {
            if((en < 0) && (en >= 1) && (en <= 999999))
                en = 0;
            else
                EmpNo = en;
    }

    public void setAge(int a)
    {
            if((a < 0) && (a >= 1) && (a <= 65))
                a = 0;
            else
                age = a;
    }

    public String getName()
    {
        return name;
    }

    public int getEmpNo()
    {
        return EmpNo;
    }

    public int getAge()
    {
        return age;
    }

    //public String showDetails()

}

Body:
Here's your problem:

(en < 0) && (en >= 1)

This can never be true. For any given int value of en, it can not be below 0 and above or equal 1. This same condition is repeated in all the if statements.

Regarding the showDtails() method it looks like there should be some logic that returns a string, presumably with the details of this Person.


问:
Gulp serve is opening a webpage, but it shows page not found error
I am new to sfpx , I started with the intro videos on MS page, I did all the setups but when I run gulp serve it redirects me to "https://localhost:4321/index.html" but browser shows "this site can't be reached" , as well as there is no "index.html" in my local project path. Please help me with possible solutions for this.

Versions of different modules installed:

Node - v14.15.0

yo - 4.3.0

gulp - 4.0.2

npm - 6.14.8

I am using a gitpod instance for my development, as well as I have tried on my windows device, I got the same errors. Please let me know if any more files or info is required to solve this error then I can share them.

What I tried:

based on some blogs I added the environment variable "NODE_NO_HTTP2":1, but this did not solve the problem

Checked if the port "4321" is not being used by any other services.No service was using this port

This issue is completely the same/similar to this one "https://stackoverflow.com/questions/70433862/unavailable-hosted-workbench-in-spfx" but I couldn't find a solution over there so reposted my version

This is the serve.json file content:

{
  "$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
  "port": 4321,
  "https": true
}
```

TIA

答:
The local workbench was deprecated in the latest version of the SPFx tools. You are supposed to use sharepoint online workbench to test your web part. Means, instead of http://localhost:4321 navigate to:

https://<yoursharepoint>.sharepoint.com/_layouts/15/workbench.aspx

Maybe you could still use the local workbench using gulp serve-deprecated instead of gulp serve (if it works depends on the version of the SPFx you are using, but soon it won't). Just test on online SharePoint workbench (for that, you need to have online SharePoint of course)

Body:
I am new to sfpx , I started with the intro videos on MS page, I did all the setups but when I run gulp serve it redirects me to "https://localhost:4321/index.html" but browser shows "this site can't be reached" , as well as there is no "index.html" in my local project path. Please help me with possible solutions for this.

Versions of different modules installed:

Node - v14.15.0

yo - 4.3.0

gulp - 4.0.2

npm - 6.14.8

I am using a gitpod instance for my development, as well as I have tried on my windows device, I got the same errors. Please let me know if any more files or info is required to solve this error then I can share them.

What I tried:

based on some blogs I added the environment variable "NODE_NO_HTTP2":1, but this did not solve the problem

Checked if the port "4321" is not being used by any other services.No service was using this port

This issue is completely the same/similar to this one "https://stackoverflow.com/questions/70433862/unavailable-hosted-workbench-in-spfx" but I couldn't find a solution over there so reposted my version

This is the serve.json file content:

{
  "$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
  "port": 4321,
  "https": true
}

TIA


问:
Replace same occurrence of word with different words using sed
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

```<code>mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>
</code>```

required output will be

```<code>mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123
</code>```

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

答:
Perhaps this might help:</p>
```<code>sed -e '1s/<<CHANGE_ME>>/localhost/' \
    -e '4s/<<CHANGE_ME>>/password123/' \
      app.properties > /home/centos/SCRIPT/io.properties_new
</code>```

Body:
I want to replace 2 same words in file(app.properties) with 2 different words using sed command.
Example:

mysql.host=<<CHANGE_ME>>
mysql.username=testuser
mysql.port=3306
mysql.db.password=<<CHANGE_ME>>

required output will be

mysql.host=localhost
mysql.username=testuser
mysql.port=3306
mysql.db.password=password123

I tried below command:

sed -e "s/<<CHANGE_ME>>/localhost/1" -e "s/<<CHANGE_ME>>/password123/2" app.properties > /home/centos/SCRIPT/io.properties_new

However I am getting localhost at both the places.

Body:
Perhaps this might help:

sed -e '1s/<<CHANGE_ME>>/localhost/' \
    -e '4s/<<CHANGE_ME>>/password123/' \
      app.properties > /home/centos/SCRIPT/io.properties_new


问:
ionic 5/ Angular 8 - ios unable to connect to local network server
the iphone can connect to the testing server, however, with local network providing the IP address 192.168.x.xx:3000 cannot connect with the error Failed to load resource: A server with the specified hostname could not be found. There is no problem with an Android device connecting but with iOS I receive the error above.

Also, I have changed the DNS manually to what is suggested in other posts to 8.8.8.8 however the issue still remains the same. thanks.

I run the command: $ ionic cordova run ios --device

答:
I have a similar situation and the problem was the windows firewall.

Configuring my app to communicate through the Windows Defender Firewall over Public at Allowed Applications solved my problem.

View a print at this answer here


问:
How provide a route to download binary file in Odoo 10
I am trying to create a route in Odoo 10 to download a binary file for gtfs real-time updater.

I searched in Odoo documentation but I didn't find any similar

This is my controller for test download binary file:

class GtfsRt(http.Controller):
    @http.route('/gtfs_rt', type='http', auth='public')
    def index(self):
        f = open('my_file', 'w+b')
        byte_arr = [120, 3, 255, 0, 100]
        binary_format = bytearray(byte_arr)
        f.write(binary_format)
        f.close()
        return f
```

<p>I would like to download the file when I go to <code>/gtfs_rt</code></p>

<p>At this moment I got this error:</p>

```Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 303, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 291, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/service/server.py", line 307, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/service/wsgi_server.py", line 186, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/service/wsgi_server.py", line 172, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1326, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1300, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/middleware/shared_data.py", line 227, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1505, in dispatch
    return response(environ, start_response)
TypeError: 'file' object is not callable
```

答:
I got here while trying to figure out how to download a CSV file without saving it in a field.

Here's how I managed.

from odoo import fields, api, models

class Report(model.TransientModel):

    report_date = fields.Date(required=True)

    @api.multi
    def button_download_csv(self):
        params = urlencode({
            'report_date': self.report_date,
        })

        # this will open the `url` in a new tab
        return {
            'url': f'/custom/reports/?{params}',
            'type': 'ir.actions.act_url'
        }
```
<pre class="lang-py prettyprint-override"><code>from io import StringIO

from odoo import http
from odoo.http import request, content_disposition, Response

class CustomerController(http.Controller):

    # auth="public" if login is not required
    @http.route('/custom/reports/', type='http', auth="user", methods=['GET'])
    def customer_report(self, **kw):
        if 'report_date' not in kw:
            return Response('Report date not provided', status=400)

        report_date = kw['report_date']

        # retrieve data from your source
        rows = [
            ('Site', 'Homepage'),
            ('Stack Overflow', 'https://stackoverflow.com/'),
            ('Github', 'https://github.com'),
        ]

        file_ = StringIO()
        result_file = csv.writer(file_)
        result_file.writerows(rows)
        file_.seek(0)

        filename = f'report-{report_date}.csv'
        file_content = file_.getvalue()

        return request.make_response(
            file_content,
            [
                ('Content-Type', 'text/csv;charset=utf8'),
                ('Content-Disposition', content_disposition(filename)),
            ]
        )
</code>```

Body:
I am trying to create a route in Odoo 10 to download a binary file for gtfs real-time updater.

I searched in Odoo documentation but I didn't find any similar

This is my controller for test download binary file:

class GtfsRt(http.Controller):
    @http.route('/gtfs_rt', type='http', auth='public')
    def index(self):
        f = open('my_file', 'w+b')
        byte_arr = [120, 3, 255, 0, 100]
        binary_format = bytearray(byte_arr)
        f.write(binary_format)
        f.close()
        return f

I would like to download the file when I go to /gtfs_rt

At this moment I got this error:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 303, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 291, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/service/server.py", line 307, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/service/wsgi_server.py", line 186, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/service/wsgi_server.py", line 172, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1326, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1300, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/middleware/shared_data.py", line 227, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/http.py", line 1505, in dispatch
    return response(environ, start_response)
TypeError: 'file' object is not callable

Body:
I got here while trying to figure out how to download a CSV file without saving it in a field.

Here's how I managed.

from odoo import fields, api, models

class Report(model.TransientModel):

    report_date = fields.Date(required=True)

    @api.multi
    def button_download_csv(self):
        params = urlencode({
            'report_date': self.report_date,
        })

        # this will open the `url` in a new tab
        return {
            'url': f'/custom/reports/?{params}',
            'type': 'ir.actions.act_url'
        }

from io import StringIO

from odoo import http
from odoo.http import request, content_disposition, Response

class CustomerController(http.Controller):

    # auth="public" if login is not required
    @http.route('/custom/reports/', type='http', auth="user", methods=['GET'])
    def customer_report(self, **kw):
        if 'report_date' not in kw:
            return Response('Report date not provided', status=400)

        report_date = kw['report_date']

        # retrieve data from your source
        rows = [
            ('Site', 'Homepage'),
            ('Stack Overflow', 'https://stackoverflow.com/'),
            ('Github', 'https://github.com'),
        ]

        file_ = StringIO()
        result_file = csv.writer(file_)
        result_file.writerows(rows)
        file_.seek(0)

        filename = f'report-{report_date}.csv'
        file_content = file_.getvalue()

        return request.make_response(
            file_content,
            [
                ('Content-Type', 'text/csv;charset=utf8'),
                ('Content-Disposition', content_disposition(filename)),
            ]
        )


问:
Format a string to a proper JSON object
I have a string (from an API call) that looks something like this:

val=

```<code>{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}
</code>```

I need to do temp=json.loads(val); but the problem is that the string is not a valid JSON. The keys and values do not have the quotes around them. I tried explicitly putting the quotes and that worked.

How can I programatically include the quotes for such a string before reading it as  a JSON?

Also, how can I replace the numbers scientific notations with decimals? eg. 0d-2 becomes "0" and 8.0d-1 becomes "0.8"?

答:
You could catch anything thats a string with regex and replace it accordingly.

Assuming your strings that need quotes:

start with a letter

can have numbers at the end

never start with numbers

never have numbers or special characters in between them

This would be a regex code to catch them:

```<code>([a-z]*\d*):
</code>```

You can try it out here. Or learn more about regex here.

Let's do it in python:

import re

# catch a string in json

json_string = '{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}' # note the single quotes!

# search the strings according to our rule
string_search = re.search('([a-z]*\d*):', json_string)

# extract the first capture group; so everything we matched in brackets
# this is to exclude the colon at the end from the found string as
# we don't want to enquote the colons as well
extracted_strings = string_search.group(1)

```
<p>This is a solution in case you will build a loop later.
However if you just want to catch all possible strings in python as a list you can do simply the following instead:</p>
<pre class="lang-py prettyprint-override"><code>import re

# catch ALL strings in json

json_string = '{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}' # note the single quotes!
extract_all_strings = re.findall(r'([a-z]*\d*):', json_string)
# note that this by default catches only our capture group in brackets
# so no extra step required
</code>```

This was about basically regex and finding everything.

With these basics you could either use re.sub to replace everything with itself just in quotes, or generate a list of replacements to verify first that everything went right (probably somethign you'd rather want to do with this maybe a little bit unstable approach) like this.
Note that this is why I made this kind of comprehensive answer instead of just pointing you to a "re.sub" one-liner.

You can apporach your scientific number notation problem accordingly.

Title: Format a string to a proper JSON object

Body:
I have a string (from an API call) that looks something like this:

val=

{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}

I need to do temp=json.loads(val); but the problem is that the string is not a valid JSON. The keys and values do not have the quotes around them. I tried explicitly putting the quotes and that worked.

How can I programatically include the quotes for such a string before reading it as  a JSON?

Also, how can I replace the numbers scientific notations with decimals? eg. 0d-2 becomes "0" and 8.0d-1 becomes "0.8"?

Body:
You could catch anything thats a string with regex and replace it accordingly.

Assuming your strings that need quotes:

start with a letter

can have numbers at the end

never start with numbers

never have numbers or special characters in between them

This would be a regex code to catch them:

([a-z]*\d*):

You can try it out here. Or learn more about regex here.

Let's do it in python:

import re

# catch a string in json

json_string = '{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}' # note the single quotes!

# search the strings according to our rule
string_search = re.search('([a-z]*\d*):', json_string)

# extract the first capture group; so everything we matched in brackets
# this is to exclude the colon at the end from the found string as
# we don't want to enquote the colons as well
extracted_strings = string_search.group(1)

This is a solution in case you will build a loop later.
However if you just want to catch all possible strings in python as a list you can do simply the following instead:

import re

# catch ALL strings in json

json_string = '{input:a,matches:[{in:["w","x","y","z"],output:{num1:0d-2,num2:7.0d-1}},
{in:["w","x"],output:{num1:0d-2,num2:8.0d-1}}]}' # note the single quotes!
extract_all_strings = re.findall(r'([a-z]*\d*):', json_string)
# note that this by default catches only our capture group in brackets
# so no extra step required

This was about basically regex and finding everything.

With these basics you could either use re.sub to replace everything with itself just in quotes, or generate a list of replacements to verify first that everything went right (probably somethign you'd rather want to do with this maybe a little bit unstable approach) like this.
Note that this is why I made this kind of comprehensive answer instead of just pointing you to a "re.sub" one-liner.

You can apporach your scientific number notation problem accordingly.


问:
Docker installation failing on Virtual box OracleLinux 8
I am getting below error on running :</p>
```<code>sudo dnf install docker-ce docker-ce-cli containerd.io

warning: /var/cache/dnf/ol7_latest-31ccda58762f86b1/packages/libcgroup-0.41-21.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID ec551f03: NOKEY
Oracle Linux 8 Latest (x86_64)                                                                              3.0 MB/s | 3.1 kB     00:00
GPG key at file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle (0xAD986DA3) is already installed
The GPG keys listed for the "Oracle Linux 8 Latest (x86_64)" repository are already installed but they are not correct for this package.
Check that the correct key URLs are configured for this repository.. Failing package is: libcgroup-0.41-21.el7.x86_64
 GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
Error: GPG check FAILED
</code>```

答:
OL8 comes with Podman and podman-docker package that effectively aliases the docker command to podman. See installation doc:

https://docs.oracle.com/en/operating-systems/oracle-linux/podman/podman-install.html

Body:
I am getting below error on running :

sudo dnf install docker-ce docker-ce-cli containerd.io

warning: /var/cache/dnf/ol7_latest-31ccda58762f86b1/packages/libcgroup-0.41-21.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID ec551f03: NOKEY
Oracle Linux 8 Latest (x86_64)                                                                              3.0 MB/s | 3.1 kB     00:00
GPG key at file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle (0xAD986DA3) is already installed
The GPG keys listed for the "Oracle Linux 8 Latest (x86_64)" repository are already installed but they are not correct for this package.
Check that the correct key URLs are configured for this repository.. Failing package is: libcgroup-0.41-21.el7.x86_64
 GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
The downloaded packages were saved in cache until the next successful transaction.
You can remove cached packages by executing 'dnf clean packages'.
Error: GPG check FAILED


问:
Need to retain, and synthesize NSStrings?
I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

```<code>self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";
</code>```

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?

答: If you have never alloc'ed them, you usually don't need to retain, but if they are instance variables in your objects, they are probably marked as retain or copy so at your object's dealloc method you should release these objects if there is a value on it.

Body:
I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?


问:
SharePoint 2016 Custom Timer Job Not Showing in Job Definition
I am stuck into something really strange behavior of SharePoint.
I have a SharePoint 2016 farm solution. which contains 5 timer jobs classes.
When I change something in any job class. all of the sudden any one of these 5 jobs stop showing in job definition. and after 1 month it again start to show up in the definition.
Moreover, if I create a new solution and create any job in it and deploy, it also doesn't show up in the job definition.

List of jobs

Job definition

答:
Are you using Feature EventReviever to add and configure the Job in Job Definitions?

This will add the job in Jobs Definition Section and Deactivating Feature will Remove the Job if you activate the Feature.

```<code>public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                DeleteExistingJob(JobName, parentWebApp);
                CreateJob(parentWebApp);
            });
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        lock (this)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    DeleteExistingJob(JobName, parentWebApp);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
</code>```

If this is not the issue and you have a Feature Event Reciever then share the cs file here.

Body:
Are you using Feature EventReviever to add and configure the Job in Job Definitions?

This will add the job in Jobs Definition Section and Deactivating Feature will Remove the Job if you activate the Feature.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                DeleteExistingJob(JobName, parentWebApp);
                CreateJob(parentWebApp);
            });
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        lock (this)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate ()
                {
                    SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
                    DeleteExistingJob(JobName, parentWebApp);
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

If this is not the issue and you have a Feature Event Reciever then share the cs file here.


问:
An AWS CI/CD Pipeline that allows manual deploy by commit

Background

I want to create the following CI/CD flow in AWS and Github, for a react app using Amplify:

A single main branch, with short-lived feature branches and PRs into main.

Each PR triggers its own test environment in Amplify, with its own temporary subdomain, which gets torn down when the PR is merged, as described here.

Merging into main does not automatically trigger a deploy to production.

Instead, there is a separate mechanism (a web page, or amplify command, or even triggers based on git tags) for manually selecting a commit from main to deploy to production.

Questions

It's not clear to me if...

Support for this flow is already built into Amplify (based on the docs I've read, I think the answer is "no", but I'm not sure).

Support for this flow is already built into AWS CodePipeline, or if it can be configured there.

There is another AWS tool that solves this.

I'm looking for answers to those questions, or specific references in the docs which address them.

答:
Support for this flow is already built into Amplify (based on the docs I've read, I think the answer is "no", but I'm not sure).

Check below links, if this help:

https://www.youtube.com/watch?v=QV2WS535nyI

https://dev.to/rajandmr/deploying-react-app-using-aws-amplify-with-ci-cd-pipeline-setup-3lid

Support for this flow is already built into AWS CodePipeline, or if it can be configured there.

For this, you need to create a full your own pipeline. Yes, you can configure your pipeline.

There is another AWS tool that solves this.

If you are okay with Jenkins, then Jenkins will help you to achieve this.
You can deploy Jenkins docker in AWS EC2 and create your pipeline. You can also use the parameterised option for selecting your environment and git branch.


问:
Power Automate parse JSON with dynamic property name
I am working on a flow to gather information from API and load it to the database.

However, while getting the response from the API call, one of the property names is variable per account.

Then the schema I am getting from the API call is like this:

```<code>{
  "type": "object",
  "properties": {
    "12305": {
      "type": "array",
      "items": {
        "type": "integer"
      }
    }
  }
}
</code>```

The property "12305" from the response varies from account to account. And I need to go through all accounts in one run.

Unfortunately, it is not possible to add variable content to the Schema value of the Parse JSON action.

Does anyone know the solution for that, please?

答:
so the solution for such case is following.

The JSON response needs to be converted to the string.

In the string the variable account id needs to be replaced to a static value

From the output new json needs to be created

Done.

Here are the steps printscreened:
final flow

Body:
I am working on a flow to gather information from API and load it to the database.

However, while getting the response from the API call, one of the property names is variable per account.

Then the schema I am getting from the API call is like this:

{
  "type": "object",
  "properties": {
    "12305": {
      "type": "array",
      "items": {
        "type": "integer"
      }
    }
  }
}

The property "12305" from the response varies from account to account. And I need to go through all accounts in one run.

Unfortunately, it is not possible to add variable content to the Schema value of the Parse JSON action.

Does anyone know the solution for that, please?


问:
How to run an OCR(Tesseract) on AWS Lambda using Java
I want to run an OCR(Tesseract) on AWS Lambda using Java.I wanted to have a basic-"Hello World" set up so I created the Handler function for AWS Lambda like so-

```<code>public class Hello implements RequestHandler<Object, String> {

    @Override
    public String handleRequest(Object input, Context context) {
        context.getLogger().log("Inside handleRequest of Hello class PPPPp ");
        context.getLogger().log("Input: " + input);

        String output = "Hello, " + input + "!";
        return output;
    }

}
</code>```

And this is working as I have tested it on the AWS Lambda console. And also Teseract is running on my local machine and tested it by passing an image and is printing the words present.
But now I am not getting how to combine these 2 (AWS Lambda and Teseract) into a single java program. I found this link which runs Teseract on Python - https://typless.com/tesseract-on-aws-lambda-ocr-as-a-service/ and tried to do the equivalent in Java, but was not able to do so as they were manipulating .py files and I am dealing with .java files.
I also came across this github link- https://github.com/tesseract-ocr/tesseract present in the AWS Lambda documentation,and this one-
https://github.com/tesseract-ocr/tesseract
but didnt understand how to use the code for my requirment.
I am stuck here and new to AWS Lambda. Any help very much appreciated. Thanks in advance.

答:
Please see the example https://github.com/jlcorradi/tesseract-example/blob/e85b93f3481109c56bb0e7255e0116691463693f/src/main/java/com/playground/tesseract/TesseractPlaygroundLambdaHandle.java

Github:  Not verified

```<code>@Log4j
public class TesseractPlaygroundLambdaHandle implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        Base64.Decoder decoder = Base64.getDecoder();
        String inputBody = input.getBody();

        Tesseract tesseract = new Tesseract();
        //tesseract.setDatapath("/home/jorgecorradi/Downloads/");
        try {
            String decodedText = tesseract.doOCR(decodeToImage(inputBody));
            return createResponse(decodedText);
        } catch (TesseractException e) {
            e.printStackTrace();
            return createResponse(e.getMessage());
        }
    }

    private APIGatewayProxyResponseEvent createResponse(String responseContent) {
        APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
        responseEvent.setBody(responseContent);
        responseEvent.setStatusCode(200);
        return responseEvent;
    }

    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            log.error("Error decoding base64 to image", e);
        }
        return image;
    }

}
</code>```

You will need to have a project/lib management tool such as Maven for example, to allow you to specify dependencies (For Terrasact), and to create a standalone jar, that you can then upload towards your Lambda.

This is in its simplest form.

https://docs.aws.amazon.com/lambda/latest/dg/java-package.html for how to deploy a standalone zip/jar towards Lambda.

Body:
I want to run an OCR(Tesseract) on AWS Lambda using Java.I wanted to have a basic-"Hello World" set up so I created the Handler function for AWS Lambda like so-

public class Hello implements RequestHandler<Object, String> {

    @Override
    public String handleRequest(Object input, Context context) {
        context.getLogger().log("Inside handleRequest of Hello class PPPPp ");
        context.getLogger().log("Input: " + input);

        String output = "Hello, " + input + "!";
        return output;
    }

}

And this is working as I have tested it on the AWS Lambda console. And also Teseract is running on my local machine and tested it by passing an image and is printing the words present.
But now I am not getting how to combine these 2 (AWS Lambda and Teseract) into a single java program. I found this link which runs Teseract on Python - https://typless.com/tesseract-on-aws-lambda-ocr-as-a-service/ and tried to do the equivalent in Java, but was not able to do so as they were manipulating .py files and I am dealing with .java files.
I also came across this github link- https://github.com/tesseract-ocr/tesseract present in the AWS Lambda documentation,and this one-
https://github.com/tesseract-ocr/tesseract
but didnt understand how to use the code for my requirment.
I am stuck here and new to AWS Lambda. Any help very much appreciated. Thanks in advance.

Body:
Please see the example https://github.com/jlcorradi/tesseract-example/blob/e85b93f3481109c56bb0e7255e0116691463693f/src/main/java/com/playground/tesseract/TesseractPlaygroundLambdaHandle.java

Github:  Not verified

@Log4j
public class TesseractPlaygroundLambdaHandle implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
        Base64.Decoder decoder = Base64.getDecoder();
        String inputBody = input.getBody();

        Tesseract tesseract = new Tesseract();
        //tesseract.setDatapath("/home/jorgecorradi/Downloads/");
        try {
            String decodedText = tesseract.doOCR(decodeToImage(inputBody));
            return createResponse(decodedText);
        } catch (TesseractException e) {
            e.printStackTrace();
            return createResponse(e.getMessage());
        }
    }

    private APIGatewayProxyResponseEvent createResponse(String responseContent) {
        APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
        responseEvent.setBody(responseContent);
        responseEvent.setStatusCode(200);
        return responseEvent;
    }

    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            log.error("Error decoding base64 to image", e);
        }
        return image;
    }

}

You will need to have a project/lib management tool such as Maven for example, to allow you to specify dependencies (For Terrasact), and to create a standalone jar, that you can then upload towards your Lambda.

This is in its simplest form.

https://docs.aws.amazon.com/lambda/latest/dg/java-package.html for how to deploy a standalone zip/jar towards Lambda.