问:
Layout in list tile - flutter
Current output:

Expected output:

Code:

```<code>SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );
</code>```

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

答:
Use custom widget for list item OR column from below code for single view. To align left and right you have to put your view in 'Align' as in below -</p>

```<code>class _ItemsState extends State<Items> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
            body: SizedBox(
                width: 380,
                height: 160,
                child: Card(
                    child: ListView.builder(
                        itemCount: 1,
                        itemBuilder: (context, index) {
                          return

                            Padding(padding: EdgeInsets.all(10.0),child:   Column(children: <Widget>[
                              Align(
                                alignment: Alignment.centerLeft,
                                child: Column(children: <Widget>[
                                  Text(
                                    'title',
                                    style: TextStyle(fontSize: 20.0 , fontWeight: FontWeight.bold,),
                                  ),
                                  Text(
                                    'body',
                                    style: TextStyle(fontSize: 14.0),  )
                                ]),
                              ),
                              Align(
                                  alignment: Alignment.centerRight,
                                  child:  CircleAvatar(
                                      maxRadius: 20.0,
                                      backgroundColor: Colors.blueGrey,
                                      child: IconButton(
                                        icon: Icon(Icons.add,
color: Colors.white,),
                                      ))
                              )
                            ]));

                        }))));
      }
    }
</code>```

Title: Layout in list tile - flutter

Body:
Current output:

Expected output:

Code:

SizedBox(
      width: 380,
      height: 180,
      child: Swiper(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Expanded(
                child: Card(
                  child: ListTile(
                    title: Text(
                      '${items[index].title}',
                    ),
                    subtitle: Text(
                      '${items[index].body}',
                    ),
                    trailing: Column(
                      children: <Widget>[
                        CircleAvatar(
                          backgroundColor: HexColor("#0087a8"),
                          child: IconButton(
                            icon: Icon(Icons.add),
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
        },
        viewportFraction: 0.8,
        scale: 0.9,
        control: SwiperControl(color: Colors.white),
      ),
    );

I am unable to create the icon button to be that way. As when i put in padding, it says that the pixels overflowed. I need to get the add button on the bottom right hand side.

Body:
Use custom widget for list item OR column from below code for single view. To align left and right you have to put your view in 'Align' as in below -

class _ItemsState extends State<Items> {
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        return Scaffold(
            body: SizedBox(
                width: 380,
                height: 160,
                child: Card(
                    child: ListView.builder(
                        itemCount: 1,
                        itemBuilder: (context, index) {
                          return

                            Padding(padding: EdgeInsets.all(10.0),child:   Column(children: <Widget>[
                              Align(
                                alignment: Alignment.centerLeft,
                                child: Column(children: <Widget>[
                                  Text(
                                    'title',
                                    style: TextStyle(fontSize: 20.0 , fontWeight: FontWeight.bold,),
                                  ),
                                  Text(
                                    'body',
                                    style: TextStyle(fontSize: 14.0),  )
                                ]),
                              ),
                              Align(
                                  alignment: Alignment.centerRight,
                                  child:  CircleAvatar(
                                      maxRadius: 20.0,
                                      backgroundColor: Colors.blueGrey,
                                      child: IconButton(
                                        icon: Icon(Icons.add,
color: Colors.white,),
                                      ))
                              )
                            ]));

                        }))));
      }
    }


来源: stackexchange

问:
Validation of result before executing the query
When running a stored procedure to fetch some rows, First I want to validate if the query will return a row before sending the result, and second if it is possible to validate without running the same query twice.

I am using a cursor to store the yielded result, So I tried the cursor attribute %ROWCOUNT & %NOTFOUND. But the doesnt quite work. Plus I want to do this without running a loop on the cursor.

```<code>procedure MODULE_LIST_GK(p_module_Id IN MODULE_LIST.MODULE_ID% TYPE,
                                     p_Error_Code     out nvarchar2,
                                     p_Error_Msg      out nvarchar2,
                                     p_Cursor         out sys_refcursor)   IS
 BEGIN
    OPEN p_Cursor FOR
       SELECT A.MODULE_ID,
         A.MODULE_NM,
         A.AUTH_STATUS_ID
         FROM MODULE_LIST A
         WHERE A.MODULE_ID=p_module_Id;

       SELECT COUNT(MODULE_ID)
       INTO v_row_num
        FROM MODULE_LIST A
        WHERE A.MODULE_ID=p_module_Id;

       IF v_row_num=0 THEN
         p_Error_Code := SQLCODE;
         p_Error_Msg := 'Does not Exists';
         Return;
       end IF;
    EXCEPTION
      WHEN OTHERS THEN
        p_error_code:= SQLCODE;
        p_error_msg := SQLERRM;
  END MODULE_LIST_GK;
</code>```

答:
In order to know whether a cursor contains rows, you must open it and fetch the first row. Once you've done this, it makes no sense anymore to return that cursor, for the recipient will not be able to fetch that first row, because the cursor already points beyond it.

So, you must select twice. What you'd do is to use ROWNUM or an EXISTS clause here to show the DBMS that you are not interested in any more rows. This can speed up the query extremely.

```<code>PROCEDURE module_list_gk(p_module_id   IN   MODULE_LIST.MODULE_ID%TYPE,
                         p_error_code  OUT  NVARCHAR2,
                         p_error_msg   OUT  NVARCHAR2,
                         p_cursor      OUT  SYS_REFCURSOR) IS
  v_count INTEGER;
BEGIN
  SELECT COUNT(*)
  INTO v_count
  FROM module_list
  WHERE module_id = p_module_Id
  AND ROWNUM = 1;

  IF v_count = 0 THEN
    p_error_code := 0; -- Or -1403 for NO DATA FOUND if you like
    p_error_msg := 'Does not Exists';
    RETURN;
  END IF;

  OPEN p_Cursor FOR
    SELECT module_id, module_nm, auth_status_id
    FROM module_list
    WHERE module_id = p_module_id;

EXCEPTION WHEN OTHERS THEN
  p_error_code:= SQLCODE;
  p_error_msg := SQLERRM;
END module_list_gk;
</code>```

SQLCODE for the first query will be 0 by the way (SELECT COUNT(*) returns one row with the number of records found - no error hence). This is why you should decide to either return zero explicitly or some error code, such as -1403.

Here is the same with EXISTS:

```<code>BEGIN
  SELECT CASE WHEN EXISTS
  (
    SELECT NULL
    FROM module_list
    WHERE module_id = p_module_Id
  ) THEN 1 ELSE 0 END
  INTO v_count
  FROM DUAL;

  IF v_count = 0 THEN
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When running a stored procedure to fetch some rows, First I want to validate if the query will return a row before sending the result, and second if it is possible to validate without running the same query twice.

I am using a cursor to store the yielded result, So I tried the cursor attribute %ROWCOUNT & %NOTFOUND. But the doesnt quite work. Plus I want to do this without running a loop on the cursor.

procedure MODULE_LIST_GK(p_module_Id IN MODULE_LIST.MODULE_ID% TYPE,
                                     p_Error_Code     out nvarchar2,
                                     p_Error_Msg      out nvarchar2,
                                     p_Cursor         out sys_refcursor)   IS
 BEGIN
    OPEN p_Cursor FOR
       SELECT A.MODULE_ID,
         A.MODULE_NM,
         A.AUTH_STATUS_ID
         FROM MODULE_LIST A
         WHERE A.MODULE_ID=p_module_Id;

       SELECT COUNT(MODULE_ID)
       INTO v_row_num
        FROM MODULE_LIST A
        WHERE A.MODULE_ID=p_module_Id;

       IF v_row_num=0 THEN
         p_Error_Code := SQLCODE;
         p_Error_Msg := 'Does not Exists';
         Return;
       end IF;
    EXCEPTION
      WHEN OTHERS THEN
        p_error_code:= SQLCODE;
        p_error_msg := SQLERRM;
  END MODULE_LIST_GK;

Body:
In order to know whether a cursor contains rows, you must open it and fetch the first row. Once you've done this, it makes no sense anymore to return that cursor, for the recipient will not be able to fetch that first row, because the cursor already points beyond it.

So, you must select twice. What you'd do is to use ROWNUM or an EXISTS clause here to show the DBMS that you are not interested in any more rows. This can speed up the query extremely.

PROCEDURE module_list_gk(p_module_id   IN   MODULE_LIST.MODULE_ID%TYPE,
                         p_error_code  OUT  NVARCHAR2,
                         p_error_msg   OUT  NVARCHAR2,
                         p_cursor      OUT  SYS_REFCURSOR) IS
  v_count INTEGER;
BEGIN
  SELECT COUNT(*)
  INTO v_count
  FROM module_list
  WHERE module_id = p_module_Id
  AND ROWNUM = 1;

  IF v_count = 0 THEN
    p_error_code := 0; -- Or -1403 for NO DATA FOUND if you like
    p_error_msg := 'Does not Exists';
    RETURN;
  END IF;

  OPEN p_Cursor FOR
    SELECT module_id, module_nm, auth_status_id
    FROM module_list
    WHERE module_id = p_module_id;

EXCEPTION WHEN OTHERS THEN
  p_error_code:= SQLCODE;
  p_error_msg := SQLERRM;
END module_list_gk;

SQLCODE for the first query will be 0 by the way (SELECT COUNT(*) returns one row with the number of records found - no error hence). This is why you should decide to either return zero explicitly or some error code, such as -1403.

Here is the same with EXISTS:

BEGIN
  SELECT CASE WHEN EXISTS
  (
    SELECT NULL
    FROM module_list
    WHERE module_id = p_module_Id
  ) THEN 1 ELSE 0 END
  INTO v_count
  FROM DUAL;

  IF v_count = 0 THEN


问:
Java coding style 2019
I am curious to know the current coding style for java. My team is forcing  to use {} for one liner if statements. Although we used to have braces for one liners current java source code does not use braces for one liner if statements anymore and I myself am inclined towards the same.

Python dropped braces altogether.

However I do not see any particular style guide in 2019.. The oracle doc still refers to the 1997 coding style.

What would be correct coding or is it something more to do with developer's preference?

```<code>   foo();

   if (condition)
      doSomething();

   bar();
</code>```

vs

```<code>   foo();

   if (condition) {
      doSomething();
   }

   bar();
</code>```

Edit 1:  As Kartik mentioned we can write one liners like this as well:

```<code>   if (condition) doSomething();
</code>```

For me, it as a developers preference and I am ok with both the approaches but in my current team some developers are of opinion not using braces is a BAD coding practice. I saw the java source code and found in many places braces are omitted. So, I don't believe this to be true. As for google coding style, it was also there for many years and many people continue to use the same. But for new code are there any new guidelines?

Edit 2: This question is marked as opinion based and put on hold

I want to clarify that I am NOT looking for opinions. I am more looking for standard guidelines which Oracle (or java open source communities) might have put forward regarding best practices as of today (2019). Most practices java/google are very old dating back to 1996 and may not be relevant today. Even if there is some reference in some new books and some can share those details it will be very helfpul

答:
I think one of the commonly used style guides for java is the one from Google, see here.

It says:

Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.

But the real general answer here is: only use such input as hint what to do. For you: sit down with your peers, and check out what you like, and then write that down, and go with it. Like: our team decided to use the google style, but to make subtle changes to it here or there.

And then make sure that your tooling supports your preferred style. One of the reasons why we selected "google style" is the fact that you get formatting templates for eclipse, IntelliJ, and even SlickEdit.

I agree that there are no "prominent" style guides for Java8 (and newer) elements, such as lengthy stream statements. That is where "decide with your team what you want" comes in again. We decided for example that

```<code>stream()
  .filter(...)
  .whatver
</code>```

each go on their own line (one reason for that is the fact that IntelliJ will then give you the return type of each line right there while editing, what I find extremely helpful when working with streams).

Title: Java coding style 2019

Body:
I am curious to know the current coding style for java. My team is forcing  to use {} for one liner if statements. Although we used to have braces for one liners current java source code does not use braces for one liner if statements anymore and I myself am inclined towards the same.

Python dropped braces altogether.

However I do not see any particular style guide in 2019.. The oracle doc still refers to the 1997 coding style.

What would be correct coding or is it something more to do with developer's preference?

   foo();

   if (condition)
      doSomething();

   bar();

vs

   foo();

   if (condition) {
      doSomething();
   }

   bar();

Edit 1:  As Kartik mentioned we can write one liners like this as well:

   if (condition) doSomething();

For me, it as a developers preference and I am ok with both the approaches but in my current team some developers are of opinion not using braces is a BAD coding practice. I saw the java source code and found in many places braces are omitted. So, I don't believe this to be true. As for google coding style, it was also there for many years and many people continue to use the same. But for new code are there any new guidelines?

Edit 2: This question is marked as opinion based and put on hold

I want to clarify that I am NOT looking for opinions. I am more looking for standard guidelines which Oracle (or java open source communities) might have put forward regarding best practices as of today (2019). Most practices java/google are very old dating back to 1996 and may not be relevant today. Even if there is some reference in some new books and some can share those details it will be very helfpul

Body:
I think one of the commonly used style guides for java is the one from Google, see here.

It says:

Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.

But the real general answer here is: only use such input as hint what to do. For you: sit down with your peers, and check out what you like, and then write that down, and go with it. Like: our team decided to use the google style, but to make subtle changes to it here or there.

And then make sure that your tooling supports your preferred style. One of the reasons why we selected "google style" is the fact that you get formatting templates for eclipse, IntelliJ, and even SlickEdit.

I agree that there are no "prominent" style guides for Java8 (and newer) elements, such as lengthy stream statements. That is where "decide with your team what you want" comes in again. We decided for example that

stream()
  .filter(...)
  .whatver

each go on their own line (one reason for that is the fact that IntelliJ will then give you the return type of each line right there while editing, what I find extremely helpful when working with streams).


问:
How to get the value of a column in the row with the first occurrence of another value in a particular column in MySQL?
I have a SQL table with the following columns:

```<code>|    Date    |    Pass/Fail    |
--------------------------------
| yyyy-mm-dd |      PASS       |

| yyyy-mm-dd |      FAIL       |
</code>```

How do I obtain the value in the "Date" column of the row with the first occurrence (ordered by date) of "PASS" in the "Pass/Fail" column?

答:
If you wanted to also capture more than one passing record should two or more records be tied as being first, then we can try using a subquery:</p>

```<code>SELECT Date, PassFail
FROM yourTable
WHERE
    PassFail = 'Pass' AND
    Date = (SELECT MIN(Date) FROM yourTable WHERE PassFail = 'Pass');
</code>```

Body:
I have a SQL table with the following columns:

|    Date    |    Pass/Fail    |
--------------------------------
| yyyy-mm-dd |      PASS       |

| yyyy-mm-dd |      FAIL       |

How do I obtain the value in the "Date" column of the row with the first occurrence (ordered by date) of "PASS" in the "Pass/Fail" column?

Body:
If you wanted to also capture more than one passing record should two or more records be tied as being first, then we can try using a subquery:

SELECT Date, PassFail
FROM yourTable
WHERE
    PassFail = 'Pass' AND
    Date = (SELECT MIN(Date) FROM yourTable WHERE PassFail = 'Pass');


问:
send a json from one component to another without being seen in the url of the target component
I'm trying to send a json from componentA to componentB. The problem is that the json appears in the url. How can I make the json not appear?

routing

```<code>const appRoutes: Routes = [
  {path: 'componentA', component: componentA},
  {path: 'componentB', component: componentA, data : {}},
  {path: '**', component: NotFoundComponent}
];
</code>```

template componentA

```<code><a *ngFor="let item aArray" (click)="fn_sendJson(item)">Send jSON</a>
</code>```

componentA .ts

```<code>this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
 this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}
</code>```

ComponentB .ts

```<code>constructor(
 private router : Router,
 private route: ActivatedRoute
 ) {
 sub:any;
 jsonReceived:any
 .
 .
 this.sub = this.route.params
 .subscribe(v => this.jsonReceived =JSON.parse(v.data));
</code>```

I have not found a way to avoid converting the original json to a string, I would like to know if there is an effective method of sending such as the json, and get it without needing it to be present in the url. Thank you

答:
When you want to send some complex data from one component to another, it is usually not a good practice to to send it through the url. What you can do is create a service like this:

sharing.service.ts

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class SharingService {
  private sharingObject: any;
  constructor() { }

  get sharingValue() {
    return this.sharingObject
  }

  set sharingValue(obj) {
    this.sharingObject = obj;
  }
}
</code>```

Now you need to inject that service in both of your components in order to sharing data between them.

First component will look like this:

first.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService, private router: Router) {
    this.myJson = {
      a: "hello",
      b: "World"
    }
  }

  ngOnInit() {
  }

  send() {
    this.sharingService.sharingValue = this.myJson;
    this.router.navigate(['/second'])
  }

}
</code>```

Now in your second component, you can access the value set by first component

second.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService) { }

  ngOnInit() {
   this.myJson = this.sharingService.sharingValue;
  }

}
</code>```

Here is the working stacklitz demo for this approach

Hope it helps :)

Body:
I'm trying to send a json from componentA to componentB. The problem is that the json appears in the url. How can I make the json not appear?

routing

const appRoutes: Routes = [
  {path: 'componentA', component: componentA},
  {path: 'componentB', component: componentA, data : {}},
  {path: '**', component: NotFoundComponent}
];

template componentA

Send jSON

componentA .ts

this.aArray={"name":"pablo","countrys":["colombia","perú"],"lastname":"ramirez"}
.
.
fn_sendJson(item:any){
 this.router.navigate(['componentB', {"data": JSON.stringify(item)}]);
}

ComponentB .ts

constructor(
 private router : Router,
 private route: ActivatedRoute
 ) {
 sub:any;
 jsonReceived:any
 .
 .
 this.sub = this.route.params
 .subscribe(v => this.jsonReceived =JSON.parse(v.data));

I have not found a way to avoid converting the original json to a string, I would like to know if there is an effective method of sending such as the json, and get it without needing it to be present in the url. Thank you

Body:
When you want to send some complex data from one component to another, it is usually not a good practice to to send it through the url. What you can do is create a service like this:

sharing.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class SharingService {
  private sharingObject: any;
  constructor() { }

  get sharingValue() {
    return this.sharingObject
  }

  set sharingValue(obj) {
    this.sharingObject = obj;
  }
}

Now you need to inject that service in both of your components in order to sharing data between them.

First component will look like this:

first.component.ts

import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService, private router: Router) {
    this.myJson = {
      a: "hello",
      b: "World"
    }
  }

  ngOnInit() {
  }

  send() {
    this.sharingService.sharingValue = this.myJson;
    this.router.navigate(['/second'])
  }

}

Now in your second component, you can access the value set by first component

second.component.ts

import { Component, OnInit } from '@angular/core';
import {SharingService} from '../sharing.service';

@Component({
  selector: 'app-second',
  templateUrl: './second.component.html',
  styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
  myJson: any;
  constructor(private sharingService: SharingService) { }

  ngOnInit() {
   this.myJson = this.sharingService.sharingValue;
  }

}

Here is the working stacklitz demo for this approach

Hope it helps :)


问:
Square multi-party transactions via W3C Web Payments API
Square provide multi-party transaction payment functionality to their merchants/customers via a native bespoke API. Is there anyway other than this feature request to surface the functionality via the Web Payments API?</p>

答:
@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

```<code>const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];
</code>```

Just tell us Square what you need us to tell you and it's done!

Body:
@adrianhopebailie has detailed a solution right here right now for Web Payment Disbursement functionality that requires no (absolutely ZERO) changes to the Payment Request OR Payment Handler APIs and W3C standards! (Always a bonus :-)

As he correctly points out, the methodData argument is opaque and pretty much down to the autonomous Payment Handler to specify. So Stripe, Square, and PayPal are free to specify to their customers the format/naming-convention for communicating Application Fees between Web App supplier and Stripe.

To quote Adrian's example: -

const methodData = [
  {
    supportedMethods: "https://square.com/",
    data: {
      parties: [{
        merchantId: "super-mini-cabs",
        portion: 0.1
      },{
        merchantId: "driver-fred",
        portion: 0.9
      }],
    },
  },
  {
    supportedMethods: "https://stripe.com",
    data: {
      application_fee_amount: 1.00,
    },
  },
  {
    supportedMethods: "https://paypal.com",
    data: {
      payouts: [{
        paypalId: 12478764,
        amount: 1.00
      },{
        paypalId: 23448764,
        amount: 9.00
      }],
    },
  },
];

Just tell us Square what you need us to tell you and it's done!


问:
converting array to object where array values are the object keys and object values are empty
I'm working on a reactjs web app I have an array like

```<code>let arr = ["name","message", etc...];
</code>```

I want to convert it to object but to look like

```<code>let desired = { name:'', message:'' };
</code>```

I tried a few things but none of them worked.

答:
You can also use forEach()

let arr = ['name', 'type', 'id', 'phone'];
let obj = {};
arr.forEach(i=>{obj[i] = ''});

console.log(obj);```

Body:
I'm working on a reactjs web app I have an array like

let arr = ["name","message", etc...];

I want to convert it to object but to look like

let desired = { name:'', message:'' };

I tried a few things but none of them worked.


问:
React Hooks: useState with onClick only updating the SECOND time button is clicked?
Edit: forgot an important part - this is noticeable if you click the button next to Jeff A. Menges and check the console log.

The important part of the code is the "setFullResults(cardResults.data.concat(cardResultsPageTwo.data))" line in the onClick of the button code. I think it SHOULD set fullResults to whatever I tell it to... except it doesn't work the first time you click it. Every time after, it works, but not the first time. That's going to be trouble for the next set, because I can't map over an undefined array, and I don't want to tell users to just click on the button twice for the actual search results to come up.

I'm guessing useEffect would work, but I don't know how to write it or where to put it. It's clearly not working at the top of the App functional component, but anywhere else I try to put it gives me an error.

I've tried "this.forceUpdate()" which a lot of places recommend as a quick fix (but recommend against using - but I've been trying to figure this out for hours), but "this.forceUpdate()" isn't a function no matter where I put it.

Please help me get this button working the first time it's clicked on.

import React, { useState, useEffect } from "react";

const App = () => {

  let artistData = require("./mass-artists.json");

  const [showTheCards, setShowTheCards] = useState();
  const [fullResults, setFullResults] = useState([]);

  useEffect(() => {
    setFullResults();
  }, []);

  let artistDataMap = artistData.map(artistName => {
    //console.log(artistName);
    return (

        {artistName}
        <button
          className="astbutton"
          onClick={ function GetCardList() {
            fetch(
              `https://api.scryfall.com/cards/search?unique=prints&q=a:"${artistName}"`
            )
              .then(response => {
                return response.json();
              })
              .then((cardResults) => {
                console.log(cardResults.has_more)
                if (cardResults.has_more === true) {
                fetch (`https://api.scryfall.com/cards/search?unique=prints&q=a:"${artistName}"&page=2`)
                .then((responsepagetwo) => {
                  return responsepagetwo.json();
                })
                .then(cardResultsPageTwo => {
                  console.log(`First Results Page: ${cardResults}`)
                  console.log(`Second Results Page: ${cardResultsPageTwo}`)
                  setFullResults(cardResults.data.concat(cardResultsPageTwo.data))
                  console.log(`Full Results: ${fullResults}`)
                })
                }
                setShowTheCards(
                  cardResults.data
                  .filter(({ digital }) => digital === false)
                  .map(cardData => {
                    if (cardData.layout === "transform") {
                      return (
                        //TODO : Transform card code
                        Transform Card (Needs special return)
                      )
                    }
                    else if (cardData.layout === "double_faced_token") {
                      return (
                        //TODO: Double Faced Token card code
                        Double Faced Token (Needs special return)
                      )
                    }
                    else {
                      return (

                          {cardData.name}

                          {cardData.set_name}

                      )
                    }
                  })
                )
              });
          }}
        >
          Show Cards
        </button>

    );
  });

  return (

      {artistDataMap}

      {showTheCards}

  );
};

export default App;
```

CodesAndBox: https://codesandbox.io/embed/compassionate-satoshi-iq3nc?fontsize=14

答: You can try refactoring the code like for onClick handler have a synthetic event. Add this event Listener as part of a class. Use arrow function so that you need not bind this function handler inside the constructor. After fetching the data try to set the state to the result and use the state to render the HTML mark up inside render method. And when I run this code, I have also seen one error in console that child elements require key attribute. I have seen you are using Array.prototype.map inside render method, but when you return the span element inside that try to add a key attribute so that when React diffing algorithm encounters a new element it reduces the time complexity to check certain nodes with this key attribute. </p>

Body:
Edit: forgot an important part - this is noticeable if you click the button next to Jeff A. Menges and check the console log.

The important part of the code is the "setFullResults(cardResults.data.concat(cardResultsPageTwo.data))" line in the onClick of the button code. I think it SHOULD set fullResults to whatever I tell it to... except it doesn't work the first time you click it. Every time after, it works, but not the first time. That's going to be trouble for the next set, because I can't map over an undefined array, and I don't want to tell users to just click on the button twice for the actual search results to come up.

I'm guessing useEffect would work, but I don't know how to write it or where to put it. It's clearly not working at the top of the App functional component, but anywhere else I try to put it gives me an error.

I've tried "this.forceUpdate()" which a lot of places recommend as a quick fix (but recommend against using - but I've been trying to figure this out for hours), but "this.forceUpdate()" isn't a function no matter where I put it.

Please help me get this button working the first time it's clicked on.

import React, { useState, useEffect } from "react";

const App = () => {

  let artistData = require("./mass-artists.json");

  const [showTheCards, setShowTheCards] = useState();
  const [fullResults, setFullResults] = useState([]);

  useEffect(() => {
    setFullResults();
  }, []);

  let artistDataMap = artistData.map(artistName => {
    //console.log(artistName);
    return (

        {artistName}
        <button
          className="astbutton"
          onClick={ function GetCardList() {
            fetch(
              `https://api.scryfall.com/cards/search?unique=prints&q=a:"${artistName}"`
            )
              .then(response => {
                return response.json();
              })
              .then((cardResults) => {
                console.log(cardResults.has_more)
                if (cardResults.has_more === true) {
                fetch (`https://api.scryfall.com/cards/search?unique=prints&q=a:"${artistName}"&page=2`)
                .then((responsepagetwo) => {
                  return responsepagetwo.json();
                })
                .then(cardResultsPageTwo => {
                  console.log(`First Results Page: ${cardResults}`)
                  console.log(`Second Results Page: ${cardResultsPageTwo}`)
                  setFullResults(cardResults.data.concat(cardResultsPageTwo.data))
                  console.log(`Full Results: ${fullResults}`)
                })
                }
                setShowTheCards(
                  cardResults.data
                  .filter(({ digital }) => digital === false)
                  .map(cardData => {
                    if (cardData.layout === "transform") {
                      return (
                        //TODO : Transform card code
                        Transform Card (Needs special return)
                      )
                    }
                    else if (cardData.layout === "double_faced_token") {
                      return (
                        //TODO: Double Faced Token card code
                        Double Faced Token (Needs special return)
                      )
                    }
                    else {
                      return (

                          {cardData.name}

                          {cardData.set_name}

                      )
                    }
                  })
                )
              });
          }}
        >
          Show Cards
        </button>

    );
  });

  return (

      {artistDataMap}

      {showTheCards}

  );
};

export default App;

CodesAndBox: https://codesandbox.io/embed/compassionate-satoshi-iq3nc?fontsize=14


问:
Django "autofocus" on form validation error
Using Django 1.9 and python 3.5,  I would like to "set focus" on the first field which fails validation in my modelform.

How is this accomplished?

Thanks.

答:
This solution worked for me:</p>

```<code>class YourForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(YourForm, self).__init__(*args, **kwargs)

    #Focus on form field whenever error occurred
    errorList=list(self.errors)
    for item in errorList:
        self.fields[item].widget.attrs.update({'autofocus': ''})
        break
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This solution worked for me:

class YourForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(YourForm, self).__init__(*args, **kwargs)

    #Focus on form field whenever error occurred
    errorList=list(self.errors)
    for item in errorList:
        self.fields[item].widget.attrs.update({'autofocus': ''})
        break


问:
Reload properties without stopping and restart Boot application
I have application.properties file,which i am using in code to fetch properties.I need to make changes to the property without explicitly stopping and starting the application jar file. I use Dev-tools in STS IDE ,but it doesnt work when jar is ran via java -jar <<>> .

I do not want to include spring cloud config or any DB as it is overkill for my application. Please suggest any other out of the box solution

答:
use commons-configuration dependency to reload your properties file and run given code when you need to reflect your properties file changes.

```<code>    Path rootLocation =  Paths.get("properties file location");
    PropertiesConfiguration config = new PropertiesConfiguration(rootLocation.toAbsolutePath().toString());
    config.setReloadingStrategy(new FileChangedReloadingStrategy());
    config.get<DatatypeOfPropertyField>("propertyName");
</code>```

I am also doing same thing. I am using external properties file. When my application starts, initializing properties to property bean class when changes occurs, executing above code and setting changes in property bean.

Body:
use commons-configuration dependency to reload your properties file and run given code when you need to reflect your properties file changes.

    Path rootLocation =  Paths.get("properties file location");
    PropertiesConfiguration config = new PropertiesConfiguration(rootLocation.toAbsolutePath().toString());
    config.setReloadingStrategy(new FileChangedReloadingStrategy());
    config.get<DatatypeOfPropertyField>("propertyName");

I am also doing same thing. I am using external properties file. When my application starts, initializing properties to property bean class when changes occurs, executing above code and setting changes in property bean.


问:
Can't get Resource from POST/PUT request (.NET FHIR client, web api 2)
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

```<code>fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);
</code>```

...

// web api 2 server:
WebApiConfig.cs:

```<code>config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));
</code>```

I tried:

```<code>[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}
</code>```

but, when I tried

```<code>[HttpPut]
public void Update([FromBody] object resource, string id = null)
{
</code>```

I can see inside "object" a deserialized Patient and use jsonParser to get it back

答:
seems, I have to write my own Fhir MediaTypeFormatter
I googled and found this code:

```<code> public class JsonFhirFormatter : FhirMediaTypeFormatter
    {
        private readonly FhirJsonParser _parser = new FhirJsonParser();
        private readonly FhirJsonSerializer _serializer = new FhirJsonSerializer();

        public JsonFhirFormatter() : base()
        {
            foreach (var mediaType in ContentType.JSON_CONTENT_HEADERS)
                SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = FhirMediaType.GetMediaTypeHeaderValue(type, ResourceFormat.Json);
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                var body = base.ReadBodyFromStream(readStream, content);

                if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = _parser.Parse<Resource>(body);
                    return Task.FromResult<object>(resource);
                }
                else
                {
                    throw Error.Internal("Cannot read unsupported type {0} from body", type.Name);
                }
            }
            catch (FormatException exception)
            {
                throw Error.BadRequest("Body parsing failed: " + exception.Message);
            }
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            using(StreamWriter streamwriter = new StreamWriter(writeStream))
            using (JsonWriter writer = new JsonTextWriter(streamwriter))
            {
                SummaryType summary = requestMessage.RequestSummary();

                if (type == typeof(OperationOutcome))
                {
                    Resource resource = (Resource)value;
                    _serializer.Serialize(resource, writer, summary);
                }
                else if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = (Resource)value;
                    _serializer.Serialize(resource, writer, summary);
                }
                else if (typeof(FhirResponse).IsAssignableFrom(type))
                {
                    FhirResponse response = (value as FhirResponse);
                    if (response.HasBody)
                    {
                        _serializer.Serialize(response.Resource, writer, summary);
                    }
                }
            }

            return Task.CompletedTask;
        }
    }
</code>```

and register it in Global.asax

Body:
When I try to send a POST / PUT request using .NET FHIR API to asp.net Web API 2 server, I get the error message:

Hl7.Fhir.Rest.FhirOperationException: the operation failed due to a

  client error (UnsupportedMediaType). The body has no content.

1) Do I need to create some kind of MediaType Handler / Formatter?

2) Is there an open source server in which code implements the best practices of the .NET FHIR API?

I looked at Fiddler, seems fhir client sends correct JSON in the body

fhirClient = new FhirClient(serverUrl);
fhirClient.PreferredFormat = ResourceFormat.Json;

Patient patient = new Patient();
//fill patient

    var response = fhirClient.Update(patient);

...

// web api 2 server:
WebApiConfig.cs:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/fhir+json"));

I tried:

[HttpPut]
public void Update([FromBody] Resource resource, string id = null)
{
// updating logic
}

//or
[HttpPut]
public void Update(Resource resource, string id = null)
{
// updating logic
}

but, when I tried

[HttpPut]
public void Update([FromBody] object resource, string id = null)
{

I can see inside "object" a deserialized Patient and use jsonParser to get it back

Body:
seems, I have to write my own Fhir MediaTypeFormatter
I googled and found this code:

 public class JsonFhirFormatter : FhirMediaTypeFormatter
    {
        private readonly FhirJsonParser _parser = new FhirJsonParser();
        private readonly FhirJsonSerializer _serializer = new FhirJsonSerializer();

        public JsonFhirFormatter() : base()
        {
            foreach (var mediaType in ContentType.JSON_CONTENT_HEADERS)
                SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = FhirMediaType.GetMediaTypeHeaderValue(type, ResourceFormat.Json);
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                var body = base.ReadBodyFromStream(readStream, content);

                if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = _parser.Parse<Resource>(body);
                    return Task.FromResult<object>(resource);
                }
                else
                {
                    throw Error.Internal("Cannot read unsupported type {0} from body", type.Name);
                }
            }
            catch (FormatException exception)
            {
                throw Error.BadRequest("Body parsing failed: " + exception.Message);
            }
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            using(StreamWriter streamwriter = new StreamWriter(writeStream))
            using (JsonWriter writer = new JsonTextWriter(streamwriter))
            {
                SummaryType summary = requestMessage.RequestSummary();

                if (type == typeof(OperationOutcome))
                {
                    Resource resource = (Resource)value;
                    _serializer.Serialize(resource, writer, summary);
                }
                else if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = (Resource)value;
                    _serializer.Serialize(resource, writer, summary);
                }
                else if (typeof(FhirResponse).IsAssignableFrom(type))
                {
                    FhirResponse response = (value as FhirResponse);
                    if (response.HasBody)
                    {
                        _serializer.Serialize(response.Resource, writer, summary);
                    }
                }
            }

            return Task.CompletedTask;
        }
    }

and register it in Global.asax


答:
Try this:

let arr = ["name","message", "etc"];
let desired = {};
for (let i = 0; i < arr.length; i++) {
    desired[arr[i]] = "";
}
console.log(desired);```

Title: converting array to object where array values are the object keys and object values are empty


问:
Pandas: Looking up the list of sheets in an excel file
The new version of Pandas uses the following interface to load Excel files:

```<code>read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])
</code>```

but what if I don't know the sheets that are available?

For example, I am working with excel files that the following sheets

Data 1, Data 2 ..., Data N, foo, bar

but I don't know N a priori.

Is there any way to get the list of sheets from an excel document in Pandas?

答:
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

```<code>def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets
</code>```

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)

Pandas, xlrd: 12 seconds

openpyxl: 24 seconds

Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.

Body:
The new version of Pandas uses the following interface to load Excel files:

read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])

but what if I don't know the sheets that are available?

For example, I am working with excel files that the following sheets

Data 1, Data 2 ..., Data N, foo, bar

but I don't know N a priori.

Is there any way to get the list of sheets from an excel document in Pandas?

Body:
I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)

Pandas, xlrd: 12 seconds

openpyxl: 24 seconds

Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.


问:
Use Android style Attributes in own Layout
I want to use this style, which is an Android Build in Style Attribute, but it won't compile. I' am missing some kind of Import?

```<code>?android:attr/listItemFirstLineStyle

<TextView
      android:id="@+id/text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1" android:layout_gravity="left|center_vertical" style="?android:attr/listItemFirstLineStyle" android:layout_marginLeft="10dip"/>`
</code>```

thx

答:
did you try to remove the question mark?

style="android:attr/listItemFirstLineStyle"

Body:
I want to use this style, which is an Android Build in Style Attribute, but it won't compile. I' am missing some kind of Import?

?android:attr/listItemFirstLineStyle

<TextView
      android:id="@+id/text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1" android:layout_gravity="left|center_vertical" style="?android:attr/listItemFirstLineStyle" android:layout_marginLeft="10dip"/>`

thx


问:
Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Cannot open server 'azurserver' requested by the login
I am connecting to Azure from SQL Server.

Task: Exporting Azure SQL Database data using bcp from SQL Server 2008 R2.

Step 1: Added IP Address in firewall settings in Azure.

Step 2: Running following script from SQL Server 2008 R2:

```<code>EXEC sp_configure N'show advanced options', 1
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure N'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE;

DECLARE @SQL NVARCHAR(MAX) = ''

SET @SQL = N'Execute xp_cmdshell ''bcp "SELECT * FROM Table;" queryout "D:\AzureTableData.txt" -c -t@_@ -S azure.database.windows.net -d DatabaseName -U user1@azure.database.windows.net -P *****"''';
</code>```

NOTE: IP address is not static at my system and because of this reason, I keep getting an error:

Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Cannot open server 'azurserver' requested by the login. Client with IP address 'XXX.XXX.XXX.XX' is not allowed to access the server.  To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect.

I can't configure firewall settings every time at Azure Portal.

答:
You mean that Add client IP doesn't work for you, do you?

If you want to connect to the Azure SQL database for one time,  you can set the firewall IP  range from 0.0.0.0 to 255.255.255.255.

But for security reasons, we don't suggest to do that.
Azure SQL database could not set the dynamic IP firewall for now.

Hope this helps.

Body:
I am connecting to Azure from SQL Server.

Task: Exporting Azure SQL Database data using bcp from SQL Server 2008 R2.

Step 1: Added IP Address in firewall settings in Azure.

Step 2: Running following script from SQL Server 2008 R2:

EXEC sp_configure N'show advanced options', 1
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure N'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE;

DECLARE @SQL NVARCHAR(MAX) = ''

SET @SQL = N'Execute xp_cmdshell ''bcp "SELECT * FROM Table;" queryout "D:\AzureTableData.txt" -c -t@_@ -S azure.database.windows.net -d DatabaseName -U user1@azure.database.windows.net -P *****"''';

NOTE: IP address is not static at my system and because of this reason, I keep getting an error:

Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Cannot open server 'azurserver' requested by the login. Client with IP address 'XXX.XXX.XXX.XX' is not allowed to access the server.  To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect.

I can't configure firewall settings every time at Azure Portal.


问:
Team Foundation Error, Page '3185ed96-1cbd-4381-a439-636973542e50' not found
I'm start using Visual Studio 2015 Enterprise and when I want to manage connections or anything else with Team Foundation Server give this error: Team Foundation Error, Page '3185ed96-1cbd-4381-a439-636973542e50' not found.
What should I do?!

One thing more...I saw this but not working for me:
Page not found in Visual Studio 2012

答:
This error means Team Explorer was unable to find any of its plugins, which are discovered via MEF. Running as Administrator should not be required.

The first action we should try is to close all VS instances, open a Developer Command Prompt as administrator, and run 'devenv /setup'. This will rebuild the various caches.

If this does not correct the issue, the next step is to try manually deleting the MEF cache dir. Please delete "%LocalAppData%\Microsoft\VisualStudio\15.0_\ComponentModelCache". The cache should be rebuilt on the next VS startup.

Regarding "Manage Connections" doing nothing, this was indeed a bug in the VS 2017 RC3 release. This has been fixed and is pending release.

For reference:
https://developercommunity.visualstudio.com/content/problem/17942/team-explorer-does-not-work-at-all-just-shows-page.html


问:
Django - how to write test for DRF ImageField
I have the following serializer:

```<code>from rest_framework.serializers import Serializer, ImageField

class MySerializer(Serializer):
    avatar = ImageField()
</code>```

how can I write a unit test for it?
I used the Django TestCase, but it raises an error.

```<code>from django.test import TestCase

class MySerializerTest(TestCase):

    def setUp(self):
        self.data = {}
        ...

    def test_image(self):
        import tempfile
        self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file
        r_data = json.dumps(self.data)
        j_data = json.loads(r_data)
        serializer = MySerializer(data=j_data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)
</code>```

but it raises the following error:

TypeError: Object of type 'BufferedRandom' is not JSON serializable

What's my mistake? how can I write a test for image field?

答:
I suggest to use SimpleUploadedFile class from django and create and image using Pillow package. See the example below.

```<code>from PIL import Image

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils.six import BytesIO

class MySerializerTest(TestCase):
    ...

    def test_image(self):
        image = BytesIO()
        Image.new('RGB', (100, 100)).save(image, 'JPEG')
        image.seek(0)

        self.data['avatar'] = SimpleUploadedFile('image.jpg', image.getvalue())
        serializer = MySerializer(data=self.data)
        self.assertEqual(serializer.is_valid(), True)
</code>```

Body:
I have the following serializer:

from rest_framework.serializers import Serializer, ImageField

class MySerializer(Serializer):
    avatar = ImageField()

how can I write a unit test for it?
I used the Django TestCase, but it raises an error.

from django.test import TestCase

class MySerializerTest(TestCase):

    def setUp(self):
        self.data = {}
        ...

    def test_image(self):
        import tempfile
        self.data['avatar'] = tempfile.NamedTemporaryFile(suffix=".jpg").file
        r_data = json.dumps(self.data)
        j_data = json.loads(r_data)
        serializer = MySerializer(data=j_data)
        if not serializer.is_valid():
            import pprint
            pprint.pprint(serializer.errors)
        self.assertEqual(serializer.is_valid(), True)

but it raises the following error:

TypeError: Object of type 'BufferedRandom' is not JSON serializable

What's my mistake? how can I write a test for image field?

Body:
I suggest to use SimpleUploadedFile class from django and create and image using Pillow package. See the example below.

from PIL import Image

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.utils.six import BytesIO

class MySerializerTest(TestCase):
    ...

    def test_image(self):
        image = BytesIO()
        Image.new('RGB', (100, 100)).save(image, 'JPEG')
        image.seek(0)

        self.data['avatar'] = SimpleUploadedFile('image.jpg', image.getvalue())
        serializer = MySerializer(data=self.data)
        self.assertEqual(serializer.is_valid(), True)


问:
How to see the value of a parameter inside a With-Block while debugging?
When debugging in a Visual Basic Project in Visual Studio 2019, I can't see the values of parameters inside a With-Block when I'm hovering over it with the mouse.

I have Resharper Ultimate installed, but it seems like it doesn't provide a function to show it either.

When using a With-Block the values of ".Name", ".URL", etc.
aren't shown when hovering over them in debug mode:

```<code>Private Sub AddCustomer()
    Dim theCustomer As New Customer

    With theCustomer
        .Name = "Coho Vineyard"
        .URL = "http://www.cohovineyard.com/"
        .City = "Redmond"
    End With

    With theCustomer.Comments
        .Add("First comment.")
        .Add("Second comment.")
    End With
End Sub
</code>```

When it is this way, the debugger shows the values just as usual:

```<code>Private Sub AddCustomer()
    Dim theCustomer As New Customer

    theCustomer.Name = "Coho Vineyard"
    theCustomer.URL = "http://www.cohovineyard.com/"
    theCustomer.City = "Redmond"

    theCustomer.Comments.Add("First comment.")
    theCustomer.Comments.Add("Second comment.")
End Sub
</code>```

How can I see the values? Or is there a way to convert the With-Blocks automatically to regular expressions?

答:
I can't see the values of parameters inside a With-Block when I'm
  hovering over it with the mouse.

Do you use DataTips?

I test it in VS2019 16.1(Community and Professional Edition). In a VB.net console app using your example code, we can use DataTips to monitor variable value in debug mode.

Hover over the thecustomer variable and we can get its details during debugging.If this option not work in your side, try repairing VS or update it to latest VS version.

Hope it helps:)

Body:
When debugging in a Visual Basic Project in Visual Studio 2019, I can't see the values of parameters inside a With-Block when I'm hovering over it with the mouse.

I have Resharper Ultimate installed, but it seems like it doesn't provide a function to show it either.

When using a With-Block the values of ".Name", ".URL", etc.
aren't shown when hovering over them in debug mode:

Private Sub AddCustomer()
    Dim theCustomer As New Customer

    With theCustomer
        .Name = "Coho Vineyard"
        .URL = "http://www.cohovineyard.com/"
        .City = "Redmond"
    End With

    With theCustomer.Comments
        .Add("First comment.")
        .Add("Second comment.")
    End With
End Sub

When it is this way, the debugger shows the values just as usual:

Private Sub AddCustomer()
    Dim theCustomer As New Customer

    theCustomer.Name = "Coho Vineyard"
    theCustomer.URL = "http://www.cohovineyard.com/"
    theCustomer.City = "Redmond"

    theCustomer.Comments.Add("First comment.")
    theCustomer.Comments.Add("Second comment.")
End Sub

How can I see the values? Or is there a way to convert the With-Blocks automatically to regular expressions?


问:
Getting an issue with my User Interface in React Native Extra space added not removing
I am trying to build a User Interface but i am getting an issue in my Layout extra space is added at the space of Header and header moving down i am not understanding how to resolve this issue i am attaching an Image of the layout please help.

Here is my code...

```<code>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {createStackNavigator, createAppContainer , createBottomTabNavigator} from 'react-navigation';
import { DrawerNavigator } from 'react-navigation';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AntIcon from "react-native-vector-icons/AntDesign";
import home from './src/Home/home';
import EmployerLayout from './src/Home/EmployerLayout';
import Employers from './src/CompleteEmployers/Employers';
import Jobs from './src/CompleteJobs/Jobs';
import Freelancers from './src/CompleteFreelancers/Freelancers';
import Profile from './src/ProfileSetting/Profile';
import DetailFreelancerScreen from './src/DetailFreelancer/DetailFreelancerScreen';
import DetailJobScreen from './src/DetailJobs/DetailJobScreen';
import DetailCompanyScreen from './src/DetailCompany/DetailCompanyScreen';
import SearchScreen from './src/DetailSearch/SearchScreen';
console.disableYellowBox = true;
const BaseUrl= "https://amentotech.com/projects/api_workreap/wp-json/api/v1";

const MainNavigator = createBottomTabNavigator({
  // MainNavigator: MainDrawer},{
  Home:{
    screen: home,
    navigationOptions:{
      tabBarLabel:'Home',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="home" color={tintColor} size={25} />
      )
    }
  },
  Jobs:{
    screen: Jobs,
    navigationOptions:{
      tabBarLabel:'Jobs',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="appstore-o" color={tintColor} size={25} />
      )
    }
  },
  Freelancers:{
    screen: Freelancers,
    navigationOptions:{
      tabBarLabel:'Freelancers',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="user" color={tintColor} size={25}/>
      )
    }
  },
  Employers:{
    screen: Employers,
    navigationOptions:{
      tabBarLabel:'Employers',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="wallet" color={tintColor} size={25}/>
      )

    }
  },
  Profile:{
    screen: Profile,
    navigationOptions:{
      tabBarLabel:'Profile',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="setting" color={tintColor} size={25} />
      )

    }
  }
},
{
  defaultNavigationOptions: ({ navigation }) => ({
    tabBarIcon: ({ focused }) => {
      const { routeName } = navigation.state;
      let IconComponent = CONST.IC_HOME;
      if (routeName === CONST.MENU_HOME) {
        IconComponent = focused ? CONST.IC_HOME_SELECTED : CONST.IC_HOME;
      } else if (routeName === CONST.MENU_CALENDAR) {
        IconComponent = focused ? CONST.IC_CALENDAR_SELECTED : CONST.IC_CALENDAR;
      }
      return IconComponent;
    }
  }),
  tabBarOptions: {
    activeTintColor: '#ff5851',

  },

});
const RootStack= createStackNavigator({
  home:MainNavigator,
  Profile:Profile,
  Employers:Employers,
  Jobs:Jobs,
  DetailFreelancerScreen:DetailFreelancerScreen,
  DetailJobScreen:DetailJobScreen,
  DetailCompanyScreen:DetailCompanyScreen,
  SearchScreen:SearchScreen,
  EmployerLayout:EmployerLayout,
})

const App = createAppContainer(RootStack);

export default App;
</code>```

Here is my code of App.js i am getting this issue from here please help

答:
What you currently have is the react-navigation's header and your own header.

To fix your issue in a specific component / screen, add the following:

```<code>static navigationOptions = {
  header: null
};
</code>```

Body:
I am trying to build a User Interface but i am getting an issue in my Layout extra space is added at the space of Header and header moving down i am not understanding how to resolve this issue i am attaching an Image of the layout please help.

Here is my code...

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {createStackNavigator, createAppContainer , createBottomTabNavigator} from 'react-navigation';
import { DrawerNavigator } from 'react-navigation';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AntIcon from "react-native-vector-icons/AntDesign";
import home from './src/Home/home';
import EmployerLayout from './src/Home/EmployerLayout';
import Employers from './src/CompleteEmployers/Employers';
import Jobs from './src/CompleteJobs/Jobs';
import Freelancers from './src/CompleteFreelancers/Freelancers';
import Profile from './src/ProfileSetting/Profile';
import DetailFreelancerScreen from './src/DetailFreelancer/DetailFreelancerScreen';
import DetailJobScreen from './src/DetailJobs/DetailJobScreen';
import DetailCompanyScreen from './src/DetailCompany/DetailCompanyScreen';
import SearchScreen from './src/DetailSearch/SearchScreen';
console.disableYellowBox = true;
const BaseUrl= "https://amentotech.com/projects/api_workreap/wp-json/api/v1";

const MainNavigator = createBottomTabNavigator({
  // MainNavigator: MainDrawer},{
  Home:{
    screen: home,
    navigationOptions:{
      tabBarLabel:'Home',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="home" color={tintColor} size={25} />
      )
    }
  },
  Jobs:{
    screen: Jobs,
    navigationOptions:{
      tabBarLabel:'Jobs',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="appstore-o" color={tintColor} size={25} />
      )
    }
  },
  Freelancers:{
    screen: Freelancers,
    navigationOptions:{
      tabBarLabel:'Freelancers',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="user" color={tintColor} size={25}/>
      )
    }
  },
  Employers:{
    screen: Employers,
    navigationOptions:{
      tabBarLabel:'Employers',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="wallet" color={tintColor} size={25}/>
      )

    }
  },
  Profile:{
    screen: Profile,
    navigationOptions:{
      tabBarLabel:'Profile',
      tabBarIcon:({tintColor})=>(
        <AntIcon name="setting" color={tintColor} size={25} />
      )

    }
  }
},
{
  defaultNavigationOptions: ({ navigation }) => ({
    tabBarIcon: ({ focused }) => {
      const { routeName } = navigation.state;
      let IconComponent = CONST.IC_HOME;
      if (routeName === CONST.MENU_HOME) {
        IconComponent = focused ? CONST.IC_HOME_SELECTED : CONST.IC_HOME;
      } else if (routeName === CONST.MENU_CALENDAR) {
        IconComponent = focused ? CONST.IC_CALENDAR_SELECTED : CONST.IC_CALENDAR;
      }
      return IconComponent;
    }
  }),
  tabBarOptions: {
    activeTintColor: '#ff5851',

  },

});
const RootStack= createStackNavigator({
  home:MainNavigator,
  Profile:Profile,
  Employers:Employers,
  Jobs:Jobs,
  DetailFreelancerScreen:DetailFreelancerScreen,
  DetailJobScreen:DetailJobScreen,
  DetailCompanyScreen:DetailCompanyScreen,
  SearchScreen:SearchScreen,
  EmployerLayout:EmployerLayout,
})

const App = createAppContainer(RootStack);

export default App;

Here is my code of App.js i am getting this issue from here please help

Body:
What you currently have is the react-navigation's header and your own header.

To fix your issue in a specific component / screen, add the following:

static navigationOptions = {
  header: null
};


问:
Unable save table after making changes in the model.py file
I am new to django any help would be much appreciated.

I have installed the django-excel tutorial app and made changes to its model.py file.

I have done the following steps :

1) python manage.py makemigrations polls

Output : Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model hpcl

2) python manage.py migrate polls

output : Operations to perform:
  Apply all migrations: polls
Running migrations:
  No migrations to apply.

```<code>Model.py file

from django.db import models

    class hpcl(models.Model):
        plannedPLT = models.IntegerField(default=0)
        pub_date = models.DateTimeField('date published')
        consumption = models.IntegerField(default=0)
        required_PLT = models.CharField(max_length=200)

        def __str__(self):
            return self.pub_date

Request Method: POST
Request URL: http://127.0.0.1:8000/polls/import/

Django Version: 2.2.1
Python Version: 3.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

The above exception (no such table: polls_hpcl) was the direct cause of the following exception:

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\polls\views.py" in import_data
  53.                     ['plannedPLT', 'pub_date', 'consumption', 'required_PLT']

File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\django_excel\__init__.py" in save_book_to_database
  63.         pe.save_book_as(**params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\core.py" in save_book_as
  112.     return sources.save_book(book, **dest_keywords)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\internal\core.py" in save_book
  56.     return _save_any(a_source, book)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\internal\core.py" in _save_any
  60.     a_source.write_data(instance)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\plugins\sources\db_sources.py" in write_data
  111.             **self._keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\plugins\renderers\django.py" in render_book_to_stream
  75.             **keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\io.py" in save_data
  129.         **keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\io.py" in store_data
  146.         writer.write(data)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\book.py" in write
  221.                 sheet_writer.close()

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\database\importers\django.py" in close
  58.                 an_object.save()

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /polls/import/
Exception Value: no such table: polls_hpcl
</code>```

答:
I solved the above problem by following the steps mentioned in the answer :
(view for a detailed explanation)
Django - no such table exception

You need to follow the following simple steps to resolve the above issue :

1)Delete your database (db.sqlite3 in my case) in your project directory

2)Remove everything from pycache folder under your project subdirectory

3)For the application you are trying to fix, go to the folder and clear migrations and pycache directories

When you are sure you have cleared all the above files, run:

python manage.py makemigrations

python manage.py migrate

Body:
I am new to django any help would be much appreciated.

I have installed the django-excel tutorial app and made changes to its model.py file.

I have done the following steps :

1) python manage.py makemigrations polls

Output : Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model hpcl

2) python manage.py migrate polls

output : Operations to perform:
  Apply all migrations: polls
Running migrations:
  No migrations to apply.

Model.py file

from django.db import models

    class hpcl(models.Model):
        plannedPLT = models.IntegerField(default=0)
        pub_date = models.DateTimeField('date published')
        consumption = models.IntegerField(default=0)
        required_PLT = models.CharField(max_length=200)

        def __str__(self):
            return self.pub_date

Request Method: POST
Request URL: http://127.0.0.1:8000/polls/import/

Django Version: 2.2.1
Python Version: 3.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

The above exception (no such table: polls_hpcl) was the direct cause of the following exception:

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\polls\views.py" in import_data
  53.                     ['plannedPLT', 'pub_date', 'consumption', 'required_PLT']

File "C:\Users\dhaval1.desai\Documents\Notes\Feedstock\Django-excelV2\django-excel-master\django_excel\__init__.py" in save_book_to_database
  63.         pe.save_book_as(**params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\core.py" in save_book_as
  112.     return sources.save_book(book, **dest_keywords)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\internal\core.py" in save_book
  56.     return _save_any(a_source, book)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\internal\core.py" in _save_any
  60.     a_source.write_data(instance)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\plugins\sources\db_sources.py" in write_data
  111.             **self._keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel\plugins\renderers\django.py" in render_book_to_stream
  75.             **keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\io.py" in save_data
  129.         **keywords

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\io.py" in store_data
  146.         writer.write(data)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\book.py" in write
  221.                 sheet_writer.close()

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\pyexcel_io\database\importers\django.py" in close
  58.                 an_object.save()

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save
  741.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in save_base
  779.                 force_update, using, update_fields,

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _save_table
  870.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py" in _do_insert
  908.                                using=using, raw=raw)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py" in manager_method
  82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py" in _insert
  1186.         return query.get_compiler(using=using).execute_sql(return_id)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  1335.                 cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in execute
  99.             return super().execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in execute
  67.         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
  76.         return executor(sql, params, many, context)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py" in _execute
  84.                 return self.cursor.execute(sql, params)

File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  383.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /polls/import/
Exception Value: no such table: polls_hpcl


答:
Set header mode to none while creating Stack Navigator. Please refer issue link here along with documentation

```<code>headerMode: 'none',
navigationOptions: ({ navigation }) => ({
  header: null,
}),

const RootStack= createStackNavigator({
  home:MainNavigator,
  Profile:Profile,
  Employers:Employers,
  Jobs:Jobs,
  DetailFreelancerScreen:DetailFreelancerScreen,
  DetailJobScreen:DetailJobScreen,
  DetailCompanyScreen:DetailCompanyScreen,
  SearchScreen:SearchScreen,
  EmployerLayout:EmployerLayout,
  headerMode: 'none',
  navigationOptions: ({ navigation }) => ({
  header: null,
  }),
})
</code>```

Title: Getting an issue with my User Interface in React Native Extra space added not removing

Body:
Set header mode to none while creating Stack Navigator. Please refer issue link here along with documentation

headerMode: 'none',
navigationOptions: ({ navigation }) => ({
  header: null,
}),

const RootStack= createStackNavigator({
  home:MainNavigator,
  Profile:Profile,
  Employers:Employers,
  Jobs:Jobs,
  DetailFreelancerScreen:DetailFreelancerScreen,
  DetailJobScreen:DetailJobScreen,
  DetailCompanyScreen:DetailCompanyScreen,
  SearchScreen:SearchScreen,
  EmployerLayout:EmployerLayout,
  headerMode: 'none',
  navigationOptions: ({ navigation }) => ({
  header: null,
  }),
})


问:
How to check if data exist in Access table
I have created a userform that insert data into an Access table. while inserting data, I want to make sure that the ID inserted must exist in the Access table. I have used the DCOUNT function to do this but this is rendering a 'Type Mismatch' error. I have tried every solution found on the internet but nothing is working here. Please help!

I have modified the DCOUNT expression to put the form variable name into '', [], creating an external variable that refers to the DCOUNT function but nothing is working

```<code>Set conn = createobject("ADODB.connection")
set rs = createobject("ADODB.recordset")
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data source = C:\MyPathMyDB.accdb"
qry = "select * from employee"

with rs
.adnew
if isnumeric(ManagerID) = false then
msgbox "Invalid Manager ID"
exit sub
elseif application.worksheetfunction.dcount("Employee_ID","Employee","activ='Yes'  and Employee_ID='"  & [EmployeeForm.ManagerID] & "'") = 0 then
msgbox "Manager does not exist"
exit sub
else
. fields("Manager_ID").value = ManagerID
end if
end with
</code>```

I expect the function to determine if the Employeeform.ManagerID exist in Employee_ID. If yes, then proceed, else display error message

答:
Dcount (the one you're trying to use) is an Access function: the Excel one is for querying a worksheet range. you will need to query your access database to see if there's a record:

For example:

```<code>sql =  "select * from employee where activ='Yes' and Employee_ID='" & _
        [EmployeeForm.ManagerID] & "'"

rs.open sql, conn

If not rs.eof then
    'got a match: add the new record and update to database
else
    msgbox "Manager not found!"
end if
</code>```

Body:
I have created a userform that insert data into an Access table. while inserting data, I want to make sure that the ID inserted must exist in the Access table. I have used the DCOUNT function to do this but this is rendering a 'Type Mismatch' error. I have tried every solution found on the internet but nothing is working here. Please help!

I have modified the DCOUNT expression to put the form variable name into '', [], creating an external variable that refers to the DCOUNT function but nothing is working

Set conn = createobject("ADODB.connection")
set rs = createobject("ADODB.recordset")
strconn = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data source = C:\MyPathMyDB.accdb"
qry = "select * from employee"

with rs
.adnew
if isnumeric(ManagerID) = false then
msgbox "Invalid Manager ID"
exit sub
elseif application.worksheetfunction.dcount("Employee_ID","Employee","activ='Yes'  and Employee_ID='"  & [EmployeeForm.ManagerID] & "'") = 0 then
msgbox "Manager does not exist"
exit sub
else
. fields("Manager_ID").value = ManagerID
end if
end with

I expect the function to determine if the Employeeform.ManagerID exist in Employee_ID. If yes, then proceed, else display error message

Body:
Dcount (the one you're trying to use) is an Access function: the Excel one is for querying a worksheet range. you will need to query your access database to see if there's a record:

For example:

sql =  "select * from employee where activ='Yes' and Employee_ID='" & _
        [EmployeeForm.ManagerID] & "'"

rs.open sql, conn

If not rs.eof then
    'got a match: add the new record and update to database
else
    msgbox "Manager not found!"
end if


问:
How to find the placement of a List within another List?
I am working with two lists. The first contains a large sequence of strings. The second contains a smaller list of strings. I need to find where the second list exists in the first list.

I worked with enumeration, and due to the large size of the data, this is very slow, I was hoping for a faster way.

```<code>    List<string> first = new List<string>() { "AAA","BBB","CCC","DDD","EEE","FFF" };

    List<string> second = new List<string>() { "CCC","DDD","EEE" };

int x = SomeMagic(first,second);
</code>```

And I would need x to = 2.

答:
Ok, here is my variant with old-good-for-each-loop:

```<code>private int SomeMagic(IEnumerable<string> source, IEnumerable<string> target)
{
    /* Some obvious checks for `source` and `target` lenght / nullity are ommited */

    // searched pattern
    var pattern = target.ToArray();
    // candidates in form `candidate index` -> `checked length`
    var candidates = new Dictionary<int, int>();
    // iteration index
    var index = 0;

    // so, lets the magic begin
    foreach (var value in source)
    {
        // check candidates
        foreach (var candidate in candidates.Keys.ToArray()) // <- we are going to change this collection
        {
            var checkedLength = candidates[candidate];
            if (value == pattern[checkedLength]) // <- here `checkedLength` is used in sense `nextPositionToCheck`
            {
                // candidate has match next value
                checkedLength += 1;
                // check if we are done here
                if (checkedLength == pattern.Length) return candidate; // <- exit point
                candidates[candidate] = checkedLength;
            }
            else
                // candidate has failed
                candidates.Remove(candidate);
        }

        // check for new candidate
        if (value == pattern[0])
            candidates.Add(index, 1);
        index++;
    }

    // we did everything we could
    return -1;
}
</code>```

We use dictionary of candidates to handle situations like:

```<code>var first = new List<string> { "AAA","BBB","CCC","CCC","CCC","CCC","EEE","FFF" };
var second = new List<string> { "CCC","CCC","CCC","EEE" };
</code>```

Body:
I am working with two lists. The first contains a large sequence of strings. The second contains a smaller list of strings. I need to find where the second list exists in the first list.

I worked with enumeration, and due to the large size of the data, this is very slow, I was hoping for a faster way.

    List<string> first = new List<string>() { "AAA","BBB","CCC","DDD","EEE","FFF" };

    List<string> second = new List<string>() { "CCC","DDD","EEE" };

int x = SomeMagic(first,second);

And I would need x to = 2.

Body:
Ok, here is my variant with old-good-for-each-loop:

private int SomeMagic(IEnumerable<string> source, IEnumerable<string> target)
{
    /* Some obvious checks for `source` and `target` lenght / nullity are ommited */

    // searched pattern
    var pattern = target.ToArray();
    // candidates in form `candidate index` -> `checked length`
    var candidates = new Dictionary<int, int>();
    // iteration index
    var index = 0;

    // so, lets the magic begin
    foreach (var value in source)
    {
        // check candidates
        foreach (var candidate in candidates.Keys.ToArray()) // <- we are going to change this collection
        {
            var checkedLength = candidates[candidate];
            if (value == pattern[checkedLength]) // <- here `checkedLength` is used in sense `nextPositionToCheck`
            {
                // candidate has match next value
                checkedLength += 1;
                // check if we are done here
                if (checkedLength == pattern.Length) return candidate; // <- exit point
                candidates[candidate] = checkedLength;
            }
            else
                // candidate has failed
                candidates.Remove(candidate);
        }

        // check for new candidate
        if (value == pattern[0])
            candidates.Add(index, 1);
        index++;
    }

    // we did everything we could
    return -1;
}

We use dictionary of candidates to handle situations like:

var first = new List<string> { "AAA","BBB","CCC","CCC","CCC","CCC","EEE","FFF" };
var second = new List<string> { "CCC","CCC","CCC","EEE" };


问:
Rebasing a branch including all its children
I have the following Git repository topology:

```<code>A-B-F (master)
   \   D (feature-a)
    \ /
     C (feature)
      \
       E (feature-b)
</code>```

By rebasing feature branch I expected to rebase the whole subtree (including child branches):

```<code>$ git rebase feature master

A-B-F (master)
     \   D (feature-a)
      \ /
       C (feature)
        \
         E (feature-b)
</code>```

However, this is the actual result:

```<code>      C' (feature)
     /
A-B-F (master)
   \   D (feature-a)
    \ /
     C
      \
       E (feature-b)
</code>```

I know I can easily fix it manually by executing:

```<code>$ git rebase --onto feature C feature-a
$ git rebase --onto feature C feature-b
</code>```

But is there a way to automatically rebase branch including all its children/descendants?

答:
```<code>git branch --format='%(refname:short)' --contains C | \
xargs -n 1 \
git rebase --committer-date-is-author-date --onto F C^
</code>```

Body:
I have the following Git repository topology:

A-B-F (master)
   \   D (feature-a)
    \ /
     C (feature)
      \
       E (feature-b)

By rebasing feature branch I expected to rebase the whole subtree (including child branches):

$ git rebase feature master

A-B-F (master)
     \   D (feature-a)
      \ /
       C (feature)
        \
         E (feature-b)

However, this is the actual result:

      C' (feature)
     /
A-B-F (master)
   \   D (feature-a)
    \ /
     C
      \
       E (feature-b)

I know I can easily fix it manually by executing:

$ git rebase --onto feature C feature-a
$ git rebase --onto feature C feature-b

But is there a way to automatically rebase branch including all its children/descendants?