问:
Updating one-to-Many relationships Failed on SaveChanges
I have two entities . The First is "Order"

```<code>public class Order : EntityBase
{

    public Guid ClientKey { get; set; }
    public Guid EmployeeKey { get; set; }
    public DateTime CreatedOn { get; set; }
    public DeliveryType DeliveryType { get; set; }
    public Address Address { get; set; }
    public Client Client { get; set; }
    public Employee Employee { get; set; }

    public bool SoftDeleted { get; set; }
    public virtual ICollection<JourneyOrder> JourneyOrder { get; set; }
    **public virtual ICollection<Item> Items
    { get; set; }**
    public virtual ICollection<ItemToBeFactored> ItemToBeFactored
    { get; set; }

    public Order() : base()
    {

        Items = new HashSet<Item>();
        ItemToBeFactored = new HashSet<ItemToBeFactored>();
        JourneyOrder = new HashSet<JourneyOrder>();
        CreatedOn = DateTime.Now;

    }
}
</code>```

and the second is : "Item":

```<code>public class Item : EntityBase
{

    public string Name { get; set; }
    public double Height { get; set; }
    public double width { get; set; }
    public string Color { get; set; }
    public Guid OrderKey { get; set; }

    **public Order CustomerOrder { get; set; }**
}
</code>```

I am trying to update the navigation property in Order entity in this code :

```<code>var order = _context.Orders.Where(x => x.Key.Equals(new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"))).Include(x => x.Items).
            First();

  order.Items = new List<Item>
  {
        new Item {  Color = "Green", width = 20d }
  };

  _context.SaveChanges();
</code>```

I got this repetitive error :

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded

The updating is working on "one-to-on" property but nut on one-many navigation property !!

Update:

I could use update in a dummy way !!
First: I cleared the items from order,
then

```<code>_context.Items.add( new Item { OrderKey = order.Key, Color = "Blue", width = 240d })
then _context.SaveChanges();
</code>```

But it is not an efficient way !! –

答:
Whenever you are loading the Order as follows:

```<code>var order = _context.Orders.Find(new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"));
</code>```

Its not loading the Items of the Order along with it and hence its not being tracked and updated!

So you have to load the Items along with Order as follows and then modify the Item collection:

```<code>var order = _context.Orders.Where(o => o.Id == new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"))
                           .Include(o => o.Items).FirstOrDefault(); // I assumed your `Order` primary key name is `Id`

  order.Items = new List<Item>
  {
        new Item {  Color = "Green", width = 20d }
  };

  _context.SaveChanges();
</code>```

Body:
I have two entities . The First is "Order"

public class Order : EntityBase
{

    public Guid ClientKey { get; set; }
    public Guid EmployeeKey { get; set; }
    public DateTime CreatedOn { get; set; }
    public DeliveryType DeliveryType { get; set; }
    public Address Address { get; set; }
    public Client Client { get; set; }
    public Employee Employee { get; set; }

    public bool SoftDeleted { get; set; }
    public virtual ICollection<JourneyOrder> JourneyOrder { get; set; }
    **public virtual ICollection<Item> Items
    { get; set; }**
    public virtual ICollection<ItemToBeFactored> ItemToBeFactored
    { get; set; }

    public Order() : base()
    {

        Items = new HashSet<Item>();
        ItemToBeFactored = new HashSet<ItemToBeFactored>();
        JourneyOrder = new HashSet<JourneyOrder>();
        CreatedOn = DateTime.Now;

    }
}

and the second is : "Item":

public class Item : EntityBase
{

    public string Name { get; set; }
    public double Height { get; set; }
    public double width { get; set; }
    public string Color { get; set; }
    public Guid OrderKey { get; set; }

    **public Order CustomerOrder { get; set; }**
}

I am trying to update the navigation property in Order entity in this code :

var order = _context.Orders.Where(x => x.Key.Equals(new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"))).Include(x => x.Items).
            First();

  order.Items = new List<Item>
  {
        new Item {  Color = "Green", width = 20d }
  };

  _context.SaveChanges();

I got this repetitive error :

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded

The updating is working on "one-to-on" property but nut on one-many navigation property !!

Update:

I could use update in a dummy way !!
First: I cleared the items from order,
then

_context.Items.add( new Item { OrderKey = order.Key, Color = "Blue", width = 240d })
then _context.SaveChanges();

But it is not an efficient way !! –

Body:
Whenever you are loading the Order as follows:

var order = _context.Orders.Find(new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"));

Its not loading the Items of the Order along with it and hence its not being tracked and updated!

So you have to load the Items along with Order as follows and then modify the Item collection:

var order = _context.Orders.Where(o => o.Id == new Guid("67972aa1-2bb4-4916-b48b-1fdc3c2f5db9"))
                           .Include(o => o.Items).FirstOrDefault(); // I assumed your `Order` primary key name is `Id`

  order.Items = new List<Item>
  {
        new Item {  Color = "Green", width = 20d }
  };

  _context.SaveChanges();


来源: stackexchange

问:
I'm getting Cannot read property 'appendChild' of null(on chrome) and this.container is null(on firefox) errors when I started using material dialog
I have a table in my frontend that has a list of all my users from a MySQL database using a spring API. I wanted to create a material dialog that would open when clicking on a user but for some reason I'm getting a bunch of errors on firefox and chrome which are mentioned above and I haven't found anything online to help even though I followed many tutorials to create the angular dialog but i still got the same erros.

Here's my component html that has the list of users:

```<code><div class="container-scroller">
<app-navbar></app-navbar>
<div class="container-fluid page-body-wrapper">
<app-sidebar></app-sidebar>
<div class="main-panel">
  <div class="content-wrapper">
    <div class="row">
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
  <div class="card-body">
    <h4 class="card-title" style="font-weight: 600">Users List</h4>
    <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>Id</th>
            <th>Profile Picture</th>
            <th>Username</th>
            <th>Last Name</th>
            <th>First Name</th>
            <th>Email</th>
            <th>Enabled</th>
            <th>Registered Date</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let u of users" (click)="openDialog()" id="myId">
            <td>{{u.id}}</td>
            <td>{{u.profilePicture}}</td>
            <td>{{u.username}}</td>
            <td>{{u.lastName}}</td>
            <td>{{u.firstName}}</td>
            <td>{{u.email}}</td>
            <ng-container *ngIf="u.enabled; else elseTemplate">
              <td class="text-success">{{u.enabled}}</td>
            </ng-container>
            <ng-template #elseTemplate>
              <td class="text-danger">{{u.enabled}}</td>
            </ng-template>
            <td>{{ u.registeredDate | date: shortDate }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>
</div>
</div>
  </div>
</div>
</div>
</div>
</code>```

the .ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['../app.component.scss', './dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
loginuser: any = {};
users: any[] = [];
constructor(private service: UserService, private dialog: MatDialog) {
this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.users = u;
  console.log(this.users);
});
}

ngOnInit() {
}

openDialog() {
console.log('selected item: ', selectedItem);
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.data = {
  id: 1,
  title: 'Angular for Beginners'
};
this.dialog.open(NewDialogComponent, dialogConfig);
const dialogRef = this.dialog.open(NewDialogComponent, dialogConfig);
}
}
</code>```

and here's the new dialog html component:

```<code><h2 mat-dialog-title>This is a Dialog title</h2>

<mat-dialog-content>

<p> Place content here </p>
</mat-dialog-content>

<mat-dialog-actions>
<button class="mat-raised-button" (click)="close()">Close</button>
</mat-dialog-actions>
</code>```

and the .ts file:

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
selector: 'app-new-dialog',
templateUrl: './new-dialog.component.html',
styleUrls: ['./new-dialog.component.scss']
})
export class NewDialogComponent implements OnInit {
description: string;

constructor(private fb: FormBuilder, private dialogRef: MatDialogRef<NewDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
  this.description = data.description;
}

ngOnInit() {}

close() {
this.dialogRef.close();
}
}
</code>```

答:
At first glance, it looks like you're opening your dialog twice:

```<code>this.dialog.open(NewDialogComponent, dialogConfig);
const dialogRef = this.dialog.open(NewDialogComponent, dialogConfig);
</code>```

Not sure if that is what is causing the exact error, but it's the first thing I noticed.

Update:

It looks now to me like this line is the error:

```<code>this.description = data.description;
</code>```

I'm not seeing any property being set for "description"-- just 'id' and 'title'.

ContentLicense: CC BY-SA 4.0

Body:
I have a table in my frontend that has a list of all my users from a MySQL database using a spring API. I wanted to create a material dialog that would open when clicking on a user but for some reason I'm getting a bunch of errors on firefox and chrome which are mentioned above and I haven't found anything online to help even though I followed many tutorials to create the angular dialog but i still got the same erros.

Here's my component html that has the list of users:

<app-navbar></app-navbar>

<app-sidebar></app-sidebar>

Users List

            Id
            Profile Picture
            Username
            Last Name
            First Name
            Email
            Enabled
            Registered Date

            {{u.id}}
            {{u.profilePicture}}
            {{u.username}}
            {{u.lastName}}
            {{u.firstName}}
            {{u.email}}
            <ng-container *ngIf="u.enabled; else elseTemplate">
              {{u.enabled}}
            </ng-container>
            <ng-template #elseTemplate>
              {{u.enabled}}
            </ng-template>
            {{ u.registeredDate | date: shortDate }}

the .ts file:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';

@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['../app.component.scss', './dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
loginuser: any = {};
users: any[] = [];
constructor(private service: UserService, private dialog: MatDialog) {
this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.users = u;
  console.log(this.users);
});
}

ngOnInit() {
}

openDialog() {
console.log('selected item: ', selectedItem);
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.data = {
  id: 1,
  title: 'Angular for Beginners'
};
this.dialog.open(NewDialogComponent, dialogConfig);
const dialogRef = this.dialog.open(NewDialogComponent, dialogConfig);
}
}

and here's the new dialog html component:

This is a Dialog title

<mat-dialog-content>

 Place content here

</mat-dialog-content>

<mat-dialog-actions>
<button class="mat-raised-button" (click)="close()">Close</button>
</mat-dialog-actions>

and the .ts file:

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';

@Component({
selector: 'app-new-dialog',
templateUrl: './new-dialog.component.html',
styleUrls: ['./new-dialog.component.scss']
})
export class NewDialogComponent implements OnInit {
description: string;

constructor(private fb: FormBuilder, private dialogRef: MatDialogRef<NewDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
  this.description = data.description;
}

ngOnInit() {}

close() {
this.dialogRef.close();
}
}

Body:
At first glance, it looks like you're opening your dialog twice:

this.dialog.open(NewDialogComponent, dialogConfig);
const dialogRef = this.dialog.open(NewDialogComponent, dialogConfig);

Not sure if that is what is causing the exact error, but it's the first thing I noticed.

Update:

It looks now to me like this line is the error:

this.description = data.description;

I'm not seeing any property being set for "description"-- just 'id' and 'title'.


问:
Redirect to 404 component without changing browser URL and make history behave right in Angular
When my backend sends me a 404 error (URL is valid, just because the resource is not found, like http://localhost:4200/post/title-not-exist), I want Angular redirect to my NotFoundComponent, without changing the URL in browser.

Code below (simplified):

constructor(private router: Router, private location: Location) {}

handleError(err: HttpErrorResponse) {
  switch (err.status) {
    case 404:
      url = this.router.routerState.snapshot.url;
      // '**' is set in the app-routing.module.ts
      // { path: '**', component: NotFoundComponent }
      this.router.navigate(['**'], { replaceUrl: false });
      // weird here too
      // without the setTimeout(), replaceState will not work
      setTimeout(() => {
        this.location.replaceState(url);
      });
      break;

    default:
      break;
  }
  return throwError(err);
}
```

Now, I can redirect to NotFoundComponent and the URL not changed, the problem is:

My history will become things like:

/post/title-exist → /post/not-exist → /post/not-exist

which should be

/post/title-exist → /post/not-exist

And the go back function will stuck here.

Without the setTimeout(), location.replaceState() will not work, the URL in browser becomes /** and not changing to the URL that snapshotted before.

答:
Update

Use skipLocationChange to keep the original URL, replaceUrl is not needed anymore.

Reference here.

Original

The key point is to change the replaceUrl in this.router.navigate from false to true, like this:

this.router.navigate(['**'], { replaceUrl: true });
```

Logic behind:

When replaceUrl is false, you are pushing a new history to your browser history stack. So the history stack becomes like this:

/post/title-exist → /post/title-not-exist → /**

And with the help of replaceState(), it changes the /** history to /post/title-not-exist, which makes the history finally becomes:

/post/title-exist → /post/title-not-exist → /** /post/title-not-exist

When replaceUrl is true, you are directly modifying the current history stack, which makes your browser history becomes like this:

/post/title-exist → /post/title-not-exist /**

Then, with the help of replaceState(), the history becomes:

/post/title-exist → /post/title-not-exist /** /post/title-not-exist

Body:
When my backend sends me a 404 error (URL is valid, just because the resource is not found, like http://localhost:4200/post/title-not-exist), I want Angular redirect to my NotFoundComponent, without changing the URL in browser.

Code below (simplified):

constructor(private router: Router, private location: Location) {}

handleError(err: HttpErrorResponse) {
  switch (err.status) {
    case 404:
      url = this.router.routerState.snapshot.url;
      // '**' is set in the app-routing.module.ts
      // { path: '**', component: NotFoundComponent }
      this.router.navigate(['**'], { replaceUrl: false });
      // weird here too
      // without the setTimeout(), replaceState will not work
      setTimeout(() => {
        this.location.replaceState(url);
      });
      break;

    default:
      break;
  }
  return throwError(err);
}

Now, I can redirect to NotFoundComponent and the URL not changed, the problem is:

My history will become things like:

/post/title-exist → /post/not-exist → /post/not-exist

which should be

/post/title-exist → /post/not-exist

And the go back function will stuck here.

Without the setTimeout(), location.replaceState() will not work, the URL in browser becomes /** and not changing to the URL that snapshotted before.

Body:
Update

Use skipLocationChange to keep the original URL, replaceUrl is not needed anymore.

Reference here.

Original

The key point is to change the replaceUrl in this.router.navigate from false to true, like this:

this.router.navigate(['**'], { replaceUrl: true });

Logic behind:

When replaceUrl is false, you are pushing a new history to your browser history stack. So the history stack becomes like this:

/post/title-exist → /post/title-not-exist → /**

And with the help of replaceState(), it changes the /** history to /post/title-not-exist, which makes the history finally becomes:

/post/title-exist → /post/title-not-exist → /** /post/title-not-exist

When replaceUrl is true, you are directly modifying the current history stack, which makes your browser history becomes like this:

/post/title-exist → /post/title-not-exist /**

Then, with the help of replaceState(), the history becomes:

/post/title-exist → /post/title-not-exist /** /post/title-not-exist


问:
Upload GL_UNSIGNED_BYTE to a GL_FLOAT texture
I have an OpenGL texture that is created normally, using GL_FLOAT as its data type:

```<code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, Dims.x, Dims.y, 0, GL_RGBA, GL_FLOAT, Data);
</code>```

(Data is sent properly as a float array.)

I then have to update the texture using data that is in the form of unsigned bytes. Is it legal to update the texture with glTexSubImage2D using GL_UNSIGNED_BYTE?

```<code>glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, Dims.x, Dims.y, GL_RGBA, GL_UNSIGNED_BYTE, NewData);
</code>```

(NewData is sent as unsigned char*.)

The documentation does not appear to mention anything about using different data types between these functions. Is it possible to update the texture this way, or would the texture data have to be converted to float*?

答:
In desktop OpenGL*, so long as the pixel transfer format is of the same kind as the internal format, the transfer will work. By "kind", I mean the two formats have to be talking about the same kind of data. You can't upload depth pixel data to a color internal format. And if the internal format is an integer format, then the pixel transfer format must be one of the _INTEGER versions.

But other than that, the sky's the limit... as long as you don't like performance. But it's not like you sending GL_FLOAT data to a 16F texture was particularly fast either.

*: I mention desktop OpenGL because OpenGL ES specifically requires the formats to match. Because they like performance ;)

Body:
I have an OpenGL texture that is created normally, using GL_FLOAT as its data type:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, Dims.x, Dims.y, 0, GL_RGBA, GL_FLOAT, Data);

(Data is sent properly as a float array.)

I then have to update the texture using data that is in the form of unsigned bytes. Is it legal to update the texture with glTexSubImage2D using GL_UNSIGNED_BYTE?

glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, Dims.x, Dims.y, GL_RGBA, GL_UNSIGNED_BYTE, NewData);

(NewData is sent as unsigned char*.)

The documentation does not appear to mention anything about using different data types between these functions. Is it possible to update the texture this way, or would the texture data have to be converted to float*?


问:
How to access docker container from another machine?
I need to access docker containers from another machine and every container use the same port.
Example:

How can i do that. I tried vpn server but i didnt get success

答: when you run the container, you must expose an port, and that port can't be the same while the containers are in the same machine. </p>


问:
How to import ORIGINAL time data from .xlsx files to MATLAB
I've got a .xlsx file with parts like this:

I want to import that into MATLAB like this:

```<code>[data,txt,raw]=xlsread('filename','D1:D6')
</code>```

But it becomes:

```<code>{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
</code>```

which rounds my original data to seconds, BUT I need to keep the milliseconds.

When I open the data file in Excel, I realized where the wrong data comes from.

And now my question: Is there a way to import the original data like 2019-05-26 08:17:40.501 into MATLAB? Both datestr or datenum can be accepted, only if it contains the same thing with original data.

I can't find out any clue in doc xlsread or doc importdata to deal with this issue. Also I've seen this question on StackOverflow, which has similar data with mine but with totally different result, and I'd assume to be a different issue.

答:
Thanks to @Phil Goddard, this issue is fixed with readtable, namely:

raw=readtable('filename');
```

the result is a table

As you see, everything goes well. The time data is actually a datetime vector, which can be checked by raw{:,4}, and can be converted to datenum or datestr or anything you like.

Generally, use readtable instead of xlsread.

Body:
I've got a .xlsx file with parts like this:

I want to import that into MATLAB like this:

[data,txt,raw]=xlsread('filename','D1:D6')

But it becomes:

{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}
{'2019/5/26 8:17:41'}

which rounds my original data to seconds, BUT I need to keep the milliseconds.

When I open the data file in Excel, I realized where the wrong data comes from.

And now my question: Is there a way to import the original data like 2019-05-26 08:17:40.501 into MATLAB? Both datestr or datenum can be accepted, only if it contains the same thing with original data.

I can't find out any clue in doc xlsread or doc importdata to deal with this issue. Also I've seen this question on StackOverflow, which has similar data with mine but with totally different result, and I'd assume to be a different issue.

Body:
Thanks to @Phil Goddard, this issue is fixed with readtable, namely:

raw=readtable('filename');

the result is a table

As you see, everything goes well. The time data is actually a datetime vector, which can be checked by raw{:,4}, and can be converted to datenum or datestr or anything you like.

Generally, use readtable instead of xlsread.


问:
Setup.py install_requires to find local src packages
I have multiple shared internal libraries that many repositories depends on. Right now, these libraries are in the same git repository and are submoduled into each application when needed. During the build time, I will pip install the libraries. The problem I am facing is these internal libraries also depends on each other, but the dependencies can't be resolved since they are in local folders.

For example, I have local library A depends on B. This will NOT work

```<code>setup(
    name='A_package',
    install_requires=[
      'B_package',  # source file in local folder
    ],
    ...
)
</code>```

since pip tries to find B_package on PyPI.

I have searched many solutions however, I can't seem to find a straight forward solution such as

```<code>install_requires=[
          '/commonlib/path/B_package',
        ],
</code>```

This way, I can just pip install A_package then B_package will also be located and installed.

The reason I would like to have shared library source code as a submodule is to make development easier so engineers can modify and commit the libraries whenever needed. I am welcome for any other suggestions.

答:
Cost of Publish Packages vs Speed of Development

The Tradeoff between these two things is the key here.

Using Git Repo : Good Speed at Small Scale, Problems when it grows

This is what I first tried in my company. We don't use submodule, we just put git repo under where pip installs packages, like /Users/xxx/miniconda3/lib/python3.6/site-packages. pip will always treat that package as installed, and we synchronize that git repo to update that package.

This works great at small scale, but it brings problems when project grows. When you are using git repo, you are using git revision instead of pypi package version so you need to maintain version dependency manually. Suppose project A uses package B, they both have their own versions, how to maintain the dependency, two options:

Always uses the latest version of B, B is backward compatible - Easy for A, but put burden on B.

Just like python package version, put a git revision or tag in A, people need to checkout B every time they switch to a different branch in A - Painful for large project with multiple branches

And if you have multiple virtualenv, you have to extra work to do.

Publish Package But Minimize the Cost : The Way to Go

This is what I ended up with in my company. I setup our own pypi server and the gitlab ci to publish package when a tag is pushed. It doesn't have the problems with the previous one and also supports a fast development iteration.

For Developer

```<code>$ git commit ...
$ git tag ...
$ git push && git push --tags
</code>```

Two commands is all they need to do to publish a package, it's cheap. And we actually use bumpversion to manage version instead of a manual tag.

For User

```<code>$ pip install -r requirements.txt
</code>```

Every time they switch to anther branch in A or someone fix bug in B, they only need to pip install.

EDIT 2019.05.27

It's possible to do what you want with setup.py. When you run pip install, it will download package, unpack it and run python setup.py install, so
you can add custom logic in setup.py:

```<code>install_requires = ['b', 'c', 'd']

# make sure it's in the python path and has been checked out
if is_package_b_installed_as_git_repo():
    install_requires.remove('b')

setup(
    name='A_package',
    install_requires=install_requries,
    ...
)
</code>```

Body:
I have multiple shared internal libraries that many repositories depends on. Right now, these libraries are in the same git repository and are submoduled into each application when needed. During the build time, I will pip install the libraries. The problem I am facing is these internal libraries also depends on each other, but the dependencies can't be resolved since they are in local folders.

For example, I have local library A depends on B. This will NOT work

setup(
    name='A_package',
    install_requires=[
      'B_package',  # source file in local folder
    ],
    ...
)

since pip tries to find B_package on PyPI.

I have searched many solutions however, I can't seem to find a straight forward solution such as

install_requires=[
          '/commonlib/path/B_package',
        ],

This way, I can just pip install A_package then B_package will also be located and installed.

The reason I would like to have shared library source code as a submodule is to make development easier so engineers can modify and commit the libraries whenever needed. I am welcome for any other suggestions.

Body:
Cost of Publish Packages vs Speed of Development

The Tradeoff between these two things is the key here.

Using Git Repo : Good Speed at Small Scale, Problems when it grows

This is what I first tried in my company. We don't use submodule, we just put git repo under where pip installs packages, like /Users/xxx/miniconda3/lib/python3.6/site-packages. pip will always treat that package as installed, and we synchronize that git repo to update that package.

This works great at small scale, but it brings problems when project grows. When you are using git repo, you are using git revision instead of pypi package version so you need to maintain version dependency manually. Suppose project A uses package B, they both have their own versions, how to maintain the dependency, two options:

Always uses the latest version of B, B is backward compatible - Easy for A, but put burden on B.

Just like python package version, put a git revision or tag in A, people need to checkout B every time they switch to a different branch in A - Painful for large project with multiple branches

And if you have multiple virtualenv, you have to extra work to do.

Publish Package But Minimize the Cost : The Way to Go

This is what I ended up with in my company. I setup our own pypi server and the gitlab ci to publish package when a tag is pushed. It doesn't have the problems with the previous one and also supports a fast development iteration.

For Developer

$ git commit ...
$ git tag ...
$ git push && git push --tags

Two commands is all they need to do to publish a package, it's cheap. And we actually use bumpversion to manage version instead of a manual tag.

For User

$ pip install -r requirements.txt

Every time they switch to anther branch in A or someone fix bug in B, they only need to pip install.

EDIT 2019.05.27

It's possible to do what you want with setup.py. When you run pip install, it will download package, unpack it and run python setup.py install, so
you can add custom logic in setup.py:

install_requires = ['b', 'c', 'd']

# make sure it's in the python path and has been checked out
if is_package_b_installed_as_git_repo():
    install_requires.remove('b')

setup(
    name='A_package',
    install_requires=install_requries,
    ...
)


问:
Error in enc2utf8(x) : argumemt is not a character vector
Error in enc2utf8(x) : argumemt is not a character vector is the error I get when I try to run the code below in R 3.1.2 . can anyone please help me understand if I am missing something here ?

OS used is Windows

```<code>#Text Cleaning: tm Code
  clean<-function(text){
  library(NLP)
  library(tm)
  sample<- Corpus(VectorSource(text),readerControl=list(language="english"))
  sample<- tm_map(sample, function(x) iconv(enc2utf8(x), sub = "bytes"))
  sample<-tm_map(sample,removePunctuation)
  sample <- tm_map(sample, stripWhitespace)
  sample<-tm_map(sample,removeNumbers)
  sample<-tm_map(sample,removeWords,stopwords('smart'))
  sample <- tm_map(sample, stripWhitespace)
  sample <- tm_map(sample, stripWhitespace)
  dtm <- DocumentTermt(sample[1:3])Matrix(sample)
  return(list(sample,dtm))
  }
 fileName <- 'input.txt'
 test = readChar(fileName, file.info(fileName)$size)
 clean (test)
</code>```

答:
Small change to your code into below 2 line may solve your problem</p>
```<code>sample<- VCorpus(VectorSource(text),readerControl=list(language="english"))
sample<- tm_map(sample, content_transformer(function(x) iconv(enc2utf8(x), sub = "bytes")))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Error in enc2utf8(x) : argumemt is not a character vector is the error I get when I try to run the code below in R 3.1.2 . can anyone please help me understand if I am missing something here ?

OS used is Windows

#Text Cleaning: tm Code
  clean<-function(text){
  library(NLP)
  library(tm)
  sample<- Corpus(VectorSource(text),readerControl=list(language="english"))
  sample<- tm_map(sample, function(x) iconv(enc2utf8(x), sub = "bytes"))
  sample<-tm_map(sample,removePunctuation)
  sample <- tm_map(sample, stripWhitespace)
  sample<-tm_map(sample,removeNumbers)
  sample<-tm_map(sample,removeWords,stopwords('smart'))
  sample <- tm_map(sample, stripWhitespace)
  sample <- tm_map(sample, stripWhitespace)
  dtm <- DocumentTermt(sample[1:3])Matrix(sample)
  return(list(sample,dtm))
  }
 fileName <- 'input.txt'
 test = readChar(fileName, file.info(fileName)$size)
 clean (test)

Body:
Small change to your code into below 2 line may solve your problem

sample<- VCorpus(VectorSource(text),readerControl=list(language="english"))
sample<- tm_map(sample, content_transformer(function(x) iconv(enc2utf8(x), sub = "bytes")))


问:
signature page in Latex
I intend to make signature page in the following two different and separate formats.

Currently the code is showing the person name on top and signature line at the bottom. I would like to get as shown in the attached image along with the date at the bottom right.

```<code>\newpage
\begin{center}{\Large\bf Signature Page}\end{center}
\vspace{0.3cm}

sometext here sometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext here.

\vfill
\newcommand{\namesigdate}[2][5cm]{%
\begin{minipage}{#1}
    #2 \vspace{1.5cm}\hrule\smallskip
\end{minipage}
}

\noindent \namesigdate{Mr.X} \ \hfill \namesigdate[5cm]{Mr.Y}
\\
\\
\vspace{1.5cm}\smallskip \\ \\
\noindent \namesigdate{Mr.XY} \ \hfill \namesigdate[5cm]{Mr.YY}
\\
\\
Date 2019May05
\\
</code>```

答:
Some notes:

\bf is deprecated. Consider \textbf and \bfseries instead.

If "Signature Page" should be one of your sections, you should consider use \section and do some settings for section using titlesec.

Code for the first layout

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{lipsum}
\newcommand\signature[2]{% Name; Department
\noindent\begin{minipage}{5cm}
    \noindent\vspace{3cm}\par
    \noindent\rule{5cm}{1pt}\par
    \noindent\textbf{#1}\par
    \noindent#2%
\end{minipage}}
\newcommand\insertdate[1][\today]{\vfill\begin{flushright}#1\end{flushright}}
\begin{document}
\begin{center}
% This is not a good practice, but as I don't know "Signature Page" is a section
% or not, I have no alternatives
\Large\bfseries Signature Page
\end{center}
\lipsum[1]

\signature{Mr. A}{ABC Department}\hfill\signature{Mr. B}{DEF Department}

\signature{Mr. C}{ABC Department}\hfill\signature{Mr. D}{DEF Department}

\signature{Mr. E}{ABC Department}\hfill\signature{Mr. F}{DEF Department}

\insertdate[May 5, 2019] % Default it will print today
\end{document}
```

<h3>Code for the second layout</h3>

<p>A little change and you will get the second one.</p>

<pre class="lang-latex prettyprint-override"><code>\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{lipsum}
\newcommand\signature[2]{% Name; Department
\begin{center}\begin{minipage}{5cm}
    \centering
    \vspace{3cm}\par
    \rule{5cm}{1pt}\par
    \textbf{#1}\par
    #2%
\end{minipage}\end{center}}
\newcommand\insertdate[1][\today]{\vfill\begin{flushright}#1\end{flushright}}
\begin{document}
\begin{center}
% This is not a good practice, but as I don't know "Signature Page" is a section
% or not, I have no alternatives
\Large\bfseries Signature Page
\end{center}
\lipsum[1]

\signature{Mr. A}{ABC Department}

\signature{Mr. C}{ABC Department}

\signature{Mr. E}{ABC Department}

\insertdate[May 5, 2019] % Default it will print today
\end{document}
</code>```

Happy TeXing! And consider going to TeX.SE for more experienced LaTeX users.

Title: signature page in Latex

Body:
I intend to make signature page in the following two different and separate formats.

Currently the code is showing the person name on top and signature line at the bottom. I would like to get as shown in the attached image along with the date at the bottom right.

\newpage
\begin{center}{\Large\bf Signature Page}\end{center}
\vspace{0.3cm}

sometext here sometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext heresometext here.

\vfill
\newcommand{\namesigdate}[2][5cm]{%
\begin{minipage}{#1}
    #2 \vspace{1.5cm}\hrule\smallskip
\end{minipage}
}

\noindent \namesigdate{Mr.X} \ \hfill \namesigdate[5cm]{Mr.Y}
\\
\\
\vspace{1.5cm}\smallskip \\ \\
\noindent \namesigdate{Mr.XY} \ \hfill \namesigdate[5cm]{Mr.YY}
\\
\\
Date 2019May05
\\

Body:
Some notes:

\bf is deprecated. Consider \textbf and \bfseries instead.

If "Signature Page" should be one of your sections, you should consider use \section and do some settings for section using titlesec.

Code for the first layout

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{lipsum}
\newcommand\signature[2]{% Name; Department
\noindent\begin{minipage}{5cm}
    \noindent\vspace{3cm}\par
    \noindent\rule{5cm}{1pt}\par
    \noindent\textbf{#1}\par
    \noindent#2%
\end{minipage}}
\newcommand\insertdate[1][\today]{\vfill\begin{flushright}#1\end{flushright}}
\begin{document}
\begin{center}
% This is not a good practice, but as I don't know "Signature Page" is a section
% or not, I have no alternatives
\Large\bfseries Signature Page
\end{center}
\lipsum[1]

\signature{Mr. A}{ABC Department}\hfill\signature{Mr. B}{DEF Department}

\signature{Mr. C}{ABC Department}\hfill\signature{Mr. D}{DEF Department}

\signature{Mr. E}{ABC Department}\hfill\signature{Mr. F}{DEF Department}

\insertdate[May 5, 2019] % Default it will print today
\end{document}

Code for the second layout

A little change and you will get the second one.

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{lipsum}
\newcommand\signature[2]{% Name; Department
\begin{center}\begin{minipage}{5cm}
    \centering
    \vspace{3cm}\par
    \rule{5cm}{1pt}\par
    \textbf{#1}\par
    #2%
\end{minipage}\end{center}}
\newcommand\insertdate[1][\today]{\vfill\begin{flushright}#1\end{flushright}}
\begin{document}
\begin{center}
% This is not a good practice, but as I don't know "Signature Page" is a section
% or not, I have no alternatives
\Large\bfseries Signature Page
\end{center}
\lipsum[1]

\signature{Mr. A}{ABC Department}

\signature{Mr. C}{ABC Department}

\signature{Mr. E}{ABC Department}

\insertdate[May 5, 2019] % Default it will print today
\end{document}

Happy TeXing! And consider going to TeX.SE for more experienced LaTeX users.


问:
How can I switch the database context of an existing DataSource?
Let's say I have an existing DataSource to a master database. I now need to create a new database, and execute some DDLs on that database. Is this possible with e.g, "USE" command, or do I need to create a new DataSource with the name of the new database in the JDBC url?</p>

答:
The USE statement works, but since it's stateful, you have to make sure that it's part of the same connection as the latter statements.

If you use Spring's JdbcTemplate instead of working with java.sql.Connection and java.sql.Statement directly, you can use a SingleConnectionDataSource.


问:
Error with pictures and 'if' in Python TelegramBot. How to fix?
I am using pyTelegramBotAPI and Python 3.7.

Bot in general works but an error occurs when the BOT should send the photo. When I write a bot message, in answer to which he must send a photo or a sticker, it goes but when next you enter the same command the bot sends nothing. I am a newbie so please suggest me how can I better write this code.

```<code>elif instead of if isn't working.
</code>```

...

```<code>@bot.message_handler(content_types=["text"])

def bot_messages(message):
    if message.text.lower() == "Привет".lower():
        bot.send_message(message.from_user.id, "Ку! ✋. Напиши /welcome.")

    if message.text.lower() == "/welcome".lower():
        bot.send_message(message.from_user.id, "Я бот Римуру. Напиши название животного, например, 'кот', и я отправлю его картинку.")
        bot.send_sticker(message.from_user.id, sticker1)

    if message.text.lower() == "питон".lower():
        bot.send_photo(message.from_user.id, photo1)
    if message.text.lower() == "мышь".lower():
        bot.send_photo(message.from_user.id, photo2)
    if message.text.lower() == "кот".lower():
        bot.send_photo(message.from_user.id, photo3)
    if message.text.lower() == "жираф".lower():
</code>```

...

答:
write this code if this code does not work, please enclose the code at https://pastebin.com and tell us its location.</p>

```<code>@bot.message_handler(func=lambda message: True)
def main(message):
    chat_id = message.chat.id
    user_id = message.from_user.id
    text = str(message.text).decode("utf-8").lower()
    if text == "привет":
        bot.send_message(user_id, "Ку! ✋. Напиши /welcome.")
    if text == "/welcome":
        bot.send_message(user_id, "Я бот Римуру. Напиши название животного, например, 'кот', и я отправлю его картинку.")
    if text == "питон":
        bot.send_photo(user_id, 'https://image.shutterstock.com/image-photo/python-snake-450w-184814297.jpg')
    if text == "мышь":
        bot.send_photo(user_id, 'https://mysekret.ru/wp-content/uploads/2017/01/5-47.jpg')
    if text == "кот":
        bot.send_photo(user_id, 'https://pp.userapi.com/c845122/v845122166/10ba66/gVecT_orwwY.jpg')
</code>```

Body:
I am using pyTelegramBotAPI and Python 3.7.

Bot in general works but an error occurs when the BOT should send the photo. When I write a bot message, in answer to which he must send a photo or a sticker, it goes but when next you enter the same command the bot sends nothing. I am a newbie so please suggest me how can I better write this code.

elif instead of if isn't working.

...

@bot.message_handler(content_types=["text"])

def bot_messages(message):
    if message.text.lower() == "Привет".lower():
        bot.send_message(message.from_user.id, "Ку! ✋. Напиши /welcome.")

    if message.text.lower() == "/welcome".lower():
        bot.send_message(message.from_user.id, "Я бот Римуру. Напиши название животного, например, 'кот', и я отправлю его картинку.")
        bot.send_sticker(message.from_user.id, sticker1)

    if message.text.lower() == "питон".lower():
        bot.send_photo(message.from_user.id, photo1)
    if message.text.lower() == "мышь".lower():
        bot.send_photo(message.from_user.id, photo2)
    if message.text.lower() == "кот".lower():
        bot.send_photo(message.from_user.id, photo3)
    if message.text.lower() == "жираф".lower():

...

Body:
write this code if this code does not work, please enclose the code at https://pastebin.com and tell us its location.

@bot.message_handler(func=lambda message: True)
def main(message):
    chat_id = message.chat.id
    user_id = message.from_user.id
    text = str(message.text).decode("utf-8").lower()
    if text == "привет":
        bot.send_message(user_id, "Ку! ✋. Напиши /welcome.")
    if text == "/welcome":
        bot.send_message(user_id, "Я бот Римуру. Напиши название животного, например, 'кот', и я отправлю его картинку.")
    if text == "питон":
        bot.send_photo(user_id, 'https://image.shutterstock.com/image-photo/python-snake-450w-184814297.jpg')
    if text == "мышь":
        bot.send_photo(user_id, 'https://mysekret.ru/wp-content/uploads/2017/01/5-47.jpg')
    if text == "кот":
        bot.send_photo(user_id, 'https://pp.userapi.com/c845122/v845122166/10ba66/gVecT_orwwY.jpg')


问:
Am I charged for creating and keeping AWS S3 buckets?
I created two buckets back in 2018 but never removed them. Rest assured that they are empty buckets with no files at all. </p>

<p>I didn't see any fee charged, so I presume Amazon/AWS didn't charge for simply creating S3 buckets? </p>

答: S3 pricing is based on object storage, not buckets. You can read more about S3 pricing on the AWS S3 pricing page here.</p>

Body:
I created two buckets back in 2018 but never removed them. Rest assured that they are empty buckets with no files at all.

I didn't see any fee charged, so I presume Amazon/AWS didn't charge for simply creating S3 buckets?


问:
How would I use javascript to make an image "jiggle" or "shiver"?
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

```<code>Copy the below code and paste it into the <HEAD> section of your page
Example:<head>Code Here</head>
<style>
.jc{
position:relative;
}
</style>

<script language="JavaScript1.2">

var ns6=document.getElementById&&!document.all
var ie=document.all

var customcollect=new Array()
var i=0

function jiggleit(num){
if ((!document.all&&!document.getElementById)) return;
customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1
}

function init(){
if (ie){
while (eval("document.all.jiggle"+i)!=null){
customcollect[i]= eval("document.all.jiggle"+i)
i++
}
}
else if (ns6){
while (document.getElementById("jiggle"+i)!=null){
customcollect[i]= document.getElementById("jiggle"+i)
i++
}
}

if (customcollect.length==1)
setInterval("jiggleit(0)",80)
else if (customcollect.length>1)
for (y=0;y<customcollect.length;y++){
var tempvariable='setInterval("jiggleit('+y+')",'+'100 )'
eval(tempvariable)
}
}

window.onload=init

</script>

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

<span id="jiggle0" class="jc"><b>YOUR IMAGE URL HERE</b></span>
</code>```

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

答:
this line has an error :

```<code>customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1
</code>```

you probably want :

```<code>customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1) ? 1 : -1;
</code>```

Body:
So my question is simple, I'm building a webpage in HTML and I want to incorporate a little JavaScript into it so as to make an image "vibrate" or "jiggle" Basically move back and forth in a relatively tight space/pattern.

I did some research and I found this:

Copy the below code and paste it into the  section of your page
Example:Code Here

NOW PASTE THIS ANYWHERE YOU WISH YOUR IMAGE TO APPEAR

YOUR IMAGE URL HERE

They called it a "shivering pic" and gave an example... its exactly what I want. I did it exactly as they described it. I added the code where they said it was needed, I copied all the right parts (none of the directions), and I made sure everything is in the right place.

I tested it out an there was no image! There was nothing! I realized that this was because I was using a black background, and if there was any text, it would also be black, so what actually was happening was that it was merely showing the URL of the image I want to add in (I could see it once I highlighted it). Regardless, still no image (just the text), and still no vibrating/jittering/shivering/jiggling. I did note that there were bold tags right where it suggests to add the image URL... so to me that would make it seem like I would be putting in text.

PLEASE HELP! How do I make this code work, or how do I make an image "shiver"?

Body:
this line has an error :

customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1)? customcollect[num].style.left=1 : customcollect[num].style.left=-1

you probably want :

customcollect[num].style.left=(parseInt(customcollect[num].style.left)==-1) ? 1 : -1;


问:
How do I write a java method that adds the digits of each number in a string
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

```<code>import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}
</code>```

And this adds ALL the numbers in a string:

```<code>String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}
</code>```

I don't know how to combine this code with code that can add the numbers this method outputs together.

答:
We can try using Java's regex engine with the pattern \d+.  Then we can iterate each match character by character, and tally the sum.

```<code>String a = "This 23 string has 738 numbers";
String pattern = "\\d+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
    System.out.print("found numbers: " + m.group(0) + " = ");
    int sum = 0;
    for (int i=0; i < m.group(0).length(); ++i) {
        sum += m.group(0).charAt(i) - '0';
    }
    System.out.println(sum);
}
</code>```

This prints:

```<code>found numbers: 23 = 5
found numbers: 738 = 18
</code>```

Body:
I am working on a challenge that requires us to input a string containing numbers. For example, "This 23 string has 738 numbers"

And the method needs to add the values of 2+3 to return 5 and 7+3+8 to return 18.

But I don't know how to make a loop to find each number in the input string, perform that operation, and continue through the rest of the string. Any suggestions or solutions?

A successful method would take a string as an input, like "This 23 string has 34 or cat 48", and the method would return 5, 7 and 12.

I have figured out how to use regular expressions to tease out the numbers from a string, but I don't know how to add the digits of each number teased out into an output

package reverseTest;

import java.util.Scanner;
public class ExtractNumbers {`enter code here`
      public static void main(String[] args)
      {
          String str;
          String numbers;

          Scanner SC=new Scanner(System.in);

          System.out.print("Enter string that contains numbers: ");
          str=SC.nextLine();

          //extracting string
          numbers=str.replaceAll("[^0-9]", "");

          System.out.println("Numbers are: " + numbers);
      }
}

And this adds ALL the numbers in a string:

String a="jklmn489pjro635ops";

    int sum = 0;

    String num = "";

    for(int i = 0; i < a.length(); i++) {
        if(Character.isDigit(a.charAt(i))) {
            num = num + a.charAt(i);
        } else {
            if(!num.equals("")) {
                sum = sum + Integer.parseInt(num);
                num = "";
            }
        }
    }
    System.out.println(sum);
}

I don't know how to combine this code with code that can add the numbers this method outputs together.

Body:
We can try using Java's regex engine with the pattern \d+.  Then we can iterate each match character by character, and tally the sum.

String a = "This 23 string has 738 numbers";
String pattern = "\\d+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(a);
while (m.find()) {
    System.out.print("found numbers: " + m.group(0) + " = ");
    int sum = 0;
    for (int i=0; i < m.group(0).length(); ++i) {
        sum += m.group(0).charAt(i) - '0';
    }
    System.out.println(sum);
}

This prints:

found numbers: 23 = 5
found numbers: 738 = 18


问:
Speed up Eloquent query
I'm trying to query a large amount of data (40K records), and planning to query much larger datasets in the future.  Eloquent seems to take a very long time to load this data. I wondered if there is a faster way to process this data. I'm attempting to look at the validity of my data, and hence checking to see if all fields are null.

I've used regular Eloquent calls. I don't think chunking the data is appropriate as I'm not planning on modifying the data in any way. I debated whether running a job every so often and calling the results of this job might be a better approach.

$journal = Journal::where('issn', $this->issn)->first();
$collection = $journal->outputs;
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));
```

答:
Just use Query Builders !

Why we should use Query Builders for lots of records instead of Eloquent ?!

Here is the reason :

Query Builder is so faster than Eloquent  :

Comparison (Eloquent vs Query Builder ) :

To insert 1000 rows for a simple table Eloquent takes 1.2 seconds and in that case DB facades take only 800 mili seconds(ms).

Another comparison :

Eloquent ORM average response time

```<code>Joins | Average (ms)
------+-------------
1     | 162,2
3     | 1002,7
4     | 1540,0

Result of select operation average response time for Eloquent ORM
</code>```

Raw SQL average response time

```<code> Joins | Average (ms)
------+-------------
1     | 116,4
3     | 130,6
4     | 155,2

Result of select operation average response time for Raw SQL
</code>```

For more information : Laravel Eloquent vs Query Builder

Edited :

Your code should be :

```<code>$journal = DB::table('journals')->where('issn', $this->issn)->first();
</code>```

And Then For using Collection ( Simple way ) :

```<code>$journal = Collection::make($journal); //For use Collection Methods
$collection = $journal->get("outputs");//Changed
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));
</code>```

Best Performance :

Use queries and Query Builder instead of collections . Because operations in SQL often is faster .

Please compare time for your last code and this code and please let me know in comments :)

Title: Speed up Eloquent query

Body:
Just use Query Builders !

Why we should use Query Builders for lots of records instead of Eloquent ?!

Here is the reason :

Query Builder is so faster than Eloquent  :

Comparison (Eloquent vs Query Builder ) :

To insert 1000 rows for a simple table Eloquent takes 1.2 seconds and in that case DB facades take only 800 mili seconds(ms).

Another comparison :

Eloquent ORM average response time

Joins | Average (ms)
------+-------------
1     | 162,2
3     | 1002,7
4     | 1540,0

Result of select operation average response time for Eloquent ORM

Raw SQL average response time

 Joins | Average (ms)
------+-------------
1     | 116,4
3     | 130,6
4     | 155,2

Result of select operation average response time for Raw SQL

For more information : Laravel Eloquent vs Query Builder

Edited :

Your code should be :

$journal = DB::table('journals')->where('issn', $this->issn)->first();

And Then For using Collection ( Simple way ) :

$journal = Collection::make($journal); //For use Collection Methods
$collection = $journal->get("outputs");//Changed
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));

Best Performance :

Use queries and Query Builder instead of collections . Because operations in SQL often is faster .

Please compare time for your last code and this code and please let me know in comments :)


问:
pom.xml error, unable to find what is wrong in my pom.xml
Screenshot of pom.xmlI am starting with Spring Project. Have the below error in the pom.xml (Spring Tool Suite)

Started a new project using Spring Tool Suite.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringInAction</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringInAction</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

On the eclipse, a Big red Cross :).................................

答:
I got my problem resolve following these steps:

right click on your project

maven->update project

then check

Force update of Snapshots/Releases

ok

As I can't see your error details, instead,
in case that does not help: you can check this thread

Body:
Screenshot of pom.xmlI am starting with Spring Project. Have the below error in the pom.xml (Spring Tool Suite)

Started a new project using Spring Tool Suite.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringInAction</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringInAction</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

On the eclipse, a Big red Cross :).................................


问:
FFmpeg, Icecast and metadata
I use FFmpeg streaming to the Icecast server on my Windows machine in the following way (sound card line in):

```<code>ffmpeg -f dshow -channels 2 -i audio="Line In" -codec:a libmp3lame -b:a 128k -legacy_icecast 1 -content_type audio/mpeg -ice_name "Radio test 1" -ice_description "This is Radio test 1" -ice_genre "Rock" -ice_url "http://www.radiotest.com" -f mp3 icecast://source:password@ip:port/mountpoint
</code>```

This works ok.

But I noticed an Icecast statistics that FFmpeg do not send "audio_info" metadata to Icecast while than edcast/altacast etc send it. And edcast/altacast do not send "user_agent" while FFmpeg is forced to send it.

Do I get FFmpeg to send "audio_info" metadata to Icecast?

答:
Can't comment but here is a start..</p>

```<code>/**
 * Please be aware. This gist requires at least PHP 5.4 to run correctly.
 * Otherwise consider downgrading the $opts array code to the classic "array" syntax.
 */
function getmp3StreamTitle($streamingUrl, $interval = 19200)
{
    $needle = 'StreamTitle=';
    $ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
    $opts = array('http' => array(
        'method' => 'GET',
        'header' => 'Icy-MetaData: 1',
        'user_agent' => $ua
    ));

    $context = stream_context_create($opts);

    $stream = fopen($streamingUrl, 'r', false, $context);
    if(!$stream) throw new Exception("Unable to open stream [{$streamingUrl}]");

    while(true) {
        $buffer = stream_get_contents($stream, $interval);
        if($buffer === false) throw new Exception('Could not read from stream.');

        if(strpos($buffer, $needle) !== false)
        {
            $text = explode($needle, $buffer)[1];
            $songtext = substr($text, 1, strpos($text, ';') - 2);
            break;
        }
    }

    fclose($stream);

    return $songtext;
}

ini_set('display_errors', 1);
header('Content-type: application/json');
</code>```

Title: FFmpeg, Icecast and metadata

Body:
I use FFmpeg streaming to the Icecast server on my Windows machine in the following way (sound card line in):

ffmpeg -f dshow -channels 2 -i audio="Line In" -codec:a libmp3lame -b:a 128k -legacy_icecast 1 -content_type audio/mpeg -ice_name "Radio test 1" -ice_description "This is Radio test 1" -ice_genre "Rock" -ice_url "http://www.radiotest.com" -f mp3 icecast://source:password@ip:port/mountpoint

This works ok.

But I noticed an Icecast statistics that FFmpeg do not send "audio_info" metadata to Icecast while than edcast/altacast etc send it. And edcast/altacast do not send "user_agent" while FFmpeg is forced to send it.

Do I get FFmpeg to send "audio_info" metadata to Icecast?

Body:
Can't comment but here is a start..

/**
 * Please be aware. This gist requires at least PHP 5.4 to run correctly.
 * Otherwise consider downgrading the $opts array code to the classic "array" syntax.
 */
function getmp3StreamTitle($streamingUrl, $interval = 19200)
{
    $needle = 'StreamTitle=';
    $ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
    $opts = array('http' => array(
        'method' => 'GET',
        'header' => 'Icy-MetaData: 1',
        'user_agent' => $ua
    ));

    $context = stream_context_create($opts);

    $stream = fopen($streamingUrl, 'r', false, $context);
    if(!$stream) throw new Exception("Unable to open stream [{$streamingUrl}]");

    while(true) {
        $buffer = stream_get_contents($stream, $interval);
        if($buffer === false) throw new Exception('Could not read from stream.');

        if(strpos($buffer, $needle) !== false)
        {
            $text = explode($needle, $buffer)[1];
            $songtext = substr($text, 1, strpos($text, ';') - 2);
            break;
        }
    }

    fclose($stream);

    return $songtext;
}

ini_set('display_errors', 1);
header('Content-type: application/json');


问:
Entity Framework foreign key when name doesn't match
I have a table called AccountValues that I would like to reference from my Account table. However rather than using AccountValuesId and AccountValues, I would like it to be a little more descriptive by prefixing MostRecent_ as follows:

```<code>[ForeignKey("AccountValues")]
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }
</code>```

My question is where should I place my ForeignKey attribute, so that I end up with an actual foreign key (e.g. FK_Something) and also have MostRecent_AccountValues automagically work?

Note: my convention is not to have plural table names. But here AccountValues is plural only because each row has a number of different values in it.

答:
Problem is in your ForeignKey name on the public long MostRecent_AccountValuesId property. ForeignKey name should match the navigation property name as follows:

```<code>[ForeignKey("MostRecent_AccountValues")] // <-- Here it is
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }
</code>```

Body:
I have a table called AccountValues that I would like to reference from my Account table. However rather than using AccountValuesId and AccountValues, I would like it to be a little more descriptive by prefixing MostRecent_ as follows:

[ForeignKey("AccountValues")]
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }

My question is where should I place my ForeignKey attribute, so that I end up with an actual foreign key (e.g. FK_Something) and also have MostRecent_AccountValues automagically work?

Note: my convention is not to have plural table names. But here AccountValues is plural only because each row has a number of different values in it.

Body:
Problem is in your ForeignKey name on the public long MostRecent_AccountValuesId property. ForeignKey name should match the navigation property name as follows:

[ForeignKey("MostRecent_AccountValues")] // <-- Here it is
public long MostRecent_AccountValuesId { get; set; }
public AccountValues MostRecent_AccountValues { get; set; }


问:
Getting Serialization exception while consuming from Kafka queue using Spring Boot
I am using Spring Boot with Kafka to consume messages from Kafka queue.

However, if there is any error in Jackson parsing of the payload.

The message remains stuck and it keeps on re-attempting for consumption, giving parsing exception all the time.

I tried using ErrorHandlingDeserializer2 in Kafka configuration and also mapped error handler, but still, the problem persists.

```<code>@Configuration
@EnableKafka
public class KafkaConfig
{

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);

        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
        props.put(ErrorHandlingDeserializer2.KEY_DESERIALIZER_CLASS, StringDeserializer.class);

        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
        props.put(ErrorHandlingDeserializer2.VALUE_DESERIALIZER_CLASS, JsonDeserializer.class);

        props.put(ConsumerConfig.GROUP_ID_CONFIG, "${connecto.group-id}");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);

        return props;
    }

    @Bean
    public ConsumerFactory<String, UserDto> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(
                consumerConfigs(),
                new StringDeserializer(),
                new JsonDeserializer<>(UserDto.class));
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, UserDto> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, UserDto> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());

        factory.setErrorHandler(new MosaicKafkaErrorHandler());

        return factory;
    }

    @Bean
    public KafkaTemplate kafkaTemplate()
    {
        return new KafkaTemplate<>(producerFactory());
    }

    @Bean
    public ProducerFactory<String, UserSearchDto> producerFactory()
    {
        Map<String, Object> config = new HashMap<>();
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        config.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory<>(config);
    }
}

public class MosaicKafkaErrorHandler implements ContainerAwareErrorHandler{

@Override
public void handle(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
        MessageListenerContainer container) {
    thrownException.printStackTrace();

    }

}
</code>```

I want to have it implemented in a way where whenever a paring exception occurs then it should just log that message and proceed with next record rather than getting stuck with it.

Following is the error-

```<code>Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.gxxx.mxxx.common.dto.UserDetailsDto` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"field1":20000,"field2":20000,"type":""}')

at org.apache.kafka.clients.consumer.KafkaConsumer.pollForFetches(KafkaConsumer.java:1230)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1187)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1154)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:741)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:698)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition kafakaqueue.identify-1 at offset 326355379. If needed, please seek past the record to continue consumption.
</code>```

答:
To solve this problem, version 2.2 introduced the ErrorHandlingDeserializer2. This deserializer delegates to a real deserializer (key or value). If the delegate fails to deserialize the record content, the ErrorHandlingDeserializer2 returns a null value and a DeserializationException in a header that contains the cause and the raw bytes. When you use a record-level MessageListener, if the ConsumerRecord contains a DeserializationException header for either the key or value, the container’s ErrorHandler is called with the failed ConsumerRecord. The record is not passed to the listener.

However, since you are using an earlier version, you can use below hack.

```<code>     @Override
        public void handle(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
                MessageListenerContainer container) {
            thrownException.printStackTrace();
            if (thrownException instanceOf SerializationException){
                String s = thrownException.getMessage().split("Error deserializing key/value for partition ")[1].split(". If needed, please seek past the record to continue consumption.")[0];
                String topics = s.split("-")[0];
                int offset = Integer.valueOf(s.split("offset ")[1]);
                int partition = Integer.valueOf(s.split("-")[1].split(" at")[0]);

                TopicPartition topicPartition = new TopicPartition(topics, partition);
                consumer.seek(topicPartition, offset + 1);
               }
            }
</code>```

Body:
I am using Spring Boot with Kafka to consume messages from Kafka queue.

However, if there is any error in Jackson parsing of the payload.

The message remains stuck and it keeps on re-attempting for consumption, giving parsing exception all the time.

I tried using ErrorHandlingDeserializer2 in Kafka configuration and also mapped error handler, but still, the problem persists.

@Configuration
@EnableKafka
public class KafkaConfig
{

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);

        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
        props.put(ErrorHandlingDeserializer2.KEY_DESERIALIZER_CLASS, StringDeserializer.class);

        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
        props.put(ErrorHandlingDeserializer2.VALUE_DESERIALIZER_CLASS, JsonDeserializer.class);

        props.put(ConsumerConfig.GROUP_ID_CONFIG, "${connecto.group-id}");
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        props.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);

        return props;
    }

    @Bean
    public ConsumerFactory<String, UserDto> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(
                consumerConfigs(),
                new StringDeserializer(),
                new JsonDeserializer<>(UserDto.class));
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, UserDto> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, UserDto> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());

        factory.setErrorHandler(new MosaicKafkaErrorHandler());

        return factory;
    }

    @Bean
    public KafkaTemplate kafkaTemplate()
    {
        return new KafkaTemplate<>(producerFactory());
    }

    @Bean
    public ProducerFactory<String, UserSearchDto> producerFactory()
    {
        Map<String, Object> config = new HashMap<>();
        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        config.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory<>(config);
    }
}

public class MosaicKafkaErrorHandler implements ContainerAwareErrorHandler{

@Override
public void handle(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
        MessageListenerContainer container) {
    thrownException.printStackTrace();

    }

}

I want to have it implemented in a way where whenever a paring exception occurs then it should just log that message and proceed with next record rather than getting stuck with it.

Following is the error-

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.gxxx.mxxx.common.dto.UserDetailsDto` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"field1":20000,"field2":20000,"type":""}')

at org.apache.kafka.clients.consumer.KafkaConsumer.pollForFetches(KafkaConsumer.java:1230)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1187)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1154)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.pollAndInvoke(KafkaMessageListenerContainer.java:741)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:698)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
org.apache.kafka.common.errors.SerializationException: Error deserializing key/value for partition kafakaqueue.identify-1 at offset 326355379. If needed, please seek past the record to continue consumption.

Body:
To solve this problem, version 2.2 introduced the ErrorHandlingDeserializer2. This deserializer delegates to a real deserializer (key or value). If the delegate fails to deserialize the record content, the ErrorHandlingDeserializer2 returns a null value and a DeserializationException in a header that contains the cause and the raw bytes. When you use a record-level MessageListener, if the ConsumerRecord contains a DeserializationException header for either the key or value, the container’s ErrorHandler is called with the failed ConsumerRecord. The record is not passed to the listener.

However, since you are using an earlier version, you can use below hack.

     @Override
        public void handle(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
                MessageListenerContainer container) {
            thrownException.printStackTrace();
            if (thrownException instanceOf SerializationException){
                String s = thrownException.getMessage().split("Error deserializing key/value for partition ")[1].split(". If needed, please seek past the record to continue consumption.")[0];
                String topics = s.split("-")[0];
                int offset = Integer.valueOf(s.split("offset ")[1]);
                int partition = Integer.valueOf(s.split("-")[1].split(" at")[0]);

                TopicPartition topicPartition = new TopicPartition(topics, partition);
                consumer.seek(topicPartition, offset + 1);
               }
            }


问:
How to read multiple files from a directory, extract specific strings and ouput to an html file?
Greetings,

I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.

```<code>
#!/usr/local/bin/perl

use warnings;
use strict;
use Cwd;

print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;

open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";

# Evaluates the file and imports it into an array.
my @comment_array = ;
close(INPUT_FILE);
chomp @comment_array;
@comment_array = grep /^\s*#/g, @comment_array;

my $comment;

foreach $comment (@comment_array) {
        $comment =~ /####/; #Pattern match to grab only #s

# Prints comments to screen
Print results in html format

# Writes comments to output.html
Writes results to html file

}

close (OUTPUT);
</code>```

答:
Take it one step at a time.  You have a lot planned, but so far you haven't even changed your prompt string to ask for a directory.

To read the entered directory name, your:

```<code>my $perlfile =STDIN;
</code>```

gives an error (under use strict;).  Start by looking that error up (use diagnostics; automates this) and trying to figure out what you should be doing instead.

Once you can prompt for a directory name and print it out, then add code to open the directory and read the directory.  Directories can be opened and read with opendir and readdir.  Make sure you can read the directory and print out the filenames before going on to the next step.

Body:
Greetings,

I have the following code and am stuck on how I would proceed to modify it so it will ask for the directory, read all files in the directory, then extract specific strings and ouput to an html file? Thanks in advance.

#!/usr/local/bin/perl

use warnings;
use strict;
use Cwd;

print "Enter filename: "; # Should be Enter directory
my $perlfile =STDIN;

open INPUT_FILE, $perlfile || die "Could not open file: $!";
open OUTPUT, '>out.html' || die "Could not open file: $!";

# Evaluates the file and imports it into an array.
my @comment_array = ;
close(INPUT_FILE);
chomp @comment_array;
@comment_array = grep /^\s*#/g, @comment_array;

my $comment;

foreach $comment (@comment_array) {
        $comment =~ /####/; #Pattern match to grab only #s

# Prints comments to screen
Print results in html format

# Writes comments to output.html
Writes results to html file

}

close (OUTPUT);

Body:
Take it one step at a time.  You have a lot planned, but so far you haven't even changed your prompt string to ask for a directory.

To read the entered directory name, your:

my $perlfile =STDIN;

gives an error (under use strict;).  Start by looking that error up (use diagnostics; automates this) and trying to figure out what you should be doing instead.

Once you can prompt for a directory name and print it out, then add code to open the directory and read the directory.  Directories can be opened and read with opendir and readdir.  Make sure you can read the directory and print out the filenames before going on to the next step.


问:
Creating a new table with cumsum - code doesn't seem to be working?
So I am using dplyr to create a new data frame to plot: date in column 1, IDCount in column 2 and CumulativeIDCount in column 3. Here is the code that I am using to do it:

```<code>df2 <- df %>%
  group_by(Date)%>%
  summarise(IDCount =n(),CumulativeIDCount=cumsum(n()))
</code>```

but the cumulativeIDCount column isn't cumulative, it's exactly the same as the IDCount column. Where am I going wrong with this code?

答:
Most probably what you need is cumsum of IDCount after the grouping

```<code>library(dplyr)

df %>%
  group_by(Date)%>%
  summarise(IDCount =n()) %>%
  mutate(CumulativeIDCount = cumsum(IDCount))
</code>```

Body:
So I am using dplyr to create a new data frame to plot: date in column 1, IDCount in column 2 and CumulativeIDCount in column 3. Here is the code that I am using to do it:

df2 <- df %>%
  group_by(Date)%>%
  summarise(IDCount =n(),CumulativeIDCount=cumsum(n()))

but the cumulativeIDCount column isn't cumulative, it's exactly the same as the IDCount column. Where am I going wrong with this code?

Body:
Most probably what you need is cumsum of IDCount after the grouping

library(dplyr)

df %>%
  group_by(Date)%>%
  summarise(IDCount =n()) %>%
  mutate(CumulativeIDCount = cumsum(IDCount))


问:
What's the default color for placeholder text in UITextField?
Does anyone know what color a UITextField's placeholder text is, by default? I'm trying to set a UITextView's text to the same color. I've read elsewhere that it is UIColor.lightGrayColor() but it is actually a little lighter.

答:
Better to grab the color off of a text field dynamically in case it changes in the future. Default to 70% gray, which is pretty close

```<code>extension UITextField {
  var placeholderColor: UIColor {
    return attributedPlaceholder?.attributes(at: 0, effectiveRange: nil)[.foregroundColor] as? UIColor ?? UIColor(white: 0.7, alpha: 1)
  }
}
</code>```

Body:
Better to grab the color off of a text field dynamically in case it changes in the future. Default to 70% gray, which is pretty close

extension UITextField {
  var placeholderColor: UIColor {
    return attributedPlaceholder?.attributes(at: 0, effectiveRange: nil)[.foregroundColor] as? UIColor ?? UIColor(white: 0.7, alpha: 1)
  }
}


问:
Need to get output of 2 tables in one column using joins only
I have this scenario question which needs to be solved using joins only. can't use except,intersect or union.

sample code:

```<code>--demo setup
create table t1 (id int)
insert into t1 values (1),(2),(3)

create table t2 (id int)
insert into t2 values (4),(5),(6)

--join
select t1.id,t2.id
from t1 full outer join
t2 on t1.id=t2.id
</code>```

--after join i am getting

```<code>id          id
----------- -----------
1           NULL
2           NULL
3           NULL
NULL        4
NULL        5
NULL        6
</code>```

--But i need is

```<code>id
-----------
1
2
3
4
5
6
</code>```

Can someone help me with this ? i know this can be easily done using union but this challenge needs to be solved using joins only.

any help is appreciated ....

答:
--solved the challenge after adding case to the code.</p>

```<code>select case when t1.id is null then t2.id else t1.id end as id
from t1 full outer join
t2 on t1.id=t2.id
</code>```

Body:
I have this scenario question which needs to be solved using joins only. can't use except,intersect or union.

sample code:

--demo setup
create table t1 (id int)
insert into t1 values (1),(2),(3)

create table t2 (id int)
insert into t2 values (4),(5),(6)

--join
select t1.id,t2.id
from t1 full outer join
t2 on t1.id=t2.id

--after join i am getting

id          id
----------- -----------
1           NULL
2           NULL
3           NULL
NULL        4
NULL        5
NULL        6

--But i need is

id
-----------
1
2
3
4
5
6

Can someone help me with this ? i know this can be easily done using union but this challenge needs to be solved using joins only.

any help is appreciated ....

Body:
--solved the challenge after adding case to the code.

select case when t1.id is null then t2.id else t1.id end as id
from t1 full outer join
t2 on t1.id=t2.id


问:
ADODBCould not load type 'ADODB.FieldsToInternalFieldsMarshaler' from assembly
I'm trying to read an ADOBD.Recordset object like this (my first time, so pardon my "noobness" :D):

```<code>Presentation.Category categorySvc = new Presentation.Category();
ADODB.Recordset categories = categorySvc.ListAll("BE", "DUE", "EN", 128);
foreach (var category in categories.Fields) // here is where I get the exception
{
   // ...
}
</code>```

The ListAll call works fine - I get the Recordset with some data which I confirm that by doing a QuickWatch on the object. But when the code reach the categories.Fields I get the following exception:

Could not load type
  'ADODB.FieldsToInternalFieldsMarshaler'
  from assembly 'TestCOMCalls,
  Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'.

I googled this error (or just by 'ADODB.FieldsToInternalFieldsMarshaler' and couldn't find anything that would help me with issue).

I wonder, am I missing a reference? Besides the normal references I have added this one to my project:

ADODB
  Microsoft ActiveX Data Objects 2.5 Library
  C:\WINDOWS\assembly\GAC\ADODB\7.0.3300.0__b03f5f7f11d50a3a\ADODB.dll

Like I said, I've never done this before but by googling a bit I was able to see some people doing this (foreach on the object.Fields) and it seem to work for them.

Any help or direction is greatly appreciated :)

Thanks!

答: I got this problem clearing temporary file(VS 2017). Solution for this exception you need to change Solution Explorer > References > adodb > "Then Right click and choose properties" > Embed Interop Types, set "True" to "False"

Body:
I'm trying to read an ADOBD.Recordset object like this (my first time, so pardon my "noobness" :D):

Presentation.Category categorySvc = new Presentation.Category();
ADODB.Recordset categories = categorySvc.ListAll("BE", "DUE", "EN", 128);
foreach (var category in categories.Fields) // here is where I get the exception
{
   // ...
}

The ListAll call works fine - I get the Recordset with some data which I confirm that by doing a QuickWatch on the object. But when the code reach the categories.Fields I get the following exception:

Could not load type
  'ADODB.FieldsToInternalFieldsMarshaler'
  from assembly 'TestCOMCalls,
  Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'.

I googled this error (or just by 'ADODB.FieldsToInternalFieldsMarshaler' and couldn't find anything that would help me with issue).

I wonder, am I missing a reference? Besides the normal references I have added this one to my project:

ADODB
  Microsoft ActiveX Data Objects 2.5 Library
  C:\WINDOWS\assembly\GAC\ADODB\7.0.3300.0__b03f5f7f11d50a3a\ADODB.dll

Like I said, I've never done this before but by googling a bit I was able to see some people doing this (foreach on the object.Fields) and it seem to work for them.

Any help or direction is greatly appreciated :)

Thanks!


问:
Why we should check for the variable being defined var m = m || function(){}
Lot of libraries i have seen methods defined like this

```<code>Common.deepCopy = Common.deepCopy || function(oldObject) {
        return $.extend(true, {}, oldObject);
    };
</code>```

What is the need of defining methods are objects like this.

Because the js files will be executed only once so there is no chance of deepCopy being defined previously.

答: It's just in case it's already been defined in another file, or if the script runs more than once.</p>

Body:
Lot of libraries i have seen methods defined like this

Common.deepCopy = Common.deepCopy || function(oldObject) {
        return $.extend(true, {}, oldObject);
    };

What is the need of defining methods are objects like this.

Because the js files will be executed only once so there is no chance of deepCopy being defined previously.


问:
Prevent "fragmentation" of wrapped text next to floated image
I'm trying to get this text to not "fragment" on smaller resolutions. It's for an assignment, and I'm restricted to using XHTML.

The image to the right is floated like this:

#image {
    width:420px;
    margin-left: 2%;
    height:370px;
    position:relative;
    float:right;
}
```

<p>with the XHTML:</p>

```

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Obviously this "fragmentation" doesn't appear on larger resolutions.

Is there an elegant way to this in CSS2.1?

答:
Nice solution @BryceHowitson.

I have just been grappling with this problem and came up with a variant on your approach. I put the Media query on the paragraph of text that followed the image.

My solution targets the clear property on the paragraph that follows the floated image. When the screen resolution leaves enough space beside the floated image for satisfactory rendering of the text, the paragraph wraps around the image. When the available width is too low for satisfactory rendering of the text, the paragraph has "clear:both" applied and the paragraph moves down below the floated image.

One 'pro' for this approach is that the CSS rule is applied to the element whose behavior we are trying to control.

However, what @BryceHowitson's solution achieves, and mine doesn't, is the centering of the image when the wrapping of the subsequent text is turned off.

CSS

```<code>.p-clear {
    @media (min-width: 400px) {
        clear: none;
    }
    @media (max-width: 400px) {
        clear: both;
    }
}
</code>```

HTML

```<code><img src="..." width="300px">
<p class="p-clear">text that needs at least 100px width</p>
</code>```

Body:
I'm trying to get this text to not "fragment" on smaller resolutions. It's for an assignment, and I'm restricted to using XHTML.

The image to the right is floated like this:

#image {
    width:420px;
    margin-left: 2%;
    height:370px;
    position:relative;
    float:right;
}

with the XHTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Obviously this "fragmentation" doesn't appear on larger resolutions.

Is there an elegant way to this in CSS2.1?

Body:
Nice solution @BryceHowitson.

I have just been grappling with this problem and came up with a variant on your approach. I put the Media query on the paragraph of text that followed the image.

My solution targets the clear property on the paragraph that follows the floated image. When the screen resolution leaves enough space beside the floated image for satisfactory rendering of the text, the paragraph wraps around the image. When the available width is too low for satisfactory rendering of the text, the paragraph has "clear:both" applied and the paragraph moves down below the floated image.

One 'pro' for this approach is that the CSS rule is applied to the element whose behavior we are trying to control.

However, what @BryceHowitson's solution achieves, and mine doesn't, is the centering of the image when the wrapping of the subsequent text is turned off.

CSS

.p-clear {
    @media (min-width: 400px) {
        clear: none;
    }
    @media (max-width: 400px) {
        clear: both;
    }
}

HTML

<img src="..." width="300px">
<p class="p-clear">text that needs at least 100px width</p>


问:
Set multiple domains in one wordpress
I have wordpress in this domain:

```<code>http://www.Dummy.com/en
</code>```

And want to use second domain such this:

```<code> http://www.Dummy2.com
</code>```

for this wordpress.

How can I redirect Dummy2 to Dummy?

This is some codes that I find out but I couldn't understand them:

wp-config.php

```<code>define('WP_SITEURL', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
define('WP_HOME', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
</code>```

答:
It is not a good practice, but:</p>

```<code>$host = $_SERVER['HTTP_HOST'];
switch ($host) {
  case 'www.Dummy.com/en':
    define('WP_HOME', 'http://www.Dummy.com/en/');
  break;
  case 'www.Dummy2.com':
    define('WP_HOME', 'http://www.Dummy2.com/');
  break;
  default:
    define('WP_HOME', 'http://www.Dummy2.com/');
  break;
}

define('WP_SITEURL', WP_HOME);
</code>```

Title: Set multiple domains in one wordpress

Body:
I have wordpress in this domain:

http://www.Dummy.com/en

And want to use second domain such this:

 http://www.Dummy2.com

for this wordpress.

How can I redirect Dummy2 to Dummy?

This is some codes that I find out but I couldn't understand them:

wp-config.php

define('WP_SITEURL', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
define('WP_HOME', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);

Body:
It is not a good practice, but:

$host = $_SERVER['HTTP_HOST'];
switch ($host) {
  case 'www.Dummy.com/en':
    define('WP_HOME', 'http://www.Dummy.com/en/');
  break;
  case 'www.Dummy2.com':
    define('WP_HOME', 'http://www.Dummy2.com/');
  break;
  default:
    define('WP_HOME', 'http://www.Dummy2.com/');
  break;
}

define('WP_SITEURL', WP_HOME);