问:
std::ranges::take_while_view cannot pipe
```<code>auto int_v10 = std::vector{8,7,3};
//fail    auto rng2 = int_v10 | std::ranges::take_while_view([](int x) {return x> 5;} ) | std::ranges::views::common;
auto rng2 = int_v10 | std::ranges::views::take_while([](int x) {return x> 5;} ) | std::ranges::views::common;
auto result4 = std::accumulate(rng2.begin(), rng2.end(),0);

std::cout<<"Result4: "<<result4<<'\n';
</code>```

https://en.cppreference.com/w/cpp/ranges/take_while_view

Why std::ranges::take_while_view result cannot pipe to next code block.
and std::ranges::views::take_while can?

答:
take_while_view has only two constructors:

```<code>take_while_view() = default;
constexpr take_while_view(V base, Pred pred);
</code>```

The second constructor needs to accept two parameters, one is base and the other is pred, so you need to struct it like this:

```<code>auto rng2 = std::ranges::take_while_view(int_v10, [](int x) {return x > 5;})
          | std::ranges::views::common;
</code>```

Body:
auto int_v10 = std::vector{8,7,3};
//fail    auto rng2 = int_v10 | std::ranges::take_while_view([](int x) {return x> 5;} ) | std::ranges::views::common;
auto rng2 = int_v10 | std::ranges::views::take_while([](int x) {return x> 5;} ) | std::ranges::views::common;
auto result4 = std::accumulate(rng2.begin(), rng2.end(),0);

std::cout<<"Result4: "<<result4<<'\n';

https://en.cppreference.com/w/cpp/ranges/take_while_view

Why std::ranges::take_while_view result cannot pipe to next code block.
and std::ranges::views::take_while can?

Body:
take_while_view has only two constructors:

take_while_view() = default;
constexpr take_while_view(V base, Pred pred);

The second constructor needs to accept two parameters, one is base and the other is pred, so you need to struct it like this:

auto rng2 = std::ranges::take_while_view(int_v10, [](int x) {return x > 5;})
          | std::ranges::views::common;


来源: stackexchange

问:
display a message when mongoDB collection is empty
I have a notices section on my website which are stored in my Mongo Database. If the collection is empty, how would i display a message to say something like "No new notices"

I am looping this on my page using EJS my code is below.

```<code>        <% for (let notice of notices) {%>
            <p class="lead"><%= notice.noticeText %>
            <% } %>
</code>```

答:
I guess you can put a condition like so:</p>
```<code>  <% if (!notices.length) {%>
    <p>desired text if no notice exists</p>
  <% } else { %>
    <% for (let notice of notices) {%>
        <p class="lead"><%= notice.noticeText %>
    <% } %>
  <% } %}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a notices section on my website which are stored in my Mongo Database. If the collection is empty, how would i display a message to say something like "No new notices"

I am looping this on my page using EJS my code is below.

        <% for (let notice of notices) {%>

<%= notice.noticeText %>
            <% } %>

Body:
I guess you can put a condition like so:

  <% if (!notices.length) {%>
    <p>desired text if no notice exists</p>
  <% } else { %>
    <% for (let notice of notices) {%>
        <p class="lead"><%= notice.noticeText %>
    <% } %>
  <% } %}


问:
New attributes are not showing up in django admin dashboard
Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql.

This is my models.py(not full)

```<code>from django.db import models
from django.db.models import CheckConstraint, Q, F

class College(models.Model):
    CITY_CHOICES=[('BAN','Bangalore')]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10)
    fest_nos=models.IntegerField()
    image=models.ImageField(default='default.jpg',upload_to='college_pics')

    class Meta():
        db_table='college'

    def __str__(self):
        return self.name

class Organizer(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=25)
    phone=models.IntegerField()
    def __str__(self):
        return self.name

class Fest(models.Model):
    FEST_CHOICES=[
        ('CUL','Cultural'),
        ('TEC','Technical'),
        ('COL','College'),
        ('SPO','Sports'),
    ]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    clg_id=models.ForeignKey(College,on_delete=models.CASCADE)
    fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10)
    fest_desc=models.TextField(default='This is a fest')
#below two field are not showing up in admin page
    start_date=models.DateField(auto_now_add=True)
    end_date=models.DateField(auto_now_add=True)
    event_nos=models.IntegerField()
    org_id=models.ManyToManyField(Organizer)
    image=models.ImageField(default='default.jpg',upload_to='fest_pics')

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(end_date__gte=F('start_date')),
                name = 'check_start_date',
            )
        ]
        db_table='fest'

    def __str__(self):
        return self.name
</code>```

The start_date and end_date attributes are the new ones added in this project. It was not there in the old one.
My admin.py file

```<code>from django.contrib import admin
from .models import College, Event, Fest, Organizer, Participated

admin.site.register(College)
admin.site.register(Organizer)
admin.site.register(Fest)
admin.site.register(Event)
admin.site.register(Participated)
</code>```

But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date.

I made migrations once again, fake migrated etc. What to do?
Is check constraint under model fest causing this problem?

答: They fields won't show up on Django Admin because they have auto_now_add=True so, the user shouldn't touch them.

Body:
Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql.

This is my models.py(not full)

from django.db import models
from django.db.models import CheckConstraint, Q, F

class College(models.Model):
    CITY_CHOICES=[('BAN','Bangalore')]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10)
    fest_nos=models.IntegerField()
    image=models.ImageField(default='default.jpg',upload_to='college_pics')

    class Meta():
        db_table='college'

    def __str__(self):
        return self.name

class Organizer(models.Model):
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=25)
    phone=models.IntegerField()
    def __str__(self):
        return self.name

class Fest(models.Model):
    FEST_CHOICES=[
        ('CUL','Cultural'),
        ('TEC','Technical'),
        ('COL','College'),
        ('SPO','Sports'),
    ]
    id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=50)
    clg_id=models.ForeignKey(College,on_delete=models.CASCADE)
    fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10)
    fest_desc=models.TextField(default='This is a fest')
#below two field are not showing up in admin page
    start_date=models.DateField(auto_now_add=True)
    end_date=models.DateField(auto_now_add=True)
    event_nos=models.IntegerField()
    org_id=models.ManyToManyField(Organizer)
    image=models.ImageField(default='default.jpg',upload_to='fest_pics')

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(end_date__gte=F('start_date')),
                name = 'check_start_date',
            )
        ]
        db_table='fest'

    def __str__(self):
        return self.name

The start_date and end_date attributes are the new ones added in this project. It was not there in the old one.
My admin.py file

from django.contrib import admin
from .models import College, Event, Fest, Organizer, Participated

admin.site.register(College)
admin.site.register(Organizer)
admin.site.register(Fest)
admin.site.register(Event)
admin.site.register(Participated)

But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date.

I made migrations once again, fake migrated etc. What to do?
Is check constraint under model fest causing this problem?


问:
SwiftUI TextEditor View content is hidden behind Navigation Bar
I'm working on a SwiftUI View with a NavigationBar. The view is very simple, it's a full-page TextEditor:

struct NotesEditingScreen: View {

    @State var text: String

    var body: some View {
        TextEditor(text: $text)
            .padding(.horizontal)
            .navigationBarTitle("Editing")
    }
}
```

The issue I'm seeing, is that when landing on this screen (via a NavigationLink) the top of the TextEditor is covered up by Navigation Bar:

My desired behavior is that the TextEditor content appears beneath the Navigation Bar, like it appears after you manually scroll to the top to reveal the text.

Is there a solution/workaround to this issue? I was hoping for either some offset, a setting on NavigationBar, or some programmatic scroll behavior that could be done onAppear. Any suggestions welcome.

答:
I think it's an unexpected behavior.

You can try this:

GeometryReader { geo in
    ScrollView {
        TextEditor(text: $text)
            .frame(height: geo.size.height)
    }
}
```

Body:
I'm working on a SwiftUI View with a NavigationBar. The view is very simple, it's a full-page TextEditor:

struct NotesEditingScreen: View {

    @State var text: String

    var body: some View {
        TextEditor(text: $text)
            .padding(.horizontal)
            .navigationBarTitle("Editing")
    }
}

The issue I'm seeing, is that when landing on this screen (via a NavigationLink) the top of the TextEditor is covered up by Navigation Bar:

My desired behavior is that the TextEditor content appears beneath the Navigation Bar, like it appears after you manually scroll to the top to reveal the text.

Is there a solution/workaround to this issue? I was hoping for either some offset, a setting on NavigationBar, or some programmatic scroll behavior that could be done onAppear. Any suggestions welcome.


问:
POST a form in which some element are file
In a js web project,
I want to POST a form with a complexe json schema, and in which some field will be file.

How do I do It?

I currently upload a file alone like this

```<code>  const data = new FormData();
    data.append('mimetype', file.type);
    data.append('filename', file.name);
    data.append('file', file);
    return this.httpClient.post(url, data)
</code>```

but I want my new form look like this:

```<code> var data ={username:"John doe",
    profilPhoto:{mimetype:..., filename:..., file: ...},
    house:{
       photo:{mimetype:..., filename:..., file: ...},
    },
    documents:[{mimetype:..., filename:..., file: ...}]

  }
</code>```

答:
As suggested in the comments encode your file to base64 then decode on the backend and save it as a blob.
Another option would be to use FormData as you do. For the array of objects, you can use JSON.stringify and then JSON.parse on backend.</p>
```<code>  addFile(data:any): Observable<any> {
    const postData=new FormData();
    postData.append('username', data.username);
    postData.append('profilPhoto', data.profilePhotoFile);
    postData.append('house', data.houseFiles);
    postData.append('documents', JSON.stringify(data.documents);
    let API_URL = this.endpoint+`/add-file`;
    return this.http.post(API_URL, postData)
  }
</code>```

Body:
In a js web project,
I want to POST a form with a complexe json schema, and in which some field will be file.

How do I do It?

I currently upload a file alone like this

  const data = new FormData();
    data.append('mimetype', file.type);
    data.append('filename', file.name);
    data.append('file', file);
    return this.httpClient.post(url, data)

but I want my new form look like this:

 var data ={username:"John doe",
    profilPhoto:{mimetype:..., filename:..., file: ...},
    house:{
       photo:{mimetype:..., filename:..., file: ...},
    },
    documents:[{mimetype:..., filename:..., file: ...}]

  }

Body:
As suggested in the comments encode your file to base64 then decode on the backend and save it as a blob.
Another option would be to use FormData as you do. For the array of objects, you can use JSON.stringify and then JSON.parse on backend.

  addFile(data:any): Observable<any> {
    const postData=new FormData();
    postData.append('username', data.username);
    postData.append('profilPhoto', data.profilePhotoFile);
    postData.append('house', data.houseFiles);
    postData.append('documents', JSON.stringify(data.documents);
    let API_URL = this.endpoint+`/add-file`;
    return this.http.post(API_URL, postData)
  }


问:
Problem with PostgresSQL password authentication failed for user when trying to access or fetch data from database?
I have an issue when trying to fetch data from postgressql. I'm playing with microservices arhitecture using  .NET Core 5.0 and postgressql as my db solution.

I'm trying to containerize my app by using docker containers. And everything works fine till I try to fetch some data through  API.

I got this type of error:

```<code>Npgsql.PostgresException (0x80004005): 28P01: password authentication failed for user "admin"
   at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
   at Npgsql.NpgsqlConnector.AuthenticateMD5(String username, Byte[] salt, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.<>c__DisplayClass38_0.<<Rent>g__RentAsync|0>d.MoveNext()
--- End of stack trace from previous location ---
   at Npgsql.NpgsqlConnection.<>c__DisplayClass41_0.<<Open>g__OpenAsync|0>d.MoveNext()
--- End of stack trace from previous location ---
   at Dapper.SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 472
</code>```

From the backend prespective, situation is pretty simple where I'm trying to fetch data by productName:

```<code>public async Task<Coupon> GetDiscount(string productName)
    {
        using var connection = new NpgsqlConnection
            (_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));

        var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>
            ("SELECT * FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName });

        if (coupon == null)
            return new Coupon
            { ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" };

        return coupon;
    }
</code>```

My appsettings.json file, or to be more precise connection string towards postgressql is this:

```<code> "DatabaseSettings": {
    "ConnectionString": "Server=localhost;Port=5432;Database=DiscountDb;User Id=admin;Password=admin1234;"
  },
</code>```

In docker compose override yml file I have:

```<code>discountdb:
    container_name: discountdb
    environment:
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=admin1234
      - POSTGRES_DB=DiscountDb
    restart: always
    ports:
        - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data/
</code>```

And as I can see, in my portainer I can see that discountdb is up and running

I'm missing something and I don't know what.

答: Check if you have a PostgreSQL instance running on your computer then stop from service and it will work fine lm using the same tutorial and stopped my locally installed postgressql service</p>

Body:
I have an issue when trying to fetch data from postgressql. I'm playing with microservices arhitecture using  .NET Core 5.0 and postgressql as my db solution.

I'm trying to containerize my app by using docker containers. And everything works fine till I try to fetch some data through  API.

I got this type of error:

Npgsql.PostgresException (0x80004005): 28P01: password authentication failed for user "admin"
   at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
   at Npgsql.NpgsqlConnector.AuthenticateMD5(String username, Byte[] salt, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Authenticate(String username, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.<>c__DisplayClass38_0.<<Rent>g__RentAsync|0>d.MoveNext()
--- End of stack trace from previous location ---
   at Npgsql.NpgsqlConnection.<>c__DisplayClass41_0.<<Open>g__OpenAsync|0>d.MoveNext()
--- End of stack trace from previous location ---
   at Dapper.SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 472

From the backend prespective, situation is pretty simple where I'm trying to fetch data by productName:

public async Task<Coupon> GetDiscount(string productName)
    {
        using var connection = new NpgsqlConnection
            (_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));

        var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>
            ("SELECT * FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName });

        if (coupon == null)
            return new Coupon
            { ProductName = "No Discount", Amount = 0, Description = "No Discount Desc" };

        return coupon;
    }

My appsettings.json file, or to be more precise connection string towards postgressql is this:

 "DatabaseSettings": {
    "ConnectionString": "Server=localhost;Port=5432;Database=DiscountDb;User Id=admin;Password=admin1234;"
  },

In docker compose override yml file I have:

discountdb:
    container_name: discountdb
    environment:
      - POSTGRES_USER=admin
      - POSTGRES_PASSWORD=admin1234
      - POSTGRES_DB=DiscountDb
    restart: always
    ports:
        - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data/

And as I can see, in my portainer I can see that discountdb is up and running

I'm missing something and I don't know what.


问:
Eslint allow multiple parsers based on glob patterns
My eslint parser as for now is @typescript-eslint/parser. I want to use @babel/plugin-proposal-optional-chaining plugin, which requires babel-eslint parser.

I saw the eslint-multiple-parsers but it says that it was deprecated :
Use ESLint configuration based on glob patterns (overrides). See https://eslint.org/docs/user-guide/configuring/#configuration-based-on-glob-patterns.

How can I set multiple parses that way?

答:
Is your goal to run parser A against files X and parser B against files Y?

@enterthenamehere-bohemian’s anwser is the solution.

Is your goal to run both parsers against the same files?

It depends…

Is your eslint running inside your editor?

As of today, I can see no solution inside a single eslint config file. You would need a single config file if you want to run it inside your editor.

Is your eslint running in your commandline or Continuous Integration environment?

You need three config files.

File .eslintrc.json

{
    "parser": "@typescript-eslint/parser",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …typescript parser rules here
    }
    …
}
```
<p>File <code>.eslintrc.babel.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
    "parser": "babel-eslint",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …babel parser rules here
    }
    …
}
</code>```

File eslint-rules.json

{
    "rules": { …
        …common eslint rules here
    }
    …
}
```
<p>Having that, you can run both in your comanndline:</p>
<pre class="lang-sh prettyprint-override"><code>eslint # <- runs .eslintrc.json
eslint --config .eslintrc.babel.json
</code>```

Body:
Is your goal to run parser A against files X and parser B against files Y?

@enterthenamehere-bohemian’s anwser is the solution.

Is your goal to run both parsers against the same files?

It depends…

Is your eslint running inside your editor?

As of today, I can see no solution inside a single eslint config file. You would need a single config file if you want to run it inside your editor.

Is your eslint running in your commandline or Continuous Integration environment?

You need three config files.

File .eslintrc.json

{
    "parser": "@typescript-eslint/parser",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …typescript parser rules here
    }
    …
}

File .eslintrc.babel.json

{
    "parser": "babel-eslint",
    "extends": ["./eslint-common-rules.json"],
    "rules": {
        …babel parser rules here
    }
    …
}

File eslint-rules.json

{
    "rules": { …
        …common eslint rules here
    }
    …
}

Having that, you can run both in your comanndline:

eslint # <- runs .eslintrc.json
eslint --config .eslintrc.babel.json


问:
react-hooks/exhaustive-deps not showing in VS code
I have a .eslintrc file with the following rules:

```<code>"rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error",
    "no-console": "warn"
},
</code>```

I've installed: eslint-plugin-prettier, eslint-config-prettier and eslint-plugin-react-hooks

I've enabled "eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ], in settings.json in vscode

but when I remove dependencies that are needed in a useEffect, it's not showing an error that I hoped it would

what else do I need to do?

答:
In .eslintrc, along with to adding rules, you must add react-hooks in the list of plugins

```<code>{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error"
  }
}

</code>```

Body:
I have a .eslintrc file with the following rules:

"rules": {
    "prettier/prettier": "error",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error",
    "no-console": "warn"
},

I've installed: eslint-plugin-prettier, eslint-config-prettier and eslint-plugin-react-hooks

I've enabled "eslint.validate": [ "javascript", "javascriptreact", "html", "typescriptreact" ], in settings.json in vscode

but when I remove dependencies that are needed in a useEffect, it's not showing an error that I hoped it would

what else do I need to do?

Body:
In .eslintrc, along with to adding rules, you must add react-hooks in the list of plugins

{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "error"
  }
}


问:
Upgrade LanguageUtil.get method
Good afternoon, I am new to liferay and I am trying to migrate the code of a portlet from 6.2 to 7.4, I need to know how to use the LanguageUtil.get() method in liferay 7.x, currently it is implemented like this in my JSP LanguageUtil.get(pageContext, "key"), but I get an error "PortletConfig get/format methods" I have tried some ways like LanguageUtil.get(themeDisplay.getLocale(), "key") but I can't get the error to go away, any suggestion or correct way is appreciated to do it.</p>
</p>

答:
In a JSP you'd often use <liferay-ui:message key="key"/>, to prevent too many code snippets in the JSP. With this, you'd have no upgrade efforts.

If you want to use LanguageUtil, with a specific ResourceBundle (e.g. the one that comes with the module that you're upgrading), you'll need the locale as well: ResourceBundleUtil.getBundle(locale, this.getClass().getClassLoader()) - you can get the relevant locale through pageContext or themeDisplay. Then use LanguageUtil.get(resourceBundle, key)

Title: Upgrade LanguageUtil.get method


问:
express.js restfulApi, How to add an error message if the request to data.js is not found?
This is the code for the app.js file, it is for use as restful Api, I want to add a error message if the data in the array(data.js) is not found.</p>
```<code>const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/api', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];

      }

      return isValid;
    });

    res.send(filteredUsers);
  });

// Start server on PORT 5000
app.listen(8080, () => {
console.log('Server started!');
});

</code>```

答:
you can send back a json as a response with 404 status and address the error, it would look something like this

```<code>if(!filteredUsers)
  res.status(404).send({
     error: "Data not found"
  })
</code>```

or it can be a simple text

```<code>if(!filteredUsers.length)
   res.status(404).send("Data Not found")
</code>```

Body:
This is the code for the app.js file, it is for use as restful Api, I want to add a error message if the data in the array(data.js) is not found.

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/api', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];

      }

      return isValid;
    });

    res.send(filteredUsers);
  });

// Start server on PORT 5000
app.listen(8080, () => {
console.log('Server started!');
});

Body:
you can send back a json as a response with 404 status and address the error, it would look something like this

if(!filteredUsers)
  res.status(404).send({
     error: "Data not found"
  })

or it can be a simple text

if(!filteredUsers.length)
   res.status(404).send("Data Not found")


问:
TypeScript: get a property from conditional types
I'm trying to get a value that either can exist or not on the property. So I have 2 types: EmptyUser and UserResponse.

EmptyUser interface only has one property.
UserResponse interface has a lot of properties AND id property that I need.

Then in my function I'm trying to use id, but I can't get it from the created types. Below is the example of code:

```<code>interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser | UserResponse;

interface State {
  users: UsersType,
}
</code>```

then in my code I'm trying to get property id from state.users:

```<code>const { id }: UsersType = state.users;
</code>```

and I receive an error: TS2339: Property 'id' does not exist on type 'UsersType'.

I would appreciate any help.

答:
Please try below code.

```<code>interface EmptyUser {
   // only this property
   unauthorized: boolean;
}

interface UserResponse {
   // ...a lot of different properties and
   id: number;
}

type UsersType = EmptyUser | UserResponse;

 interface State {
   users: UsersType,
 }

 let state : State = {
   users : {
      id : 2,
      unauthorized : false
   }
 };

const { id }  = state.users as UserResponse;
console.log(id);
</code>```

Playground link

Body:
I'm trying to get a value that either can exist or not on the property. So I have 2 types: EmptyUser and UserResponse.

EmptyUser interface only has one property.
UserResponse interface has a lot of properties AND id property that I need.

Then in my function I'm trying to use id, but I can't get it from the created types. Below is the example of code:

interface EmptyUser {
  // only this property
  unauthorized: boolean;
}

interface UserResponse {
  // ...a lot of different properties and
  id: number;
}

export type UsersType = EmptyUser | UserResponse;

interface State {
  users: UsersType,
}

then in my code I'm trying to get property id from state.users:

const { id }: UsersType = state.users;

and I receive an error: TS2339: Property 'id' does not exist on type 'UsersType'.

I would appreciate any help.

Body:
Please try below code.

interface EmptyUser {
   // only this property
   unauthorized: boolean;
}

interface UserResponse {
   // ...a lot of different properties and
   id: number;
}

type UsersType = EmptyUser | UserResponse;

 interface State {
   users: UsersType,
 }

 let state : State = {
   users : {
      id : 2,
      unauthorized : false
   }
 };

const { id }  = state.users as UserResponse;
console.log(id);

Playground link


问:
Postgres: Updating rows based on aggregated value without returning duplicated lines
I have a table and I want to select rows that have are from the same hour. Since I want to lock them, I want to update another column and set a value started to now().

I also want only a single group at a time, therefore the LIMIT 1.

with subq as (SELECT some_column, array_agg(timestamp) as timestamps, array_agg(id) as ids, hour FROM (
    SELECT *, date_trunc('hour', timestamp) as hour from some_table FOR UPDATE
) as inner_table GROUP BY some_column, hour LIMIT 1)

UPDATE some_table SET started = now() FROM subq WHERE some_table.id = any(subq.ids)
RETURNING subq.some_column, subq.timestamps
```

This seems to work except it returns me one line per updated line. As I am only referring to subq in the RETURNING, these lines are duplicates.

Is there something I can do about it? I don't know whether my initial subquery and update need to be improved or if this is okay and I only need to find a way to suppress RETURNING except the first line.

答:
During writing the question, another solution came to my mind which seems to do the trick. Instead of RETURNING I could wrap the UPDATE into another subquery and then return the original subquery:

with subq as (SELECT some_column, array_agg(timestamp) as timestamps, array_agg(id) as ids, hour FROM (
    SELECT *, date_trunc('hour', timestamp) as hour from some_table FOR UPDATE
) as inner_table GROUP BY some_column, hour LIMIT 1),
update_subq as (
    UPDATE some_table SET started = now() FROM subq WHERE some_table.id = any(subq.ids)
)
SELECT * FROM subq;
```

Body:
I have a table and I want to select rows that have are from the same hour. Since I want to lock them, I want to update another column and set a value started to now().

I also want only a single group at a time, therefore the LIMIT 1.

with subq as (SELECT some_column, array_agg(timestamp) as timestamps, array_agg(id) as ids, hour FROM (
    SELECT *, date_trunc('hour', timestamp) as hour from some_table FOR UPDATE
) as inner_table GROUP BY some_column, hour LIMIT 1)

UPDATE some_table SET started = now() FROM subq WHERE some_table.id = any(subq.ids)
RETURNING subq.some_column, subq.timestamps

This seems to work except it returns me one line per updated line. As I am only referring to subq in the RETURNING, these lines are duplicates.

Is there something I can do about it? I don't know whether my initial subquery and update need to be improved or if this is okay and I only need to find a way to suppress RETURNING except the first line.


问:
Resizing <video> element to parent div
Has anyone been able to successfully resize a video element to a parent div?

My video element contains a webcam stream that comes in with a ratio of 4:3. I'd like to break the ratio and adjust it to the div size. I've tried the following:

Set width and height 100% > this doesn't do anything, 4:3 remains

Set min-height and min-width 100% > this makes the video resize to something really huge that overflows the div

position:absolute, bottom, top, left and right: 0px also a huge flow over the parent div

Using javascript to get the parent divs height and width, then setting it for the video: No effect, 4:3 ratio remains, no size change.

How to do it?

EDIT: Thanks Gaurav for that greatly detailed reply. It looks good, I wish it would work for me though.

```<code>.parentDiv // Results in around 400x400 pixels for me
{
    position: absolute;
    top: 11px;
    right: 10px;
    left: 10px;
    height: -webkit-calc(50% - 18px);
    height: calc(50% - 18px);
    display: block;
}
</code>```

My video element is in there, I gave it your CSS solution. Unfortunately it only turned white. Could my parentDiv css have anything to do with that?

EDIT 2: Here's the HTML:

```<code><div class="parentDiv">
    <video class="cam_video" autoplay></video>
</div>
</code>```

This is mainly it . The src-attribute of the video is set to my webcam stream.

EDIT 3:

If I right-click and inspect the white (now red scribbled) part in this screenshot https://s22.postimg.cc/th4ha8nmp/ratio2.png, Chrome shows me that the white also belongs to the stream.

It seems as if the stream of the webcam comes along with white stripes at the top and bottom. This is.. annoying.

答:
You can try to add this is your css:</p>
```<code>min-height: 100%;
min-width: 100%;
object-fit: cover;
</code>```

Title: Resizing <video> element to parent div

Body:
Has anyone been able to successfully resize a video element to a parent div?

My video element contains a webcam stream that comes in with a ratio of 4:3. I'd like to break the ratio and adjust it to the div size. I've tried the following:

Set width and height 100% > this doesn't do anything, 4:3 remains

Set min-height and min-width 100% > this makes the video resize to something really huge that overflows the div

position:absolute, bottom, top, left and right: 0px also a huge flow over the parent div

Using javascript to get the parent divs height and width, then setting it for the video: No effect, 4:3 ratio remains, no size change.

How to do it?

EDIT: Thanks Gaurav for that greatly detailed reply. It looks good, I wish it would work for me though.

.parentDiv // Results in around 400x400 pixels for me
{
    position: absolute;
    top: 11px;
    right: 10px;
    left: 10px;
    height: -webkit-calc(50% - 18px);
    height: calc(50% - 18px);
    display: block;
}

My video element is in there, I gave it your CSS solution. Unfortunately it only turned white. Could my parentDiv css have anything to do with that?

EDIT 2: Here's the HTML:

    <video class="cam_video" autoplay></video>

This is mainly it . The src-attribute of the video is set to my webcam stream.

EDIT 3:

If I right-click and inspect the white (now red scribbled) part in this screenshot https://s22.postimg.cc/th4ha8nmp/ratio2.png, Chrome shows me that the white also belongs to the stream.

It seems as if the stream of the webcam comes along with white stripes at the top and bottom. This is.. annoying.

Body:
You can try to add this is your css:

min-height: 100%;
min-width: 100%;
object-fit: cover;


问:
Validate file input type for mandatory presence in html
I have a popup with a form containing file upload cfgfile

```<code><form id="mainForm" method="post" enctype="multipart/form-data" action="">
            <input type="hidden" id="resulttype" value="Create"/>
            <input type="hidden" id="sessiontoken" name="sessiontoken" />
            <input type="hidden" id="cfgid" name="cfgid"/>
            <img  id="titleImage" alt="title" src="/csm/view/images/creat_conform_title.gif" width="216" hspace="4" height="17" vspace="4"/>
            <table id="popupInfo" align="center" width="90%" border="0" cellspacing="0" cellpadding="0">
              <tr>
                <td>To create a new configuration,please download the CSMClient Utility from the "Download CSMClient" option.Run the utility in your environment and upload the generated output XML file.</td>
              </tr>
            </table>
            <table id="downloadLinks" align="center" cellpadding="2" width="90%" border="0" cellspacing="0">
                <tr><td>
                <input name="Button1" type="button" onclick="openDownloadPage()"  id="button1" value="Download CSMClient" class="btn" />
                <a href="https://my-prod.informatica.com/infakb/howto/1/Pages/31738.aspx" target='_new' >How to run CSMClient</a></td></tr>
            </table>
            <table align="center" class="csm-table" width="90%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <td valign="middle" width="30%" >Name </td>
                    <td width="70%"><input type="text" id="cfgname" name="cfgname" tabindex="1" size="26" maxlength="64" value="" /> </td>
                </tr>
                <tr>
                  <td valign="middle" height="65">Description </td>
                  <td height="65">
                  <textarea type="text" class="dis_box" tabindex="2" id="cfgdesc" name="cfgdesc"  ></textarea>
                  </td>
                </tr>
                <tr valign="middle"><tr>
                <td>Type</td><td>
                <select type="select" id="cfgenv" name="cfgenv" tabindex="3">
                    <option value="Production" >Production                </option>
                    <option value="Development" >Development</option>
                    <option value="Test/QA" >Test/QA</option>
                </select></td></tr>
                <tr valign="middle"><td>Upload CSMClient Output File</td>
                    <!-- <td><input type="file" id="cfgfile" name="cfgfile" tabindex="4"  class="multi"  maxlength="1" accept="xml" id="filefield" ></td>-->
                    <td id="filetd"><input type="file" id="cfgfile" name="cfgfile" tabindex="4" /></td>
                </tr>
            </table>
            <table align="center" border="0" cellpadding="10" cellspacing="0" width="84%">
            <tr>
                <td colspan="3" align="center">
                    <label>
                        <input type="submit"  tabindex="5"  value="Create Configuration" id="btnSummary" class="btn" onClick="" />
                        <!--<input  type="button"  tabindex="5"  value="Create Configuration" id="btnSummary" class="btn" onClick="micoxUpload('postUploadInfo','Loading...','Error in upload'); return false;" />-->
                        <!--onClick="micoxUpload(this.form,'/csm/upload','postUploadInfo','Loading...','Error in upload'); return false;"-->
                    </label>

                    <label>
                        <input type="button"  tabindex="6" value="Cancel" id="btnCancel" class="btn"/>
                    </label>
                </td>
              </tr>
            </table>
        </form>
</code>```

When I reload the popup the previous value appears in it, and since we cannot set values for input file type I am removing the cfgfile and dynamically creating a new with same id.

```<code>var fileholder = document.createElement("input");
fileholder.name="cfgfile";
fileholder.type="file";

$('#cfgfile').remove();
$('#filetd').empty();
$("#filetd").append(fileholder);
</code>```

Till here everything is perfect. But how can I validate whether user has selected any file or not? I used below code, but all the time I get EMPTY. So summarizing how can I validate  my input file type to check whether user has entered anything or not.

```<code>if($.trim($("#cfgfile").val()) === "")
    {
        alert("EMPTY");
        event.preventDefault();
    }
</code>```

答:
When you reload the page, you are setting the name, but not the ID in your script, so the #cfgfile selector doesn't match anything. Try:

```<code>var fileholder = document.createElement("input");
fileholder.name="cfgfile";
fileholder.type="file";
fileholder.id = "cfgfile";
</code>```

Since you're already using jQuery, you can do it like this instead:

```<code>var fileholder = $("<input/>" , {
    type: "file",
    id: "cfgfile",
    name: "cfgfile"
});
$("#filetd").append(fileholder);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a popup with a form containing file upload cfgfile

<form id="mainForm" method="post" enctype="multipart/form-data" action="">
            <input type="hidden" id="resulttype" value="Create"/>
            <input type="hidden" id="sessiontoken" name="sessiontoken" />
            <input type="hidden" id="cfgid" name="cfgid"/>

                To create a new configuration,please download the CSMClient Utility from the "Download CSMClient" option.Run the utility in your environment and upload the generated output XML file.

                <input name="Button1" type="button" onclick="openDownloadPage()"  id="button1" value="Download CSMClient" class="btn" />
                How to run CSMClient

                    Name
                    <input type="text" id="cfgname" name="cfgname" tabindex="1" size="26" maxlength="64" value="" />

                  Description

                  <textarea type="text" class="dis_box" tabindex="2" id="cfgdesc" name="cfgdesc"  ></textarea>

                Type
                <select type="select" id="cfgenv" name="cfgenv" tabindex="3">
                    <option value="Production" >Production                </option>
                    <option value="Development" >Development</option>
                    <option value="Test/QA" >Test/QA</option>
                </select>

Upload CSMClient Output File

                    <input type="file" id="cfgfile" name="cfgfile" tabindex="4" />

                        <input type="submit"  tabindex="5"  value="Create Configuration" id="btnSummary" class="btn" onClick="" />

                        <input type="button"  tabindex="6" value="Cancel" id="btnCancel" class="btn"/>

        </form>

When I reload the popup the previous value appears in it, and since we cannot set values for input file type I am removing the cfgfile and dynamically creating a new with same id.

var fileholder = document.createElement("input");
fileholder.name="cfgfile";
fileholder.type="file";

$('#cfgfile').remove();
$('#filetd').empty();
$("#filetd").append(fileholder);

Till here everything is perfect. But how can I validate whether user has selected any file or not? I used below code, but all the time I get EMPTY. So summarizing how can I validate  my input file type to check whether user has entered anything or not.

if($.trim($("#cfgfile").val()) === "")
    {
        alert("EMPTY");
        event.preventDefault();
    }

Body:
When you reload the page, you are setting the name, but not the ID in your script, so the #cfgfile selector doesn't match anything. Try:

var fileholder = document.createElement("input");
fileholder.name="cfgfile";
fileholder.type="file";
fileholder.id = "cfgfile";

Since you're already using jQuery, you can do it like this instead:

var fileholder = $("<input/>" , {
    type: "file",
    id: "cfgfile",
    name: "cfgfile"
});
$("#filetd").append(fileholder);


问:
How to import other modules defined in the same Android app project inside Kotlin code?
I was trying to understand how to create multiple independent modules inside a project and use them in the main app module. I am using android studio Arctic Fox 2020.3.1. I have difficulty in importing the module into Kotlin code. Here is the step I followed.

I have created a 'basic activity' project named MyAppProj. It created a project with module app inside it. (build+run works fine)

Next I added a new module to the project MyAppProj. Since I needed to call C++, I created a 'Android native library' module. As per the suggestion from Android Studio, I used MyAppProj:nativelib as the module name. I didn't know what that ":" was for. (build+run works fine)

Now I have the following structure:

█ Question: What should I do to use the NativeLib class (defined inside MyAppProj:nativelib module) inside the app module's MainActivity.kt file?

All the paths that I tried so far have failed, such as:

```<code>import com.myhomeorg.myappproj.nativelib
import nativelib
</code>```

Note: I am a beginner in Android development. Your help will be greatly appreciated!

答:
You need to add below code in build.gradle:

```<code>dependencies {
    implementation project(":MyAppProj")
}
</code>```

and then add below code in settings.gradle:

include ':MyAppProj'

in Android studio click on file -> new -> import module -> add library location path (MyAppProj file) -> finish
it will automatically add

Body:
I was trying to understand how to create multiple independent modules inside a project and use them in the main app module. I am using android studio Arctic Fox 2020.3.1. I have difficulty in importing the module into Kotlin code. Here is the step I followed.

I have created a 'basic activity' project named MyAppProj. It created a project with module app inside it. (build+run works fine)

Next I added a new module to the project MyAppProj. Since I needed to call C++, I created a 'Android native library' module. As per the suggestion from Android Studio, I used MyAppProj:nativelib as the module name. I didn't know what that ":" was for. (build+run works fine)

Now I have the following structure:

█ Question: What should I do to use the NativeLib class (defined inside MyAppProj:nativelib module) inside the app module's MainActivity.kt file?

All the paths that I tried so far have failed, such as:

import com.myhomeorg.myappproj.nativelib
import nativelib

Note: I am a beginner in Android development. Your help will be greatly appreciated!

Body:
You need to add below code in build.gradle:

dependencies {
    implementation project(":MyAppProj")
}

and then add below code in settings.gradle:

include ':MyAppProj'

in Android studio click on file -> new -> import module -> add library location path (MyAppProj file) -> finish
it will automatically add


问:
async function doesn't seem to run inside sync code
im trying to make a command that connects to the database, i created a little CLI script that loops through files in specific folders to get command class modules

my problem is that in one of my commands, i'm trying to connect to sequelize, and it just doesn't seem to be doing anything. i get no output to the console, nor does it even seem to try to connect

this is probably because i'm still kind of struggling to figure out how to properly do sync / async / await stuff...notice how i use glob.sync cause i want to loop through the files sychronously, but then in my command i need to connect to the database using await

cli.js:

#! /usr/bin/env node

const patterns = [
    './node_modules/unity/src/commands/**/*.js',
    './src/commands/**/*.js',
]
const glob = require('glob')
const path = require('path')
const yargs = require('yargs')
const signature = yargs.argv._[0]
const process = require('process')

patterns.forEach(pattern => {
    glob.sync(pattern).forEach(file => {
        const commandPath = path.resolve(file)
        const command = require(commandPath)

        if (command.signature == signature) {
            command.argv = yargs.argv
            command.run()

            process.exit()
        }
    })
})

console.log('Command not found.')
```
<p>here is an example command in one of the <code>commands</code> folders:</p>
<pre class="lang-js prettyprint-override"><code>const { Sequelize } = require('sequelize')

class MigrateCommand {
    static signature = 'migrate'
    static argv = {}

    static run() {
        const sequelize = new Sequelize({
            dialect: 'mysql',
            host: 'localhost',
            port: 3306,
            database: 'dio_unity2',
            username: 'root',
            password: '',
        })

        const connect = async () => {
            try {
                await sequelize.authenticate()
                console.log('Connection successful.')
            }
            catch (error) {
                console.error('Unable to connect.', error)
            }
        }

        connect()

        console.log('migrate run complete')
    }
}

module.exports = MigrateCommand
</code>```

i've set npx up so i can just run npx unity migrate and it will call this command based on the migrate signature

now my console should say connection successful or unable to connect and then migrate run complete, but all i see in the console is migrate run complete. it's like it isn't even trying to connect at all...

i have no idea what i'm doing wrong here.

答:
You can't make an asynchronous process synchronous without spawning a new thread and synchronously waiting on it. (There's an npm package that does that, via execSync.)

But the good news here is there's no need to in your code. You want to do things in series, but doing things in series isn't quite the same as doing them synchronously. Here's how:

First, run can't make the async process it's starting via authenticate synchronous. So instead, run should just be async (and we don't need connect):

```<code>static async run() {
    const sequelize = new Sequelize({
        dialect: 'mysql',
        host: 'localhost',
        port: 3306,
        database: 'dio_unity2',
        username: 'root',
        password: '',
    })

    try {
        await sequelize.authenticate()
        console.log('Connection successful.')
    } catch (error) {
        console.error('Unable to connect.', error)
    }

    console.log('migrate run complete')
}
</code>```

Next, in the script, we loop through your patterns and files using an async function:

```<code>(async () => {
    for (const pattern of patterns) {
        for (const file of glob.sync(pattern)) {
            const commandPath = path.resolve(file)
            const command = require(commandPath)

            if (command.signature == signature) {
                command.argv = yargs.argv
                await command.run() // *** Note the `await`
                process.exit()
            }
        }
    }
    console.log("Command not found.")
})();
</code>```

That does the work asynchronously, but one after another (in series).

If it were me, I wouldn't use process.exit() to terminate the process, it's a very aggressive form of process termination which may prevent some things from finishing (details here), and may not be as clear to people doing code maintenance later as alternatives.. Now that we've put the code in a wrapper function, I'd just return out of the function to break the loops:

```<code>await command.run();
return;
</code>```

Body:
im trying to make a command that connects to the database, i created a little CLI script that loops through files in specific folders to get command class modules

my problem is that in one of my commands, i'm trying to connect to sequelize, and it just doesn't seem to be doing anything. i get no output to the console, nor does it even seem to try to connect

this is probably because i'm still kind of struggling to figure out how to properly do sync / async / await stuff...notice how i use glob.sync cause i want to loop through the files sychronously, but then in my command i need to connect to the database using await

cli.js:

#! /usr/bin/env node

const patterns = [
    './node_modules/unity/src/commands/**/*.js',
    './src/commands/**/*.js',
]
const glob = require('glob')
const path = require('path')
const yargs = require('yargs')
const signature = yargs.argv._[0]
const process = require('process')

patterns.forEach(pattern => {
    glob.sync(pattern).forEach(file => {
        const commandPath = path.resolve(file)
        const command = require(commandPath)

        if (command.signature == signature) {
            command.argv = yargs.argv
            command.run()

            process.exit()
        }
    })
})

console.log('Command not found.')

here is an example command in one of the commands folders:

const { Sequelize } = require('sequelize')

class MigrateCommand {
    static signature = 'migrate'
    static argv = {}

    static run() {
        const sequelize = new Sequelize({
            dialect: 'mysql',
            host: 'localhost',
            port: 3306,
            database: 'dio_unity2',
            username: 'root',
            password: '',
        })

        const connect = async () => {
            try {
                await sequelize.authenticate()
                console.log('Connection successful.')
            }
            catch (error) {
                console.error('Unable to connect.', error)
            }
        }

        connect()

        console.log('migrate run complete')
    }
}

module.exports = MigrateCommand

i've set npx up so i can just run npx unity migrate and it will call this command based on the migrate signature

now my console should say connection successful or unable to connect and then migrate run complete, but all i see in the console is migrate run complete. it's like it isn't even trying to connect at all...

i have no idea what i'm doing wrong here.

Body:
You can't make an asynchronous process synchronous without spawning a new thread and synchronously waiting on it. (There's an npm package that does that, via execSync.)

But the good news here is there's no need to in your code. You want to do things in series, but doing things in series isn't quite the same as doing them synchronously. Here's how:

First, run can't make the async process it's starting via authenticate synchronous. So instead, run should just be async (and we don't need connect):

static async run() {
    const sequelize = new Sequelize({
        dialect: 'mysql',
        host: 'localhost',
        port: 3306,
        database: 'dio_unity2',
        username: 'root',
        password: '',
    })

    try {
        await sequelize.authenticate()
        console.log('Connection successful.')
    } catch (error) {
        console.error('Unable to connect.', error)
    }

    console.log('migrate run complete')
}

Next, in the script, we loop through your patterns and files using an async function:

(async () => {
    for (const pattern of patterns) {
        for (const file of glob.sync(pattern)) {
            const commandPath = path.resolve(file)
            const command = require(commandPath)

            if (command.signature == signature) {
                command.argv = yargs.argv
                await command.run() // *** Note the `await`
                process.exit()
            }
        }
    }
    console.log("Command not found.")
})();

That does the work asynchronously, but one after another (in series).

If it were me, I wouldn't use process.exit() to terminate the process, it's a very aggressive form of process termination which may prevent some things from finishing (details here), and may not be as clear to people doing code maintenance later as alternatives.. Now that we've put the code in a wrapper function, I'd just return out of the function to break the loops:

await command.run();
return;


问:
In Power BI, is there a way to repoint the data source while keeping all the field formatting and calculated columns in the visuals?
I have a PBI that I set up initially from a CSV file on my desk top to test functionality while waiting for the DB connection.  I've finally gotten the connection but I don't see how I can retain all the changes and calculated columns I put in to the report with the CSV file.  Any ideas or am I out of luck?</p>

答:
Open your report and go to File -> Options and settings -> Data source settings:

There make sure Data sources in current file is selected and click on Change Source button.


问:
Secure login with Jwt or oAuth?
I have a e eCommerce App and want to use a login/token that is Full secure. Is Jwt enough for 10k User or should I Use oAuth? Oauth ja expensive 1.5k dollar for 10k monthly active users</p>

答:
OAuth and JWT can't be compared as these are two completely different things.

OAuth is the standard for authorizing users. It gives you flows that your app can use to get authorization in order to access a user's resources.

JWT is a format for a token. JWTs can be used as access tokens, but they can be used for other things as well. Also, access tokens don't have to be in the form of a JWT.

In short - OAuth will tell you how to get an access token, and JWT is just one format of the token that you can obtain using an OAuth flow.

OAuth can also be further extended with OpenID Connect, which is used for authenticating users.

The answer to "should I use OAuth" is of course never concrete. It all depends on the setup of your application. If you have just your own backend and you are looking for ways of securing it with user accounts, then you don't need OAuth, you just need sessions and secure features for logging in users (maybe two-factor authentication). If you have a separate application on your front end and an API, then using OAuth flows will grant you standard ways of obtaining access tokens.

As for JWTs, you should use them only if you see a valid use case for that. If you don't need to pass information in a token directly to your APIs, then you don't need the JWT, you'll be fine with any random-string token.

Oauth ja expensive 1.5k dollar for 10k monthly active users

I don't understand this part. What do you mean that OAuth is expensive? OAuth is a standard and it's free to use. If you mean that paying for an OAuth server is expensive then this of course depends on the vendor. There are many different OAuth vendors out there, and there are also free solutions (either where you have to code some things yourself, like the Spring Security Server, or complete products like Keycloak or the Curity Identity Server's Community Edition.

Title: Secure login with Jwt or oAuth?


问:
What is the alternative for getMonthValue(),getDayOfMonth() in java 7?
```<code>SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();
</code>```

How Do I make this Java 7 compatible? What changes should I do?

```<code>String part = date.getYear() + "" + String.format("%02d", date.getMonthValue()) + ""
        + String.format("%02d", date.getDayOfMonth()) + "" + String.format("%02d", date.getHour()) + ""
        + String.format("%02d", date.getMinute()) + "" + String.format("%02d", date.getSecond());
</code>```

答:
The terrible Date, Calendar, and SimpleDateFormat classes were supplanted by the modern java.time classes defined in JSR 310 and built into Java 8+.

No need to hack together the output string. Use a DateTimeFormatter object instead.

```<code>ZonedDateTime zdt = ZonedDateTime.now() ;
String output =
    zdt
    .truncatedTo( ChronoUnit.SECONDS )
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
</code>```

For Java 6 and 7, add the back-port of java.time to your project, the ThreeTen-Backport library. The API is nearly identical to java.time, so later upgrading your project to modern Java will involve little more than changing the import statements.

As you may know, Java 6 and 7 are years past their end-of-life. I suggest you consider migrating to Java 8, 11, or 17, if at all possible.

Body:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();

How Do I make this Java 7 compatible? What changes should I do?

String part = date.getYear() + "" + String.format("%02d", date.getMonthValue()) + ""
        + String.format("%02d", date.getDayOfMonth()) + "" + String.format("%02d", date.getHour()) + ""
        + String.format("%02d", date.getMinute()) + "" + String.format("%02d", date.getSecond());

Body:
The terrible Date, Calendar, and SimpleDateFormat classes were supplanted by the modern java.time classes defined in JSR 310 and built into Java 8+.

No need to hack together the output string. Use a DateTimeFormatter object instead.

ZonedDateTime zdt = ZonedDateTime.now() ;
String output =
    zdt
    .truncatedTo( ChronoUnit.SECONDS )
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;

For Java 6 and 7, add the back-port of java.time to your project, the ThreeTen-Backport library. The API is nearly identical to java.time, so later upgrading your project to modern Java will involve little more than changing the import statements.

As you may know, Java 6 and 7 are years past their end-of-life. I suggest you consider migrating to Java 8, 11, or 17, if at all possible.


问:
Embedding web component with easy implementation on the client side
Sorry that the question below is not as specific as it might probably be but that’s the problem - I’ve done my research but I lack domain knowledge to decide if my conclusions are correct :)

I want to make a web component that will be easily embeddable on any website (no matter what frontend technology it uses). Idea is that:

I provide someone (let's call him/her a client)  with 2 things:

a code to paste on frontend (perfectly if this code would just fetch/render externally hosted (by me) script - to not force clients to implement possible changes on their side)

api key identifying client

Client pastes code on his frontend and provides api token to queries

Then it should have two way communication with my backend (through web)

Imo this is exactly the case like e.g. embedding google map: (https://developers.google.com/maps/documentation/embed/map-generator#create-project)

```<code> <iframe width="600" height="450" style="border:0" loading="lazy" allowfullscreen
src="https://www.google.com/maps/embed/v1/undefined?origin=...&q=...&destination=...&center=...&zoom=...&key=...">
</code>```

As far as I understand they just create iframe and fetch .js from their server. Now, I would like to know if doing it that way is my best option. I’m looking for a framework to make development as fast as possible. I’ve found lit-elements (https://lit.dev/)  - do you think it might be a good choice?

答:
Yes that is absolutely possible. Load your js as a module.

```<code><script type="module" src="path-to-your-module.mjs"></script>
</code>```

Then you can achieve the following (all inlined for presentability here):

<my-element apiKey="CAFEBABE"></my-element>```

This would work, no matter which framework you use.

Body:
Sorry that the question below is not as specific as it might probably be but that’s the problem - I’ve done my research but I lack domain knowledge to decide if my conclusions are correct :)

I want to make a web component that will be easily embeddable on any website (no matter what frontend technology it uses). Idea is that:

I provide someone (let's call him/her a client)  with 2 things:

a code to paste on frontend (perfectly if this code would just fetch/render externally hosted (by me) script - to not force clients to implement possible changes on their side)

api key identifying client

Client pastes code on his frontend and provides api token to queries

Then it should have two way communication with my backend (through web)

Imo this is exactly the case like e.g. embedding google map: (https://developers.google.com/maps/documentation/embed/map-generator#create-project)

As far as I understand they just create iframe and fetch .js from their server. Now, I would like to know if doing it that way is my best option. I’m looking for a framework to make development as fast as possible. I’ve found lit-elements (https://lit.dev/)  - do you think it might be a good choice?

Body:
Yes that is absolutely possible. Load your js as a module.

<script type="module" src="path-to-your-module.mjs"></script>

Then you can achieve the following (all inlined for presentability here):

<script type="module">
import {
  LitElement,
  html,
  css
} from "https://unpkg.com/lit-element/lit-element.js?module";

class ElementWithAPIKey extends LitElement {

 static get properties() {
  return {
    apiKey: {type: String}
  };
 }

 render() {
  return html`
      <h1>Example APIKEY: ${this.apiKey}</h1>
  `;
 }
}

customElements.define("my-element", ElementWithAPIKey);
</script>
<my-element apiKey="CAFEBABE"></my-element>

This would work, no matter which framework you use.


问:
Problem using RefreshIndicator with a NestedScrollView
I have 3 tab pages and I want to have a "pull to refresh" type of functionality when I pull to refresh the area inside of the respective tabs. I tried to use RefreshIndicator in the body area but it's hasn't been working properly. It made the header and the scrolling just not function properly anymore.

New to flutter and I'm really stumped, does anyone have any ideas of what I'm doing wrong here? Any help would be appreciated, TYIA!

```<code>@override
  Widget build(BuildContext context) => Scaffold(
        body: DefaultTabController(
          length: 3,
          child: NestedScrollView(
            floatHeaderSlivers: true,
            headerSliverBuilder: (context, value) {
              return <Widget>[
                SliverAppBar(
                  backgroundColor: kMainBG,
                  expandedHeight: 100,
                  toolbarHeight: 40,
                  floating: true,
                  pinned: true,
                  leading: IconButton(//icon stuff),
                  actions: <Widget>[IconButton(// icon stuff)],
                  title: Padding( // Padding & text),
                  titleSpacing: 0,
                  centerTitle: true,
                  bottom: TabBar(
                    isScrollable: true,
                    padding: EdgeInsets.only(
                        left: 10, right: 10),
                    unselectedLabelColor: tabUnselected,
                    labelColor: tabSelected,
                    labelStyle: TextStyle(// Styling Stuff),
                    tabs: [
                      Tab(text: 'STORES'),
                      Tab(text: 'OFFERS'),
                      Tab(text: 'EVENTS'),
                    ],
                    indicator: MaterialIndicator(
                      color: tabIndicator,
                      bottomLeftRadius: 50,
                      bottomRightRadius: 50,
                      topLeftRadius: 50,
                      topRightRadius: 50,
                    ),
                  ),
                ),
              ];
            },
            body: TabBarView(
              children: [
                Container(
                  color: kMainBG,
                  child: StoresTab(),
                ),
                Container(
                  color: kMainBG,
                  child: OffersTab(),
                ),
                Container(
                  color: kMainBG,
                  child: EventsTab(),
                ),
              ],
            ),
          ),
        ),
      );

</code>```

答:
This code is working for me, it's mostly built on top of @Nuts answer, but it needed some tweaking and my edit was rejected see here

Example:-

```<code>DefaultTabController(
      length: tabs.length,
      child: RefreshIndicator(
        notificationPredicate: (notification) {
          // with NestedScrollView local(depth == 2) OverscrollNotification are not sent
          return notification.depth == 2;
        },
        onRefresh: () => Future.value(null),
        child: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverAppBar(...)
            ];
          },
          body: TabBarView(
            children: tabs,
          ),
        ),
      ),
    )
</code>```

Body:
I have 3 tab pages and I want to have a "pull to refresh" type of functionality when I pull to refresh the area inside of the respective tabs. I tried to use RefreshIndicator in the body area but it's hasn't been working properly. It made the header and the scrolling just not function properly anymore.

New to flutter and I'm really stumped, does anyone have any ideas of what I'm doing wrong here? Any help would be appreciated, TYIA!

@override
  Widget build(BuildContext context) => Scaffold(
        body: DefaultTabController(
          length: 3,
          child: NestedScrollView(
            floatHeaderSlivers: true,
            headerSliverBuilder: (context, value) {
              return <Widget>[
                SliverAppBar(
                  backgroundColor: kMainBG,
                  expandedHeight: 100,
                  toolbarHeight: 40,
                  floating: true,
                  pinned: true,
                  leading: IconButton(//icon stuff),
                  actions: <Widget>[IconButton(// icon stuff)],
                  title: Padding( // Padding & text),
                  titleSpacing: 0,
                  centerTitle: true,
                  bottom: TabBar(
                    isScrollable: true,
                    padding: EdgeInsets.only(
                        left: 10, right: 10),
                    unselectedLabelColor: tabUnselected,
                    labelColor: tabSelected,
                    labelStyle: TextStyle(// Styling Stuff),
                    tabs: [
                      Tab(text: 'STORES'),
                      Tab(text: 'OFFERS'),
                      Tab(text: 'EVENTS'),
                    ],
                    indicator: MaterialIndicator(
                      color: tabIndicator,
                      bottomLeftRadius: 50,
                      bottomRightRadius: 50,
                      topLeftRadius: 50,
                      topRightRadius: 50,
                    ),
                  ),
                ),
              ];
            },
            body: TabBarView(
              children: [
                Container(
                  color: kMainBG,
                  child: StoresTab(),
                ),
                Container(
                  color: kMainBG,
                  child: OffersTab(),
                ),
                Container(
                  color: kMainBG,
                  child: EventsTab(),
                ),
              ],
            ),
          ),
        ),
      );

Body:
This code is working for me, it's mostly built on top of @Nuts answer, but it needed some tweaking and my edit was rejected see here

Example:-

DefaultTabController(
      length: tabs.length,
      child: RefreshIndicator(
        notificationPredicate: (notification) {
          // with NestedScrollView local(depth == 2) OverscrollNotification are not sent
          return notification.depth == 2;
        },
        onRefresh: () => Future.value(null),
        child: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return [
              SliverAppBar(...)
            ];
          },
          body: TabBarView(
            children: tabs,
          ),
        ),
      ),
    )


问:
How would I loop through directories with PowerShell to grab text files?
I'm trying to find out a way use a loop to go through directories with different names, go into a folder in each of those with the same name (TSO), grab the text file, use it for functions (Extractor and VisioMaker), then repeat the process for the next folders. To clarify, I'm only having a problem with the loop portion. Here's the directory format:

Main Folder (TestCircuits) >

Folder1 > TSO > Name1.txt

Folder2 > TSO > Name2.txt

Folder3 > TSO > Name3.txt

...

```<code>Set-Location " \TestCircuits"

       #Testing

       $location =  " \TestCircuits"

       Foreach-Object {

       #select only the latest text file
       $Global:fileM = Get-ChildItem "*\TSO\*.txt" | sort LastWriteTime | select -last 1 | Get-Item

       #set new variable for clarity in later function
       $Global:ccsd = $fileM

       #use recurse for the loop? Seems to work fine
       $Global:files = Get-ChildItem " \TestCircuits" -Recurse

       #path format for the loop might be janky, but seems to work
       $Global:textFileData = Get-ChildItem " \TestCircuits\*\TSO\$ccsd" | Get-Content
       $Global:textFileDataRaw = Get-ChildItem " \TestCircuits\*\TSO\$ccsd" | Get-Content -raw

              foreach ($fileM in $files) {
                   #need to use $fileM but not sure how

                  Function Extractor {
                      #code that sets variables from text in each file
                      #uses $ccsd variable to get text
                                }

                  Function VisioMaker {
                      #code that makes Visio doc from variables each time
                      #variables used are from Extractor function
                                }
                }
}
</code>```

Any help would be appreciated. Thanks!

答:
There are still a few things I don't understand. For instance why you would use global variables. Global variables are only used when you initially need to set them and use them in numerous functions, but normally you would just pass the correct variables to each function.

I have made a few adjustments for your script to make it work.

```<code>Set-Location " \TestCircuits"

#Testing

$location = " \TestCircuits"

#Get all folder recursively that are named TSO
$tsoFolders = Get-ChildItem -Recurse -Directory -Filter 'TSO'

#Loop through each folder, get the latest written text file per folder and use the functions foreach latest file
foreach($tsoFolder in $tsoFolders){
    #select only the latest text file
    $Global:fileM = Get-ChildItem -Path $tsoFolder.FullName -Filter "*.txt" | sort LastWriteTime | select -last 1 | Get-Item

    #set new variable for clarity in later function
    $Global:ccsd = $fileM

    #path format for the loop might be janky, but seems to work
    $Global:textFileData =  Get-Content $ccsd.FullName
    $Global:textFileDataRaw = Get-Content $ccsd.FullName -Raw

    Function Extractor {
        #code that sets variables from text in each file
        #uses $ccsd variable to get text
    }

    Function VisioMaker {
        #code that makes Visio doc from variables each time
        #variables used are from Extractor function
    }
}
</code>```

This function only processes each last written text file per TSO folder, but can easily be adjusted to process all text files.

To loop through the files, you could simply call the function and the function can be outside the loop. See the below example of how to use it better without the gloval variables:

```<code>Function Extractor ($FileData, $RawFileData){
    #$FileData is available here and $RawFileData

    #code that sets variables from text in each file
    #uses $ccsd variable to get text
}

Function VisioMaker ($FileData, $RawFileData){
    #$FileData is available here and $RawFileData

    #code that makes Visio doc from variables each time
    #variables used are from Extractor function
}

Set-Location " \TestCircuits"

#Testing

$location = " \TestCircuits"

#Get all folder recursively that are named TSO
$tsoFolders = Get-ChildItem -Recurse -Directory -Filter 'TSO'

#Loop through each folder, get the latest written text file per folder and use the functions foreach latest file
foreach($tsoFolder in $tsoFolders){
    #select only the latest text file
    $fileM = Get-ChildItem -Path $tsoFolder.FullName -Filter "*.txt" | sort LastWriteTime | select -last 1 | Get-Item

    #set new variable for clarity in later function
    $ccsd = $fileM

    #path format for the loop might be janky, but seems to work
    $textFileData =  Get-Content $ccsd.FullName
    $textFileDataRaw = Get-Content $ccsd.FullName -Raw

    #call the extractor function with the file data
    Extractor -FileData $textFileData -RawFileData $textFileDataRaw

    #call the VisioMaker function with the file data
    VisioMaker -FileData $textFileData -RawFileData $textFileDataRaw
}
</code>```

Body:
I'm trying to find out a way use a loop to go through directories with different names, go into a folder in each of those with the same name (TSO), grab the text file, use it for functions (Extractor and VisioMaker), then repeat the process for the next folders. To clarify, I'm only having a problem with the loop portion. Here's the directory format:

Main Folder (TestCircuits) >

Folder1 > TSO > Name1.txt

Folder2 > TSO > Name2.txt

Folder3 > TSO > Name3.txt

...

Set-Location " \TestCircuits"

       #Testing

       $location =  " \TestCircuits"

       Foreach-Object {

       #select only the latest text file
       $Global:fileM = Get-ChildItem "*\TSO\*.txt" | sort LastWriteTime | select -last 1 | Get-Item

       #set new variable for clarity in later function
       $Global:ccsd = $fileM

       #use recurse for the loop? Seems to work fine
       $Global:files = Get-ChildItem " \TestCircuits" -Recurse

       #path format for the loop might be janky, but seems to work
       $Global:textFileData = Get-ChildItem " \TestCircuits\*\TSO\$ccsd" | Get-Content
       $Global:textFileDataRaw = Get-ChildItem " \TestCircuits\*\TSO\$ccsd" | Get-Content -raw

              foreach ($fileM in $files) {
                   #need to use $fileM but not sure how

                  Function Extractor {
                      #code that sets variables from text in each file
                      #uses $ccsd variable to get text
                                }

                  Function VisioMaker {
                      #code that makes Visio doc from variables each time
                      #variables used are from Extractor function
                                }
                }
}

Any help would be appreciated. Thanks!

Body:
There are still a few things I don't understand. For instance why you would use global variables. Global variables are only used when you initially need to set them and use them in numerous functions, but normally you would just pass the correct variables to each function.

I have made a few adjustments for your script to make it work.

Set-Location " \TestCircuits"

#Testing

$location = " \TestCircuits"

#Get all folder recursively that are named TSO
$tsoFolders = Get-ChildItem -Recurse -Directory -Filter 'TSO'

#Loop through each folder, get the latest written text file per folder and use the functions foreach latest file
foreach($tsoFolder in $tsoFolders){
    #select only the latest text file
    $Global:fileM = Get-ChildItem -Path $tsoFolder.FullName -Filter "*.txt" | sort LastWriteTime | select -last 1 | Get-Item

    #set new variable for clarity in later function
    $Global:ccsd = $fileM

    #path format for the loop might be janky, but seems to work
    $Global:textFileData =  Get-Content $ccsd.FullName
    $Global:textFileDataRaw = Get-Content $ccsd.FullName -Raw

    Function Extractor {
        #code that sets variables from text in each file
        #uses $ccsd variable to get text
    }

    Function VisioMaker {
        #code that makes Visio doc from variables each time
        #variables used are from Extractor function
    }
}

This function only processes each last written text file per TSO folder, but can easily be adjusted to process all text files.

To loop through the files, you could simply call the function and the function can be outside the loop. See the below example of how to use it better without the gloval variables:

Function Extractor ($FileData, $RawFileData){
    #$FileData is available here and $RawFileData

    #code that sets variables from text in each file
    #uses $ccsd variable to get text
}

Function VisioMaker ($FileData, $RawFileData){
    #$FileData is available here and $RawFileData

    #code that makes Visio doc from variables each time
    #variables used are from Extractor function
}

Set-Location " \TestCircuits"

#Testing

$location = " \TestCircuits"

#Get all folder recursively that are named TSO
$tsoFolders = Get-ChildItem -Recurse -Directory -Filter 'TSO'

#Loop through each folder, get the latest written text file per folder and use the functions foreach latest file
foreach($tsoFolder in $tsoFolders){
    #select only the latest text file
    $fileM = Get-ChildItem -Path $tsoFolder.FullName -Filter "*.txt" | sort LastWriteTime | select -last 1 | Get-Item

    #set new variable for clarity in later function
    $ccsd = $fileM

    #path format for the loop might be janky, but seems to work
    $textFileData =  Get-Content $ccsd.FullName
    $textFileDataRaw = Get-Content $ccsd.FullName -Raw

    #call the extractor function with the file data
    Extractor -FileData $textFileData -RawFileData $textFileDataRaw

    #call the VisioMaker function with the file data
    VisioMaker -FileData $textFileData -RawFileData $textFileDataRaw
}


问:
After Anaconda installation, python gets recognized in cmd launched by Anaconda Navigator only - Does it mean python can be used within Anaconda?
Learning from this post , I understand that installing Anaconda on Windows 10 PC will automatically install Python compiler, so we don't need to install Python separately after we install Anaconda. Sounds good.

I install Anaconda and then start the Navigator.
Then I launch CMD.exe from Anaconda Navigator and type python --version to check the python compiler installed on my machine. So far so good.

Then I start CMD.exe manually from windows 10 as Administrator (Click Start --> Type CMD manually --> Right Click --> Run as Administrator).
Then I type python --version , it shows "Not Found".

Does it mean that when installing Anaconda , Python is available only within Anaconda platform? Not globally anywhere within the Windows OS ?

答:
This is only an issue of how PATH is set. Note how there is an additional (base) prepended to the C:\>.... prompt. This indicates that a conda environment is currently active, which is what you are currently referring to as being "inside of anaconda". But more correctly, you should think of it like: I have a cmd prompt and the conda base environment is currently active.

When you run cmd from anaconda navigator, this get's done automatically. When you launch it by just starting cmd.exe, then this does not get done automatically. This behaviour could be influenced by checking the Add Anaconda to PATH during the installation.

To get a cmd prompt with the (base) environment active, you can do different things:

Start cmd from your anaconda navigator (as you have done so far)

Start the Anaconda Command Prompt, which you can find through hitting the windows key and then start typing the name

Start a normal cmd and then execute <CONDA Install Dir>\Scripts\activate.bat


答:
You can return error in restful api noed js like this:

```<code>if (!data) return res.status(404).send({ msg: 'data not found' })
</code>```

actually in your code you should use it like this:

```<code>const data = require('./data');

app.use('/api', (req, res, next) => {
if (!data) return res.status(404).send({ msg: 'data not found' })

    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];

      }

      return isValid;
    });

    res.send(filteredUsers);
  });
</code>```

good luck :)

Title: express.js restfulApi, How to add an error message if the request to data.js is not found?

Body:
This is the code for the app.js file, it is for use as restful Api, I want to add a error message if the data in the array(data.js) is not found.

const express = require('express');
const data = require('./data');

// Initialize App
const app = express();

// Assign route
app.use('/api', (req, res, next) => {
    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];

      }

      return isValid;
    });

    res.send(filteredUsers);
  });

// Start server on PORT 5000
app.listen(8080, () => {
console.log('Server started!');
});

Body:
You can return error in restful api noed js like this:

if (!data) return res.status(404).send({ msg: 'data not found' })

actually in your code you should use it like this:

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

app.use('/api', (req, res, next) => {
if (!data) return res.status(404).send({ msg: 'data not found' })

    const filters = req.query;
    const filteredUsers = data.filter(user => {
      let isValid = true;
      for (key in filters) {
        console.log(key, user[key], filters[key]);
        isValid = isValid && user[key] == filters[key];

      }

      return isValid;
    });

    res.send(filteredUsers);
  });

good luck :)


问:
Dynamically create textboxes using javascript and insert that text box values into mysql
Hi i have created some text boxes dynamically using javascript according to the no of inputs.
I want to save that textbox values to mysql database. am very new to javascript. Thanks in advance.

Here is my code:

```<code>    <script>

   function add_col()
   {
   var num_box = document.getElementById("num_text").value;
   if(num_box)
   {
   for(var i=0; i<num_box; i++)
   {

   var tableName1 = document.getElementById("uTable");

   var newTR1 = document.getElementById("tr1");

   var newName1 = document.createElement("TD");

   newName1.innerHTML = "<input type='text'  name='site' id='site' value='cell value'>";

   var newTR2 = document.getElementById("tr2");

   var newPhone1 = document.createElement("TD");

   newPhone1.innerHTML = "<input type='text'  name='cell' id='cell' value='site value'>";

   newTR1.appendChild(newName1);

   newTR2.appendChild(newPhone1);

   tableName1.appendChild(newTR1);
   tableName1.appendChild(newTR2);

    document.form1.reset()

    }

   }

   }
   </script>

    <form name="form1" id="form1" method="post">

        <p>
          <input type="text" name="num_text" id="num_text"/>
          <input type="button" name="Submit" value="INPUT" onclick="add_col();" />
        </p>
        <p> </p>
        <table  id="uTable"width="183" border="0">
          <tr id="tr1">
            <td>Name</td>

          </tr>
          <tr id="tr2">
            <td>Phone</td>

          </tr>

      </table>
        <input type="submit" name="Submit2" value="Insert"  />
    </form>
</code>```

答:
You could use an array for your input fields. Such that you could have something like name='cell[]' and name='site[]' then pass the array to the server. Also you may want to look into jquery to help you out with the javascript. Just makes it cleaner and easy to use javascript.

also i would probably forgo using a table. check out definition lists. This link will help:
http://www.maxdesign.com.au/articles/definition/ It would be easier to add or remove elements.

Body:
Hi i have created some text boxes dynamically using javascript according to the no of inputs.
I want to save that textbox values to mysql database. am very new to javascript. Thanks in advance.

Here is my code:

    <form name="form1" id="form1" method="post">

          <input type="text" name="num_text" id="num_text"/>
          <input type="button" name="Submit" value="INPUT" onclick="add_col();" />

            Name

            Phone

        <input type="submit" name="Submit2" value="Insert"  />
    </form>


问:
Swift CollectionView items do not scroll
my CollectionView's items do not scroll, when I scroll down the first items stay at their place, without any change, you can see what I mean on the image: collectionview
Here is the code of the collectionView:

```<code>func setUpCollectionView() {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
                    layout.sectionInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15)
                    layout.itemSize = CGSize(width: 100, height: 100)

                    myCollectionView = UICollectionView(frame: self.contentView.frame, collectionViewLayout: layout)
                    myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
                    myCollectionView?.backgroundColor = UIColor.clear
                    myCollectionView?.allowsSelection = true

                    myCollectionView?.dataSource = self
                    myCollectionView?.delegate = self

                    contentView.addSubview(myCollectionView ?? UICollectionView())
        myCollectionView?.register(SpendingCell.self, forCellWithReuseIdentifier: "Spending")

        myCollectionView?.translatesAutoresizingMaskIntoConstraints = false
        myCollectionView?.topAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
        myCollectionView?.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true
        myCollectionView?.heightAnchor.constraint(equalToConstant: 350).isActive = true
    }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Spending", for: indexPath) as! SpendingCell
        cell.setUpSpending(cost: categories[indexPath.row])
        return cell

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 23
        }
</code>```

and the collectionView cell:

```<code>class SpendingCell: UICollectionViewCell {

    let stackView = UIStackView()
    let SpendingButton = UIImageView()
    let nameLabel = UILabel()
    let sumLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(stackView)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setUpSpending(cost: Spending) {
        stackView.alignment = .center
        stackView.axis = .vertical
        stackView.distribution = .fillProportionally
        stackView.spacing = 5

        stackView.addArrangedSubview(SpendingButton)
        stackView.addArrangedSubview(nameLabel)

        //Constraints
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        stackView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        stackView.heightAnchor.constraint(equalToConstant: 100).isActive = true

        SpendingButton.image = cost.image
        SpendingButton.contentMode = .scaleAspectFit
        SpendingButton.layer.cornerRadius = 40
        SpendingButton.layer.masksToBounds = true

        SpendingButton.translatesAutoresizingMaskIntoConstraints = false
        SpendingButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
        SpendingButton.heightAnchor.constraint(equalToConstant: 80).isActive = true

        nameLabel.text = cost.title
        nameLabel.textAlignment = .center
        nameLabel.textColor = .black
        nameLabel.font = UIFont.boldSystemFont(ofSize: 10)

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
        nameLabel.heightAnchor.constraint(equalToConstant: 15).isActive = true
    }

}

</code>```

Could someone please help me how to change that? Thanks in advance!

答:
```<code>func makeKeyboardCollectionView() {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 70, height: 40)
    layout.scrollDirection = .vertical
    keyboardCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    contentView.addSubview(keyboardCollectionView)

    keyboardCollectionView.snp.makeConstraints({ make in
        make.top.equalTo(vocabularyLabel.snp.bottom).inset(-5)
        make.left.equalToSuperview().inset(40)
        make.right.equalToSuperview().inset(50)
        make.height.equalTo(210)
    })
    keyboardCollectionView.backgroundColor = .clear
    keyboardCollectionView.showsVerticalScrollIndicator = false
    keyboardCollectionView.register(KeyboardCollectionViewCell.self, forCellWithReuseIdentifier: KeyboardCollectionViewCell.identifier)
    keyboardCollectionView.dataSource = self
    keyboardCollectionView.delegate = self
}
</code>```

Body:
my CollectionView's items do not scroll, when I scroll down the first items stay at their place, without any change, you can see what I mean on the image: collectionview
Here is the code of the collectionView:

func setUpCollectionView() {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
                    layout.sectionInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15)
                    layout.itemSize = CGSize(width: 100, height: 100)

                    myCollectionView = UICollectionView(frame: self.contentView.frame, collectionViewLayout: layout)
                    myCollectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
                    myCollectionView?.backgroundColor = UIColor.clear
                    myCollectionView?.allowsSelection = true

                    myCollectionView?.dataSource = self
                    myCollectionView?.delegate = self

                    contentView.addSubview(myCollectionView ?? UICollectionView())
        myCollectionView?.register(SpendingCell.self, forCellWithReuseIdentifier: "Spending")

        myCollectionView?.translatesAutoresizingMaskIntoConstraints = false
        myCollectionView?.topAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
        myCollectionView?.widthAnchor.constraint(equalTo: contentView.widthAnchor).isActive = true
        myCollectionView?.heightAnchor.constraint(equalToConstant: 350).isActive = true
    }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Spending", for: indexPath) as! SpendingCell
        cell.setUpSpending(cost: categories[indexPath.row])
        return cell

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 23
        }

and the collectionView cell:

class SpendingCell: UICollectionViewCell {

    let stackView = UIStackView()
    let SpendingButton = UIImageView()
    let nameLabel = UILabel()
    let sumLabel = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(stackView)

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setUpSpending(cost: Spending) {
        stackView.alignment = .center
        stackView.axis = .vertical
        stackView.distribution = .fillProportionally
        stackView.spacing = 5

        stackView.addArrangedSubview(SpendingButton)
        stackView.addArrangedSubview(nameLabel)

        //Constraints
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        stackView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        stackView.widthAnchor.constraint(equalToConstant: 100).isActive = true
        stackView.heightAnchor.constraint(equalToConstant: 100).isActive = true

        SpendingButton.image = cost.image
        SpendingButton.contentMode = .scaleAspectFit
        SpendingButton.layer.cornerRadius = 40
        SpendingButton.layer.masksToBounds = true

        SpendingButton.translatesAutoresizingMaskIntoConstraints = false
        SpendingButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
        SpendingButton.heightAnchor.constraint(equalToConstant: 80).isActive = true

        nameLabel.text = cost.title
        nameLabel.textAlignment = .center
        nameLabel.textColor = .black
        nameLabel.font = UIFont.boldSystemFont(ofSize: 10)

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.widthAnchor.constraint(equalToConstant: 100).isActive = true
        nameLabel.heightAnchor.constraint(equalToConstant: 15).isActive = true
    }

}

Could someone please help me how to change that? Thanks in advance!