问:
Angular Material table matSort not working
I'm having troubles with my table

I fetch data and then pass it to my table

Here is my code:

html

```<code><div class="mainContainer">
  <div class="mat-elevation-z8 content">

  <mat-table
    class="mat-elevation-z3 productsTable"
    matSort
    mat-table
    [dataSource]="productsDataForTable">

    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Title
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        {{row.name.en}}
      </mat-cell>
    </ng-container>

  <ng-container matColumnDef="image">
      <mat-header-cell *matHeaderCellDef>
        Image
      </mat-header-cell>
      <mat-cell *matCellDef="let prod; let i = index" >
        <img class="prodThumbnail" src={{prodsThumbnails[i]}} alt="Product thumbnail">
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Description
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.description.en}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Weight
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.weight + ' ' + prod.weightUnit}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="SKU">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        SKU
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.sku}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="price">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Price
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        $ {{prod.prices[0].unitPrice}} {{prod.prices[0].currency}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Category
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.category}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Status
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.status}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
        Actions
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        <mat-icon class="actionOnProductButton" (click)="openProductDetailsDialog(prod)">create</mat-icon>
        <mat-icon class="actionOnProductButton" (click)="openDeleteProductDialog(prod)">delete</mat-icon>
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="tableHeaders"></mat-header-row>
    <mat-row
      class="table-rows"
      *matRowDef="let row; columns: tableHeaders;">

    </mat-row>

  </mat-table>

  </div>
</div>
</code>```

TS

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Catalog } from '../../catalog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ProductsService } from '../../products.service';
import { EnvironmentConfigService } from 'src/app/manufacturer/environment-config.service';

@Component({
  selector: 'app-catalog-details',
  templateUrl: './catalog-details.component.html',
  styleUrls: ['./catalog-details.component.scss']
})
export class CatalogDetailsComponent implements OnInit {

  catalogID: string;
  productsFetched: any;

  // For product thumbnail in table
  prodsThumbnails = [];

  // Data for products table
  productsDataForTable: MatTableDataSource<[]>;
  tableHeaders = [
    'image',
    'title',
    'description',
    'weight',
    'SKU',
    'price',
    'category',
    'status',
    'actions'
  ];

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(
    private envService: EnvironmentConfigService,
    private prodsService: ProductsService,
    private snackBar: MatSnackBar,
    public dialog: MatDialog,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private catService: CatalogsService
  ) { }

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      this.getProducts(params.id);
    });
  }

  getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
      this.productsDataForTable = new MatTableDataSource(prods);
      this.productsDataForTable.sort = this.sort;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
  }

}
</code>```

The table was with *ngIf and i read that a matTable shouldn't has that because the @ViewChild(MatSort, {static: true}) sort: MatSort would be undefined so i erased an *ngIf that I was actually using but I still cant achieve the sorting.

I tried matPagination feature too without success, I suppose it is due to the same error.

I'll appreciate any help

答:
Try this: </p>

```<code> ngAfterViewInit() {
      this.productsDataForTable = new MatTableDataSource(this.productsFetched);
      this.productsDataForTable.sort = this.sort;
  }

    getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }
</code>```

Body:
I'm having troubles with my table

I fetch data and then pass it to my table

Here is my code:

html

  <mat-table
    class="mat-elevation-z3 productsTable"
    matSort
    mat-table
    [dataSource]="productsDataForTable">

    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Title
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        {{row.name.en}}
      </mat-cell>
    </ng-container>

  <ng-container matColumnDef="image">
      <mat-header-cell *matHeaderCellDef>
        Image
      </mat-header-cell>
      <mat-cell *matCellDef="let prod; let i = index" >

      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="description">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Description
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.description.en}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Weight
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.weight + ' ' + prod.weightUnit}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="SKU">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        SKU
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.sku}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="price">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Price
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        $ {{prod.prices[0].unitPrice}} {{prod.prices[0].currency}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="category">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Category
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.category}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header>
        Status
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        {{prod.status}}
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
        Actions
      </mat-header-cell>
      <mat-cell *matCellDef="let prod">
        <mat-icon class="actionOnProductButton" (click)="openProductDetailsDialog(prod)">create</mat-icon>
        <mat-icon class="actionOnProductButton" (click)="openDeleteProductDialog(prod)">delete</mat-icon>
      </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="tableHeaders"></mat-header-row>
    <mat-row
      class="table-rows"
      *matRowDef="let row; columns: tableHeaders;">

    </mat-row>

  </mat-table>

TS

import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Catalog } from '../../catalog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ProductsService } from '../../products.service';
import { EnvironmentConfigService } from 'src/app/manufacturer/environment-config.service';

@Component({
  selector: 'app-catalog-details',
  templateUrl: './catalog-details.component.html',
  styleUrls: ['./catalog-details.component.scss']
})
export class CatalogDetailsComponent implements OnInit {

  catalogID: string;
  productsFetched: any;

  // For product thumbnail in table
  prodsThumbnails = [];

  // Data for products table
  productsDataForTable: MatTableDataSource<[]>;
  tableHeaders = [
    'image',
    'title',
    'description',
    'weight',
    'SKU',
    'price',
    'category',
    'status',
    'actions'
  ];

  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor(
    private envService: EnvironmentConfigService,
    private prodsService: ProductsService,
    private snackBar: MatSnackBar,
    public dialog: MatDialog,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private catService: CatalogsService
  ) { }

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      this.getProducts(params.id);
    });
  }

  getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
      this.productsDataForTable = new MatTableDataSource(prods);
      this.productsDataForTable.sort = this.sort;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }

  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000,
    });
  }

}

The table was with *ngIf and i read that a matTable shouldn't has that because the @ViewChild(MatSort, {static: true}) sort: MatSort would be undefined so i erased an *ngIf that I was actually using but I still cant achieve the sorting.

I tried matPagination feature too without success, I suppose it is due to the same error.

I'll appreciate any help

Body:
Try this:

 ngAfterViewInit() {
      this.productsDataForTable = new MatTableDataSource(this.productsFetched);
      this.productsDataForTable.sort = this.sort;
  }

    getProducts(id: string) {
    this.prodsService.getProducts(id)
    .subscribe((prods: any) => {
      this.prodsThumbnails = [];
      for (const prod of prods) {
        if (prod && prod.images && prod.images.length > 0 && prod.images[0].path && prod.images[0].path !== '') {
          const src = `${this.envService.getEnvService().getBackendUrl()}/${prod.images[0].path}`;
          this.prodsThumbnails.push(src);
        } else {
          this.prodsThumbnails.push('../../../../assets/images/placeholder-img.png');
        }
      }
      this.productsFetched = prods;
    },
    err => {
      console.log('Error fetching products');
      this.openSnackBar('Error getting porducts data', 'Ok');
    });
  }


来源: stackexchange

问:
How do I setup a PdfReader filepath?
This may seem like a trivial question, I would like to open an existing pdf template, edit and flatten the file, then send as an email attachment. But how do I setup PdfReader to read my file located in my Content folder (Content/Documents/PDFFile.pdf). This is what I have which gives the error "(whatever path I try).pdf not found as a file or resource". </p>

```<code>       using (MemoryStream ms = new MemoryStream())
        {
            //Error is here...
            PdfReader reader = new PdfReader("~/Content/Documents/PDFFile.pdf");

            PdfStamper formFiller = new PdfStamper(reader, ms);
            AcroFields formFields = formFiller.AcroFields;
            formFields.SetField("Name", formData.Name);
            formFields.SetField("Location", formData.Address);
            formFields.SetField("Date", DateTime.Today.ToShortDateString());
            formFields.SetField("Email", formData.Email);
            formFiller.FormFlattening = true;
            formFiller.Close();

            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress("to@email.com"));
            msg.From = new MailAddress("from@email.com");
            msg.Subject = "Application Form";
            msg.Body = "TEST";
            msg.IsBodyHtml = true;
            msg.Attachments.Add(new Attachment(ms, "Application.pdf", "application/x-pdf"));
            SmtpClient client = new SmtpClient("10.1.1.15");
            client.UseDefaultCredentials = true;
        }
</code>```

<p>Any suggestions/ideas/recommendations? </p>

答: Try using Server.MapPath("/Path/Here.pdf"); or Request.PhysicalApplicationPath("/Path/Here.pdf");

ContentLicense: CC BY-SA 3.0

Title: How do I setup a PdfReader filepath?

Body:
This may seem like a trivial question, I would like to open an existing pdf template, edit and flatten the file, then send as an email attachment. But how do I setup PdfReader to read my file located in my Content folder (Content/Documents/PDFFile.pdf). This is what I have which gives the error "(whatever path I try).pdf not found as a file or resource".

       using (MemoryStream ms = new MemoryStream())
        {
            //Error is here...
            PdfReader reader = new PdfReader("~/Content/Documents/PDFFile.pdf");

            PdfStamper formFiller = new PdfStamper(reader, ms);
            AcroFields formFields = formFiller.AcroFields;
            formFields.SetField("Name", formData.Name);
            formFields.SetField("Location", formData.Address);
            formFields.SetField("Date", DateTime.Today.ToShortDateString());
            formFields.SetField("Email", formData.Email);
            formFiller.FormFlattening = true;
            formFiller.Close();

            MailMessage msg = new MailMessage();

            msg.To.Add(new MailAddress("to@email.com"));
            msg.From = new MailAddress("from@email.com");
            msg.Subject = "Application Form";
            msg.Body = "TEST";
            msg.IsBodyHtml = true;
            msg.Attachments.Add(new Attachment(ms, "Application.pdf", "application/x-pdf"));
            SmtpClient client = new SmtpClient("10.1.1.15");
            client.UseDefaultCredentials = true;
        }

Any suggestions/ideas/recommendations?


问:
How to calculate average of sub-lists based on Timestamp values
I have 2 lists. The 1st list is the Timestamps (sec) when data was measured. And 2nd list contains data.

I want to calculate the average of data every 10 sec. Note that timestamp between 2 consecutive data points is not fixed.

Example:

```<code>Timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
Data = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

And the expected output is supposed to be:

```<code>Output = [average of [1,2,3] , average of [4,5] , average of [6,7,8]]
</code>```

I was wondering if there is any built-in function in Python like average-if analysis to do it automatically.

Thank you for your help.

答:
You can use for that the math function floor with defaultdict as

```<code>from collections import defaultdict
from math import floor

timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
data = [1, 2, 3, 4, 5, 6, 7, 8]
average_dc= defaultdict(list)
for t, d in sorted(zip(timestamp, data), key=lambda x : x[0]):
     average_dc[math.floor(t / 10)].append(d)
averages = [sum(i)/ len(i) for i in average_dc.values()]
</code>```

Output

```<code>[2.0, 4.5, 7.0]
</code>```

The sorted(zip(timestamp, data), key=lambda x : x[0]) will concat the timestamp value with the value from data on the same index and then the for loop will insert to average_dc the relevant data value base on the related timestamp value.

In the last line, the list comprehension will iterate over each list in the average_dc and will calculate the average of it.

ContentLicense: CC BY-SA 4.0

Body:
I have 2 lists. The 1st list is the Timestamps (sec) when data was measured. And 2nd list contains data.

I want to calculate the average of data every 10 sec. Note that timestamp between 2 consecutive data points is not fixed.

Example:

Timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
Data = [1, 2, 3, 4, 5, 6, 7, 8]

And the expected output is supposed to be:

Output = [average of [1,2,3] , average of [4,5] , average of [6,7,8]]

I was wondering if there is any built-in function in Python like average-if analysis to do it automatically.

Thank you for your help.

Body:
You can use for that the math function floor with defaultdict as

from collections import defaultdict
from math import floor

timestamp = [2, 5, 8, 11, 18, 23, 25, 28]
data = [1, 2, 3, 4, 5, 6, 7, 8]
average_dc= defaultdict(list)
for t, d in sorted(zip(timestamp, data), key=lambda x : x[0]):
     average_dc[math.floor(t / 10)].append(d)
averages = [sum(i)/ len(i) for i in average_dc.values()]

Output

[2.0, 4.5, 7.0]

The sorted(zip(timestamp, data), key=lambda x : x[0]) will concat the timestamp value with the value from data on the same index and then the for loop will insert to average_dc the relevant data value base on the related timestamp value.

In the last line, the list comprehension will iterate over each list in the average_dc and will calculate the average of it.


问:
Scraping the entire website using beautiful soup. Any other better method is also appreciated
I am trying to scrape storytel.in. In the website after selecting any 1 of the categories we can see set of books. In that page you only have book name mentioned. I want to fetch author, narrator, rating, category, bookid from the website which can be inspected by opening the individual book in new tab. Below is my code

```<code>response = get('https://www.storytel.com/in/en/categories/8-History?pageNumber=1', headers = headers)
soup = BeautifulSoup(response.text,"html.parser")
books_div = soup.find_all('div', class_='gridItem')
for container in books_div:
    name = container.find('div',class_='gridBookTitle').a.text
    titles.append(name)

    b_id = container.div.find('a').get('href')
    b_id = b_id[-6:-1]
    book_id.append(b_id)

    for i,t in zip(book_id,titles):
        response1 = get('https://www.storytel.com/in/en/books/'+i+'-'+t, headers = headers)
        soup = BeautifulSoup(response1.text,"html.parser")
        tab_div = soup.find('div', class_='bookDetailDesc')
        a_name = tab_div.find('span', class_:'expandAuthorName').text
        author.append(a_name)
        b_rating = tab_div.find('span', id='dennisBookRating').text
        rating.append(b_rating)
</code>```

I am getting error while executing this.Any leads on how this can be done. Thanks in advance.

答:
If you just want to get the text of the website and nothing specific, this works:

import requests
from bs4 import BeautifulSoup

website = requests.get('https://www.storytel.com/in/en/categories/8-History?pageNumber=1').text
soup = BeautifulSoup(website, features="lxml")
print(soup.get_text())
```

Body:
I am trying to scrape storytel.in. In the website after selecting any 1 of the categories we can see set of books. In that page you only have book name mentioned. I want to fetch author, narrator, rating, category, bookid from the website which can be inspected by opening the individual book in new tab. Below is my code

response = get('https://www.storytel.com/in/en/categories/8-History?pageNumber=1', headers = headers)
soup = BeautifulSoup(response.text,"html.parser")
books_div = soup.find_all('div', class_='gridItem')
for container in books_div:
    name = container.find('div',class_='gridBookTitle').a.text
    titles.append(name)

    b_id = container.div.find('a').get('href')
    b_id = b_id[-6:-1]
    book_id.append(b_id)

    for i,t in zip(book_id,titles):
        response1 = get('https://www.storytel.com/in/en/books/'+i+'-'+t, headers = headers)
        soup = BeautifulSoup(response1.text,"html.parser")
        tab_div = soup.find('div', class_='bookDetailDesc')
        a_name = tab_div.find('span', class_:'expandAuthorName').text
        author.append(a_name)
        b_rating = tab_div.find('span', id='dennisBookRating').text
        rating.append(b_rating)

I am getting error while executing this.Any leads on how this can be done. Thanks in advance.


问:
Search returns an empty array
```<code>router.get('/direcciones', isAuthenticated, async (req, res) => {
    let id = req.user._id
    let id2 = id.toString()
    await Dir.find({
        uid: {
            $elemMatch: { _id: id2}
        }
        },  async (err, dir) => {
            console.log(dir);
            res.render('direcciones', {dir: dir, id: id})
    });
});
</code>```

When I search by ID I don't get any results.

```<code>_id:ObjectId("5ed71f27e391a332b8f4aea8")
active:true
dir:"asdasd, Pariahuanca, Los Olivos, Peru"
dirname:"aeds"
uid:Object
   _id:ObjectId("5ed6ef2251c32527a03bf1ca")
__v:0
</code>```

This is the Schema.

What should I do?

答:
One mistake is that you convert your _id, that is already coming as string, to string with .toString(). You should convert it to an ObjectId if your field is an Object Id in your database.

```<code>id2 = mongoose.Types.ObjectId(req.user._id);
</code>```

Title: Search returns an empty array

Body:
router.get('/direcciones', isAuthenticated, async (req, res) => {
    let id = req.user._id
    let id2 = id.toString()
    await Dir.find({
        uid: {
            $elemMatch: { _id: id2}
        }
        },  async (err, dir) => {
            console.log(dir);
            res.render('direcciones', {dir: dir, id: id})
    });
});

When I search by ID I don't get any results.

_id:ObjectId("5ed71f27e391a332b8f4aea8")
active:true
dir:"asdasd, Pariahuanca, Los Olivos, Peru"
dirname:"aeds"
uid:Object
   _id:ObjectId("5ed6ef2251c32527a03bf1ca")
__v:0

This is the Schema.

What should I do?

Body:
One mistake is that you convert your _id, that is already coming as string, to string with .toString(). You should convert it to an ObjectId if your field is an Object Id in your database.

id2 = mongoose.Types.ObjectId(req.user._id);


问:
Implement Load More function in getItemCount, is it possible?
I have an adapter and have this code below, my goals are to make some load more function using gridlayoutmanager and get the data from my API URL. My question is, can I use something like if else condition or something on that getItemCount method? If it is possible, how do I implement it on my code? Thanks.</p>

```<code>@Override
    public int getItemCount() {
        return (eventList==null)?0:eventList.size();
    }
</code>```

答:
Here is an example of a custom adapter for a RecyclerView

```<code>
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Object> customRows = new ArrayList<Object>();
    private AdapterActionListener adapterActionListener;

    public CustomAdapter(Context context, ArrayList<Object> customRows)
    {
        this.context = context;
        this.customRows.addAll(customRows);
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void refill(ArrayList<Object> customRows)
    {
        this.customRows.clear();
        this.customRows.addAll(customRows);
        this.notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        return Utility.ADAPTER_VIEWTYPE_DEFAULT;
    }

    @Override
    public long getItemId(int index) {
        return index + 1;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // ... custom implementation
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        // ... custom implementation
    }

    @Override
    public int getItemCount() {
        return customRows.size();
    }

}
</code>```

If you load more data in your activity of fragment, you need to call

```<code>adapter.refill(data);
</code>```

Body:
I have an adapter and have this code below, my goals are to make some load more function using gridlayoutmanager and get the data from my API URL. My question is, can I use something like if else condition or something on that getItemCount method? If it is possible, how do I implement it on my code? Thanks.

@Override
    public int getItemCount() {
        return (eventList==null)?0:eventList.size();
    }

Body:
Here is an example of a custom adapter for a RecyclerView

public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Object> customRows = new ArrayList<Object>();
    private AdapterActionListener adapterActionListener;

    public CustomAdapter(Context context, ArrayList<Object> customRows)
    {
        this.context = context;
        this.customRows.addAll(customRows);
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void refill(ArrayList<Object> customRows)
    {
        this.customRows.clear();
        this.customRows.addAll(customRows);
        this.notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        return Utility.ADAPTER_VIEWTYPE_DEFAULT;
    }

    @Override
    public long getItemId(int index) {
        return index + 1;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // ... custom implementation
        return view;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        // ... custom implementation
    }

    @Override
    public int getItemCount() {
        return customRows.size();
    }

}

If you load more data in your activity of fragment, you need to call

adapter.refill(data);


问:
How to declare the elements of an array non-nullable?
In the following simple table

CREATE TABLE foo (
  things VARCHAR ARRAY
);
```

<p>It's possible to insert <code>null</code> as an element of <code>things</code>:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO foo VALUES ('{"hi", null, "ho"}');
</code>```

But I'd like to not allow this.

Changing the definition to the following, however,

CREATE TABLE foo (
  things VARCHAR ARRAY NOT NULL
);
```

<p>Only prevents this</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO foo VALUES (null);
</code>```

which is not what I want. (I still want to allow that.)

So how can I declare not the column, but the elements of the array column to be non-nullable?

答:
You can use check with array_position() as following

```<code>CREATE TABLE foo (
  things text[] NOT NULL check (array_position(things, null) is null)
);
</code>```

and you can also check for empty array

```<code>CREATE TABLE foo (
  things text[] NOT NULL check (things <> '{}' and array_position(things, null) is null)
);
</code>```

Body:
In the following simple table

CREATE TABLE foo (
  things VARCHAR ARRAY
);

It's possible to insert null as an element of things:

INSERT INTO foo VALUES ('{"hi", null, "ho"}');

But I'd like to not allow this.

Changing the definition to the following, however,

CREATE TABLE foo (
  things VARCHAR ARRAY NOT NULL
);

Only prevents this

INSERT INTO foo VALUES (null);

which is not what I want. (I still want to allow that.)

So how can I declare not the column, but the elements of the array column to be non-nullable?

Body:
You can use check with array_position() as following

CREATE TABLE foo (
  things text[] NOT NULL check (array_position(things, null) is null)
);

and you can also check for empty array

CREATE TABLE foo (
  things text[] NOT NULL check (things <> '{}' and array_position(things, null) is null)
);


问:
Can't trigger condition in decision table
I can't seem to trigger my condition when I tried to put it in a decision table. The condition works fine from a .drl file but I just can't seem to make it work through a decision table. Here are the details of my code:

Decision table:

Class:

```<code>import java.util.HashMap;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class MainApp {

    public static void main (String args[]) {
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.getKieClasspathContainer();
        KieSession kSession = kContainer.newKieSession("ksession-dtables");

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("companyCode", "MP");

        System.out.println(map.get("companyCode"));

        kSession.insert(map);
        kSession.fireAllRules();

        System.out.println(map.get("companyCode"));
    }
}
</code>```

Somehow this is the only output I get:

The output I expect will be something like this:

```<code>MP
Company is MP
</code>```

Any help will be much appreciated.

答:
I got it and it was a very noob mistake.

The value in cell C1 must contain the package where the decision table is. No wonder I can't trigger any condition at all.

Thanks for anyone who was looking to solve this.

Body:
I can't seem to trigger my condition when I tried to put it in a decision table. The condition works fine from a .drl file but I just can't seem to make it work through a decision table. Here are the details of my code:

Decision table:

Class:

import java.util.HashMap;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class MainApp {

    public static void main (String args[]) {
        KieServices ks = KieServices.Factory.get();
        KieContainer kContainer = ks.getKieClasspathContainer();
        KieSession kSession = kContainer.newKieSession("ksession-dtables");

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("companyCode", "MP");

        System.out.println(map.get("companyCode"));

        kSession.insert(map);
        kSession.fireAllRules();

        System.out.println(map.get("companyCode"));
    }
}

Somehow this is the only output I get:

The output I expect will be something like this:

MP
Company is MP

Any help will be much appreciated.


问:
How to make a table with automatic column widths without using HTML table?
I have a big table I'm trying to add some hover effects to and finding that CSS tables are relatively inflexible, so I'd like to try to implement some other way (see background below).

I'm thinking CSS grid might work. How can I make a CSS table using CSS grid? I need the columns widths to adjust automatically (and of course be synced between rows), as they do with a regular CSS table, and (I think) I need each row to be a parent element to its cells, as in tables.

I read here that the level 2 specifications of CSS grid incorporate a subgrid, but I've been unable to find an example of using subgrid to duplicate basic table functionality. It seems most browsers don't yet implement subgrid, so display: contents might be an alternative.

Background in case you need it: I'm trying to implement a sort of action-bar hover-overlay, as in Gmail: when you hover the cursor over a row/email, an overlay appears on the right side of the row with various actions you can perform on the row/email, such as Move to folder, Delete. Gmail displays the table rows as flex boxes to make this possible, but that means the column widths have to be set "by hand." In my case I have a massive table of various data and setting column widths by hand isn't feasible.

UPDATE: what does it look like? It's an ordinary table with rows and columns. You have certainly seen such things before. I'm asking a general question and the particulars of the table are irrelevant.

Here is a screen shot from Gmail, fwiw:

答:
Using css grid's repeat function, you can create columns automatically depending on the content inside the grid. I have added absolute position on last column so that it overlaps the row.

.row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, max-content));
  border-bottom: 1px solid #999;
  padding: 10px;
  grid-gap: 15px;
  cursor: pointer;
  align-items: center;
  position: relative;
  background: #fff;
}

.row span.action {
  display: none;
  position: absolute;
  right: 0;
  padding: 10px;
  background: #fff;
}

i {
  padding: 0 3px;
}

.row:hover span.action {
  display: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
</div></code>```

Body:
Using css grid's repeat function, you can create columns automatically depending on the content inside the grid. I have added absolute position on last column so that it overlaps the row.

.row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, max-content));
  border-bottom: 1px solid #999;
  padding: 10px;
  grid-gap: 15px;
  cursor: pointer;
  align-items: center;
  position: relative;
  background: #fff;
}

.row span.action {
  display: none;
  position: absolute;
  right: 0;
  padding: 10px;
  background: #fff;
}

i {
  padding: 0 3px;
}

.row:hover span.action {
  display: initial;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
  <div class="row">
    <span>Code Academy</span>
    <span>Save your spot to learn from home today. Save your spot to learn from home today</span>
    <span class="action">
        <i class="fas fa-trash-alt"></i>
        <i class="far fa-envelope-open"></i>
        <i class="fas fa-reply"></i>
      </span>
  </div>
</div>


问:
XML To MySQL 5.0
Hi All and apologies if the question seems too trivial,

I am trying to save an XML data to a MySQL 5.0 data base. I am using the following:

```<code>LOAD DATA LOCAL INFILE 'C:\\Documents and Settings\\user1\\My Documents\\ArtifactData.xml'
INTO TABLE test_case
</code>```

This loads the data to the table, but all fields are treated as the first column only, and not broken down into proper columns. Here is a sample xml tag.

```<code><test_case>
            <module_id_test_case_id>test case id</module_id_test_case_id>
            <description>Some description</description>
            <design_complexity>Low</design_complexity>
            <execution_status>Pass</execution_status>
</test_case>
</code>```

Here are the columns of the sample test_case table I am working with.
module_id_test_case_id,description,design_complexity,execution_status

After reading the file, all the fields are persisted as module_id_test_case_id, even data under description, design_complexity and execution_status tags.

When I use ROWS IDENTIFIED BY <>, there is a SQL syntax error thrown.

Can somebody please advice me on how to solve this isse?

Thanks.

答:
You cannot use LOAD DATA INFILE to load XML data in that way.

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

look here for how to import data from xml
http://dev.mysql.com/tech-resources/articles/xml-in-mysql5.1-6.0.html#xml-5.1-importing

ContentLicense: CC BY-SA 2.5

Title: XML To MySQL 5.0

Body:
Hi All and apologies if the question seems too trivial,

I am trying to save an XML data to a MySQL 5.0 data base. I am using the following:

LOAD DATA LOCAL INFILE 'C:\\Documents and Settings\\user1\\My Documents\\ArtifactData.xml'
INTO TABLE test_case

This loads the data to the table, but all fields are treated as the first column only, and not broken down into proper columns. Here is a sample xml tag.

<test_case>
            <module_id_test_case_id>test case id</module_id_test_case_id>
            <description>Some description</description>
            <design_complexity>Low</design_complexity>
            <execution_status>Pass</execution_status>
</test_case>

Here are the columns of the sample test_case table I am working with.
module_id_test_case_id,description,design_complexity,execution_status

After reading the file, all the fields are persisted as module_id_test_case_id, even data under description, design_complexity and execution_status tags.

When I use ROWS IDENTIFIED BY <>, there is a SQL syntax error thrown.

Can somebody please advice me on how to solve this isse?

Thanks.


问:
Encoding issue in Postgres ERROR "UTF8" is it best to set encoding to UTF8 or to make the data WIN1252 compatible?
I created a table importing a CSV file from an excel spreadsheet. When I try to run the select statement below I get the error.

```<code>test=# SELECT * FROM dt_master;
ERROR:  character with byte sequence 0xc2 0x9d in encoding "UTF8" has no equivalent in encoding "WIN1252"
</code>```

I have read the solution posted in this stack overflow post and was able to overcome the issue by setting the encoding to UTF8, so up to that point I am still able to keep working with the data. My question, however, is whether setting the encoding to UTF8 actually is solving the problem or it is just a workaround that and will create other problems down the road and I would be better off removing the conflicting characters and making the data WIN1252 compliant.
Thank you

答:
You have a weird character in your database (Unicode code point 9D, a control character) that probably got there by mistake.

You have to set the client encoding to the encoding that your application expects; no other value will produce correct results, even if you get rid of the error. The error has a reason.

You have two choices:

Fix the data in the database. The character is very likely not what was intended.

Change the application to use LATIN1 or (better) UTF-8 internally and set the client encoding appropriately.

Using UTF-8 everywhere would have the advantage that you are safe from this kind of problem.

Body:
I created a table importing a CSV file from an excel spreadsheet. When I try to run the select statement below I get the error.

test=# SELECT * FROM dt_master;
ERROR:  character with byte sequence 0xc2 0x9d in encoding "UTF8" has no equivalent in encoding "WIN1252"

I have read the solution posted in this stack overflow post and was able to overcome the issue by setting the encoding to UTF8, so up to that point I am still able to keep working with the data. My question, however, is whether setting the encoding to UTF8 actually is solving the problem or it is just a workaround that and will create other problems down the road and I would be better off removing the conflicting characters and making the data WIN1252 compliant.
Thank you


问:
How do I create RDS parameter groups from an arbitrary number of input parameters?
I have a four different environments:

dev

sit

uat

prod

The parameter group values differ for each environment. Below value will go in variable file for each environment.

Below are the parameters of an example AWS RDS parameter group. In other environments, there may be more or less parameters:

```<code>parameter {
  name = "character_set_client"
  value = "utf8mb4"
}

parameter {
  name = "character_set_connection"
  value = "utf8mb4"
}

parameter {
  name = "character_set_server"
  value = "utf8mb4"
}

parameter {
  name = "log_bin_trust_function_creators"
  value = "1"
}
</code>```

I'm curious how to represent this in variables and how to write the resources to use those variables to make RDS Parameter Groups with an arbitrary number of parameters.

How do I create RDS parameter groups from an arbitrary number of input parameters?

答:
You can use a dynamic block:

```<code>dynamic "parameter" {
    for_each = var.parameters
    content {
      name         = parameter.value.name
      value        = parameter.value.value
    }
  }
</code>```

The variable can be a list of maps:

```<code>variable "parameters" {
  type        = list(map(string))
  default     = []
}
</code>```

terraform.tfvars:

```<code>parameters = [
  {
  name = "character_set_connection"
  value = "utf8mb4"
  },
  {
  name = "character_set_server"
  value = "utf8mb4"
  },
  {
  name = "log_bin_trust_function_creators"
  value = "1"
  }
]
</code>```

Body:
I have a four different environments:

dev

sit

uat

prod

The parameter group values differ for each environment. Below value will go in variable file for each environment.

Below are the parameters of an example AWS RDS parameter group. In other environments, there may be more or less parameters:

parameter {
  name = "character_set_client"
  value = "utf8mb4"
}

parameter {
  name = "character_set_connection"
  value = "utf8mb4"
}

parameter {
  name = "character_set_server"
  value = "utf8mb4"
}

parameter {
  name = "log_bin_trust_function_creators"
  value = "1"
}

I'm curious how to represent this in variables and how to write the resources to use those variables to make RDS Parameter Groups with an arbitrary number of parameters.

How do I create RDS parameter groups from an arbitrary number of input parameters?

Body:
You can use a dynamic block:

dynamic "parameter" {
    for_each = var.parameters
    content {
      name         = parameter.value.name
      value        = parameter.value.value
    }
  }

The variable can be a list of maps:

variable "parameters" {
  type        = list(map(string))
  default     = []
}

terraform.tfvars:

parameters = [
  {
  name = "character_set_connection"
  value = "utf8mb4"
  },
  {
  name = "character_set_server"
  value = "utf8mb4"
  },
  {
  name = "log_bin_trust_function_creators"
  value = "1"
  }
]


问:
function for the sum of all even numbers
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

```<code>function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")
</code>```

答:
My suggestion:

function isNumber(char) {
  return parseInt(char) !== 'NaN';
}

function functionFive(str) {
   // 1. split str into array
   const charList = str.split('');

   // 2. filter out non-numbers
   const numberList = str.filter(isNumber);

   // 3. return the sum of the numbers using reduce
   return numberList.reduce((acc, curr) => curr % 2 === 0 ? acc + curr : acc, 0);
}
functionFive("sau213e89q8e7ey1")

```

Hope it helps and its easy to understand :)

Body:
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")

Body:
My suggestion:

function isNumber(char) {
  return parseInt(char) !== 'NaN';
}

function functionFive(str) {
   // 1. split str into array
   const charList = str.split('');

   // 2. filter out non-numbers
   const numberList = str.filter(isNumber);

   // 3. return the sum of the numbers using reduce
   return numberList.reduce((acc, curr) => curr % 2 === 0 ? acc + curr : acc, 0);
}
functionFive("sau213e89q8e7ey1")

Hope it helps and its easy to understand :)


答:
I'd just search for all even single digit numbers with the exception of zero (because it will not contribute to the sum) with a regex and sum the resulting array, ie

const functionFive = str => (str.match(/2|4|6|8/g) || [])
  .reduce((sum, num) => sum + parseInt(num, 10), 0)

console.info(functionFive("sau213e89q8e7ey1"))```

Title: function for the sum of all even numbers


答:
You can use a check constraint:

```<code>CREATE TABLE foo
(
  things text[],
  constraint check_things_not_null
    check ( cardinality(things) = cardinality(array_remove(things, null)))
);
</code>```

alternatively you can use array_position()

```<code>
CREATE TABLE foo
(
  things text[],
  constraint check_things_not_null
    check ( array_position(things, null) is null)
);
</code>```

Title: How to declare the elements of an array non-nullable?

Body:
You can use a check constraint:

CREATE TABLE foo
(
  things text[],
  constraint check_things_not_null
    check ( cardinality(things) = cardinality(array_remove(things, null)))
);

alternatively you can use array_position()

CREATE TABLE foo
(
  things text[],
  constraint check_things_not_null
    check ( array_position(things, null) is null)
);


问:
Missing "VCL Form" option in Delphi "File, New, Other Files" menu
I was given a new laptop at work.  I had Delphi on my old laptop.  We only have 1 licence for Delphi.  It was removed from my old laptop and installed on my new laptop.

Normally I would go "File, New, VCL Forms Application" and start putting objects on the Main Form.  Then, I go to "File, New, Other Files" and I have only "Project Group" and "Text File" showing.  How do I get "VCL Form" to show?
enter image description here

delphi
delphi other optiondelphi customise option

答: In Embarcadero® RAD Studio 10.2 it looks like File->New and then you have options: VCL Forms Application-Delphi, VCL Form-Delphi and etc.</p>


问:
Read text file, modify in certain place and save as a new file in python
I have 10 text file. Each file contains 1000 rows like this,

```<code>     1000 atoms
     2 atom types
     -5.0 5.0 xlo xhi
     -5.0 5.0 ylo yhi
     -5.0 5.0 zlo zhi

     Atoms # atomic

     35 1 0.0 -0.2154398 -0.2154398
     40 1 0.0 -0.2154398 -0.6463404
     45 1 0.0 -0.2154398 -1.07722
     ..........
</code>```

My aim is to read the file, skip first 9 rows. Then change second column if last column is negative. Then write everything in new file.
I have tries so far,

```<code>import itertools
import glob

for i  in glob.glob("*.txt"):
    with open(i) as fin, open('n'+i,'w') as fout:
        fout.write("1000 atoms" "\n"  )
        fout.write("2 atom types" "\n" )
        fout.write("-5.0 5.0 xlo xhi" "\n"  )
        fout.write("-5.0 5.0 ylo yhi" "\n"  )
        fout.write("-5.0 5.0 zlo zhi" "\n" "\n" )
        fout.write("Atoms # atomic" "\n" "\n"  )
        for line in itertools.islice(fin, 9, None):
            fields = line.split()
            fields[1] = "1" if float(fields[-1]) < 0 else "2"
            fout.write(" ".join(fields) + "\n")
</code>```

This code gives me what I expect. But I wonder how can I write automatically first 9 rows instead of writing them manually using fout.write("") in a new file.

答:
I have figured it out,

```<code>import itertools
import glob

for i  in glob.glob("*.txt"):
    with open(i) as fin, open('n'+i,'w') as fout:
        toplines= [next(fin) for x in range(10)]
        fout.write("".join(toplines))
        for line in itertools.islice(fin,None):
            fields = line.split()
            fields[1] = "1" if float(fields[-1]) < 0 else "2"
            fout.write(" ".join(fields) + "\n")
</code>```

any other innovative answer will be appreciated.

Body:
I have 10 text file. Each file contains 1000 rows like this,

     1000 atoms
     2 atom types
     -5.0 5.0 xlo xhi
     -5.0 5.0 ylo yhi
     -5.0 5.0 zlo zhi

     Atoms # atomic

     35 1 0.0 -0.2154398 -0.2154398
     40 1 0.0 -0.2154398 -0.6463404
     45 1 0.0 -0.2154398 -1.07722
     ..........

My aim is to read the file, skip first 9 rows. Then change second column if last column is negative. Then write everything in new file.
I have tries so far,

import itertools
import glob

for i  in glob.glob("*.txt"):
    with open(i) as fin, open('n'+i,'w') as fout:
        fout.write("1000 atoms" "\n"  )
        fout.write("2 atom types" "\n" )
        fout.write("-5.0 5.0 xlo xhi" "\n"  )
        fout.write("-5.0 5.0 ylo yhi" "\n"  )
        fout.write("-5.0 5.0 zlo zhi" "\n" "\n" )
        fout.write("Atoms # atomic" "\n" "\n"  )
        for line in itertools.islice(fin, 9, None):
            fields = line.split()
            fields[1] = "1" if float(fields[-1]) < 0 else "2"
            fout.write(" ".join(fields) + "\n")

This code gives me what I expect. But I wonder how can I write automatically first 9 rows instead of writing them manually using fout.write("") in a new file.

Body:
I have figured it out,

import itertools
import glob

for i  in glob.glob("*.txt"):
    with open(i) as fin, open('n'+i,'w') as fout:
        toplines= [next(fin) for x in range(10)]
        fout.write("".join(toplines))
        for line in itertools.islice(fin,None):
            fields = line.split()
            fields[1] = "1" if float(fields[-1]) < 0 else "2"
            fout.write(" ".join(fields) + "\n")

any other innovative answer will be appreciated.


问:
Add an object to multiple others and put the results into an array
I have many objects like

```<code>   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
   }
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
   }
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
   }
</code>```

I need to merge them with jq, like

```<code>jq -s '.' firstone.json secondone.json thirdone.json
</code>```

After merge, I get:

```<code>[
   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
   },
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
   },
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
   }
]
</code>```

but I want to add in every object - another one:

```<code>   {
      "thisMustBeInEveryarray": "thisone"
   }
</code>```

But like:

```<code>[
   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   },
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   },
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   }
]
</code>```

Is it even possible to be done in one iteration with jq? Because if I merge them like
jq -s '.' firstone.json secondone.json thirdone.json mustbeinevery.json, I get mustbeinevery.json just like the last element of the whole array.

答:
Specify mustbeinevery.json as the first input so that you can refer to others by inputs keyword, and add them inside an array constructor.

```<code>jq '[inputs+.]' mustbeinevery.json firstone.json secondone.json thirdone.json
</code>```

Body:
I have many objects like

   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
   }
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
   }
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
   }

I need to merge them with jq, like

jq -s '.' firstone.json secondone.json thirdone.json

After merge, I get:

[
   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
   },
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
   },
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
   }
]

but I want to add in every object - another one:

   {
      "thisMustBeInEveryarray": "thisone"
   }

But like:

[
   {
      "name":"blablabla1",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   },
   {
      "name":"blablabla2",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   },
   {
      "name":"blablabla3",
      "something": "blablabla"
      "something2": "blablabla"
      "thisMustBeInEveryarray": "thisone"
   }
]

Is it even possible to be done in one iteration with jq? Because if I merge them like
jq -s '.' firstone.json secondone.json thirdone.json mustbeinevery.json, I get mustbeinevery.json just like the last element of the whole array.

Body:
Specify mustbeinevery.json as the first input so that you can refer to others by inputs keyword, and add them inside an array constructor.

jq '[inputs+.]' mustbeinevery.json firstone.json secondone.json thirdone.json


问:
How to accept both ref and non ref values as a function argument
I want to take any kind of values inside a function (r/lvalue) and I also want to ensure that the value will not be mutated in the scope of the function, even if the value itself is not a const.

struct Tree(T) {
    T item;
    Tree!T* parent, left, right;

    this(T item) {
        this.item = item;
    }

    Tree!T* searchTree(const ref T item) {
        if (&this is null)
            return null;
        if (this.item == item)
            return &this;
        return (this.item < item) ? this.right.searchTree(item) : this.right.searchTree(item);
    }
}

unittest {
    auto text1 = "Hello", text2 = "World";

    auto tree2 = Tree!string(text1);
    assert(tree2.searchTree(text2) is null);
    assert(tree2.searchTree(text1) !is null);

}
```
<p>This works with ref parameters however if I give int literals to the function, it fails:</p>
<pre class="lang-d prettyprint-override"><code>    auto tree1 = Tree!int(4);
    assert(tree1.searchTree(5) is null);
    assert(tree1.searchTree(4) !is null);
</code>```

答:
Templates to the rescue! D has a feature called auto ref that automatically generates the overloads for ref and non-ref parameters. The only requirement is that the function must be a template.

For your searchTree function, that means it needs to have this signature:

```<code>    Tree!T* searchTree()(const auto ref T item)
</code>```

With that simple change, your code should compile and do The Right Thing™.

Body:
I want to take any kind of values inside a function (r/lvalue) and I also want to ensure that the value will not be mutated in the scope of the function, even if the value itself is not a const.

struct Tree(T) {
    T item;
    Tree!T* parent, left, right;

    this(T item) {
        this.item = item;
    }

    Tree!T* searchTree(const ref T item) {
        if (&this is null)
            return null;
        if (this.item == item)
            return &this;
        return (this.item < item) ? this.right.searchTree(item) : this.right.searchTree(item);
    }
}

unittest {
    auto text1 = "Hello", text2 = "World";

    auto tree2 = Tree!string(text1);
    assert(tree2.searchTree(text2) is null);
    assert(tree2.searchTree(text1) !is null);

}

This works with ref parameters however if I give int literals to the function, it fails:

    auto tree1 = Tree!int(4);
    assert(tree1.searchTree(5) is null);
    assert(tree1.searchTree(4) !is null);

Body:
Templates to the rescue! D has a feature called auto ref that automatically generates the overloads for ref and non-ref parameters. The only requirement is that the function must be a template.

For your searchTree function, that means it needs to have this signature:

    Tree!T* searchTree()(const auto ref T item)

With that simple change, your code should compile and do The Right Thing™.


问:
Is there a way to keep adding moving objects to the screen in JS?
I am working on a simple game, like Crossy Road, where the player is a spaceship, and they have to cross a lane which contains other ships moving from top to down.  I've tried to use setInterval(), but that doesn't seem to. work, here is the link for the project in Code.org:

https://studio.code.org/projects/gamelab/mVC2Bqadlg-heWiFlPvrPX3D7AfH5Ty4EVbTAGLM3rE

I'll also include a snippet:

/*
function randomAnimation() {
  var thing = createSprite(randomNumber(250,300),0);
  thing.velocityY = randomNumber(5,10);
  thing.velocityX = 0;
  thing.scale = 0.5;
  var randNumber = randomNumber(1,6);
  if (randNumber === 1) {
    thing.setAnimation("enemy1");
  }
  else if (randNumber === 2) {
    thing.setAnimation("enemy2");
  }
  else if (randNumber === 3) {
    thing.setAnimation("enemy3");
  }
  else if (randNumber === 4) {
    thing.setAnimation("enemy4");
  }
  else if (randNumber === 5) {
    thing.setAnimation("enemy5");
  }
  else if (randNumber === 6) {
    thing.setAnimation("enemy6");
  }
}
*/

function draw() {
  background("white");
  setInterval(function() {
    var thing = createSprite(randomNumber(150, 300), 0);
    /*thing.velocityY = randomNumber(5,10);
    thing.velocityX = 0;
    thing.scale = 0.5;
    var randNumber = randomNumber(1,6);
    if (randNumber === 1) {
      thing.setAnimation("enemy1");
    }
    else if (randNumber === 2) {
      thing.setAnimation("enemy2");
    }
    else if (randNumber === 3) {
      thing.setAnimation("enemy3");
    }
    else if (randNumber === 4) {
      thing.setAnimation("enemy4");
    }
    else if (randNumber === 5) {
      thing.setAnimation("enemy5");
    }
    else if (randNumber === 6) {
      thing.setAnimation("enemy6");
    }*/
    var enemies = createGroup();

  }, 2000);
  drawSprites();
}```

As you can see, a lot of the code is commented, that is code that I tried using but didn't work as expected. The first bit of commented code is a function I created, I tried calling this function in a setInterval() outside of the draw() function, but that worked, creating a new ship every 2000ms, but they didn't have any velocity. I tried calling it in the. draw() function, but that caused one ship to appear every frame, which makes it impossible to cross said lane. I know that I need to use groups for this function, I just don't know how.

Also, there's an if statement which is used to randomly change the animation of the spawned sprites.

答:
I'd try the following approach:

```<code>
// Create a group outside of any functions, so it's available to all of them.
var enemies = createGroup();

// Create a function that just builds a single enemy
function createEnemy() {
  // set velocity, scale, etc.
}

// In setInterval, create an enemy and add it to your group
setInterval(function() {
  var enemy = createEnemy();
  enemies.add(enemy);
}, 2000);

// A function to handle animation
function draw() {
  drawSprites();
}

</code>```

I'm not familiar with the studio.code.org platform, so I'm not sure whether each sprite's animation should be initialized in createEnemy() or draw(). If it's in draw(), I see you have access to group.setAnimationEach(), which might be the way to go.

Body:
I am working on a simple game, like Crossy Road, where the player is a spaceship, and they have to cross a lane which contains other ships moving from top to down.  I've tried to use setInterval(), but that doesn't seem to. work, here is the link for the project in Code.org:

https://studio.code.org/projects/gamelab/mVC2Bqadlg-heWiFlPvrPX3D7AfH5Ty4EVbTAGLM3rE

I'll also include a snippet:

/*
function randomAnimation() {
  var thing = createSprite(randomNumber(250,300),0);
  thing.velocityY = randomNumber(5,10);
  thing.velocityX = 0;
  thing.scale = 0.5;
  var randNumber = randomNumber(1,6);
  if (randNumber === 1) {
    thing.setAnimation("enemy1");
  }
  else if (randNumber === 2) {
    thing.setAnimation("enemy2");
  }
  else if (randNumber === 3) {
    thing.setAnimation("enemy3");
  }
  else if (randNumber === 4) {
    thing.setAnimation("enemy4");
  }
  else if (randNumber === 5) {
    thing.setAnimation("enemy5");
  }
  else if (randNumber === 6) {
    thing.setAnimation("enemy6");
  }
}
*/

function draw() {
  background("white");
  setInterval(function() {
    var thing = createSprite(randomNumber(150, 300), 0);
    /*thing.velocityY = randomNumber(5,10);
    thing.velocityX = 0;
    thing.scale = 0.5;
    var randNumber = randomNumber(1,6);
    if (randNumber === 1) {
      thing.setAnimation("enemy1");
    }
    else if (randNumber === 2) {
      thing.setAnimation("enemy2");
    }
    else if (randNumber === 3) {
      thing.setAnimation("enemy3");
    }
    else if (randNumber === 4) {
      thing.setAnimation("enemy4");
    }
    else if (randNumber === 5) {
      thing.setAnimation("enemy5");
    }
    else if (randNumber === 6) {
      thing.setAnimation("enemy6");
    }*/
    var enemies = createGroup();

  }, 2000);
  drawSprites();
}

As you can see, a lot of the code is commented, that is code that I tried using but didn't work as expected. The first bit of commented code is a function I created, I tried calling this function in a setInterval() outside of the draw() function, but that worked, creating a new ship every 2000ms, but they didn't have any velocity. I tried calling it in the. draw() function, but that caused one ship to appear every frame, which makes it impossible to cross said lane. I know that I need to use groups for this function, I just don't know how.

Also, there's an if statement which is used to randomly change the animation of the spawned sprites.

Body:
I'd try the following approach:

// Create a group outside of any functions, so it's available to all of them.
var enemies = createGroup();

// Create a function that just builds a single enemy
function createEnemy() {
  // set velocity, scale, etc.
}

// In setInterval, create an enemy and add it to your group
setInterval(function() {
  var enemy = createEnemy();
  enemies.add(enemy);
}, 2000);

// A function to handle animation
function draw() {
  drawSprites();
}

I'm not familiar with the studio.code.org platform, so I'm not sure whether each sprite's animation should be initialized in createEnemy() or draw(). If it's in draw(), I see you have access to group.setAnimationEach(), which might be the way to go.


问:
splitting a string using strtok()
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

```<code>int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);
</code>```

The printf calls are for debugging.

答:
The problem is that you start off with a string like this (blanks in the string don't materially affect the argument):

```<code> milk$$$45
</code>```

Assuming DELIMITER is "$" (repeating the dollar sign as in "$$$" won't make it look for multiple $ signs), then after that, you have:

```<code>milk\0$$45
</code>```

The search in the second strtok() continues at the first remaining $.  It isolates the token $$45 with no spaces.  (If there's a space before the number, then it isolates the token $$ instead.)  When you pass $$45 to atoi(), it is evaluated as 0.  You could see this for yourself with printf("[[%s]]\n", number);.

You should probably fix it by using:

```<code>char *number = strtok(NULL, " \t$");
</code>```

This will skip leading blank, tab, $ characters, and then stop at the next one (or the null byte at the end of the string).  Note that the code does not ensure that there are 3 $ signs separating the name and the number.

Title: splitting a string using strtok()

Body:
I have a string I would like to split into two different strings, the delimiter is $$$.
For instance: milk $$$ 45
On the left side is the product name and on the right is its quantity.
I've used strtok to split the string but I can't extract the number unfortunately.

int num;
char *token = strtok(str, DELIMITER);
printf("%s\n", token);
strcpy(component->name, token);
char *number = strtok(NULL, "       ");
num = atoi(number);
printf("%s\n", number);

The printf calls are for debugging.

Body:
The problem is that you start off with a string like this (blanks in the string don't materially affect the argument):

 milk$$$45

Assuming DELIMITER is "$" (repeating the dollar sign as in "$$$" won't make it look for multiple $ signs), then after that, you have:

milk\0$$45

The search in the second strtok() continues at the first remaining $.  It isolates the token $$45 with no spaces.  (If there's a space before the number, then it isolates the token $$ instead.)  When you pass $$45 to atoi(), it is evaluated as 0.  You could see this for yourself with printf("[[%s]]\n", number);.

You should probably fix it by using:

char *number = strtok(NULL, " \t$");

This will skip leading blank, tab, $ characters, and then stop at the next one (or the null byte at the end of the string).  Note that the code does not ensure that there are 3 $ signs separating the name and the number.


问:
Solve this interview question: Letter Soup (JS)
This is an interview question that I could not solve yet... I have this matrix:

```<code>[
 ['A', 'B', 'R'],
 ['H', 'A', 'H'],
 ['A', 'P', 'R'],
 ['P', 'L', 'A'],
 ['G', 'E', 'F']
]
</code>```

I need to find the word "APPLE", but the letters that I can choose must be closest as possible, in this case: (2;0) (2;1) (3;0) (3;1) (4;1)

I must find the word and return the coordinates of its characters

Using Javascript how do you manage to do it?

I Tried this:

const soup = [
 ['A', 'B', 'R'],
 ['H', 'A', 'H'],
 ['A', 'P', 'R'],
 ['P', 'L', 'A'],
 ['G', 'E', 'F']
];

const word = 'APPLE';
const letters = word.split('');
let hashTable = {};

for (let letter of letters) {
  for (let line = 0; line < soup.length; line++) {
    for (let i = 0; i < soup[line].length; i++ ) {
      console.log(soup[line][i]);
      if (letter === soup[line][i]) {
       hashTable[letter] = [line, i];
      }
    }
  }
}

console.log(hashTable);```

答:
You can use matrix row and columns as key and use the alphabet as the value. as in your case you are storing p two times in the same object. so we cannot duplicate keys in object use below code for your reference

const soup = [
  ["A", "B", "R"],
  ["H", "A", "H"],
  ["A", "P", "R"],
  ["P", "L", "A"],
  ["G", "E", "F"]
];

const word = "APPLE";
let index = 0;
let hashTable = {};

for (let line = 0; line < soup.length; line++) {
  for (let i = 0; i < soup[line].length; i++) {
    if (word[index] === soup[line][i] && index < word.length) {
      const col = i + 1;
      const row =  line + 1
      const key = row + "," + col;
      hashTable[key] = soup[line][i];
      index++;
    }
  }
}

console.log(hashTable);```

Body:
This is an interview question that I could not solve yet... I have this matrix:

[
 ['A', 'B', 'R'],
 ['H', 'A', 'H'],
 ['A', 'P', 'R'],
 ['P', 'L', 'A'],
 ['G', 'E', 'F']
]

I need to find the word "APPLE", but the letters that I can choose must be closest as possible, in this case: (2;0) (2;1) (3;0) (3;1) (4;1)

I must find the word and return the coordinates of its characters

Using Javascript how do you manage to do it?

I Tried this:

const soup = [
 ['A', 'B', 'R'],
 ['H', 'A', 'H'],
 ['A', 'P', 'R'],
 ['P', 'L', 'A'],
 ['G', 'E', 'F']
];

const word = 'APPLE';
const letters = word.split('');
let hashTable = {};

for (let letter of letters) {
  for (let line = 0; line < soup.length; line++) {
    for (let i = 0; i < soup[line].length; i++ ) {
      console.log(soup[line][i]);
      if (letter === soup[line][i]) {
       hashTable[letter] = [line, i];
      }
    }
  }
}

console.log(hashTable);


问:
How can I strip tab characters from a string in Ruby?
I have a program that loads some tab-separated lines into a MySQL table. One of the values has tabs in it, which is causing some problems. The data is created column by column, so I need to find a way to strip the tab character out of an individual field with gsub. I do not, however, want to get rid of anything else, like spaces.</p>

答:
It's really easy \t is the tab character.

```<code>result = string.gsub /\t/, ''
</code>```

or, in-place

```<code>string.gsub! /\t/, ''
</code>```

Body:
It's really easy \t is the tab character.

result = string.gsub /\t/, ''

or, in-place

string.gsub! /\t/, ''


问:
NaN resulting from sum of values in nodeJS
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

```<code>const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});
</code>```

HTML

```<code><form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>
</code>```

答:
Remove space from name, use type number and you can use parseInt too</p>

```<code>`<form action="/" method="POST">
    <input type="number" name="num1" placeholder="First Number " />
    <input type="number" name="num2" placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {

      var num1, num2, total = 0;
      consol.log(req.body.num2)
      num1 = parseInt(req.body.num1);a
      num2 = parseInt(req.body.num2);
      total = num1 + num2;
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});`
</code>```

Body:
I'm fairly new to Javascript. But I created an HTML code that takes input and then the NodeJS runs it on the server to calculate the sum. I downloaded both modules properly. But I still seem to get Nan as the sum of numbers.

The code seems to work properly for a friend. And I copy pasted his JS code to mine, still no luck.

JS

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {
      console.log(req.body);
      var num1, num2, total = 0;
      num1 = req.body.num1;
      num2 = req.body.num2;
      total = num1 + num2;
      console.log(total);
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});

HTML

<form action="/" method="POST">
    <input type="text " name="num1 " placeholder="First Number " />
    <input type="text " name="num2 " placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>

Body:
Remove space from name, use type number and you can use parseInt too

`<form action="/" method="POST">
    <input type="number" name="num1" placeholder="First Number " />
    <input type="number" name="num2" placeholder="Second Number " />
    <button type="submit " name="submit ">Calculate</button>
</form>

const express = require("express");

const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});

app.post("/", function(req, res) {

      var num1, num2, total = 0;
      consol.log(req.body.num2)
      num1 = parseInt(req.body.num1);a
      num2 = parseInt(req.body.num2);
      total = num1 + num2;
      res.send("The result of the calculation is " + total);
});

app.listen(3000, function() {
     console.log("The server is running on port 3000.");
});`


问:
Compare Dates in Array of MongoDB Object with different formats
I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"

My Slot Json Object

```<code>{
  date: [
    2020-06-03T00:00:00.000Z,
    2020-06-05T00:00:00.000Z,
    2020-06-07T00:00:00.000Z
  ],
  __v: 0
}
</code>```

I have to loop over each date in the date array and compare it with the date I get from frontend.

Let's say user input date is

```<code>let userInput = '2020-06-03';
</code>```

And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for

```<code>'2020-06-03' and '2020-06-03T00:00:00.000Z'
</code>```

I am looking at a solution which is appropriate when looping over all these array elements.

答:
Have the format of date strings(input) and the array of dates be properly specified for parsing. Then you could straight away use the isSame() to check if the dates are equal

let input = "2020-06-03";
let arr = [
  "2020-06-03T00:00:00.000Z",
  "2020-06-05T00:00:00.000Z",
  "2020-06-07T00:00:00.000Z"
];
let result = arr.map(item =>
  moment(item, "YYYY-MM-DD hh:mm:ss zz").isSame(input, "YYYY-MM-DD")
);
console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.js"></script></code>```

Body:
I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"

My Slot Json Object

{
  date: [
    2020-06-03T00:00:00.000Z,
    2020-06-05T00:00:00.000Z,
    2020-06-07T00:00:00.000Z
  ],
  __v: 0
}

I have to loop over each date in the date array and compare it with the date I get from frontend.

Let's say user input date is

let userInput = '2020-06-03';

And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for

'2020-06-03' and '2020-06-03T00:00:00.000Z'

I am looking at a solution which is appropriate when looping over all these array elements.

Body:
Have the format of date strings(input) and the array of dates be properly specified for parsing. Then you could straight away use the isSame() to check if the dates are equal

let input = "2020-06-03";
let arr = [
  "2020-06-03T00:00:00.000Z",
  "2020-06-05T00:00:00.000Z",
  "2020-06-07T00:00:00.000Z"
];
let result = arr.map(item =>
  moment(item, "YYYY-MM-DD hh:mm:ss zz").isSame(input, "YYYY-MM-DD")
);
console.log(result);

<script src="https://momentjs.com/downloads/moment.js"></script>


问:
Could not find or load main class when trying to connect MariaDB
Error: Could not find or load main class...

What am I doing wrong when trying to connect Maria DB in java? I'm a novice developer in java so don't be rude...

Am I compiling in a wrong way this file? Also I tried to download mysql and mariaDb drivers but still had no success...I think the driver is not the problem, appreciate all the guidance and help.

This is all my code:

```<code>Panaderia.java

package proyecto;

import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.sql.*;

public class Panaderia extends JFrame implements ActionListener{
    JTextArea tablas_ta;
    JTextArea registros_ta;
    JButton consultarTablas_btn;
    JButton consultarRegistros_btn;
    JTextField textField;

    /*
     * Método constructor
     **/
    public Panaderia(){

        super("Ejemplo de Java + MySQL");

        //Configurar la operación de salida por defecto para JFrame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,750);

        setLayout(new FlowLayout());

        consultarTablas_btn = new JButton("Consultar tablas");
        consultarTablas_btn.setActionCommand("ConsultarTablas");
        add(consultarTablas_btn);

        tablas_ta = new JTextArea(10, 70);
        add(tablas_ta);

        textField = new JTextField(30);
        add(textField);

        consultarRegistros_btn = new JButton("Consultar registros");
        consultarRegistros_btn.setActionCommand("ConsultarRegistros");
        add(consultarRegistros_btn);

        registros_ta = new JTextArea(10, 70);
        add(registros_ta);

        // Usar este objeto como Manejador de eventos
        consultarTablas_btn.addActionListener(this);
        consultarRegistros_btn.addActionListener(this);
        textField.addActionListener(this);

        this.setVisible(true);
    }

    public static void main(String[] args) {

        Panaderia mjf = new Panaderia();
    }

    @Override
    public void actionPerformed(ActionEvent evento) {
        String db, dbuser, pass;
            db = "ejemplos";//cambiar por el nombre de la base de datos que desean utilizar
            dbuser = "root";
            pass = "";
        if(evento.getActionCommand()=="ConsultarTablas") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SHOW TABLES");

                while( rs.next() ) {
                    tablas_ta.append( rs.getString(1) + "\n");
                }

                tablas_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

        if(evento.getActionCommand()=="ConsultarRegistros") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();

                ResultSet rs = stmt.executeQuery("SELECT * FROM "+textField.getText());

                String registro = "";

                while( rs.next() ) {
                    for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
                        registro = registro + "\t" + rs.getString(i);
                    }
                    registros_ta.append( registro +"\n");
                    registro = "";
                }

                registros_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }
}

</code>```

The error showing in terminal is:

How should you fix it?

答:
In order to run your application from the command Line your
Panaderia.java and the mysql.jar file should reside in the same
folder. If not you have to give the path aswel.

so the proyecto folder contains Panaderia.java and mysql.jar file.Open command line from the root folder where you see the proyecto folder

To compile your code :
javac -cp proyecto\mysql-connector-java-5.1.49.jar; proyecto\Panaderia.java

To run : java -cp proyecto\mysql-connector-java-5.1.49.jar; proyecto.Panaderia

Hope this will help you.

Body:
Error: Could not find or load main class...

What am I doing wrong when trying to connect Maria DB in java? I'm a novice developer in java so don't be rude...

Am I compiling in a wrong way this file? Also I tried to download mysql and mariaDb drivers but still had no success...I think the driver is not the problem, appreciate all the guidance and help.

This is all my code:

Panaderia.java

package proyecto;

import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.sql.*;

public class Panaderia extends JFrame implements ActionListener{
    JTextArea tablas_ta;
    JTextArea registros_ta;
    JButton consultarTablas_btn;
    JButton consultarRegistros_btn;
    JTextField textField;

    /*
     * Método constructor
     **/
    public Panaderia(){

        super("Ejemplo de Java + MySQL");

        //Configurar la operación de salida por defecto para JFrame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,750);

        setLayout(new FlowLayout());

        consultarTablas_btn = new JButton("Consultar tablas");
        consultarTablas_btn.setActionCommand("ConsultarTablas");
        add(consultarTablas_btn);

        tablas_ta = new JTextArea(10, 70);
        add(tablas_ta);

        textField = new JTextField(30);
        add(textField);

        consultarRegistros_btn = new JButton("Consultar registros");
        consultarRegistros_btn.setActionCommand("ConsultarRegistros");
        add(consultarRegistros_btn);

        registros_ta = new JTextArea(10, 70);
        add(registros_ta);

        // Usar este objeto como Manejador de eventos
        consultarTablas_btn.addActionListener(this);
        consultarRegistros_btn.addActionListener(this);
        textField.addActionListener(this);

        this.setVisible(true);
    }

    public static void main(String[] args) {

        Panaderia mjf = new Panaderia();
    }

    @Override
    public void actionPerformed(ActionEvent evento) {
        String db, dbuser, pass;
            db = "ejemplos";//cambiar por el nombre de la base de datos que desean utilizar
            dbuser = "root";
            pass = "";
        if(evento.getActionCommand()=="ConsultarTablas") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SHOW TABLES");

                while( rs.next() ) {
                    tablas_ta.append( rs.getString(1) + "\n");
                }

                tablas_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

        if(evento.getActionCommand()=="ConsultarRegistros") {

            try {
                Class.forName("com.mysql.jdbc.Driver");

                Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/"+db, dbuser, pass);

                Statement stmt = con.createStatement();

                ResultSet rs = stmt.executeQuery("SELECT * FROM "+textField.getText());

                String registro = "";

                while( rs.next() ) {
                    for(int i=1;i<=rs.getMetaData().getColumnCount();i++){
                        registro = registro + "\t" + rs.getString(i);
                    }
                    registros_ta.append( registro +"\n");
                    registro = "";
                }

                registros_ta.append("\n");

                con.close();

            } catch(Exception e) {
                System.out.println(e);
            }

        }

    }
}

The error showing in terminal is:

How should you fix it?


问:
Magento category->getUrlPath() and trailing slashes
we're trying to get the URL of a product within a category, and have this code:

```<code>$_categories = $_relatedProduct->getCategoryIds();
$_category = Mage::getModel('catalog/category')->load($_categories[0]);
$url = $this->getUrl($_category->getUrlPath()).'/'.$_relatedProduct->getUrlPath();
</code>```

The problem is that, on our development server, the call to $category->getUrlPath() doesn't return a value with a trailing slash, but it does on our production server. Does anybody know whether there's a config option we need to set so the returned values are consistent?

Edit:
Just to clarify, the issue is that the generated URLs appear like this on on development server:

http://devserver.com/category/product

but like this on the live server:

http://liveserver.com/category//product  (two slashes after category)

答:
Edit2: Updated answer was off base

Is your base URL the same on both? I'd check there - I would imagine it has a trailing slash on one of them.

Edit: You can check in core_config_data table or through the interface - I just don't have Mage on my dev computer to check!

Body:
we're trying to get the URL of a product within a category, and have this code:

$_categories = $_relatedProduct->getCategoryIds();
$_category = Mage::getModel('catalog/category')->load($_categories[0]);
$url = $this->getUrl($_category->getUrlPath()).'/'.$_relatedProduct->getUrlPath();

The problem is that, on our development server, the call to $category->getUrlPath() doesn't return a value with a trailing slash, but it does on our production server. Does anybody know whether there's a config option we need to set so the returned values are consistent?

Edit:
Just to clarify, the issue is that the generated URLs appear like this on on development server:

http://devserver.com/category/product

but like this on the live server:

http://liveserver.com/category//product  (two slashes after category)