问:
Unable to use firebase documentId() in node js admin sdk (firebase-admin npm package grammar issue)
My database looks like:

```<code>db-dev
   user-metadata
       portfolios
            meta
               pending
                       userId
                              events-collection
                                           doc1
                                           doc2
                                           ...
                       userId2
                              events-collection
                                           doc1
                                           doc2
                                           ...
               verified
                       userId
                              events-collection
                                           doc1
                                           doc2
                                           ...
                       userId2
                              events-collection
                                           doc1
                                           doc2
                                           ...

</code>```

I want to fetch all docs that belong to verified events-collection. Following this answer and this Blog Post I tried to do the following:

```<code>export const getVerifiedEvents = async (eventType: DocumentType) => {
  //eventType is either pending or verified
  const rootRef = Server.db.collection(
    `${constDocumentRefs.merchants_meta_loc}/${eventType}`
  );

  const documents = await const documents = await Server.db
    .collectionGroup('events-collection')
    .orderBy(documentId())
    .startAt(rootRef.path)
    .endAt(rootRef.path + '\uf8ff')
    .get();
  return documents.docs.map((doc) => doc.data());
};
</code>```

But the above code throws me the following error:

```<code>TypeError: Cannot read properties of undefined (reading 'documentId')
  13 |   const documents = await Server.db
  14 |     .collectionGroup('events-collection')
> 15 |     .orderBy(firestore.documentId())
     |             ^
  16 |     .startAt(rootRef.path)
  17 |     .endAt(rootRef.path + '\uf8ff')
  18 |     .get();
</code>```

Here's how my Server instance looks like:

```<code>import { auth, db, storage } from './firebase_server';

const firebaseServer = {
  auth,
  db,
  storage,
};

export default firebaseServer;
</code>```

Where auth,db and storage are imported from following files:

```<code>import admin from 'firebase-admin';

const keyString = process.env.FB_ADMIN_PRIVATE_KEY ?? '{"privateKey": ""}';

const { privateKey } = JSON.parse(keyString);

if (privateKey === '') {
  console.log('FIREBASE_PRIVATE_KEY is not set');
}

if (admin.apps.length === 0)
  admin.initializeApp({
    credential: admin.credential.cert({
      clientEmail: process.env.FB_ADMIN_CLIENT_EMAIL,
      privateKey: privateKey,
      projectId: process.env.FB_ADMIN_PROJECT_ID,
    }),
  });

const db = admin.firestore();
const auth = admin.auth();
const storage = admin.storage();

export { auth, db, storage };
</code>```

To be precise, I am using firebase-admin ["firebase-admin": "^10.0.1"] npm package and this is just not working whereas in lots of places they have been directly using documentId() with ease. What's the correct grammar for the same?

答:
The term "undefined" refers to a variable that has been declared but not given a value.
Only objects can have properties and functions in JavaScript. Because undefined is not an object type, executing a method or setting a property on it results in a TypeError: Undefined property cannot be read.

The path could be a single field name (pointing to a document's top level field) or a list of field names (referring to a nested field in the document).

The internal variable id in JavaScript just returns id.
Example: .orderBy(firebase.firestore.FieldPath.documentId())

The example that is in the blog you are following is presented like:

.orderBy(FieldPath.documentId())

Body:
My database looks like:

db-dev
   user-metadata
       portfolios
            meta
               pending
                       userId
                              events-collection
                                           doc1
                                           doc2
                                           ...
                       userId2
                              events-collection
                                           doc1
                                           doc2
                                           ...
               verified
                       userId
                              events-collection
                                           doc1
                                           doc2
                                           ...
                       userId2
                              events-collection
                                           doc1
                                           doc2
                                           ...

I want to fetch all docs that belong to verified events-collection. Following this answer and this Blog Post I tried to do the following:

export const getVerifiedEvents = async (eventType: DocumentType) => {
  //eventType is either pending or verified
  const rootRef = Server.db.collection(
    `${constDocumentRefs.merchants_meta_loc}/${eventType}`
  );

  const documents = await const documents = await Server.db
    .collectionGroup('events-collection')
    .orderBy(documentId())
    .startAt(rootRef.path)
    .endAt(rootRef.path + '\uf8ff')
    .get();
  return documents.docs.map((doc) => doc.data());
};

But the above code throws me the following error:

TypeError: Cannot read properties of undefined (reading 'documentId')
  13 |   const documents = await Server.db
  14 |     .collectionGroup('events-collection')
> 15 |     .orderBy(firestore.documentId())
     |             ^
  16 |     .startAt(rootRef.path)
  17 |     .endAt(rootRef.path + '\uf8ff')
  18 |     .get();

Here's how my Server instance looks like:

import { auth, db, storage } from './firebase_server';

const firebaseServer = {
  auth,
  db,
  storage,
};

export default firebaseServer;

Where auth,db and storage are imported from following files:

import admin from 'firebase-admin';

const keyString = process.env.FB_ADMIN_PRIVATE_KEY ?? '{"privateKey": ""}';

const { privateKey } = JSON.parse(keyString);

if (privateKey === '') {
  console.log('FIREBASE_PRIVATE_KEY is not set');
}

if (admin.apps.length === 0)
  admin.initializeApp({
    credential: admin.credential.cert({
      clientEmail: process.env.FB_ADMIN_CLIENT_EMAIL,
      privateKey: privateKey,
      projectId: process.env.FB_ADMIN_PROJECT_ID,
    }),
  });

const db = admin.firestore();
const auth = admin.auth();
const storage = admin.storage();

export { auth, db, storage };

To be precise, I am using firebase-admin ["firebase-admin": "^10.0.1"] npm package and this is just not working whereas in lots of places they have been directly using documentId() with ease. What's the correct grammar for the same?


来源: stackexchange

问:
I can't fix Heroku "Could not find a required file, Name: index.html" error
I am new to Heroku. I tried deleting .gitignore and rearranging my files around, but it still gives me that error. I have a program with React.js as the front end and Node.js as the backend. I need this to deploy to Heroku. The image below shows the error I get.

In my Node.js code, I tried specifying where Heroku should in "client" folder for the "index.html" file.  This is my node.js code:

//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

const express = require('express');
const request = require('request');

const app = express();
const apiKey = 'api-key-here';

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../client/build')));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/getCoinInfo', (req, res) => {
  console.log('The request has been received!!')
  request(
    { url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }
      res.json(JSON.parse(body));
    }
  )
});

// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));```

Also here is my file structure.

What are your suggestions to fix this problem?

答:
Your index.html file appears to be in client/public, not in client/build.

But if there is another index.html in build, you could try using join instead of resolve:

app.use(express.static(path.join(__dirname, 'client', 'build')));
```

ContentLicense: CC BY-SA 4.0

Body:
I am new to Heroku. I tried deleting .gitignore and rearranging my files around, but it still gives me that error. I have a program with React.js as the front end and Node.js as the backend. I need this to deploy to Heroku. The image below shows the error I get.

In my Node.js code, I tried specifying where Heroku should in "client" folder for the "index.html" file.  This is my node.js code:

//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

const express = require('express');
const request = require('request');

const app = express();
const apiKey = 'api-key-here';

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../client/build')));

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/getCoinInfo', (req, res) => {
  console.log('The request has been received!!')
  request(
    { url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }
      res.json(JSON.parse(body));
    }
  )
});

// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Also here is my file structure.

What are your suggestions to fix this problem?


问:
PHP MySQL Joining of few joined tables
There are 2 queries:

```<code>select * from gallery_images JOIN photo_galleries ON photo_galleries.albumID=gallery_images.albumID

select * from multimedia_video JOIN video_content ON multimedia_video.id=video_content.id_href
</code>```

Also i have "albumDateCreated" field on "photo_galleries" table and "DateCreated" field on "multimedia_video". I want to sort my queries by these fields

What is the best technique to JOIN my 2 "joins"?

答:
Just the way you created the others:</p>

```<code>SELECT * FROM gallery_images
    JOIN photo_galleries ON photo_galleries.albumID=gallery_images.albumID
    JOIN multimedia_video ON photo_galleries.albumDateCreated=multimedia_video.DateCreated
    JOIN video_content ON multimedia_video.id=video_content.id_href
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP MySQL Joining of few joined tables

Body:
There are 2 queries:

select * from gallery_images JOIN photo_galleries ON photo_galleries.albumID=gallery_images.albumID

select * from multimedia_video JOIN video_content ON multimedia_video.id=video_content.id_href

Also i have "albumDateCreated" field on "photo_galleries" table and "DateCreated" field on "multimedia_video". I want to sort my queries by these fields

What is the best technique to JOIN my 2 "joins"?

Body:
Just the way you created the others:

SELECT * FROM gallery_images
    JOIN photo_galleries ON photo_galleries.albumID=gallery_images.albumID
    JOIN multimedia_video ON photo_galleries.albumDateCreated=multimedia_video.DateCreated
    JOIN video_content ON multimedia_video.id=video_content.id_href


问:
"User is unauthorized" error with sample web viewer app
I'm following the instructions here: https://www.itwinjs.org/learning/tutorials/develop-web-viewer/ to create a sample web viewer app. The doc says to update variable IMJS_CONTEXT_ID which is not in the .env file and doesn't appear with "Show IDs" for my iModel (I have created a github issue for the doc already). I've tried updating the variable IMJS_ITWIN_ID instead with the "iTwin ID" from my iModel. When I start the app I get an error page "An Error Has Occurred: The user is unauthorized. Please provide valid authentication credentials". I have checked the variables IMJS_AUTH_CLIENT_CLIENT_ID, IMJS_AUTH_CLIENT_REDIRECT_URI, IMJS_AUTH_CLIENT_SCOPES, IMJS_ITWIN_ID, IMJS_IMODEL_ID and all appear to be correct. Is there something else I need to configure?</p>

答:
Sorry, the tutorial you're referring to is a bit outdated now. Have you taken a look at https://developer.bentley.com/tutorials/web-application-quick-start/?
In the new @itwin/web-viewer-react templates we renamed IMJS_CONTEXT_ID to IMJS_ITWIN_ID. We also made some changes to the required scopes, you'll need namely imodelaccess:read, imodels:read, and realitydata:read. Please make sure your auth client has the above scopes and you have access to the model. If you still have trouble, feel free to continue the discussion over at https://github.com/iTwin/itwinjs-core/discussions


问:
Search and find a string value in all columns
I need to find if a string value exists in any column in my table.
It's possible create automatically procedure or query in Firebird that perform this work without making explicit column names?

Column names can be find with this query:

select RDB$RELATION_FIELDS.rdb$field_name as NC from
RDB$RELATION_FIELDS where RDB$RELATION_FIELDS.rdb$relation_name =
MY_Table_name

I would use a procedure similar to that in Firebird:

http://www.mssqltips.com/sqlservertip/1522/searching-and-finding-a-string-value-in-all-columns-in-a-sql-server-table/

```<code>SET TERM ^^ ;

CREATE PROCEDURE P_FINDSTRINGINTABLE (
  STRTOFIND VarChar(255),
  TBLNAME VarChar(255))
 returns (
  SQLCOMMAND VarChar(25000))
AS
DECLARE VARIABLE condSTR VARCHAR(8000);
DECLARE VARIABLE columnName VARCHAR(8000);
begin
  sqlCommand = 'select * from '|| upper( :TBLNAME );

  condSTR = '';
  for select RDB$RELATION_FIELDS.rdb$field_name as NC from RDB$RELATION_FIELDS where RDB$RELATION_FIELDS.rdb$relation_name = upper( :TBLNAME )
  into  :columnName
  do begin
     condSTR = condSTR||columnName||' LIKE ''%'||STRTOFIND||'%'' OR ';
  end

  IF ( CHAR_LENGTH(condSTR) > 0 ) THEN
  begin
     condSTR = ' where ' || left(condSTR, CHAR_LENGTH (condSTR)-3)  || ';';
     sqlCommand = sqlCommand|| condSTR;
  end
  ELSE sqlCommand = sqlCommand||';' ;

end ^^

SET TERM ; ^^
</code>```

I've created the right string SQL for my search.
Now, if I execute this Firebird procedure, it returns the SQL command as string.

Are there methods to automatically execute the returned select?

答:
Here is the syntax, based on the above posts, to simply run a SELECT statement, without creating a stored procedure:</p>
```<code>SET TERM ^ ;
EXECUTE BLOCK
RETURNS
( table_with_value varchar(200),
    column_with_value varchar(200),
    containing_value varchar(4000))
AS
declare variable all_tables varchar(200);
declare variable all_columns varchar(200);
declare variable all_values varchar(4000);
BEGIN
    FOR SELECT
        r.rdb$relation_name, f.rdb$field_name
        from rdb$relation_fields f
        JOIN RDB$FIELDS ON (RDB$FIELDS.RDB$FIELD_NAME = f.RDB$FIELD_SOURCE)
        join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name
        and r.rdb$view_blr is null
        and (r.rdb$system_flag is null or r.rdb$system_flag = 0)
        and RDB$FIELDS.RDB$FIELD_TYPE in (37, 40)
        and RDB$FIELDS.RDB$FIELD_TYPE is not null
        order by 1, f.rdb$field_position INTO :all_tables, :all_columns
    DO
    BEGIN
        FOR EXECUTE STATEMENT 'SELECT "' || all_columns || '" FROM "' || all_tables || '"'
            INTO :all_values
        DO
        BEGIN
            IF (all_Values like '%SEARCH_VALUE%') THEN
            BEGIN
                table_With_Value = all_Tables;
                column_With_Value = all_Columns;
                containing_value = all_Values;
                SUSPEND;
           END
        END
    END
END^
SET TERM ^ ;
</code>```

Body:
I need to find if a string value exists in any column in my table.
It's possible create automatically procedure or query in Firebird that perform this work without making explicit column names?

Column names can be find with this query:

select RDB$RELATION_FIELDS.rdb$field_name as NC from
RDB$RELATION_FIELDS where RDB$RELATION_FIELDS.rdb$relation_name =
MY_Table_name

I would use a procedure similar to that in Firebird:

http://www.mssqltips.com/sqlservertip/1522/searching-and-finding-a-string-value-in-all-columns-in-a-sql-server-table/

SET TERM ^^ ;

CREATE PROCEDURE P_FINDSTRINGINTABLE (
  STRTOFIND VarChar(255),
  TBLNAME VarChar(255))
 returns (
  SQLCOMMAND VarChar(25000))
AS
DECLARE VARIABLE condSTR VARCHAR(8000);
DECLARE VARIABLE columnName VARCHAR(8000);
begin
  sqlCommand = 'select * from '|| upper( :TBLNAME );

  condSTR = '';
  for select RDB$RELATION_FIELDS.rdb$field_name as NC from RDB$RELATION_FIELDS where RDB$RELATION_FIELDS.rdb$relation_name = upper( :TBLNAME )
  into  :columnName
  do begin
     condSTR = condSTR||columnName||' LIKE ''%'||STRTOFIND||'%'' OR ';
  end

  IF ( CHAR_LENGTH(condSTR) > 0 ) THEN
  begin
     condSTR = ' where ' || left(condSTR, CHAR_LENGTH (condSTR)-3)  || ';';
     sqlCommand = sqlCommand|| condSTR;
  end
  ELSE sqlCommand = sqlCommand||';' ;

end ^^

SET TERM ; ^^

I've created the right string SQL for my search.
Now, if I execute this Firebird procedure, it returns the SQL command as string.

Are there methods to automatically execute the returned select?

Body:
Here is the syntax, based on the above posts, to simply run a SELECT statement, without creating a stored procedure:

SET TERM ^ ;
EXECUTE BLOCK
RETURNS
( table_with_value varchar(200),
    column_with_value varchar(200),
    containing_value varchar(4000))
AS
declare variable all_tables varchar(200);
declare variable all_columns varchar(200);
declare variable all_values varchar(4000);
BEGIN
    FOR SELECT
        r.rdb$relation_name, f.rdb$field_name
        from rdb$relation_fields f
        JOIN RDB$FIELDS ON (RDB$FIELDS.RDB$FIELD_NAME = f.RDB$FIELD_SOURCE)
        join rdb$relations r on f.rdb$relation_name = r.rdb$relation_name
        and r.rdb$view_blr is null
        and (r.rdb$system_flag is null or r.rdb$system_flag = 0)
        and RDB$FIELDS.RDB$FIELD_TYPE in (37, 40)
        and RDB$FIELDS.RDB$FIELD_TYPE is not null
        order by 1, f.rdb$field_position INTO :all_tables, :all_columns
    DO
    BEGIN
        FOR EXECUTE STATEMENT 'SELECT "' || all_columns || '" FROM "' || all_tables || '"'
            INTO :all_values
        DO
        BEGIN
            IF (all_Values like '%SEARCH_VALUE%') THEN
            BEGIN
                table_With_Value = all_Tables;
                column_With_Value = all_Columns;
                containing_value = all_Values;
                SUSPEND;
           END
        END
    END
END^
SET TERM ^ ;


问:
Tensorflow 2.3 problems with saving and loading model
So after I saved my model with model.save('path') yesterday, I only found out today that there is some problem with tf 2.3 and keras saving the model. The problem is already described here: Keras giving low accuracy after loading model .
But the accepted solution doesn't help me. When I load the model using model = tf.keras.models.load_model('path') it returns a lower test accuracy than before saving it. Using

```<code>model.compile(optimizer = SGD(lr = 1e-3, momentum = 0.9, decay = 1e-6), #RMSProp
             loss = 'binary_crossentropy',
             metrics = ['sparse_categorical_accuracy'])
</code>```

did not help because before saving the model I used 'accuracy' and not 'sparse_categorical_accuracy' and I'm now getting the following error when trying to train or test the model:

```<code>InvalidArgumentError:  Can not squeeze dim[1], expected a dimension of 1, got 2
     [[node Squeeze (defined at <ipython-input-34-11b07af8f987>:4) ]] [Op:__inference_test_function_363481]

Function call stack:
test_function
</code>```

So now my question: is there any way to load my saved model and get the saved state or do I need to restart training from zero again?

答:
As trivial as that may sound, did you check your the input data after loading the model? Is it preprocessed in exactly the same way as it was during training?

Most common: normalization and prefetching

Testing the loaded model with non normalized data (after beeing trained with normalization) will result in a bad performance, as you described.

The following works in my experience even with CustomMaskWarning.

```<code># Saving
model.save(path)
# Loading
model = tf.keras.models.load_model(path)

# for only saving weights
model.save_weights(path)
# loading weights
model = create_model()  # create exactly the same model as trained
model.load_weights(path)
</code>```

(The ".h5" format causes issues if you have CustomMaskWarning and didnt resolve them by overriding get_config and setting a config.)

Body:
So after I saved my model with model.save('path') yesterday, I only found out today that there is some problem with tf 2.3 and keras saving the model. The problem is already described here: Keras giving low accuracy after loading model .
But the accepted solution doesn't help me. When I load the model using model = tf.keras.models.load_model('path') it returns a lower test accuracy than before saving it. Using

model.compile(optimizer = SGD(lr = 1e-3, momentum = 0.9, decay = 1e-6), #RMSProp
             loss = 'binary_crossentropy',
             metrics = ['sparse_categorical_accuracy'])

did not help because before saving the model I used 'accuracy' and not 'sparse_categorical_accuracy' and I'm now getting the following error when trying to train or test the model:

InvalidArgumentError:  Can not squeeze dim[1], expected a dimension of 1, got 2
     [[node Squeeze (defined at <ipython-input-34-11b07af8f987>:4) ]] [Op:__inference_test_function_363481]

Function call stack:
test_function

So now my question: is there any way to load my saved model and get the saved state or do I need to restart training from zero again?

Body:
As trivial as that may sound, did you check your the input data after loading the model? Is it preprocessed in exactly the same way as it was during training?

Most common: normalization and prefetching

Testing the loaded model with non normalized data (after beeing trained with normalization) will result in a bad performance, as you described.

The following works in my experience even with CustomMaskWarning.

# Saving
model.save(path)
# Loading
model = tf.keras.models.load_model(path)

# for only saving weights
model.save_weights(path)
# loading weights
model = create_model()  # create exactly the same model as trained
model.load_weights(path)

(The ".h5" format causes issues if you have CustomMaskWarning and didnt resolve them by overriding get_config and setting a config.)


问:
Yargs : access processed argv in fail function
I use yargs for a complexe command line (with subcommands via commandDir).
I'd like to use the .fail(fn) to send an email every time the given command failed. The .fail(fn) is correctly triggered but I'd like to be able to have access to the args given to the command. .fail(fn) only gives me access to msg, err, yargs.

```<code>require('yargs')
.commandDir('commands', {recurse: false})
.option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging',
    default: false
})
.option('senderr', {
    alias: 'se',
    type: 'boolean',
    description: 'Send error(s) via email',
    default: true
})
.demandCommand()
.help()
.fail(function (msg, err, yargs) {
    console.log(err);
    process.exit(1);
})
.locale('fr')
.argv
</code>```

Is it possible to access the argv.senderr value inside the fail function ?
Thanks !

答: I ran into the same issue and there doesn't appear to be a current solution, however I recently posted a github issue: https://github.com/yargs/yargs/issues/2133</p>

Body:
I use yargs for a complexe command line (with subcommands via commandDir).
I'd like to use the .fail(fn) to send an email every time the given command failed. The .fail(fn) is correctly triggered but I'd like to be able to have access to the args given to the command. .fail(fn) only gives me access to msg, err, yargs.

require('yargs')
.commandDir('commands', {recurse: false})
.option('verbose', {
    alias: 'v',
    type: 'boolean',
    description: 'Run with verbose logging',
    default: false
})
.option('senderr', {
    alias: 'se',
    type: 'boolean',
    description: 'Send error(s) via email',
    default: true
})
.demandCommand()
.help()
.fail(function (msg, err, yargs) {
    console.log(err);
    process.exit(1);
})
.locale('fr')
.argv

Is it possible to access the argv.senderr value inside the fail function ?
Thanks !


问:
How to tell if a website is static or dynamic?
My prof said that dynamic pages get created by the computer, while static pages are created by the user.

Thank you so much!

答:
Regarding: "How to tell if a website is static or dynamic?"
Static websites are simple web pages (typically written in languages like JavaScript, HTML, CSS, etc.) and stored in a web server. In the case of static web pages, as soon as a server receives a request for a page, it immediately sends a response to the client with no additional processing. Users will always view the same content regardless of their location, device type, and web browser.

In static websites, the displayed content remains the same unless someone manually edits the HTML source code on every page that’s part of the website. These pages contain no alterations based on any user input. Hence the name- static web pages. You don't necessarily need any prior experience with database design and web programming to create and maintain a static website. As long as they don't change when we update them, the code for static web pages stays the same.

On the other hand, Dynamic web pages have greater complexity than static ones because they display different content for each user while retaining the same layout and design. A dynamic website generates web pages in real-time. The flexible nature of the content allows for customization based on the requests from the user or the browser used by them. Such pages are usually written in languages like CGI, AJAX, ASP or ASP.NET, and they usually take more time to load than static web pages. They are frequently implemented to show information that changes frequently, e.g., weather updates, stock prices, etc.

Server-side code used to construct a dynamic web page can generate real-time HTML pages for each request from an individual user. While static websites are mostly informational, dynamic websites contain interactive, continually changing elements. In order to provide an interactive website experience for visitors, web developers usually combine both client-side and server-side programming techniques.

Dynamic web pages usually contain application programs for various services and require server-side resources like databases. A dynamic website accesses content from a CMS (Content Management System), which means that the website reflects any changes made in the database content. These sites use client-side scripting, server-side scripting, or both for generating content. Separating the site’s design from its content makes it easier for web designers to create pages without having to worry about formatting issues. After uploading content into the database, websites retrieve their content from there when responding to user requests.

Now, regarding "Would www.tagpro.gg (the homepage) be static or dynamic?"
I have visited the homepage and it is a dynamic webpage actually as you mentioned.


问:
How to get all analytical data from SendGrid using "Unique Args" or is there another way?
Example:

to: john@gmail.com, mark@gmail.com, lisa@gmail.com

subject: "New feature"

body: "We have developed a new feature,..."

What I need:

a combined analytics data from all recipients about this particular email

an identifier for each email, with which I can track how well email is performing

I've found two approaches:

Categories

Unique Arguments

Solution with "categories" suits my intent, but I believe its purpose is to label multiple emails with the same topic.

Solution with "unique arguments" isn't the best, because my app needs most of the analytical data SendGrid provides (clicks, opens, delivered, bounces, blocks,... etc) with as few interactions with SendGrid as possible. If I would use this approach, API calls would skyrocket.

My questions are:

What do you recommend I use?

Is there another way I could approach the problem, if so, what?

答: The solution are Event Webhooks. Check out this link.</p>


问:
How to split into new column via multi-column layout only when text is overflowing
I'm looking for a way to dynamically break a continuous text into multiple columns only if the content of the first column is overflowing. It should be responsive and work for any device width. The solution can be (S)css or JavaScript.

I already tried using column-count like suggested here but this always creates multiple columns no matter if there is still enough space in the first column.

This is about what I want to achieve just without the mentioned column-count

.content {
  height: 90vh;
}

.text {
  width: 300px;
  column-count: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="content">
   <div class="text">
      Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Cras ultricies ligula sed magna dictum porta. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.
   </div>
 </div></code>```

答:
This is pretty hacky, but I think you can do this in JS by calculating the size of the text and then modifying column-count if it exceeds a certain value. Something like:

```<code>const textElement = document.getElementsByClassName('text')[0];
const textElementHeight = textElement.getBoundingClientRect().height
const numColumns = textElementHeight / SOME_CONSTANT;
textElement.style.columnCount = numColumns
</code>```

Body:
I'm looking for a way to dynamically break a continuous text into multiple columns only if the content of the first column is overflowing. It should be responsive and work for any device width. The solution can be (S)css or JavaScript.

I already tried using column-count like suggested here but this always creates multiple columns no matter if there is still enough space in the first column.

This is about what I want to achieve just without the mentioned column-count

.content {
  height: 90vh;
}

.text {
  width: 300px;
  column-count: 2;
}

      Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Cras ultricies ligula sed magna dictum porta. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Nulla porttitor accumsan tincidunt. Lorem ipsum dolor sit amet,
      consectetur adipiscing elit. Pellentesque in ipsum id orci porta dapibus. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.

Body:
This is pretty hacky, but I think you can do this in JS by calculating the size of the text and then modifying column-count if it exceeds a certain value. Something like:

const textElement = document.getElementsByClassName('text')[0];
const textElementHeight = textElement.getBoundingClientRect().height
const numColumns = textElementHeight / SOME_CONSTANT;
textElement.style.columnCount = numColumns


问:
How to insert some text within the input using Selenium and Python
In a webpage I have the following element:

```<code><div id="learning_form" class="learning_form">
                <table cellspacing="0" cellpadding="0">
                    <tbody><tr><td><input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;"></td></tr>
                </tbody></table>
                <div id="check"><h4 style="text-align: center;">Sprawdź</h4></div>
                <div id="special_characters"><div> </div><div> </div></div>
            </div>
</code>```

How I can insert text here using selenium in python?
I tried using:

```<code>driver.find_element(By.ID,"learning_form").send_keys("some text")
</code>```

but it doesn't work.

Snapshot of the element:

答:
```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#answer"))).send_keys("value")
</code>```

It seems you need to send values to the input with an id answer.

```<code><input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;">
</code>```

Import:

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
In a webpage I have the following element:

<input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;">

Sprawdź

How I can insert text here using selenium in python?
I tried using:

driver.find_element(By.ID,"learning_form").send_keys("some text")

but it doesn't work.

Snapshot of the element:

Body:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#answer"))).send_keys("value")

It seems you need to send values to the input with an id answer.

<input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;">

Import:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答:
You have indeed forgotten.  In C and C++, you don't get any automatic initialization; the contents of c after int c; are whatever happens to be at the address referred to by c at the time.

Best practice: initialize at the definition: int c = 0;.

Oh, PS, and take some care that the MySQL int type matches the C int type; I think it does but I'm not positive.  It will be, however, both architecture and compiler sensitive, since sizeof(int) isn't the same in all C environments.

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

ContentLicense: CC BY-SA 2.5

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

OwnerDisplayName: Charlie Martin


问:
BigQuery SQL: percent with 2 decimal places
In BigQuery standard SQL, I need to present a result of division as percentage with 2 decimal places, e.g. 21.23%.
The only way I've been able to achieve this is by the doing the following:

ROUND the result to 2 decimal places

CAST it as a string

FORMAT to add the percent character

FORMAT('%s%%', CAST(ROUND((val_1 / val_2) * 100, 2) AS STRING))

It feels like a workaround...

Is there a proper way of doing it?
Primarily, I'd like to keep the output as a float, not a string.

Thanks!

答:
as @nick winridge pointed out, there's an issue with less than 2 non-zero decimal places. This is a little hack that I added to fix that..</p>
```<code>CREATE TEMP FUNCTION NUMFORMAT(number FLOAT64) AS (
  CONCAT(REGEXP_EXTRACT(cast(((number + 0.000001) as string), r'\d*\.\d{2}'), ' %')
);
</code>```

Body:
as @nick winridge pointed out, there's an issue with less than 2 non-zero decimal places. This is a little hack that I added to fix that..

CREATE TEMP FUNCTION NUMFORMAT(number FLOAT64) AS (
  CONCAT(REGEXP_EXTRACT(cast(((number + 0.000001) as string), r'\d*\.\d{2}'), ' %')
);


问:
Typescript generic constraint for type with only properties from another type
I'm trying to create a Overwrite type that can overwrite an existing type's properties with a different type. For instance:

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop2: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: string }
</code>```

I found this SO answer which does the job nicely, however it's a bit too permissive for my liking, as it allows you to replace properties that were never in the original type to begin with.

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: number; prop3: string }
</code>```

Below is the Overwrite type from that other thread.

```<code>type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
</code>```

How do I need to modify it to prohibit replacement keys that are not present in the initial type?

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA
</code>```

答:
You could achieve this with a mapped type like this:

```<code>type TypeA = { prop1: string; prop2: number };

type Overwrite<T, U extends Partial<Record<keyof T, any>>> = { [Key in keyof T]: undefined extends U[Key] ? T[Key] : U[Key] };

type OverwrittenTypeWorks = Overwrite<TypeA, { prop2: string }>; //  { prop1: string, prop2: string }
type WrongOverwrittenType = Overwrite<TypeA, { prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA
</code>```

TypeScript playground

Body:
I'm trying to create a Overwrite type that can overwrite an existing type's properties with a different type. For instance:

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop2: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: string }

I found this SO answer which does the job nicely, however it's a bit too permissive for my liking, as it allows you to replace properties that were never in the original type to begin with.

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: number; prop3: string }

Below is the Overwrite type from that other thread.

type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

How do I need to modify it to prohibit replacement keys that are not present in the initial type?

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA

Body:
You could achieve this with a mapped type like this:

type TypeA = { prop1: string; prop2: number };

type Overwrite<T, U extends Partial<Record<keyof T, any>>> = { [Key in keyof T]: undefined extends U[Key] ? T[Key] : U[Key] };

type OverwrittenTypeWorks = Overwrite<TypeA, { prop2: string }>; //  { prop1: string, prop2: string }
type WrongOverwrittenType = Overwrite<TypeA, { prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA

TypeScript playground


问:
how to insert into database with multiple array in php
hi guys can someone help me how to this. I have here the problems I can't solve it
for example

data for manny

```<code> <input type="text" name="name[]" value="Manny" >

 <input type="text" name="course[]" value="BSIT" >
 <input type="text" name="level[]" value="2nd year" >

 <input type="text" name="course[]" value="BSCS" >
 <input type="text" name="level[]" value="3rd year" >

 <input type="text" name="course[]" value="BSENG" >
 <input type="text" name="level[]" value="4th year" >
</code>```

data for Floyd

```<code> <input type="text" name="name[]" value="Floyd" >

 <input type="text" name="course[]" value="ABM" >
 <input type="text" name="level[]" value="Grade 11" >

 <input type="text" name="course[]" value="STEM" >
 <input type="text" name="level[]" value="Grade 12" >
</code>```

Manny hold 3 classes while Floyd hold 2 classes. so how can I insert it into database I guess use an array is suit for this problem but I don't know how. please help me with this

答:
I think it will make more sense to use an array if the structure "data for Manny" and "data for Floyd" are the same. Not like when you are having "GRADE" in "data for Floyd" and "YEAR" in "data for Manny".

Moreover, what exactly are you trying to achieve? You don't want to treat Manny and Floyd data separately?

You can have a check and see if this is going to help.

```<code>    Manny Data
        <input type="text" name="Manny[name]" value="Manny"><br>
        <select name="Manny[year1]">
            <option value="BSIT">BSIT</option>
        </select><br>

        <select name="Manny[year2]">
            <option value="BSCS">BSCS</option>
        </select><br>

        <select name="Manny[year3]">
            <option value="BSENG">BSENG</option>
        </select><br>

    Floyd Data
        <input type="text" name="Floyd[name]" value="Floyd"><br>
        <select name="Floyd[Grade 11]">
            <option value="ABM">ABM</option>
        </select><br>

        <select name="Floyd[Grade 12]">
            <option value="STEM">STEM</option>
        </select><br>
</code>```

=====RESULT=====

```<code>    Array(
[Manny] => Array
    (
        [name] => Manny
        [year1] => BSIT
        [year2] => BSCS
        [year3] => BSENG
    )

[Floyd] => Array
    (
        [name] => Floyd
        [Grade 11] => ABM
        [Grade 12] => STEM
    )
)
</code>```

$_POST["Manny"] contains all Manny's data.

$_POST["Floyd"] contains all Floyd's data.

Body:
hi guys can someone help me how to this. I have here the problems I can't solve it
for example

data for manny

 <input type="text" name="name[]" value="Manny" >

 <input type="text" name="course[]" value="BSIT" >
 <input type="text" name="level[]" value="2nd year" >

 <input type="text" name="course[]" value="BSCS" >
 <input type="text" name="level[]" value="3rd year" >

 <input type="text" name="course[]" value="BSENG" >
 <input type="text" name="level[]" value="4th year" >

data for Floyd

 <input type="text" name="name[]" value="Floyd" >

 <input type="text" name="course[]" value="ABM" >
 <input type="text" name="level[]" value="Grade 11" >

 <input type="text" name="course[]" value="STEM" >
 <input type="text" name="level[]" value="Grade 12" >

Manny hold 3 classes while Floyd hold 2 classes. so how can I insert it into database I guess use an array is suit for this problem but I don't know how. please help me with this

Body:
I think it will make more sense to use an array if the structure "data for Manny" and "data for Floyd" are the same. Not like when you are having "GRADE" in "data for Floyd" and "YEAR" in "data for Manny".

Moreover, what exactly are you trying to achieve? You don't want to treat Manny and Floyd data separately?

You can have a check and see if this is going to help.

    Manny Data
        <input type="text" name="Manny[name]" value="Manny"><br>
        <select name="Manny[year1]">
            <option value="BSIT">BSIT</option>
        </select><br>

        <select name="Manny[year2]">
            <option value="BSCS">BSCS</option>
        </select><br>

        <select name="Manny[year3]">
            <option value="BSENG">BSENG</option>
        </select><br>

    Floyd Data
        <input type="text" name="Floyd[name]" value="Floyd"><br>
        <select name="Floyd[Grade 11]">
            <option value="ABM">ABM</option>
        </select><br>

        <select name="Floyd[Grade 12]">
            <option value="STEM">STEM</option>
        </select><br>

=====RESULT=====

    Array(
[Manny] => Array
    (
        [name] => Manny
        [year1] => BSIT
        [year2] => BSCS
        [year3] => BSENG
    )

[Floyd] => Array
    (
        [name] => Floyd
        [Grade 11] => ABM
        [Grade 12] => STEM
    )
)

$_POST["Manny"] contains all Manny's data.

$_POST["Floyd"] contains all Floyd's data.


问:
How to deselect a checkbox using two condition/if statements (one a dropdown select and one a radio)
I'm trying to set this condition in a form:

If the #Size (from a dropdown selection) = 'extra-cab' AND a radio select button called 'canopy-14x-select' (from a group of radio buttons called 'Canopy') are both selected, then the checkbox with a class called .rack-kit is deselected.

I'm not sure how to nest these into each other, I've attempted it below but it isn't working.

Any help would be much appreciated.

```<code>$('#Size').on('change', function() {
         if (this.value == 'extra-cab') {
                if ($(this).attr("id") == "canopy-14x-select") {
                    $('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
                }
            }
</code>```

Thank you in advance :)

答:
Assuming that the radio buttons share the same [name] attaribute and everything is in a <form>, reference it as $('[name="X"]:checked') X being the [name] of radio button group. This example unchecks when select is 2 and radio is 3.

$('form').on('change', function(e) {
  if ($('#A').val() === '2' && $('[name="B"]:checked').val() === '3') {
    $('.D').prop('checked', false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <select id='A'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
  </select><br>

  <input name='B' type='radio' value='1'><label>1</label><br>
  <input name='B' type='radio' value='2'><label>2</label><br>
  <input name='B' type='radio' value='3'><label>3</label><br>

  <input class='D' type='checkbox'>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Body:
I'm trying to set this condition in a form:

If the #Size (from a dropdown selection) = 'extra-cab' AND a radio select button called 'canopy-14x-select' (from a group of radio buttons called 'Canopy') are both selected, then the checkbox with a class called .rack-kit is deselected.

I'm not sure how to nest these into each other, I've attempted it below but it isn't working.

Any help would be much appreciated.

$('#Size').on('change', function() {
         if (this.value == 'extra-cab') {
                if ($(this).attr("id") == "canopy-14x-select") {
                    $('.rack-kit input[type="checkbox"]:checked').prop('checked', false).trigger('change');
                }
            }

Thank you in advance :)

Body:
Assuming that the radio buttons share the same [name] attaribute and everything is in a <form>, reference it as $('[name="X"]:checked') X being the [name] of radio button group. This example unchecks when select is 2 and radio is 3.

$('form').on('change', function(e) {
  if ($('#A').val() === '2' && $('[name="B"]:checked').val() === '3') {
    $('.D').prop('checked', false);
  }
});

<form>
  <select id='A'>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
  </select><br>

  <input name='B' type='radio' value='1'><label>1</label><br>
  <input name='B' type='radio' value='2'><label>2</label><br>
  <input name='B' type='radio' value='3'><label>3</label><br>

  <input class='D' type='checkbox'>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Using List Comprehension for a number sequence (1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 .....) in Python
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

```<code># Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)
</code>```

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

```<code># Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)
</code>```

Which would print:

```<code>[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

```<code>L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)
</code>```

I just want this as output:

```<code>[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
</code>```

Thanks!

答:
I know it's not allowed in the problem, but assume we can use math library, there's a really interesting solution that goes like this:

from math import sqrt, floor

print([1] + [1 * ((-1+sqrt(1+8*i))/2 > 0 and floor((-1+sqrt(1+8*i))/2) == (-1+sqrt(1+8*i))/2 or (-1-sqrt(1+8*i))/2 > 0 and floor((-1-sqrt(1+8*i))/2) == (-1-sqrt(1+8*i))/2) for i in range(1, 67)])
```

The key observation is that all ones in the target list has an index that's a triangular number except for the one on index 0(no pun intended). So we can just check if the current index is a triangular number.

The nth triangular number can be expressed as:

Let i be the current index we are checking. All we need to do is to solve:

And check if one of the roots is a natural number.

Again, I know this is not a valid answer. I just want to show it as the idea is interesting.

Body:
I'm doing exercise questions from A Practical Introduction to Python Programming by Brian Heinold (pg 83) and there was a simpler question:

Using a for loop, create the list below, which consists of ones separated by increasingly many
zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

# Question 11
L = [1]
for i in range(11):
  if i == 0:
    L.append(1)
  else:
    for j in range(i):
      L.append(0)
    L.append(1)
print(L)

Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes. The last two ones in the list should be separated by ten zeroes.
[1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....]

I'm having difficulty with converting it into one line using list comprehension. Best I could do was

# Question 15
L = [[1, [0]*i] for i in range(11)]
print(L)
L = [j for row in L for j in row]
print(L)

Which would print:

[[1, []], [1, [0]], [1, [0, 0]], [1, [0, 0, 0]], [1, [0, 0, 0, 0]], [1, [0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0]], [1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]
[1, [], 1, [0], 1, [0, 0], 1, [0, 0, 0], 1, [0, 0, 0, 0], 1, [0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0], 1, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Flattening the list any further would result in a TypeError: 'int' object is not iterable and I would have to add another 1 at the end of the list using a seperate command which I guess would be fine. To add the code for flattening the list kinda goes over my head.

This is a second attempt using if/else statements, that gives the produces the same output and gives the same TypeError for when I try to flatten it completely.

L = [1 if i%2 == 0 else [0]*(i//2) for i in range(22)]
L = [j for row in L for j in row]
print(L)

I just want this as output:

[1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

Thanks!

Body:
I know it's not allowed in the problem, but assume we can use math library, there's a really interesting solution that goes like this:

from math import sqrt, floor

print([1] + [1 * ((-1+sqrt(1+8*i))/2 > 0 and floor((-1+sqrt(1+8*i))/2) == (-1+sqrt(1+8*i))/2 or (-1-sqrt(1+8*i))/2 > 0 and floor((-1-sqrt(1+8*i))/2) == (-1-sqrt(1+8*i))/2) for i in range(1, 67)])

The key observation is that all ones in the target list has an index that's a triangular number except for the one on index 0(no pun intended). So we can just check if the current index is a triangular number.

The nth triangular number can be expressed as:

Let i be the current index we are checking. All we need to do is to solve:

And check if one of the roots is a natural number.

Again, I know this is not a valid answer. I just want to show it as the idea is interesting.


问:
Extending a class that has injected services without duplicating injectors in child class?
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}
```
<p>I realize that it would be more performant to repeat all the injected services, and then pass them all up to <code>BasePageComponent</code> as so:</p>
<pre class="lang-js prettyprint-override"><code>export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}
</code>```

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}
```

Does this pattern exist and I'm just not googling the right keyword?

答:
Thanks to @MikeOne's comment for his link to another answer ( Inject a service manually ).

I was able to use Injector.get for the 15 small services that are used in basically every child component. Then for the larger services and the services that are only used on a few child components, I injected them into the relevant components.

For anyone else that comes here in the future: One snag I ran into is that Angular's ActivatedRoute apparently doesn't work with the Injector.get (see How to retrieve a route param using Injector.get(ActivatedRoute)?), so I had to inject that into each the relevant components, which was a majority of them, but that is still better than 16 one off services being initialized on every page.

Body:
Ok, so I'm getting deep into TypeScript inheritance (specifically in Angular 11), and I've set up a BasePageComponent to provide all the necessary functions and services that exist across pages.
The issue I've run into, is that now my base is getting bloated, because there are services that are used only on one or two pages, but in order to extend the base, we have included those in the base.

export class BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    public exampleOneOffService: ExampleOneOffService
  ) {}
}

I realize that it would be more performant to repeat all the injected services, and then pass them all up to BasePageComponent as so:

export class ChildPageComponent extends BasePageComponent {

  constructor(
    public uiPopupService: UiPopUpService,
    public loaderService: LoaderService,
    public questionService: QuestionService,
    public aBunchOfOthers: OTHERS,
    private exampleOneOffService: ExampleOneOffService
  ) {
    super(uiPopupService, loaderService, questionService, aBunchOfOthers);
  }
}

I will do the above, if there's no other way, but I have as hinted at in the sample code, I have a bunch of other micro services that are included in the base (like 15-20), so I want to be able to do something like this, where I just declare the one additional service, and still inherit all the others from the parent class, but I am not seeing a way to do this.

export class ChildPageComponent extends BasePageComponent {

  constructor(private otherExampleService: OtherExampleService){
    super()
  };
}

Does this pattern exist and I'm just not googling the right keyword?


问:
Request image from WMS to local storage in Java
I have been trying to retrieve image from WMS in Java using the Geotools and save the image locally. I have simply followed this link https://gitlab.com/-/snippets/1883964 by Ian Turton and from the official documentation https://docs.geotools.org/latest/userguide/extension/wms/wms.html

My code is

```<code>package wmsexplore;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.geotools.ows.ServiceException;
import org.geotools.ows.wms.WebMapServer;
import org.geotools.ows.wms.request.GetMapRequest;
import org.geotools.ows.wms.response.GetMapResponse;

public class WMSConnector {
  public static void main(String[] args) {

    URL url = null;
    try {
      url = new URL("http://maps.heigit.org/osm-wms/service?service=WMS&request=GetCapabilities&version=1.1.0");
    } catch (MalformedURLException e) {
      // will not happen
    }

    WebMapServer wms = null;
    try {
      wms = new WebMapServer(url);
      GetMapRequest request = wms.createGetMapRequest();
      request.addLayer("osm_auto:all", "");
      String format = "image/png";
      request.setFormat(format);
      request.setDimensions("1000", "1000"); // sets the dimensions of the image
                                           // to be returned from the server
      request.setTransparent(true);
      request.setSRS("EPSG:4326");
      request.setBBox("-71.13,42.32,-71.03,42.42");

      try {
        GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
        if (response.getContentType().equalsIgnoreCase(format)) {
          BufferedImage image = ImageIO.read(response.getInputStream());
          File outputfile = new File("saved.png");
          ImageIO.write(image, "png", outputfile);
        } else {
          StringWriter writer = new StringWriter();
          IOUtils.copy(response.getInputStream(), writer);
          String error = writer.toString();
          System.out.println(error);

        }
      } catch (ServiceException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

      }
    } catch (IOException e) {
      // There was an error communicating with the server
      // For example, the server is down
    } catch (ServiceException e) {
      // The server returned a ServiceException (unusual in this case)
    }

  }
}
</code>```

The error I have been getting is :

```<code>Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?REQUEST=GetCapabilities&VERSION=1.1.0&SERVICE=WMS
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?request=capabilities&service=WMS&wmtver=1.0.0
</code>```

What might have gone wrong here? Thanks for the help in advance !!

答:
I think the problem is as the error message indicates.

In the code snippet below the
<< LF >> character sequence is to indicate a LF character. And any white space present is white space. Between the DTD URL string and the VendorSpecificCapabilities element there is no white space. Unless the LF character is considered white space; which I think is an edge case in an implementation. It is this that could be the cause of the problem.

```<code><?xml version="1.0"?><<LF>>
<!DOCTYPE WMT_MS_Capabilities SYSTEM
"http://schemas.opengis.net/wms/1.1.0/capabilities_1_1_0.dtd"<<LF>>
[<<LF>>
 <!ELEMENT VendorSpecificCapabilities EMPTY><<LF>>
 ]>  <!-- end of DOCTYPE declaration --><<LF>>
<WMT_MS_Capabilities version="1.1.0"><<LF>>
<Service><<LF>>
...
</code>```

The line wrapping between the SYSTEM word and the DTD URL string is an artifact of stackoverflow

Body:
I have been trying to retrieve image from WMS in Java using the Geotools and save the image locally. I have simply followed this link https://gitlab.com/-/snippets/1883964 by Ian Turton and from the official documentation https://docs.geotools.org/latest/userguide/extension/wms/wms.html

My code is

package wmsexplore;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.geotools.ows.ServiceException;
import org.geotools.ows.wms.WebMapServer;
import org.geotools.ows.wms.request.GetMapRequest;
import org.geotools.ows.wms.response.GetMapResponse;

public class WMSConnector {
  public static void main(String[] args) {

    URL url = null;
    try {
      url = new URL("http://maps.heigit.org/osm-wms/service?service=WMS&request=GetCapabilities&version=1.1.0");
    } catch (MalformedURLException e) {
      // will not happen
    }

    WebMapServer wms = null;
    try {
      wms = new WebMapServer(url);
      GetMapRequest request = wms.createGetMapRequest();
      request.addLayer("osm_auto:all", "");
      String format = "image/png";
      request.setFormat(format);
      request.setDimensions("1000", "1000"); // sets the dimensions of the image
                                           // to be returned from the server
      request.setTransparent(true);
      request.setSRS("EPSG:4326");
      request.setBBox("-71.13,42.32,-71.03,42.42");

      try {
        GetMapResponse response = (GetMapResponse) wms.issueRequest(request);
        if (response.getContentType().equalsIgnoreCase(format)) {
          BufferedImage image = ImageIO.read(response.getInputStream());
          File outputfile = new File("saved.png");
          ImageIO.write(image, "png", outputfile);
        } else {
          StringWriter writer = new StringWriter();
          IOUtils.copy(response.getInputStream(), writer);
          String error = writer.toString();
          System.out.println(error);

        }
      } catch (ServiceException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

      }
    } catch (IOException e) {
      // There was an error communicating with the server
      // For example, the server is down
    } catch (ServiceException e) {
      // The server returned a ServiceException (unusual in this case)
    }

  }
}

The error I have been getting is :

Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?REQUEST=GetCapabilities&VERSION=1.1.0&SERVICE=WMS
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: FATAL White spaces are required between publicId and systemId.
Feb 09, 2022 2:09:36 AM org.geotools.xml.XMLSAXHandler fatalError
SEVERE: col 50, line 1
Feb 09, 2022 2:09:36 AM org.geotools.data.ows.AbstractOpenWebService internalIssueRequest
SEVERE: Failed to execute request http://maps.heigit.org/osm-wms/service?request=capabilities&service=WMS&wmtver=1.0.0

What might have gone wrong here? Thanks for the help in advance !!

Body:
I think the problem is as the error message indicates.

In the code snippet below the
<< LF >> character sequence is to indicate a LF character. And any white space present is white space. Between the DTD URL string and the VendorSpecificCapabilities element there is no white space. Unless the LF character is considered white space; which I think is an edge case in an implementation. It is this that could be the cause of the problem.

<?xml version="1.0"?><<LF>>
<!DOCTYPE WMT_MS_Capabilities SYSTEM
"http://schemas.opengis.net/wms/1.1.0/capabilities_1_1_0.dtd"<<LF>>
[<<LF>>
 <!ELEMENT VendorSpecificCapabilities EMPTY><<LF>>
 ]>  <!-- end of DOCTYPE declaration --><<LF>>
<WMT_MS_Capabilities version="1.1.0"><<LF>>
<Service><<LF>>
...

The line wrapping between the SYSTEM word and the DTD URL string is an artifact of stackoverflow


问:
SwiftUI: Saving likes in CoreData for each individual cell
How do I save the like state for each individual cell? I decided to save via CoreData, but the like is saved for all cells at once.

In the Core Data model (LikedDB) there is an attribute such as isLiked

In the class there is a variable isLiked, which changes the state of the like:

```<code>class ModelsViewModel: ObservableObject{

    @Published var isLiked = false

    func like() {
        isLiked.toggle()
    }
}
</code>```

This is how I save the like state from ModelsViewModel
And in label I use

```<code>struct CellView: View{

   //For CoreData
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: LikedDBE.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \LikedDBE.name, ascending: true)]) var manyLikedDB: FetchedResults<LikedDBE>

    //For like
    @ObservedObject var cellViewModel: ModelsViewModel = ModelsViewModel()

    var body: some View{

        Button(action: {
        let likedDBE = LikedDBE(context: self.managedObjectContext)
        likedDBE.isLiked = cellViewModel.isLiked //I indicate that isLiked from CoreData = isLiked from ModelsViewModel()

        do{
            cellViewModel.like() //func from ModelsViewModel()
            try self.managedObjectContext.save() //Save
        } catch{
            print(error)
        }

        }, label: {
        Image(systemName: cellViewModel.isLiked ? "heart.fill" : "heart") //Here I use
           .frame(width: 22, height: 22)
           .foregroundColor(cellViewModel.isLiked ? .red : .black) //And here I use
})
</code>```

And if I use cellViewModel.isLiked, then when I click like, the like is displayed only on the one I clicked on, but the state is not saved when restarting the application, if I use likedDB.isLiked, then the like is displayed on all cells at once, but the like is saved after restarting.

I want the like to be only on the cell I clicked on and it will be saved after restarting the application.

答:
Short answer you need something like this.

```<code>Button("add", action: {
    //Create a new object
    let new: LikedDBE = store.create()
    //Trigger a child view that observes the object
    selection = new.objectID
})
</code>```

It is a button that creates the object and triggers a child view so you can observe and edit it.

Long answer will be below just copy and paste all the code into your ContentView file there are comment throughout.

```<code>import SwiftUI
import CoreData

struct ContentView: View {
    @StateObject var store: CoreDataPersistence = .init()
    var body: some View{
        LikesListView()
        //This context is aware of you are in canvas/preview
            .environment(\.managedObjectContext, store.context)
    }
}
struct LikesListView: View {
    @EnvironmentObject var store: CoreDataPersistence

    @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \LikedDBE.name, ascending: true)]) var manyLikedDB: FetchedResults<LikedDBE>
    //Control what NavigationLink is opened
    @State var selection: NSManagedObjectID? = nil

    var body: some View {
        NavigationView{
            List{
                ForEach(manyLikedDB){ object in
                    NavigationLink(object.name ?? "no name", tag: object.objectID, selection: $selection, destination: {LikeEditView(obj: object)})
                }
            }.toolbar(content: {
                Button("add", action: {
                    //Create a new object
                    let new: LikedDBE = store.create()
                    //Trigger a child view that observes the object
                    selection = new.objectID
                })
            })
        }.environmentObject(store)
    }
}
struct LikeEditView: View{
    @EnvironmentObject var store: CoreDataPersistence
    @Environment(\.dismiss) var dismiss
    //Observe the CoreData object so you can see changes and make them
    @ObservedObject var obj: LikedDBE
    var body: some View{
        TextField("name", text: $obj.name.bound).textFieldStyle(.roundedBorder)
        Toggle(isOn: $obj.isLiked, label: {
            Text("is liked")
        })
            .toolbar(content: {
                ToolbarItem(placement: .navigationBarLeading){
                    Button("cancel", role: .destructive, action: {
                        store.resetStore()
                        dismiss()
                    })
                }
                ToolbarItem(placement: .navigationBarTrailing){

                    Button("save", action: {
                        store.update(obj)
                        dismiss()
                    })
                }
            })
            .navigationBarBackButtonHidden(true)
    }
}
struct LikesListView_Previews: PreviewProvider {
    static var previews: some View {
        LikesListView()
    }
}

///Generic CoreData Helper not needed jsuto make stuff easy.
class CoreDataPersistence: ObservableObject{
    //Use preview context in canvas/preview
    //The context is for both Entities,
    let context = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" ? PersistenceController.preview.container.viewContext : PersistenceController.shared.container.viewContext
    ///Non observing array of objects
    func getAllObjects<T: NSManagedObject>() -> [T]{
        let listRequest = T.fetchRequest()
        do {
            return try context.fetch(listRequest).typeArray()
        } catch let error {
            print ("Error fetching. \(error)")
            return []
        }
    }
    ///Creates an NSManagedObject of any type
    func create<T: NSManagedObject>() -> T{
        T(context: context)
        //Can set any defaults in awakeFromInsert() in an extension for the Entity
        //or override this method using the specific type
    }
    ///Updates an NSManagedObject of any type
    func update<T: NSManagedObject>(_ obj: T){
        //Make any changes like a last modified variable
        save()
    }
    ///Creates a sample
    func addSample<T: NSManagedObject>() -> T{
        let new: T = create()
        //Can add sample data here by type checking or overriding this method
        return new
    }
    ///Deletes  an NSManagedObject of any type
    func delete(_ obj: NSManagedObject){
        context.delete(obj)
        save()
    }
    func resetStore(){
        context.rollback()
        save()
    }
    private func save(){
        do{
            try context.save()
        }catch{
            print(error)
        }
    }
}
extension Optional where Wrapped == String {
    var _bound: String? {
        get {
            return self
        }
        set {
            self = newValue
        }
    }
    var bound: String {
        get {
            return _bound ?? ""
        }
        set {
            _bound = newValue
        }
    }

}
</code>```

Body:
How do I save the like state for each individual cell? I decided to save via CoreData, but the like is saved for all cells at once.

In the Core Data model (LikedDB) there is an attribute such as isLiked

In the class there is a variable isLiked, which changes the state of the like:

class ModelsViewModel: ObservableObject{

    @Published var isLiked = false

    func like() {
        isLiked.toggle()
    }
}

This is how I save the like state from ModelsViewModel
And in label I use

struct CellView: View{

   //For CoreData
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: LikedDBE.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \LikedDBE.name, ascending: true)]) var manyLikedDB: FetchedResults<LikedDBE>

    //For like
    @ObservedObject var cellViewModel: ModelsViewModel = ModelsViewModel()

    var body: some View{

        Button(action: {
        let likedDBE = LikedDBE(context: self.managedObjectContext)
        likedDBE.isLiked = cellViewModel.isLiked //I indicate that isLiked from CoreData = isLiked from ModelsViewModel()

        do{
            cellViewModel.like() //func from ModelsViewModel()
            try self.managedObjectContext.save() //Save
        } catch{
            print(error)
        }

        }, label: {
        Image(systemName: cellViewModel.isLiked ? "heart.fill" : "heart") //Here I use
           .frame(width: 22, height: 22)
           .foregroundColor(cellViewModel.isLiked ? .red : .black) //And here I use
})

And if I use cellViewModel.isLiked, then when I click like, the like is displayed only on the one I clicked on, but the state is not saved when restarting the application, if I use likedDB.isLiked, then the like is displayed on all cells at once, but the like is saved after restarting.

I want the like to be only on the cell I clicked on and it will be saved after restarting the application.

Body:
Short answer you need something like this.

Button("add", action: {
    //Create a new object
    let new: LikedDBE = store.create()
    //Trigger a child view that observes the object
    selection = new.objectID
})

It is a button that creates the object and triggers a child view so you can observe and edit it.

Long answer will be below just copy and paste all the code into your ContentView file there are comment throughout.

import SwiftUI
import CoreData

struct ContentView: View {
    @StateObject var store: CoreDataPersistence = .init()
    var body: some View{
        LikesListView()
        //This context is aware of you are in canvas/preview
            .environment(\.managedObjectContext, store.context)
    }
}
struct LikesListView: View {
    @EnvironmentObject var store: CoreDataPersistence

    @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \LikedDBE.name, ascending: true)]) var manyLikedDB: FetchedResults<LikedDBE>
    //Control what NavigationLink is opened
    @State var selection: NSManagedObjectID? = nil

    var body: some View {
        NavigationView{
            List{
                ForEach(manyLikedDB){ object in
                    NavigationLink(object.name ?? "no name", tag: object.objectID, selection: $selection, destination: {LikeEditView(obj: object)})
                }
            }.toolbar(content: {
                Button("add", action: {
                    //Create a new object
                    let new: LikedDBE = store.create()
                    //Trigger a child view that observes the object
                    selection = new.objectID
                })
            })
        }.environmentObject(store)
    }
}
struct LikeEditView: View{
    @EnvironmentObject var store: CoreDataPersistence
    @Environment(\.dismiss) var dismiss
    //Observe the CoreData object so you can see changes and make them
    @ObservedObject var obj: LikedDBE
    var body: some View{
        TextField("name", text: $obj.name.bound).textFieldStyle(.roundedBorder)
        Toggle(isOn: $obj.isLiked, label: {
            Text("is liked")
        })
            .toolbar(content: {
                ToolbarItem(placement: .navigationBarLeading){
                    Button("cancel", role: .destructive, action: {
                        store.resetStore()
                        dismiss()
                    })
                }
                ToolbarItem(placement: .navigationBarTrailing){

                    Button("save", action: {
                        store.update(obj)
                        dismiss()
                    })
                }
            })
            .navigationBarBackButtonHidden(true)
    }
}
struct LikesListView_Previews: PreviewProvider {
    static var previews: some View {
        LikesListView()
    }
}

///Generic CoreData Helper not needed jsuto make stuff easy.
class CoreDataPersistence: ObservableObject{
    //Use preview context in canvas/preview
    //The context is for both Entities,
    let context = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" ? PersistenceController.preview.container.viewContext : PersistenceController.shared.container.viewContext
    ///Non observing array of objects
    func getAllObjects<T: NSManagedObject>() -> [T]{
        let listRequest = T.fetchRequest()
        do {
            return try context.fetch(listRequest).typeArray()
        } catch let error {
            print ("Error fetching. \(error)")
            return []
        }
    }
    ///Creates an NSManagedObject of any type
    func create<T: NSManagedObject>() -> T{
        T(context: context)
        //Can set any defaults in awakeFromInsert() in an extension for the Entity
        //or override this method using the specific type
    }
    ///Updates an NSManagedObject of any type
    func update<T: NSManagedObject>(_ obj: T){
        //Make any changes like a last modified variable
        save()
    }
    ///Creates a sample
    func addSample<T: NSManagedObject>() -> T{
        let new: T = create()
        //Can add sample data here by type checking or overriding this method
        return new
    }
    ///Deletes  an NSManagedObject of any type
    func delete(_ obj: NSManagedObject){
        context.delete(obj)
        save()
    }
    func resetStore(){
        context.rollback()
        save()
    }
    private func save(){
        do{
            try context.save()
        }catch{
            print(error)
        }
    }
}
extension Optional where Wrapped == String {
    var _bound: String? {
        get {
            return self
        }
        set {
            self = newValue
        }
    }
    var bound: String {
        get {
            return _bound ?? ""
        }
        set {
            _bound = newValue
        }
    }

}


问:
Is there any way to change input type="date" format?
By default, the input type="date" shows date as YYYY-MM-DD.

The question is, is it possible to force it's format to something like: DD-MM-YYYY?

答:
Angular devs (and maybe others) could consider this partial solution.

My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.

It's not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It's not going to be very helpful if you have just one date input.

```<code><input class="form-control"
       [type]="myInputFocus ? 'date' : 'text'"
       id="myInput"
       name="myInput"
       #myInput="ngModel"
       [(ngModel)]="myDate"
       (focus)="myInputFocus = true"
       (blur)="myInputFocus = false">
</code>```

And simply declare myInputFocus = false at the beginning of you component class.
Obviously point myDate to your desired control.

Body:
Angular devs (and maybe others) could consider this partial solution.

My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.

It's not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It's not going to be very helpful if you have just one date input.

<input class="form-control"
       [type]="myInputFocus ? 'date' : 'text'"
       id="myInput"
       name="myInput"
       #myInput="ngModel"
       [(ngModel)]="myDate"
       (focus)="myInputFocus = true"
       (blur)="myInputFocus = false">

And simply declare myInputFocus = false at the beginning of you component class.
Obviously point myDate to your desired control.