问:
Getting markdown email as a plain text
I am using laravel Mailable and markdown to send an email but it send an email like below,
not getting what I am doing wrong.

```<code>Hello cus1
    Please click the button below to verify your email address.

    <table class="action" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
    <tr>
        <td align="center">
            <table width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation">
                <tr>
                    <td align="center">
                        <table border="0" cellpadding="0" cellspacing="0" role="presentation">
                            <tr>
                                <td>
                                    <a href="https://google.com" class="button button-primary"
                                       target="_blank">Verify Email Address</a>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>

    If you did not create an account, no further action is required.

    Thanks,<br>
    PMS
</code>```

Below is my welcome_email.blade.php used to generate email template

```<code>@component('mail::message')
    # Hello {{ $user->name }},

    Please click the button below to verify your email address.

    @component('mail::button', ['url' => $verificationUrl])
        Verify Email Address
    @endcomponent

    If you did not create an account, no further action is required.

    Thanks,<br>
    {{ config('app.name') }}
@endcomponent
</code>```

答:
You should try removing the indentation inside the blade file. Sometimes the markdown gets crazy because of that.

Try something like this:

```<code>@component('mail::message')
# Hello {{ $user->name }},

Please click the button below to verify your email address.

@component('mail::button', ['url' => $verificationUrl])
Verify Email Address
@endcomponent

If you did not create an account, no further action is required.

Thanks,<br>
{{ config('app.name') }}
@endcomponent
</code>```

Title: Getting markdown email as a plain text

Body:
I am using laravel Mailable and markdown to send an email but it send an email like below,
not getting what I am doing wrong.

Hello cus1
    Please click the button below to verify your email address.

                                    Verify Email Address

    If you did not create an account, no further action is required.

    Thanks,

    PMS

Below is my welcome_email.blade.php used to generate email template

@component('mail::message')
    # Hello {{ $user->name }},

    Please click the button below to verify your email address.

    @component('mail::button', ['url' => $verificationUrl])
        Verify Email Address
    @endcomponent

    If you did not create an account, no further action is required.

    Thanks,

    {{ config('app.name') }}
@endcomponent

Body:
You should try removing the indentation inside the blade file. Sometimes the markdown gets crazy because of that.

Try something like this:

@component('mail::message')
# Hello {{ $user->name }},

Please click the button below to verify your email address.

@component('mail::button', ['url' => $verificationUrl])
Verify Email Address
@endcomponent

If you did not create an account, no further action is required.

Thanks,<br>
{{ config('app.name') }}
@endcomponent


来源: stackexchange

问:
Programmatically saving a SQL Server database to xml files and restoring it again
I want to save a whole MS SQL 2008 Database into XML files... using asp.net.

Now I am bit lost here.. what would be the best method to achieve this? Datasets?

And I need to restore the database later again.. using these XML files. I am thinking about using datasets for reading the tables and writing to xml and using the SQLBulkCopy class to restore the database again. But I am not sure whether this would be the right approach..

Any clues and tips for me?

答:
Red Gate's SQL Packager lets you package a database into an exe or to a VS project, so you might want to take a look at that. You can specify which tables you want to consider for data.

Is there any specific reason you want to do this using xml?

ContentLicense: CC BY-SA 3.0


问:
Show column names of the table in 1st data row of the query output dynamically in Oracle
There is one table , let us say VW_RESULT like below :

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

Now I have to show the column names in the 1st row.

I want output like this :

Col1      Col2      Col3

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

I can easily achieve this if the number of columns is fixed, using UNION ALL.

But the number of columns will vary from time to time.

I want to make this dynamic so that I don't have to put column names manually.

I am using Oracle 11g.

答:
To achieve your requirement, all your datatype should be string as all the columns are strings. In case if any of your datatype is other than string it will not work. Eg: ID column seems to be integer datatype, if you are trying to merge 'ID' string into ID column, according to SQL standard, it will fail. However below is the solution if all the columns in the respective table is in string format.</p>

```<code>declare

v_Sql1 varchar(1000);
v_Sql2 varchar(1000);

begin

select  (LISTAGG(chr(39)||column_name||chr(39), ',') WITHIN GROUP (ORDER BY
column_id)) into v_Sql1 from cols where table_name = 'VW_RESULT';

v_Sql2:= 'select * from
(select  column_name from cols where table_name = ''VW_RESULT'')
pivot
(
max(column_name)
for column_name in (' || v_Sql1 || '))
union select * from VW_RESULT';

dbms_output.put_line(v_Sql1);
dbms_output.put_line(v_Sql2);

execute immediate v_Sql2;

end;
/
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To achieve your requirement, all your datatype should be string as all the columns are strings. In case if any of your datatype is other than string it will not work. Eg: ID column seems to be integer datatype, if you are trying to merge 'ID' string into ID column, according to SQL standard, it will fail. However below is the solution if all the columns in the respective table is in string format.

declare

v_Sql1 varchar(1000);
v_Sql2 varchar(1000);

begin

select  (LISTAGG(chr(39)||column_name||chr(39), ',') WITHIN GROUP (ORDER BY
column_id)) into v_Sql1 from cols where table_name = 'VW_RESULT';

v_Sql2:= 'select * from
(select  column_name from cols where table_name = ''VW_RESULT'')
pivot
(
max(column_name)
for column_name in (' || v_Sql1 || '))
union select * from VW_RESULT';

dbms_output.put_line(v_Sql1);
dbms_output.put_line(v_Sql2);

execute immediate v_Sql2;

end;
/


问:
Mocking a method with prophet
Assume there is a method

```<code>public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}
</code>```

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

```<code>    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;
</code>```

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?

答: For arbitrary parameters you could take a look at Faker library. It generates arbitrary fake data for you.</p>

Title: Mocking a method with prophet

Body:
Assume there is a method

public function updateTimestamp($sessionId, $data)
{
    return $this->memcached->touch($sessionId, time() + $this->ttl);
}

that I'd like to test. Infection changes the + in time() + $this->ttl to - and all my tests are still passing. So I'd like to make a test that will mock Memcached's touch in it and will conditionally return true/false basing on the second argument passed to it.

So doing something like:

    // $ttl is set;
    $memcachedMock
        ->touch(
            'sessionId',
            $certainValuePassedToTouch
        )
        ->willReturn(
            $certainValuePassedToTouch >= time() + $ttl
                ? true
                : false
        )
        ;

There are two problems now:

I don't know how to make such a condition for an arbitrary integer parameter passed to the method being mocked

basing on time() seems to be very unreliable, so how can I reliably test it if time() is used in the method itself?


问:
TypeScript: Firestore withConverter and refrences
I am fairly new to Firestore/Firebase. I have this Album class that can hold a reference to a parent Album

```<code>export class Album {
    constructor(public id: string,
                public title: string,
                public parent: Album | null,
    ) {
    }
}

export class AlbumConverter implements FirestoreDataConverter<ImageData> {
    toFirestore(album: Album): firebase.firestore.DocumentData {
        return {
            id: album.id,
            title: album.title,
            parent: album.parent ?.....
</code>```

My question is, how should I implement the toFirestore and fromFirestore? what's the proper way to use DataConverter when dealing with references?

Thank you!

答:
You must pass a DocumentReference as parent.

To get the reference you can do for exemple :

```<code>   function getRef = (id: string): Promise<any> {
        return new Promise<Track>(async (resolve, reject) => {
            const query = this.db.collection(this.collectionPath).where('id', '==', id);
            const querySnapshot = await query.get();

            if (querySnapshot.empty) {
                return reject("not found")
            }

            return resolve(querySnapshot.docs[0].ref);
        });
    }
</code>```

And then :

```<code>const parentRef = await getRef(parentId);

const albumConverter = {
    toFirestore: (album: Album) => {
        return {
            id: album.id,
            title: album.title,
            parent: parentRef
        }
    }
}
</code>```

Body:
I am fairly new to Firestore/Firebase. I have this Album class that can hold a reference to a parent Album

export class Album {
    constructor(public id: string,
                public title: string,
                public parent: Album | null,
    ) {
    }
}

export class AlbumConverter implements FirestoreDataConverter<ImageData> {
    toFirestore(album: Album): firebase.firestore.DocumentData {
        return {
            id: album.id,
            title: album.title,
            parent: album.parent ?.....

My question is, how should I implement the toFirestore and fromFirestore? what's the proper way to use DataConverter when dealing with references?

Thank you!

Body:
You must pass a DocumentReference as parent.

To get the reference you can do for exemple :

   function getRef = (id: string): Promise<any> {
        return new Promise<Track>(async (resolve, reject) => {
            const query = this.db.collection(this.collectionPath).where('id', '==', id);
            const querySnapshot = await query.get();

            if (querySnapshot.empty) {
                return reject("not found")
            }

            return resolve(querySnapshot.docs[0].ref);
        });
    }

And then :

const parentRef = await getRef(parentId);

const albumConverter = {
    toFirestore: (album: Album) => {
        return {
            id: album.id,
            title: album.title,
            parent: parentRef
        }
    }
}


问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答:
math.h is part of the Standard C Library.

If you are interested in source code, the GNU C Library (glibc) is available to inspect.

EDIT TO ADD:

As others have said, math functions are typically implemented at the hardware level.

Title: Implementation of ceil() and floor()


问:
Is there a way to pretty print SELECT query result in ClickHouse?
Alternative in ClickHouse Select query to pretty print like in MySQL vertically.

For example -

SELECT * from table \g;
```

<p>I found this resource but its just text
https://clickhouse-docs.readthedocs.io/en/latest/formats/vertical.html</p>

<p>With --multiline as a parameter for clickhouse-client I am getting following error . Though i can use \G format as per one of the answer without this param :</p>

``` :) select * from hits_v1 limit 2; \G
:-] ;

Syntax error (Multi-statements are not allowed): failed at position 30 (end of query):

select * from hits_v1 limit 2; \G ;
```

答:
ClickHouse supports this feature:

You can specify \G instead of or after the semicolon. This indicates Vertical format.

select * from numbers(2)\G
/* result
Row 1:
──────
number: 0

Row 2:
──────
number: 1
*/
```

<pre class="lang-sql prettyprint-override"><code>select * from numbers(2);\G
/* result
Row 1:
──────
number: 0

Row 2:
──────
number: 1
*/
</code>```

Body:
Alternative in ClickHouse Select query to pretty print like in MySQL vertically.

For example -

SELECT * from table \g;

I found this resource but its just text
https://clickhouse-docs.readthedocs.io/en/latest/formats/vertical.html

With --multiline as a parameter for clickhouse-client I am getting following error . Though i can use \G format as per one of the answer without this param :

 :) select * from hits_v1 limit 2; \G
:-] ;

Syntax error (Multi-statements are not allowed): failed at position 30 (end of query):

select * from hits_v1 limit 2; \G ;

Body:
ClickHouse supports this feature:

You can specify \G instead of or after the semicolon. This indicates Vertical format.

select * from numbers(2)\G
/* result
Row 1:
──────
number: 0

Row 2:
──────
number: 1
*/

select * from numbers(2);\G
/* result
Row 1:
──────
number: 0

Row 2:
──────
number: 1
*/


问:
How to simulate mouse events to test Directive in Angular
I am trying to test a column resizable directive which listens to mouse events like mouseup, mousemove, mousedown.

resize-column.directive.ts

```<code>import { Directive, OnInit, Renderer2, Input, ElementRef, HostListener } from "@angular/core";

@Directive({
  selector: "[resizeColumn]"
})
export class ResizeColumnDirective implements OnInit {

  @Input() index: number;
  private startX: number;
  private startWidth: number;
  private column: HTMLElement;
  private table: HTMLElement;
  private pressed: boolean;

  constructor(private renderer: Renderer2, private el: ElementRef) {
    this.column = this.el.nativeElement;
  }

  ngOnInit() {
    if (this.resizable) {
      const row = this.renderer.parentNode(this.column);
      this.table = this.renderer.parentNode(row);

      const resizer = this.renderer.createElement("span");
      this.renderer.addClass(resizer, "resize-holder");
      this.renderer.appendChild(this.column, resizer);
      this.renderer.listen(resizer, "mousedown", this.onMouseDown);
    }
  }

  onMouseDown = (event: MouseEvent) => {
    this.pressed = true;
    this.startX = event.pageX;
    this.startWidth = this.column.offsetWidth;
  };

  @HostListener('document: mousemove')
  onMouseMove(event: MouseEvent) {
    const offset = 35;
    if (this.pressed && event.buttons) {
      this.renderer.addClass(this.table, "resizing");

      // Calculate width of column
      let width =
        this.startWidth + (event.pageX - this.startX - offset);

      const tableCells = Array.from(this.table.querySelectorAll(".custom-row")).map(
        (row: any) => row.querySelectorAll(".custom-cell").item(this.index)
      );

      // Set table header width
      this.renderer.setStyle(this.column, "max-width", `${width}px`);
      this.renderer.setStyle(this.column, "flex-basis", `${width}px`);

      // Set table cells width
      for (const cell of tableCells) {
        this.renderer.setStyle(cell, "max-width", `${width}px`);
        this.renderer.setStyle(cell, "flex-basis", `${width}px`);
      }
    }
  };

  @HostListener('document: mouseup')
  onMouseUp(){
    if (this.pressed) {
      this.pressed = false;
      this.renderer.removeClass(this.table, "resizing");
    }
  };
}
</code>```

I want to create unit test for this directive but I am not able to simulate mouse events. I am using triggerEventHandler to handle events but I am not able to update the values of max-width and flex-basis after simulating mousedown and mousemove.

resize-column.directive.spec.ts

```<code>import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ResizeColumnDirective } from './resize-column.directive';

@Component({
    template: `
    <custom-table>
        <custom-row>
            <custom-header *ngFor="let column of displayedColumns; let i = index"
                 resizeColumn [index]="i">
                {{column.label}}
            </custom-header>
        </custom-row>
        <custom-row *ngFor="let row of rowDatas">
            <custom-cell *ngFor="let column of displayedColumns">{{row[column.field]}}
            </custom-cell>
        </custom-row>
    </custom-table>`
})
class TestComponent {
    displayedColumns = [
        { field: 'name', label: 'Name' },
        { field: 'sex', label: 'Sex' },
        { field: 'age', label: 'Age' }
    ];

    rowDatas = [{
        name: 'Albert',
        sex: 'M',
        age: '20'
    }.....];
}

describe('RsizableDirective', () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ResizeColumnDirective, TestComponent, table component components....]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create component', () => {
        expect(component).toBeDefined();
    });

    it('should update the flex and max-width value on mouse move', () => {
        const headerEl = fixture.debugElement.query(By.css('custom-header'));
        console.log(headerEl.nativeElement.style.flex);
        headerEl.triggerEventHandler('mousedown', { pageX: 50 });
        headerEl.triggerEventHandler('mousemove', { pageX: 150 });
        fixture.detectChanges();
        console.log(headerEl.nativeElement.style.flex);
    });
});
</code>```

Please help me on how to test this directive and suggest is there any better way to write test for this as I am new to Jasmine. Thanks in advance.

答:
Try to use

```<code>headerEl.dispatchEvent(new MouseEvent('mousemove', {clientX: 50, clientY: 150}));
</code>```

or

```<code>headerEl.dispatchEvent(new Event('mousemove', {pageX: 50, pageY: 150}));
</code>```

Update:

I've checked your code, there're two points here:

You should use document.dispatchEvent(new MouseEvent('mousemove',
{clientX: 50, clientY: 150, buttons: 1})) to simulate mouse move event

Add '$event' to your @HostListener to prevent undefined in a handler

```<code>@HostListener('document: mousemove', ['$event'])
onMouseMove(event: MouseEvent) {
  const offset = 35;
  if (this.pressed && event.buttons) {
    //your code
  }
};
</code>```

Keep in mind that the variable pressed should be true to make your code work

Body:
I am trying to test a column resizable directive which listens to mouse events like mouseup, mousemove, mousedown.

resize-column.directive.ts

import { Directive, OnInit, Renderer2, Input, ElementRef, HostListener } from "@angular/core";

@Directive({
  selector: "[resizeColumn]"
})
export class ResizeColumnDirective implements OnInit {

  @Input() index: number;
  private startX: number;
  private startWidth: number;
  private column: HTMLElement;
  private table: HTMLElement;
  private pressed: boolean;

  constructor(private renderer: Renderer2, private el: ElementRef) {
    this.column = this.el.nativeElement;
  }

  ngOnInit() {
    if (this.resizable) {
      const row = this.renderer.parentNode(this.column);
      this.table = this.renderer.parentNode(row);

      const resizer = this.renderer.createElement("span");
      this.renderer.addClass(resizer, "resize-holder");
      this.renderer.appendChild(this.column, resizer);
      this.renderer.listen(resizer, "mousedown", this.onMouseDown);
    }
  }

  onMouseDown = (event: MouseEvent) => {
    this.pressed = true;
    this.startX = event.pageX;
    this.startWidth = this.column.offsetWidth;
  };

  @HostListener('document: mousemove')
  onMouseMove(event: MouseEvent) {
    const offset = 35;
    if (this.pressed && event.buttons) {
      this.renderer.addClass(this.table, "resizing");

      // Calculate width of column
      let width =
        this.startWidth + (event.pageX - this.startX - offset);

      const tableCells = Array.from(this.table.querySelectorAll(".custom-row")).map(
        (row: any) => row.querySelectorAll(".custom-cell").item(this.index)
      );

      // Set table header width
      this.renderer.setStyle(this.column, "max-width", `${width}px`);
      this.renderer.setStyle(this.column, "flex-basis", `${width}px`);

      // Set table cells width
      for (const cell of tableCells) {
        this.renderer.setStyle(cell, "max-width", `${width}px`);
        this.renderer.setStyle(cell, "flex-basis", `${width}px`);
      }
    }
  };

  @HostListener('document: mouseup')
  onMouseUp(){
    if (this.pressed) {
      this.pressed = false;
      this.renderer.removeClass(this.table, "resizing");
    }
  };
}

I want to create unit test for this directive but I am not able to simulate mouse events. I am using triggerEventHandler to handle events but I am not able to update the values of max-width and flex-basis after simulating mousedown and mousemove.

resize-column.directive.spec.ts

import { Component, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ResizeColumnDirective } from './resize-column.directive';

@Component({
    template: `
    <custom-table>
        <custom-row>
            <custom-header *ngFor="let column of displayedColumns; let i = index"
                 resizeColumn [index]="i">
                {{column.label}}
            </custom-header>
        </custom-row>
        <custom-row *ngFor="let row of rowDatas">
            <custom-cell *ngFor="let column of displayedColumns">{{row[column.field]}}
            </custom-cell>
        </custom-row>
    </custom-table>`
})
class TestComponent {
    displayedColumns = [
        { field: 'name', label: 'Name' },
        { field: 'sex', label: 'Sex' },
        { field: 'age', label: 'Age' }
    ];

    rowDatas = [{
        name: 'Albert',
        sex: 'M',
        age: '20'
    }.....];
}

describe('RsizableDirective', () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ResizeColumnDirective, TestComponent, table component components....]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create component', () => {
        expect(component).toBeDefined();
    });

    it('should update the flex and max-width value on mouse move', () => {
        const headerEl = fixture.debugElement.query(By.css('custom-header'));
        console.log(headerEl.nativeElement.style.flex);
        headerEl.triggerEventHandler('mousedown', { pageX: 50 });
        headerEl.triggerEventHandler('mousemove', { pageX: 150 });
        fixture.detectChanges();
        console.log(headerEl.nativeElement.style.flex);
    });
});

Please help me on how to test this directive and suggest is there any better way to write test for this as I am new to Jasmine. Thanks in advance.

Body:
Try to use

headerEl.dispatchEvent(new MouseEvent('mousemove', {clientX: 50, clientY: 150}));

or

headerEl.dispatchEvent(new Event('mousemove', {pageX: 50, pageY: 150}));

Update:

I've checked your code, there're two points here:

You should use document.dispatchEvent(new MouseEvent('mousemove',
{clientX: 50, clientY: 150, buttons: 1})) to simulate mouse move event

Add '$event' to your @HostListener to prevent undefined in a handler

@HostListener('document: mousemove', ['$event'])
onMouseMove(event: MouseEvent) {
  const offset = 35;
  if (this.pressed && event.buttons) {
    //your code
  }
};

Keep in mind that the variable pressed should be true to make your code work


问:
How do I can tranform a cataegorical variable to continuos variable in R?
I have a DataFrame with many variables such as percentage, year, hectares and others, but I have one that is the distance, I am evaluating the direct impact (area directly impacted) and the extent of this impact by buffers in km around the direct impact and I compare it to the control.
I have:

At this point, my variables are categorical, even though they represent distances.

```<code> Distances:"dirImpct",1km","2km","3km","4km","5km","6km","7km","8km","9km","10km","20km","30km","40km","50km","60km","70km", "controle")
</code>```

I want something like this:

```<code>Distances:  dirImpct < km < control
DirImpact= distance  0
km= distances, (1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70)
control= distances > 70
</code>```

Body:
I have a DataFrame with many variables such as percentage, year, hectares and others, but I have one that is the distance, I am evaluating the direct impact (area directly impacted) and the extent of this impact by buffers in km around the direct impact and I compare it to the control.
I have:

At this point, my variables are categorical, even though they represent distances.

 Distances:"dirImpct",1km","2km","3km","4km","5km","6km","7km","8km","9km","10km","20km","30km","40km","50km","60km","70km", "controle")

I want something like this:

Distances:  dirImpct < km < control
DirImpact= distance  0
km= distances, (1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70)
control= distances > 70

Body:
You may transform to factor and rename the levels.

dat$Distances <- factor(dat$Distances)
lvl <- levels(dat$Distances)
levels(dat$Distances)[c(length(lvl) - 1, length(lvl))] <-
  c("0", "dist > 70")
dat
#             x Distances
# 1  -0.5448391 dist > 70
# 2  -0.7178019       1km
# 3   0.8157044       2km
# 4   0.2789727       3km
# 5   0.4940412       4km
# 6   0.4096203       5km
# 7  -0.9503315       6km
# 8  -0.3750518       7km
# 9   0.3385260       8km
# 10  0.3666900       9km
# 11  0.9265970      10km
# 12  0.2554600      20km
# 13  1.4776808      30km
# 14 -0.3211048      40km
# 15 -0.9469399      50km
# 16 -0.1853323      60km
# 17 -0.4438878      70km
# 18 -1.0206900         0

Data:

dat <- data.frame(x=rnorm(length(Distances)),
           Distances=c("dirImpct","1km","2km","3km","4km","5km","6km","7km",
                      "8km","9km","10km","20km","30km","40km","50km","60km",
                      "70km", "controle")
)


问:
Integrating openID and oauth as website login, signin and authentication system
First of all let me start by saying that this question is not about different openID and oAuth implementations. There are many classes about these.

My question is what to do after authenticating a user:

How to add this user to the user table in the database?

How to handle different logins for the same user? (Remy Sharp's example suggests
something for openID)

How to combine oAuth and openID in the database?

Any ideas?

答: The most simple way would seem for me, to have a basic user table, where you add the user at register and have a extra 1:n table where you save possible authentications. Maybe you need more than one table, if there are methods, which need way more columns than others.</p>


问:
PHP EOF showing only one result

Possible Duplicate:

  PHP EOF shows only one result from loop

Hello

Seems like I can not find the solution for such problem.

I am using the following code.

it should display all the results given by the mySQL loop in the EOF.

But it is showing only the first results, nothing else.

What I am doing wrong?

Please help me

```<code>function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "<div id=\"menu\" style=\"display:none;\"><li><a href=\"".$site['url'].$rowYiBmenu['linkHref']."\" onMouseOut=\"javascript: $('#menu').hide('9000');\"><img class=\"imgmenu\" src=\"".$site['url'].$rowYiBmenu['linkIcon']."\">".$rowYiBmenu['linkTitle']."</a></li></div>";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF
<div style="width:520px; background-color: #EEE; height:30px;">
{$menu}
</div>
EOF;
return $bannerCode;
}
</code>```

答:
Though this won't fix your issue, I see you are using mysql_fetch_array(). This is rather pointless, as you are doing associative matching afterwards ($rowYiBmenu['linkHref'], for example). It will work for you, but it's a waste of resources, as the results will be loaded in a numeric array as well (making the $rowYiBmenu array twice as large, just wasting memory).

Also, you didn't declare the $menu variable, you just 'added on'. Before the while statement, put $menu = ''; (or anything else that will declare an empty string for that variable).

Lastly, use single quotes around html strings. That way you don't have to keep escaping double quotes for when adding an attribute. For example, the $menu line in the while statement should look like this:

```<code>$menu .= '<div id="menu" style="display:none;"><li><a href="'.$site['url'].$rowYiBmenu['linkHref'].'" onMouseOut="javascript: $(\'#menu\').hide(9000);"><img class="imgmenu" src="'.$site['url'].$rowYiBmenu['linkIcon'].'">'.$rowYiBmenu['linkTitle'].'</a></li></div>';
</code>```

I'm not sure if I helped you with your problem at all, but I thought this would help you clean up your code a bit (the cleaner the code, the less prone to errors and the easier it is to spot errors).

Title: PHP EOF showing only one result

Body:
Possible Duplicate:

  PHP EOF shows only one result from loop

Hello

Seems like I can not find the solution for such problem.

I am using the following code.

it should display all the results given by the mySQL loop in the EOF.

But it is showing only the first results, nothing else.

What I am doing wrong?

Please help me

function getYiBAdminBanner() {
global $site;
global $dir;
$queryYiBmenu = "SELECT * FROM `(YiB)_cPanel_Menu` WHERE Type = 'top'";
$resultYiBmenu=mysql_query($queryYiBmenu) or die("Errore select menu: ".mysql_error());
$countYiBmenu = mysql_num_rows($resultYiBmenu);
while($rowYiBmenu = mysql_fetch_array($resultYiBmenu)) {
$menu .= "

".$rowYiBmenu['linkTitle']."

";
}
if($countYiBmenu <= 0){
$menu = "No Modules Installed";
}
$bannerCode .= <<<EOF

{$menu}

EOF;
return $bannerCode;
}

Body:
Though this won't fix your issue, I see you are using mysql_fetch_array(). This is rather pointless, as you are doing associative matching afterwards ($rowYiBmenu['linkHref'], for example). It will work for you, but it's a waste of resources, as the results will be loaded in a numeric array as well (making the $rowYiBmenu array twice as large, just wasting memory).

Also, you didn't declare the $menu variable, you just 'added on'. Before the while statement, put $menu = ''; (or anything else that will declare an empty string for that variable).

Lastly, use single quotes around html strings. That way you don't have to keep escaping double quotes for when adding an attribute. For example, the $menu line in the while statement should look like this:

$menu .= '<div id="menu" style="display:none;"><li><a href="'.$site['url'].$rowYiBmenu['linkHref'].'" onMouseOut="javascript: $(\'#menu\').hide(9000);"><img class="imgmenu" src="'.$site['url'].$rowYiBmenu['linkIcon'].'">'.$rowYiBmenu['linkTitle'].'</a></li></div>';

I'm not sure if I helped you with your problem at all, but I thought this would help you clean up your code a bit (the cleaner the code, the less prone to errors and the easier it is to spot errors).


问:
Parsing Data from Access to Excel via vba code to split onto sheets based on field contents
I have been trying to find a way to adapt the code i have written (based heavily on the Youtube video and coding provided by Access Jitsu to split my data across mutliple sheets based on the value in one field.
I have a number of fields and the purpose is for a comparison between invoicing and costs which i want to split by years onto separate sheets in excel.

Can anyone assist with how i would parse the field to split the data onto individual sheets based on the Year (in the code [Yr]) field.

many thanks in advance.

Code below. couldnt get it to display as all one entry

```<code>Private Sub Command2_Click()
On Error GoTo SubError

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim SQL As String
Dim rs1 As DAO.Recordset
Dim i As Integer

'Show user work is being performed
DoCmd.Hourglass (True)

'*********************************************
'              RETRIEVE DATA
'*********************************************
'SQL statement to retrieve data from database
SQL = "SELECT [Job Opened], [Job Number], [Job Title], " & _
"[ProposalRef], [QuotedValue], [Invoiced], " & _
"[Uplifted Cost], [Profit], [Diff], [Last Date Worked], [Reason], [Status], [Yr]" & _
"FROM [BIID] " & _
"ORDER BY [Job Number] "

'Execute query and populate recordset
Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

'If no data, don't bother opening Excel, just quit
If rs1.RecordCount = 0 Then
    MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
    GoTo SubExit
End If

'*********************************************
'             BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet

'Early Binding
Set xlApp = Excel.Application

xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

With xlSheet
    .Name = "BIID-All"
    .Cells.Font.Name = "Calibri"
    .Cells.Font.Size = 10

    'Set column widths
    .Columns("A").ColumnWidth = 11
    .Columns("B").ColumnWidth = 10
    .Columns("C").ColumnWidth = 40
    .Columns("D").ColumnWidth = 16
    .Columns("E").ColumnWidth = 14
    .Columns("F").ColumnWidth = 12
    .Columns("G").ColumnWidth = 12
    .Columns("H").ColumnWidth = 12
    .Columns("I").ColumnWidth = 10
    .Columns("J").ColumnWidth = 15
    .Columns("K").ColumnWidth = 45
    .Columns("L").ColumnWidth = 8
    .Columns("M").ColumnWidth = 5

    'Format columns
    .Columns("A").NumberFormat = "dd/mm/yyyy"
    .Columns("J").NumberFormat = "dd/mm/yyyy"
    .Columns("F").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("G").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("H").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("I").NumberFormat = "#,###,##0.00%;-#,###,##0.00%"

    'Column Headings
    .Range("A2").Value = "Date Opened"
    .Range("B2").Value = "Job Number"
    .Range("C2").Value = "Job Title"
    .Range("D2").Value = "Proposal Ref."
    .Range("E2").Value = "Quoted Value"
    .Range("F2").Value = "Total Invoiced"
    .Range("G2").Value = "Uplifted Cost"
    .Range("H2").Value = "Proft"
    .Range("I2").Value = "Difference"
    .Range("J2").Value = "Last Date Worked"
    .Range("K2").Value = "Reason"
    .Range("L2").Value = "Status"
    .Range("M2").Value = "Year"

    .Range("A1").Value = "Date Updated"
    .Range("B1").Value = Date

    'Format Column Headings
    .Range("A2:M2").Cells.Font.Bold = True
    .Range("A2:M2").Cells.Font.Color = RGB(68, 84, 106)
    .Range("A2:B2").HorizontalAlignment = xlCenter
    .Range("E2:J2").HorizontalAlignment = xlCenter

    'provide initial value to row counter
    i = 3
    'Loop through recordset and copy date from recordset to sheet
    Do While Not rs1.EOF

        .Range("A" & i).Value = rs1![Job Opened]
        .Range("B" & i).Value = rs1![Job Number]
        .Range("C" & i).Value = rs1![Job Title]
        .Range("D" & i).Value = rs1![ProposalRef]
        .Range("E" & i).Value = rs1![QuotedValue]
        .Range("F" & i).Value = rs1![Invoiced]
        .Range("G" & i).Value = rs1![Uplifted Cost]
        .Range("H" & i).Value = rs1![Profit]
        .Range("I" & i).Value = rs1![Diff]
        .Range("J" & i).Value = rs1![Last Date Worked]
        .Range("K" & i).Value = rs1![Reason]
        .Range("L" & i).Value = rs1![Status]
        .Range("M" & i).Value = rs1![Yr]

        i = i + 1
        rs1.MoveNext

        Loop

        'Total Average %
        .Range("F" & i).HorizontalAlignment = xlRight
        .Range("F" & i, "H" & i).Merge
        .Range("F" & i).Value = "Average % Profit (Billed vs Uplifted Cost)"
        .Range("F" & i).Cells.Font.Bold = True
        .Range("I" & i).Formula = "=AVERAGE(I3:I" & i - 1

        'Add borders
        .Range("A2:M2").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M2").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:A" & i - 1).Borders(xlEdgeLeft).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeRight).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlInsideVertical).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous

        'Add Conditional formatting
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlGreater, 0)
            .Font.Color = RGB(0, 176, 80)
        End With
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlLess, 0)
            .Font.Color = vbRed
        End With

    End With

SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rs1.Close
Set rs1 = Nothing
Exit Sub

 SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
    "An error occurred"
GoTo SubExit
 End Sub
</code>```

答:
Piece of advice, this:

```<code>Do While Not rs1.EOF

    .Range("A" & i).Value = rs1![Job Opened]
    .Range("B" & i).Value = rs1![Job Number]
    .Range("C" & i).Value = rs1![Job Title]
    .Range("D" & i).Value = rs1![ProposalRef]
    .Range("E" & i).Value = rs1![QuotedValue]
    .Range("F" & i).Value = rs1![Invoiced]
    .Range("G" & i).Value = rs1![Uplifted Cost]
    .Range("H" & i).Value = rs1![Profit]
    .Range("I" & i).Value = rs1![Diff]
    .Range("J" & i).Value = rs1![Last Date Worked]
    .Range("K" & i).Value = rs1![Reason]
    .Range("L" & i).Value = rs1![Status]
    .Range("M" & i).Value = rs1![Yr]

    i = i + 1
    rs1.MoveNext

Loop
</code>```

can be shortened to this:

```<code>.Range("A" & i).CopyFromRecordset rs1
</code>```

Body:
I have been trying to find a way to adapt the code i have written (based heavily on the Youtube video and coding provided by Access Jitsu to split my data across mutliple sheets based on the value in one field.
I have a number of fields and the purpose is for a comparison between invoicing and costs which i want to split by years onto separate sheets in excel.

Can anyone assist with how i would parse the field to split the data onto individual sheets based on the Year (in the code [Yr]) field.

many thanks in advance.

Code below. couldnt get it to display as all one entry

Private Sub Command2_Click()
On Error GoTo SubError

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim SQL As String
Dim rs1 As DAO.Recordset
Dim i As Integer

'Show user work is being performed
DoCmd.Hourglass (True)

'*********************************************
'              RETRIEVE DATA
'*********************************************
'SQL statement to retrieve data from database
SQL = "SELECT [Job Opened], [Job Number], [Job Title], " & _
"[ProposalRef], [QuotedValue], [Invoiced], " & _
"[Uplifted Cost], [Profit], [Diff], [Last Date Worked], [Reason], [Status], [Yr]" & _
"FROM [BIID] " & _
"ORDER BY [Job Number] "

'Execute query and populate recordset
Set rs1 = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

'If no data, don't bother opening Excel, just quit
If rs1.RecordCount = 0 Then
    MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
    GoTo SubExit
End If

'*********************************************
'             BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet

'Early Binding
Set xlApp = Excel.Application

xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)

With xlSheet
    .Name = "BIID-All"
    .Cells.Font.Name = "Calibri"
    .Cells.Font.Size = 10

    'Set column widths
    .Columns("A").ColumnWidth = 11
    .Columns("B").ColumnWidth = 10
    .Columns("C").ColumnWidth = 40
    .Columns("D").ColumnWidth = 16
    .Columns("E").ColumnWidth = 14
    .Columns("F").ColumnWidth = 12
    .Columns("G").ColumnWidth = 12
    .Columns("H").ColumnWidth = 12
    .Columns("I").ColumnWidth = 10
    .Columns("J").ColumnWidth = 15
    .Columns("K").ColumnWidth = 45
    .Columns("L").ColumnWidth = 8
    .Columns("M").ColumnWidth = 5

    'Format columns
    .Columns("A").NumberFormat = "dd/mm/yyyy"
    .Columns("J").NumberFormat = "dd/mm/yyyy"
    .Columns("F").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("G").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("H").NumberFormat = "£#,###,##0.00;-£#,###,##0.00"
    .Columns("I").NumberFormat = "#,###,##0.00%;-#,###,##0.00%"

    'Column Headings
    .Range("A2").Value = "Date Opened"
    .Range("B2").Value = "Job Number"
    .Range("C2").Value = "Job Title"
    .Range("D2").Value = "Proposal Ref."
    .Range("E2").Value = "Quoted Value"
    .Range("F2").Value = "Total Invoiced"
    .Range("G2").Value = "Uplifted Cost"
    .Range("H2").Value = "Proft"
    .Range("I2").Value = "Difference"
    .Range("J2").Value = "Last Date Worked"
    .Range("K2").Value = "Reason"
    .Range("L2").Value = "Status"
    .Range("M2").Value = "Year"

    .Range("A1").Value = "Date Updated"
    .Range("B1").Value = Date

    'Format Column Headings
    .Range("A2:M2").Cells.Font.Bold = True
    .Range("A2:M2").Cells.Font.Color = RGB(68, 84, 106)
    .Range("A2:B2").HorizontalAlignment = xlCenter
    .Range("E2:J2").HorizontalAlignment = xlCenter

    'provide initial value to row counter
    i = 3
    'Loop through recordset and copy date from recordset to sheet
    Do While Not rs1.EOF

        .Range("A" & i).Value = rs1![Job Opened]
        .Range("B" & i).Value = rs1![Job Number]
        .Range("C" & i).Value = rs1![Job Title]
        .Range("D" & i).Value = rs1![ProposalRef]
        .Range("E" & i).Value = rs1![QuotedValue]
        .Range("F" & i).Value = rs1![Invoiced]
        .Range("G" & i).Value = rs1![Uplifted Cost]
        .Range("H" & i).Value = rs1![Profit]
        .Range("I" & i).Value = rs1![Diff]
        .Range("J" & i).Value = rs1![Last Date Worked]
        .Range("K" & i).Value = rs1![Reason]
        .Range("L" & i).Value = rs1![Status]
        .Range("M" & i).Value = rs1![Yr]

        i = i + 1
        rs1.MoveNext

        Loop

        'Total Average %
        .Range("F" & i).HorizontalAlignment = xlRight
        .Range("F" & i, "H" & i).Merge
        .Range("F" & i).Value = "Average % Profit (Billed vs Uplifted Cost)"
        .Range("F" & i).Cells.Font.Bold = True
        .Range("I" & i).Formula = "=AVERAGE(I3:I" & i - 1

        'Add borders
        .Range("A2:M2").Borders(xlEdgeTop).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M2").Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:A" & i - 1).Borders(xlEdgeLeft).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeRight).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlInsideVertical).LineStyle = XlLineStyle.xlContinuous
        .Range("A2:M" & i - 1).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous

        'Add Conditional formatting
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlGreater, 0)
            .Font.Color = RGB(0, 176, 80)
        End With
        With .Range("I3:I" & i).FormatConditions.Add(xlCellValue, xlLess, 0)
            .Font.Color = vbRed
        End With

    End With

SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rs1.Close
Set rs1 = Nothing
Exit Sub

 SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.Description, vbCritical + vbOKOnly, _
    "An error occurred"
GoTo SubExit
 End Sub

Body:
Piece of advice, this:

Do While Not rs1.EOF

    .Range("A" & i).Value = rs1![Job Opened]
    .Range("B" & i).Value = rs1![Job Number]
    .Range("C" & i).Value = rs1![Job Title]
    .Range("D" & i).Value = rs1![ProposalRef]
    .Range("E" & i).Value = rs1![QuotedValue]
    .Range("F" & i).Value = rs1![Invoiced]
    .Range("G" & i).Value = rs1![Uplifted Cost]
    .Range("H" & i).Value = rs1![Profit]
    .Range("I" & i).Value = rs1![Diff]
    .Range("J" & i).Value = rs1![Last Date Worked]
    .Range("K" & i).Value = rs1![Reason]
    .Range("L" & i).Value = rs1![Status]
    .Range("M" & i).Value = rs1![Yr]

    i = i + 1
    rs1.MoveNext

Loop

can be shortened to this:

.Range("A" & i).CopyFromRecordset rs1


问:
git clone works; git submodule fails "Permission denied"
On a private repository from gitlab, when I run git clone git@git.privateserver.local:group/project-submodule.git the clone completes successfully.

As part of the cloning process, I'm asked for the passphrase of my private key.

When I run
submodule update --init "group/project-submodule"

It fails with:

Permission denied, please try again.
  Permission denied, please try again.
  Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
  fatal: Could not read from remote repository.

While trying to process the submodule getting, I'm not asked for the passphrase for my private key.

(I had to anonymize it)

fatal: clone of 'git@git.privateserver.local:group/project-submodule.git' into submodule path 'C:/Users/user/repos/project-module/project-submodule' failed

I've checked the .gitmodules file and it contains the right data (I think it can be confirmed by the error message).

The main element that calls my attention is that I'm not asked for my private key passphrase. Even weirder because, when I use git clone directly, it runs as expected.

I also already diagnosed by accessing with ssh and it asks me for the passphrase just like it happens when I execute a pull or a clone

Using git for windows "git version 2.16.2.windows.1"

答:
I was also facing same issue. While downloading submodules, GIT doesn't ask for ssh key password and that's where problem is.

Creating new ssh key without passphrase worked for me.


问:
Why can HAVING reference COUNT(column_name) but not the column_name itself?
I am trying to better understand how MySQL works. I came across a problem with subgroups. From question Unknown column in 'having clause', I understand why this code will return an error:

```<code>SELECT b.Title, b.Isbn
FROM Book AS b
INNER JOIN Writing AS w ON w.Book_id = b.ID
GROUP BY b.ID
HAVING w.Author_id = 1 AND b.Title LIKE "%Head%"
</code>```

That error is: "Unknown column 'w.Author_id' in 'having clause'" because:

The SQL standard requires that HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions. However, MySQL supports an extension to this behavior, and permits HAVING to refer to columns in the SELECT list and columns in outer subqueries as well.

But, if instead of w.Author_id = 1, I use COUNT(w.Author_id) > 1, the code exectues and works correctly:

```<code>SELECT b.Title, b.Isbn
FROM Book AS b
INNER JOIN Writing AS w ON w.Book_id = b.ID
GROUP BY b.ID
HAVING COUNT(w.Author_id) > 1 AND b.Title LIKE "%Head%"
</code>```

So, my question is: what is it about COUNT() that makes w.Author_id accessible? I apologize if this is a silly/obvious question - I'm still a novice at SQL.

答:
The documentation seems pretty clear on this subject.  But let me see if I can explain it better for you.

The HAVING clause is essentially a WHERE clause that "takes place" after the GROUP BY.  That is, the aggregation has already happened, so the data that is available is the aggregated data.

In your example, there is no Author_Id returned by the aggregation.  And MySQL doesn't know how to generate one.

However, COUNT(w.Author_Id) is an aggregated result.  MySQL can just add that (conceptually) to the results returned by the aggregation and filter on it.

Your query is equivalent to:

```<code>SELECT Title, Isbn
FROM (SELECT b.Title, b.Isbn, COUNT(*) as cnt
      FROM Book b JOIN
           Writing w
           ON w.Book_id = b.ID
      GROUP BY b.ID
     ) b
WHERE cnt > 1 AND b.Title LIKE '%Head%';
</code>```

That said, the query is better written as:

```<code>SELECT b.Title, b.Isbn
FROM Book b JOIN
     Writing w
     ON w.Book_id = b.ID
WHERE b.Title LIKE '%Head%'
GROUP BY b.ID
HAVING COUNT(*) > 1;
</code>```

You can filter on the title before aggregating and that is usually much more efficient.

Body:
I am trying to better understand how MySQL works. I came across a problem with subgroups. From question Unknown column in 'having clause', I understand why this code will return an error:

SELECT b.Title, b.Isbn
FROM Book AS b
INNER JOIN Writing AS w ON w.Book_id = b.ID
GROUP BY b.ID
HAVING w.Author_id = 1 AND b.Title LIKE "%Head%"

That error is: "Unknown column 'w.Author_id' in 'having clause'" because:

The SQL standard requires that HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions. However, MySQL supports an extension to this behavior, and permits HAVING to refer to columns in the SELECT list and columns in outer subqueries as well.

But, if instead of w.Author_id = 1, I use COUNT(w.Author_id) > 1, the code exectues and works correctly:

SELECT b.Title, b.Isbn
FROM Book AS b
INNER JOIN Writing AS w ON w.Book_id = b.ID
GROUP BY b.ID
HAVING COUNT(w.Author_id) > 1 AND b.Title LIKE "%Head%"

So, my question is: what is it about COUNT() that makes w.Author_id accessible? I apologize if this is a silly/obvious question - I'm still a novice at SQL.

Body:
The documentation seems pretty clear on this subject.  But let me see if I can explain it better for you.

The HAVING clause is essentially a WHERE clause that "takes place" after the GROUP BY.  That is, the aggregation has already happened, so the data that is available is the aggregated data.

In your example, there is no Author_Id returned by the aggregation.  And MySQL doesn't know how to generate one.

However, COUNT(w.Author_Id) is an aggregated result.  MySQL can just add that (conceptually) to the results returned by the aggregation and filter on it.

Your query is equivalent to:

SELECT Title, Isbn
FROM (SELECT b.Title, b.Isbn, COUNT(*) as cnt
      FROM Book b JOIN
           Writing w
           ON w.Book_id = b.ID
      GROUP BY b.ID
     ) b
WHERE cnt > 1 AND b.Title LIKE '%Head%';

That said, the query is better written as:

SELECT b.Title, b.Isbn
FROM Book b JOIN
     Writing w
     ON w.Book_id = b.ID
WHERE b.Title LIKE '%Head%'
GROUP BY b.ID
HAVING COUNT(*) > 1;

You can filter on the title before aggregating and that is usually much more efficient.


答:
When you put w.Author_id in the expression COUNT(w.Author_id) > 1 you are satisfying the requirement for HAVING clause that

HAVING must reference only columns in the GROUP BY clause or columns used in aggregate functions

while the ID column alone won't, because it is not part of the GROUP BY clause nor is within an aggregate function (which COUNT is).

Title: Why can HAVING reference COUNT(column_name) but not the column_name itself?


问:
Loop Iteration Efficient
You have a loop that iterates over 1,000 items. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?</p>

答:
```<code>for(i=3;i<len;i=i+4) { // where len is the length of your array
  ary[i]+='\n';        // use string append operator of your language.
}
</code>```

which will add a newline to every fourth item, i.e. items 3, 7, 11, etc.

EDIT

Changed to fulfill the OP's criteria.

Title: Loop Iteration Efficient

Body:
for(i=3;i<len;i=i+4) { // where len is the length of your array
  ary[i]+='\n';        // use string append operator of your language.
}

which will add a newline to every fourth item, i.e. items 3, 7, 11, etc.

EDIT

Changed to fulfill the OP's criteria.


问:
Passing service account(json file) location to application.properties
I have one maven project which wanted to have service account(json file) for authentication and maven should product the .war not .jar.

Considering that, I wanted to specify the json file location into project application.properties, like this:

spring.cloud.gcp.credentials.location=file:src/main/resources/service-account/service-account-key.json

I am new to the .war world, now the problem is when i build the project locally I am able to get the json file as it is in my resource folder and I am using tomcat locally which is working fine.

But in case of when i deploy into google app engine and its war nature service-account-key.json file is not found on the mentioned location.

Can anyone help on the same, where i need to put in for that as a part of build only i can refer and use the service account json file at both the time locally and after deploy as well.

thanks for you help in advance.

答:
You can reference the file in resources by prepending classpath: instead of file:

See my answer here.


问:
Integration tests with Gradle Kotlin DSL
I'm using this blog post to configure integration tests for a Spring Boot project, but I'm pretty stuck on declaring the source sets. I also found this post on StackOverflow, but I think I'm a bit further already.

My project structure is

```<code>project
|_ src
  |_ main
  | |_ kotlin
  | |_ resources
  |_ testIntegration
  | |_ kotlin
  | |_ resources
  |_ test
  | |_ kotlin
  | |_ resources
  |_ build.gradle.kts
  |_ ... other files
</code>```

And build.gradle.kts

```<code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    idea
    kotlin("jvm")
    id("org.springframework.boot") version "2.0.5.RELEASE"
    id("org.jetbrains.kotlin.plugin.spring") version "1.2.71"
}

fun DependencyHandlerScope.springBoot(module: String) = this.compile("org.springframework.boot:spring-boot-$module:2.0.5.RELEASE")
fun DependencyHandlerScope.springBootStarter(module: String) = this.springBoot("starter-$module")

dependencies {
    springBoot("devtools")

    springBootStarter("batch")
    springBootStarter("... spring boot dependencies")

    compile("... more dependencies")

    testCompile("... more test dependencies")
}

val test by tasks.getting(Test::class) {
    useJUnitPlatform { }
}

kotlin {
    sourceSets {
        val integrationTest by creating {
            kotlin.srcDir("src/testIntegration/kotlin")
            resources.srcDir("src/testIntegration/resources")
        }
    }
}

val integrationTestCompile by configurations.creating {
    extendsFrom(configurations["testCompile"])
}
val integrationTestRuntime by configurations.creating {
    extendsFrom(configurations["testRuntime"])
}

val testIntegration by tasks.creating(Test::class) {
    group = "verification"
    testClassesDirs = kotlin.sourceSets["integrationTest"].kotlin
}

idea {
    module {
        testSourceDirs.addAll(kotlin.sourceSets["integrationTest"].kotlin.srcDirs)
        testSourceDirs.addAll(kotlin.sourceSets["integrationTest"].resources.srcDirs)
    }
}
</code>```

I think I'm pretty  much in the right direction. At least it doesn't throw an exception any more :)

When I run the testIntegration task, I get the following output:

```<code>Testing started at 12:08 ...
12:08:49: Executing task 'testIntegration'...

> Task :project:compileKotlin UP-TO-DATE
> Task :project:compileJava NO-SOURCE
> Task :project:processResources UP-TO-DATE
> Task :project:classes UP-TO-DATE
> Task :project:compileTestKotlin UP-TO-DATE
> Task :project:compileTestJava NO-SOURCE
> Task :project:processTestResources UP-TO-DATE
> Task :project:testClasses UP-TO-DATE
> Task :project:testIntegration
BUILD SUCCESSFUL in 2s
5 actionable tasks: 1 executed, 4 up-to-date
12:08:51: Task execution finished 'testIntegration'.
</code>```

Also, IntelliJ doesn't recognise the testIntegration directories as Kotlin packages.

答:
I didnt like the use of withConvention and how the kotlin src dir was set. So after check out both gradle docs here and here, I came up with this:

```<code>sourceSets {
    create("integrationTest") {
        kotlin {
            compileClasspath += main.get().output + configurations.testRuntimeClasspath
            runtimeClasspath += output + compileClasspath
        }
    }
}

val integrationTest = task<Test>("integrationTest") {
    description = "Runs the integration tests"
    group = "verification"
    testClassesDirs = sourceSets["integrationTest"].output.classesDirs
    classpath = sourceSets["integrationTest"].runtimeClasspath
    mustRunAfter(tasks["test"])
}

tasks.check {
    dependsOn(integrationTest)
}
</code>```

I preferr the less verbose style when using kotlin { and the use of variable for the new integrationTestTask.

Body:
I'm using this blog post to configure integration tests for a Spring Boot project, but I'm pretty stuck on declaring the source sets. I also found this post on StackOverflow, but I think I'm a bit further already.

My project structure is

project
|_ src
  |_ main
  | |_ kotlin
  | |_ resources
  |_ testIntegration
  | |_ kotlin
  | |_ resources
  |_ test
  | |_ kotlin
  | |_ resources
  |_ build.gradle.kts
  |_ ... other files

And build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    idea
    kotlin("jvm")
    id("org.springframework.boot") version "2.0.5.RELEASE"
    id("org.jetbrains.kotlin.plugin.spring") version "1.2.71"
}

fun DependencyHandlerScope.springBoot(module: String) = this.compile("org.springframework.boot:spring-boot-$module:2.0.5.RELEASE")
fun DependencyHandlerScope.springBootStarter(module: String) = this.springBoot("starter-$module")

dependencies {
    springBoot("devtools")

    springBootStarter("batch")
    springBootStarter("... spring boot dependencies")

    compile("... more dependencies")

    testCompile("... more test dependencies")
}

val test by tasks.getting(Test::class) {
    useJUnitPlatform { }
}

kotlin {
    sourceSets {
        val integrationTest by creating {
            kotlin.srcDir("src/testIntegration/kotlin")
            resources.srcDir("src/testIntegration/resources")
        }
    }
}

val integrationTestCompile by configurations.creating {
    extendsFrom(configurations["testCompile"])
}
val integrationTestRuntime by configurations.creating {
    extendsFrom(configurations["testRuntime"])
}

val testIntegration by tasks.creating(Test::class) {
    group = "verification"
    testClassesDirs = kotlin.sourceSets["integrationTest"].kotlin
}

idea {
    module {
        testSourceDirs.addAll(kotlin.sourceSets["integrationTest"].kotlin.srcDirs)
        testSourceDirs.addAll(kotlin.sourceSets["integrationTest"].resources.srcDirs)
    }
}

I think I'm pretty  much in the right direction. At least it doesn't throw an exception any more :)

When I run the testIntegration task, I get the following output:

Testing started at 12:08 ...
12:08:49: Executing task 'testIntegration'...

> Task :project:compileKotlin UP-TO-DATE
> Task :project:compileJava NO-SOURCE
> Task :project:processResources UP-TO-DATE
> Task :project:classes UP-TO-DATE
> Task :project:compileTestKotlin UP-TO-DATE
> Task :project:compileTestJava NO-SOURCE
> Task :project:processTestResources UP-TO-DATE
> Task :project:testClasses UP-TO-DATE
> Task :project:testIntegration
BUILD SUCCESSFUL in 2s
5 actionable tasks: 1 executed, 4 up-to-date
12:08:51: Task execution finished 'testIntegration'.

Also, IntelliJ doesn't recognise the testIntegration directories as Kotlin packages.

Body:
I didnt like the use of withConvention and how the kotlin src dir was set. So after check out both gradle docs here and here, I came up with this:

sourceSets {
    create("integrationTest") {
        kotlin {
            compileClasspath += main.get().output + configurations.testRuntimeClasspath
            runtimeClasspath += output + compileClasspath
        }
    }
}

val integrationTest = task<Test>("integrationTest") {
    description = "Runs the integration tests"
    group = "verification"
    testClassesDirs = sourceSets["integrationTest"].output.classesDirs
    classpath = sourceSets["integrationTest"].runtimeClasspath
    mustRunAfter(tasks["test"])
}

tasks.check {
    dependsOn(integrationTest)
}

I preferr the less verbose style when using kotlin { and the use of variable for the new integrationTestTask.


问:
List combination challenge in Python 3
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

```<code>['01101001', '01110110', '01100101', '01101011']
</code>```

I want to get the list combined with each value like below. (result list)

```<code>['00001111', '11110100', '10010110', '01011011']
</code>```

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

答:
Idiomatic Python code makes heavy use of iterators. What you are trying to do is a form of parallel iteration over your strings, which is what zip can do.

If strings = ['01101001', '01110110', '01100101', '01101011']

Then [''.join(chars) for chars in zip(*strings)] evaluates to

```<code>['0000', '1111', '1111', '0100', '1001', '0110', '0101', '1011']
</code>```

That is almost what you want. It would be nice if you could iterate over the list by pairs. You can do so in several ways, including by using this nice solution due to @mic_e:

```<code>#the following pairwise iterator is due to mic_e
#from https://stackoverflow.com/a/30426000/4996248

def pairwise(it):
    it = iter(it)
    while True:
        try:
            yield next(it), next(it)
        except StopIteration:
            # no more elements in the iterator
            return
</code>```

Then simply:

```<code>new_strings = [a+b for a,b in pairwise(''.join(chars) for chars in zip(*strings))]
</code>```

which is ['00001111', '11110100', '10010110', '01011011'].

Title: List combination challenge in Python 3

Body:
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

['01101001', '01110110', '01100101', '01101011']

I want to get the list combined with each value like below. (result list)

['00001111', '11110100', '10010110', '01011011']

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

Body:
Idiomatic Python code makes heavy use of iterators. What you are trying to do is a form of parallel iteration over your strings, which is what zip can do.

If strings = ['01101001', '01110110', '01100101', '01101011']

Then [''.join(chars) for chars in zip(*strings)] evaluates to

['0000', '1111', '1111', '0100', '1001', '0110', '0101', '1011']

That is almost what you want. It would be nice if you could iterate over the list by pairs. You can do so in several ways, including by using this nice solution due to @mic_e:

#the following pairwise iterator is due to mic_e
#from https://stackoverflow.com/a/30426000/4996248

def pairwise(it):
    it = iter(it)
    while True:
        try:
            yield next(it), next(it)
        except StopIteration:
            # no more elements in the iterator
            return

Then simply:

new_strings = [a+b for a,b in pairwise(''.join(chars) for chars in zip(*strings))]

which is ['00001111', '11110100', '10010110', '01011011'].


问:
Positioning children widgets at the center and at the end of a Column parent widget
I have to position 2 children widgets inside a Column parent widget. I want one of them to be positioned in the center and the other at the end of the column. What is the best way to do that?

import 'package:flutter/material.dart';

class Screen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center, // this is wrong, it positions both the widgets in the center
        children: <Widget>[
          Text('This text should be at the center of the column'),
          Text('This text should be at the end of the column'),
        ],
      ),
    );
  }
}
```

答:
(EDIT: I changed the code and added grey to mine in order to show a comparison, so you can see what I mean when I say it will be offset by half. You have to increase the font size to see the difference.)

It's not quite as easy as the other answers because the first text has to be centered and if you only use two elements in your Column then no matter what you do it's either going to make the top item be off-center by half the height of the bottom text (as in using only two Expandeds) or the design will be rigid and therefore may not display correctly on different sized devices.

So, the trick is to use three Flexibles (2 Expandeds and a Spacer). Put the Spacer on top. It and the bottom Expanded must have the same flex value in order to center the middle Expanded.

Only then will using "alignment: Alignment.center" give the needed result for the top text.

```<code>import 'package:flutter/material.dart';

class CenteringOneItemWithAnotherItemInTheColumn extends StatelessWidget {
  const CenteringOneItemWithAnotherItemInTheColumn({
    Key key,
  }) : super(
    key: key,
  );

  /// Adjust these values as needed
  final int sameFlexValueTopAndBottom = 40; // 40%
  final int middleFlexValue = 20; // 20%

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Column Alignment Question'),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Spacer(),
              const Text(
                'Cent',
                style: TextStyle(
                  fontSize: 64,
                ),
              ),
              const Spacer(),
              const Text(
                'Bot',
                style: TextStyle(
                  fontSize: 64,
                ),
              ),
            ],
          ),
          Column(
            children: <Widget>[
              /// The key is to have the Spacer and the bottom Expanded
              /// use the same value for flex. That will cause the middle
              /// child of the Column to be centered vertically.
              Expanded(
                flex: sameFlexValueTopAndBottom,
                child: Container(
                  width: 100,
                  color: Colors.grey[300],
                ),
              ),
              Expanded(
                flex: middleFlexValue,
                child: const Align(
                  alignment: Alignment.center,
                  child: Text(
                    'Cent',
                    style: TextStyle(
                      fontSize: 64,
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: sameFlexValueTopAndBottom,
                child: Container(
                  color: Colors.grey[300],
                  child: const Align(
                    alignment: Alignment.bottomCenter,
                    child: Text(
                      'Bot',
                      style: TextStyle(
                        fontSize: 64,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
(EDIT: I changed the code and added grey to mine in order to show a comparison, so you can see what I mean when I say it will be offset by half. You have to increase the font size to see the difference.)

It's not quite as easy as the other answers because the first text has to be centered and if you only use two elements in your Column then no matter what you do it's either going to make the top item be off-center by half the height of the bottom text (as in using only two Expandeds) or the design will be rigid and therefore may not display correctly on different sized devices.

So, the trick is to use three Flexibles (2 Expandeds and a Spacer). Put the Spacer on top. It and the bottom Expanded must have the same flex value in order to center the middle Expanded.

Only then will using "alignment: Alignment.center" give the needed result for the top text.

import 'package:flutter/material.dart';

class CenteringOneItemWithAnotherItemInTheColumn extends StatelessWidget {
  const CenteringOneItemWithAnotherItemInTheColumn({
    Key key,
  }) : super(
    key: key,
  );

  /// Adjust these values as needed
  final int sameFlexValueTopAndBottom = 40; // 40%
  final int middleFlexValue = 20; // 20%

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Column Alignment Question'),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Spacer(),
              const Text(
                'Cent',
                style: TextStyle(
                  fontSize: 64,
                ),
              ),
              const Spacer(),
              const Text(
                'Bot',
                style: TextStyle(
                  fontSize: 64,
                ),
              ),
            ],
          ),
          Column(
            children: <Widget>[
              /// The key is to have the Spacer and the bottom Expanded
              /// use the same value for flex. That will cause the middle
              /// child of the Column to be centered vertically.
              Expanded(
                flex: sameFlexValueTopAndBottom,
                child: Container(
                  width: 100,
                  color: Colors.grey[300],
                ),
              ),
              Expanded(
                flex: middleFlexValue,
                child: const Align(
                  alignment: Alignment.center,
                  child: Text(
                    'Cent',
                    style: TextStyle(
                      fontSize: 64,
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: sameFlexValueTopAndBottom,
                child: Container(
                  color: Colors.grey[300],
                  child: const Align(
                    alignment: Alignment.bottomCenter,
                    child: Text(
                      'Bot',
                      style: TextStyle(
                        fontSize: 64,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}


问:
QueryDSL how do I create a SubQuery with its own joins?
I am trying to build a subquery for a QueryDSL select that uses an exists clause in a BooleanExpression.

The data model is such that there are projects which contain a single media. Media can have many dimensions. I am looking to select projects that have certain dimensional data and am using a subquery to accomplish that.

The subquery looks like this:

```<code>QProject project = QProject.project;
QMedia media = QMedia.media;

Predicate subExpression = JPAExpressions.selectOne()
            .from(media)
            .innerJoin(media.dimensions)
            .where(project.media.id.eq(media.id),
                dimension.dimensionType.id.eq(Long.valueOf(inputDimensionType))).exists();
</code>```

I store this as a predicate but, when I try to utilize it inside of a parent query I get an error: antlr.NoViableAltException: unexpected token: elements

The generated portion that is causing the error looks something like this (from the hibernate.hql.internal logs):

```<code>... and ((exists (select 1
from com.app.model.Media media
  inner join elements(media.dimensions)
</code>```

That is the error that happens when I plug it into a master query like this:

```<code>JPAQuery<ResponseCurve> query = new JPAQuery<>(this.entityManager);
query.select().from(project)
  .where(project.state.eq(inputState))
  .where(subExpression);
</code>```

答:
There are two possible issues with this query:

You're trying to reference alias dimensions, but you never associated it with the join to media.dimensions

You're dereferencing dimension.dimensionType without a join. For identifier values this is possible, for any other property, it is not.

What about:

```<code>QProject project = QProject.project;
QMedia media = QMedia.media;
QDimension dimension = QDimension.dimension;

Predicate subExpression = JPAExpressions.selectOne()
        .from(project.media, media)
        .innerJoin(media.dimensions, dimension )
        .on(dimension.dimensionType.id.eq(Long.valueOf(inputDimensionType))
</code>```

Body:
I am trying to build a subquery for a QueryDSL select that uses an exists clause in a BooleanExpression.

The data model is such that there are projects which contain a single media. Media can have many dimensions. I am looking to select projects that have certain dimensional data and am using a subquery to accomplish that.

The subquery looks like this:

QProject project = QProject.project;
QMedia media = QMedia.media;

Predicate subExpression = JPAExpressions.selectOne()
            .from(media)
            .innerJoin(media.dimensions)
            .where(project.media.id.eq(media.id),
                dimension.dimensionType.id.eq(Long.valueOf(inputDimensionType))).exists();

I store this as a predicate but, when I try to utilize it inside of a parent query I get an error: antlr.NoViableAltException: unexpected token: elements

The generated portion that is causing the error looks something like this (from the hibernate.hql.internal logs):

... and ((exists (select 1
from com.app.model.Media media
  inner join elements(media.dimensions)

That is the error that happens when I plug it into a master query like this:

JPAQuery<ResponseCurve> query = new JPAQuery<>(this.entityManager);
query.select().from(project)
  .where(project.state.eq(inputState))
  .where(subExpression);

Body:
There are two possible issues with this query:

You're trying to reference alias dimensions, but you never associated it with the join to media.dimensions

You're dereferencing dimension.dimensionType without a join. For identifier values this is possible, for any other property, it is not.

What about:

QProject project = QProject.project;
QMedia media = QMedia.media;
QDimension dimension = QDimension.dimension;

Predicate subExpression = JPAExpressions.selectOne()
        .from(project.media, media)
        .innerJoin(media.dimensions, dimension )
        .on(dimension.dimensionType.id.eq(Long.valueOf(inputDimensionType))


问:
React-Apollo catch when server is down
In my React ApolloGraphQL app with a node server, I'm trying to have it catch errors when my node server is down. All works great and normal when the node server us up... graphQL errors are caught and displayed.  But when I stop the node server, I get a runtime error that I can't avoid. When the node server is down, the server responds with a 503 Service Unavailable response and an html page that isn't JSON.

The apollo client is set up like this:

```<code>const client = new ApolloClient({
  assumeImmutableResults: true,
  fetchOptions: {
    credentials: "include"
  },
  fetch: fetch,
  onError: ({ graphQLErrors, networkError }) => {
    if (graphQLErrors)
      graphQLErrors.map(({ message, locations, path }) =>
        console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,),);
    if (networkError) {console.log(`[Network error]: ${networkError}`);}
    response = {errors:null};
  },
  cache: new InMemoryCache({
    freezeResults: true,
    dataIdFromObject: obj => {
      let dataId = null;
      switch (obj.__typename) {
        default:
          dataId = defaultDataIdFromObject(obj);
      }
      return dataId;
    },
    cacheRedirects: {
      Query: {
        productVariant: (_, args, { getCacheKey }) => {
          const cacheKey = getCacheKey({ __typename: "ProductVariant", ...args });
          return cacheKey;
        }
      }
    },
  }),
});
</code>```

The above onError block response with this message:

```<code>Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
</code>```

I have the mutation set up this way:

```<code>const [mutateVariant, {data, error, loading}] = useMutation(UPDATE_PRODUCT_META);
</code>```

And I call it like so:

```<code>mutateVariant({ variables: {inputM: {...buildMetaInput(editedData)} },
    errorPolicy: 'ignore', onError: (error) => Logger("Error:", error)});
</code>```

You can see I've tried it with different errorPolicy settings and adding an onError callback.

But I keep getting unhandled runtime errors and don't seem to be able to catch and handle them:

```<code>Unhandled Runtime Error

Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Call Stack
ApolloError           webpack-internal:///./node_modules/apollo-client/bundle.esm.js (76:28)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (1041:48)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error/<               webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:76)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:27)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error                 webpack-internal:///./node_modules/apollo-link-error/lib/bundle.esm.js (53:34)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
createHttpLink/</</<  webpack-internal:///./node_modules/apollo-link-http/lib/bundle.esm.js (92:26)
</code>```

the returned error data from the useMutation hook:

```<code>graphQLErrors: Array []
message: "Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
networkError: {…}
  bodyText: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>503 Service
  Unavailable</title>\n</head><body>\n<h1>Service Unavailable</h1>\n<p>The server is temporarily unable
  to service your\nrequest due to maintenance downtime or capacity\nproblems. Please try again later.
  </p>\n<p>Additionally, a 503 Service Unavailable\nerror was encountered while trying to use an
  ErrorDocument to handle the request.</p>\n</body></html>\n"
  name: "ServerParseError"
  response: Object {  }
  statusCode: 503
</code>```

How do I catch this error?

答:
The mutateVariant function returns a promise. Try adding a .catch() after it is called.</p>

```<code>mutateVariant().catch(() => {...});
</code>```

Title: React-Apollo catch when server is down

Body:
In my React ApolloGraphQL app with a node server, I'm trying to have it catch errors when my node server is down. All works great and normal when the node server us up... graphQL errors are caught and displayed.  But when I stop the node server, I get a runtime error that I can't avoid. When the node server is down, the server responds with a 503 Service Unavailable response and an html page that isn't JSON.

The apollo client is set up like this:

const client = new ApolloClient({
  assumeImmutableResults: true,
  fetchOptions: {
    credentials: "include"
  },
  fetch: fetch,
  onError: ({ graphQLErrors, networkError }) => {
    if (graphQLErrors)
      graphQLErrors.map(({ message, locations, path }) =>
        console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,),);
    if (networkError) {console.log(`[Network error]: ${networkError}`);}
    response = {errors:null};
  },
  cache: new InMemoryCache({
    freezeResults: true,
    dataIdFromObject: obj => {
      let dataId = null;
      switch (obj.__typename) {
        default:
          dataId = defaultDataIdFromObject(obj);
      }
      return dataId;
    },
    cacheRedirects: {
      Query: {
        productVariant: (_, args, { getCacheKey }) => {
          const cacheKey = getCacheKey({ __typename: "ProductVariant", ...args });
          return cacheKey;
        }
      }
    },
  }),
});

The above onError block response with this message:

Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I have the mutation set up this way:

const [mutateVariant, {data, error, loading}] = useMutation(UPDATE_PRODUCT_META);

And I call it like so:

mutateVariant({ variables: {inputM: {...buildMetaInput(editedData)} },
    errorPolicy: 'ignore', onError: (error) => Logger("Error:", error)});

You can see I've tried it with different errorPolicy settings and adding an onError callback.

But I keep getting unhandled runtime errors and don't seem to be able to catch and handle them:

Unhandled Runtime Error

Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Call Stack
ApolloError           webpack-internal:///./node_modules/apollo-client/bundle.esm.js (76:28)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (1041:48)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error/<               webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:76)
error                 webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:27)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error                 webpack-internal:///./node_modules/apollo-link-error/lib/bundle.esm.js (53:34)
notifySubscription    webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify              webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error                 webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
createHttpLink/</</<  webpack-internal:///./node_modules/apollo-link-http/lib/bundle.esm.js (92:26)

the returned error data from the useMutation hook:

graphQLErrors: Array []
message: "Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
networkError: {…}
  bodyText: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n\n<title>503 Service
  Unavailable</title>\n\n
Service Unavailable
\n
The server is temporarily unable
  to service your\nrequest due to maintenance downtime or capacity\nproblems. Please try again later.

\n
Additionally, a 503 Service Unavailable\nerror was encountered while trying to use an
  ErrorDocument to handle the request.
\n\n"
  name: "ServerParseError"
  response: Object {  }
  statusCode: 503

How do I catch this error?

Body:
The mutateVariant function returns a promise. Try adding a .catch() after it is called.

mutateVariant().catch(() => {...});


问:
Is it possible to capture AVTP packets with tcpdump?
I'm new to Automotive Network. I am trying to capture some AVTP (IEEE1722) protocol packets on an Android device. Is it possible to capture AVTP packets with tcpdump on Android? I heard someone said tcpdump can only capture network layer packets, but AVTP is a transfer layer protocol. Does this means it's impossible?</p>

答:
tcpdump can only capture network layer packets

This is not true. tcpdump and friends can capture ethernet and 802.11 frames, which are at layer 2 while the network layer is layer 3 in the OSI model.

tcpdump will copy bytes going over the network interface that it has access to, regardless of protocol, for layers >= 2. It looks like AVTP (IEEE1722) is a layer 2 protocol, like ethernet. You can check what interfaces tcpdump sees with tcpdump -D.

For sample packet captures (8) of this protocol, you can use https://tshark.dev/search/pcaptable/ and search for protocol ieee1722. Wireshark uses the display filter ieee1722 for this protocol (ieee1722 filter reference).


问:
How to correct system clock in vagrant automatically
How to Correct Timezone

Last time, I figured out how to adjust a system clock in vagrant server. However, when I halt the vagrant and start it again, the system clock is always 9 hours late. I can adjust by using ntp command manually, but I'd like to know how to adjust the system clock automatically.

I have tried the below, but it still doesn't work. Are there any suggestions?

How to sync time on host wake-up within VirtualBox?

答:
The simplest way is to set the timezone automatically is to use the vagrant-timezone plugin.

Install it once with:

vagrant plugin install vagrant-timezone
```
<p><br/><br/></p>
<p>After that, add the below to your <code>Vagrantfile</code>:</p>
<pre class="lang-rb prettyprint-override"><code>if Vagrant.has_plugin?("vagrant-timezone")
   config.timezone.value = "UTC"
end
</code>```

You may replace "UTC" with any of the tz values listed here.
For example: "Asia/Kolkata".

Or you can use your host's timezone with this entry in your Vagrantfile:

if Vagrant.has_plugin?("vagrant-timezone")
   config.timezone.value = :host
end
```

Body:
The simplest way is to set the timezone automatically is to use the vagrant-timezone plugin.

Install it once with:

vagrant plugin install vagrant-timezone

After that, add the below to your Vagrantfile:

if Vagrant.has_plugin?("vagrant-timezone")
   config.timezone.value = "UTC"
end

You may replace "UTC" with any of the tz values listed here.
For example: "Asia/Kolkata".

Or you can use your host's timezone with this entry in your Vagrantfile:

if Vagrant.has_plugin?("vagrant-timezone")
   config.timezone.value = :host
end


问:
Qt: Correct way to post events to a QThread?
In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread?

```<code>QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);
</code>```

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient.  Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?

答:
Events are processed by the main event loop, which lives in QApplication or QCoreApplication. So it does not make sense to send events to QObjects in other threads (unless you create another event loop there which I am not sure is possible).

You can send events from other threads to your main thread, though. The myWorkerThread in your example is owned by the main thread, because it is created there. Objects created by your worker thread in run() and below are owned by this thread.

You also can send signals to slots in other thread, for example if you want to draw a widget (which must be done in the main thread) from your worker thread or similar.

Body:
In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread?

QThread* myWorkerThread = // ...

QApplication::instance()->postEvent (myWorkerThread, new MyWorkRequestEvent(/* ... */);

If I read the documentation correctly, it states that events are processed on the thread of the object that own the event recipient.  Since QThread was created by the main thread, it is owned by the main thread -- so would this event be processed by the main thread (which would be counter-intuitive, and in my case would be wrong)?


问:
How can ı find intersection points of cp and cp_p_g on axis M?
```<code>import numpy as np
import matplotlib.pyplot as plt

Cp_0=-0.464
M=np.arange(0.3,1,0.1) #Mach number for range<0.3-1>
Cp=(2/(1.4*M**2))*(((1+0.2*M**2)/(1.2))**3.5-1) #Aerodynamic relation for isentropic flow
Cp_p_g=Cp_0/((1-M**2)**0.5) #prandtl-Glauert rule

plt.plot(M,Cp)
plt.plot(M,Cp_p_g)
plt.grid("major")
plt.title('NACA**-***') #Title varies on the NACA profiles that we work
plt.xlabel("M")
plt.ylabel("Cp")
</code>```

cp and cp_p_g curves

I have added a plot of two curves, cp and, cp_p_g,  for better understanding of the problem

答:
You can refine your x-meshgrid using linspace and then look for the difference of the two curves

```<code>M = np.linspace(0.3, 1, 200)

# Remaining code

idx = np.argmin(np.abs(Cp_p_g-Cp))

plt.axvline(M[idx], c='k', ls='--')
plt.axhline(Cp_p_g[idx], c='k', ls='--')
</code>```

Body:
import numpy as np
import matplotlib.pyplot as plt

Cp_0=-0.464
M=np.arange(0.3,1,0.1) #Mach number for range<0.3-1>
Cp=(2/(1.4*M**2))*(((1+0.2*M**2)/(1.2))**3.5-1) #Aerodynamic relation for isentropic flow
Cp_p_g=Cp_0/((1-M**2)**0.5) #prandtl-Glauert rule

plt.plot(M,Cp)
plt.plot(M,Cp_p_g)
plt.grid("major")
plt.title('NACA**-***') #Title varies on the NACA profiles that we work
plt.xlabel("M")
plt.ylabel("Cp")

cp and cp_p_g curves

I have added a plot of two curves, cp and, cp_p_g,  for better understanding of the problem

Body:
You can refine your x-meshgrid using linspace and then look for the difference of the two curves

M = np.linspace(0.3, 1, 200)

# Remaining code

idx = np.argmin(np.abs(Cp_p_g-Cp))

plt.axvline(M[idx], c='k', ls='--')
plt.axhline(Cp_p_g[idx], c='k', ls='--')


问:
How to create stock price alert with EXCEL/How to handle Auto refreshing data ,Dynamic data with macros
My aim with this is to create stock price alert(like Pop up message)/Because excel sheet contains more than 300 stock list
i don't want to scroll down excel sheet every time to check if refreshed price falls into any of these categories..

I have 8 columns in excel which consists of following information-

Column A-Stock Name

Column B-current stock price data which refreshes in every 5-10 seconds...

Column C-Ticker name

Next columns(D,E,F,G,H) i set them with manually entered prices for corresponding stocks for alert purpose.

If Refreshed price in column B falls in range 99% or 101% of columns values in D,E,F,G or H
i want to display a pop up message with Stock name with that cell address of corresponding cell in column D,E,F,G,or H ...

For Ex. If D2,E2,F2,G2 or H2 contains value 104.50 which is static and if B2 cell update its price dynamically to 105 then, B2 value falls in range 99% of D2(103.95) and 101% of D2(106.05) of D2..Once this Condition satisfies i want a popup alert...Any kind of help to simplify this task is most appreciated...

答:
Check please the latest update of file:
https://drive.google.com/file/d/1itIZl3kMFR9f2Tf3ObB0qUprfp2rLm4r/view?usp=sharing

I added a scheduler, another sub iterates for each cell in B column every 5 seconds
I changed msgbox into debug.print to prevent crash excel.
You can find output messages in Immediate window:

Added:

Blockquote


问:
How to RoundUp a decimal value with a base distinct from degree of 10?
A regular RoundUp function with a base of 10 looks as below:

```<code>public static decimal RoundUp(this decimal value, int decimals)
        {
            var k = (decimal)Math.Pow(10, decimals);
            return Math.Ceiling((value * k)) / k;
        }
</code>```

so it works like this:

```<code>decimal number = 10.12345m;
number.RoundUp(3) => 10.124
number.RoundUp(2) => 10.13
number.RoundUp(1) => 10.2
etc.
</code>```

I would like to have a function that rounds up to the nearest value as the following:

```<code>decimal number = 10.12345m;
number.RoundUp(0.1) => 10.2
number.RoundUp(0.25) => 10.25
number.RoundUp(2.0) => 12
number.RoundUp(5.0) => 15
number.RoundUp(10) => 20
</code>```

Note RoundUp by @basis means the result is dividable on the @basis without the rest:

```<code>RoundUp(10.12345m, 0.15) => 10.2   check 10.2 / 0.15 = 68
</code>```

neighbors are 10.05 and 10.35, so the correct rounding of 10.12345 is 10.2

```<code>RoundUp(5, 2.25) => 6.75   check 6.75 / 2.25 = 3
</code>```

i.e. 2.25x2 =4.50 is less than 5. so 5 round up by 2.25 will be 6.75

```<code>RoundUp(5, 2.50) => 5.0   check 5 / 2.5 = 2
</code>```

答:
It turns out it's quite simple math:

```<code> public static decimal RoundUp(this decimal value, decimal @base)
    {
        var n = Math.Ceiling((value + @base) / @base) -1;
        return (n * @base);
    }
}
</code>```

rextester link

Body:
A regular RoundUp function with a base of 10 looks as below:

public static decimal RoundUp(this decimal value, int decimals)
        {
            var k = (decimal)Math.Pow(10, decimals);
            return Math.Ceiling((value * k)) / k;
        }

so it works like this:

decimal number = 10.12345m;
number.RoundUp(3) => 10.124
number.RoundUp(2) => 10.13
number.RoundUp(1) => 10.2
etc.

I would like to have a function that rounds up to the nearest value as the following:

decimal number = 10.12345m;
number.RoundUp(0.1) => 10.2
number.RoundUp(0.25) => 10.25
number.RoundUp(2.0) => 12
number.RoundUp(5.0) => 15
number.RoundUp(10) => 20

Note RoundUp by @basis means the result is dividable on the @basis without the rest:

RoundUp(10.12345m, 0.15) => 10.2   check 10.2 / 0.15 = 68

neighbors are 10.05 and 10.35, so the correct rounding of 10.12345 is 10.2

RoundUp(5, 2.25) => 6.75   check 6.75 / 2.25 = 3

i.e. 2.25x2 =4.50 is less than 5. so 5 round up by 2.25 will be 6.75

RoundUp(5, 2.50) => 5.0   check 5 / 2.5 = 2

Body:
It turns out it's quite simple math:

 public static decimal RoundUp(this decimal value, decimal @base)
    {
        var n = Math.Ceiling((value + @base) / @base) -1;
        return (n * @base);
    }
}

rextester link