问:
Laravel DD api doesn't show full array
I am currently in the process of requesting information from an API. When I try to decode the response of json with json_decode() it doesn't give me the right data. When I use var_dump() it does. How can I make my code correctly display the API data?

I have tried looking on the internet. I have used var_dump() with succes yet it doesn't show the information right as with the dd().

```<code> $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);
        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            $json = json_decode($response);
        }
</code>```

This is the code I use to access the API data. This is the response with var_dump($json):

```<code>
Example: array(344) {
  [0]=>
  object(stdClass)#1148 (1) {
    ["product"]=>
    object(stdClass)#1141 (3) {
      ["information"]=>
      object(stdClass)#1140 (1) {
        ["deliveryDays"]=>
        string(2) "10"
      }
      ["attributes"]=>
      array(6) {
        [0]=>
        object(stdClass)#1142 (2) {
          ["attribute"]=>
          string(18) "Type of sunglasses"
          ["value"]=>
          string(5) "basic"
        }
        [1]=>
        object(stdClass)#1143 (2) {
          ["attribute"]=>
          string(15) "variantid (mcp)"
          ["value"]=>
          string(9) "P105675W1"
        }
        [2]=>
        object(stdClass)#1144 (2) {
          ["attribute"]=>
          string(11) "color (mcp)"
          ["value"]=>
          string(17) "Solid Black/White"
        }
        [3]=>
        object(stdClass)#1145 (2) {
          ["attribute"]=>
          string(8) "quantity"
          ["value"]=>
          string(3) "100"
        }
        [4]=>
        object(stdClass)#1146 (2) {
          ["attribute"]=>
          string(16) "printing process"
          ["value"]=>
          string(12) "tampon print"
        }
        [5]=>
        object(stdClass)#1147 (2) {
          ["attribute"]=>
          string(13) "delivery type"
          ["value"]=>
          string(6) "normal"
        }
      }
      ["price"]=>
      float(213.3)
    }
  }
</code>```

When I use dd($json):

```<code>
  +"product": {#1150 ▼
      +"information": {#1149 ▶}
      +"attributes": array:6 [▼
        0 => {#1151 …2}
        1 => {#1152 …2}
        2 => {#1153 …2}
        3 => {#1154 …2}
        4 => {#1155 …2}
        5 => {#1156 …2}
      ]
      +"price": 407.7
    }
</code>```

As you can see, the API shows ...2 in array 6 but it should show a value. What is wrong about my code?

I want the API to dd the data correctly and show me the data in the api

答:
There is too much data to display for dd(), it is limiting results to save your browser and keep speeds higher.

This is because dd() is using CSS & JS to display data nicely, if a lot of data would be rendered your browser would eventually not be able to handle this.

If you want to see the results of the first item you will have to dd that exact item you want to view for example:

```<code>$json->product->attributes{0}
</code>```

Title: Laravel DD api doesn't show full array

Body:
I am currently in the process of requesting information from an API. When I try to decode the response of json with json_decode() it doesn't give me the right data. When I use var_dump() it does. How can I make my code correctly display the API data?

I have tried looking on the internet. I have used var_dump() with succes yet it doesn't show the information right as with the dd().

 $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);
        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            $json = json_decode($response);
        }

This is the code I use to access the API data. This is the response with var_dump($json):

Example: array(344) {
  [0]=>
  object(stdClass)#1148 (1) {
    ["product"]=>
    object(stdClass)#1141 (3) {
      ["information"]=>
      object(stdClass)#1140 (1) {
        ["deliveryDays"]=>
        string(2) "10"
      }
      ["attributes"]=>
      array(6) {
        [0]=>
        object(stdClass)#1142 (2) {
          ["attribute"]=>
          string(18) "Type of sunglasses"
          ["value"]=>
          string(5) "basic"
        }
        [1]=>
        object(stdClass)#1143 (2) {
          ["attribute"]=>
          string(15) "variantid (mcp)"
          ["value"]=>
          string(9) "P105675W1"
        }
        [2]=>
        object(stdClass)#1144 (2) {
          ["attribute"]=>
          string(11) "color (mcp)"
          ["value"]=>
          string(17) "Solid Black/White"
        }
        [3]=>
        object(stdClass)#1145 (2) {
          ["attribute"]=>
          string(8) "quantity"
          ["value"]=>
          string(3) "100"
        }
        [4]=>
        object(stdClass)#1146 (2) {
          ["attribute"]=>
          string(16) "printing process"
          ["value"]=>
          string(12) "tampon print"
        }
        [5]=>
        object(stdClass)#1147 (2) {
          ["attribute"]=>
          string(13) "delivery type"
          ["value"]=>
          string(6) "normal"
        }
      }
      ["price"]=>
      float(213.3)
    }
  }

When I use dd($json):

  +"product": {#1150 ▼
      +"information": {#1149 ▶}
      +"attributes": array:6 [▼
        0 => {#1151 …2}
        1 => {#1152 …2}
        2 => {#1153 …2}
        3 => {#1154 …2}
        4 => {#1155 …2}
        5 => {#1156 …2}
      ]
      +"price": 407.7
    }

As you can see, the API shows ...2 in array 6 but it should show a value. What is wrong about my code?

I want the API to dd the data correctly and show me the data in the api

Body:
There is too much data to display for dd(), it is limiting results to save your browser and keep speeds higher.

This is because dd() is using CSS & JS to display data nicely, if a lot of data would be rendered your browser would eventually not be able to handle this.

If you want to see the results of the first item you will have to dd that exact item you want to view for example:

$json->product->attributes{0}


来源: stackexchange

问:
htaccess redirect add querystring

I'm triying to redirect www.myweb.com to www.myweb.com/?lang=en

Any try i made redirect all the traffic in the website or creates a loop.

Any help?

答:
I thinkg it should be easier for you to set the GET variable lang to 'en' in php, rather than redirecting... In your code, before handling the lang variable, try:</p>

```<code>if (!isset($_GET['lang'])) {
    $_GET['lang'] = 'en;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: htaccess redirect add querystring

Body:
I thinkg it should be easier for you to set the GET variable lang to 'en' in php, rather than redirecting... In your code, before handling the lang variable, try:

if (!isset($_GET['lang'])) {
    $_GET['lang'] = 'en;
}


问:
Laravel Carbon Data Missing
In my model I have the following:

```<code>protected $dates = [
    'start',
    'end',
    'created_at',
    'updated_at'
];
</code>```

I am using a datetime picker to insert the start and end dates, in this format:

```<code>2016-01-23 22:00
</code>```

Without the seconds. When I do it like this, I get this error:

```<code>InvalidArgumentException in Carbon.php line 425:
Data missing
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 22:00') in Model.php line 3015
</code>```

If I do include the seconds, it works. The seconds are not important to me, and I do not want to include them in my datetime picker fields. Any way around this so I can still use those fields as date fields?

答:
This is one possibility

You need to check the column of resultant data. If your column name 'created_at' or 'updated_at' is null, then it will through this error.

How to Solve ?
First of all, you need to store the data in those two columns using Laravel carbon.
Eg:

```<code>$user = new User();
$user->created_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->updated_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->save();
</code>```

That's All, I hope it will work

Happy Coding....

Title: Laravel Carbon Data Missing

Body:
In my model I have the following:

protected $dates = [
    'start',
    'end',
    'created_at',
    'updated_at'
];

I am using a datetime picker to insert the start and end dates, in this format:

2016-01-23 22:00

Without the seconds. When I do it like this, I get this error:

InvalidArgumentException in Carbon.php line 425:
Data missing
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 22:00') in Model.php line 3015

If I do include the seconds, it works. The seconds are not important to me, and I do not want to include them in my datetime picker fields. Any way around this so I can still use those fields as date fields?

Body:
This is one possibility

You need to check the column of resultant data. If your column name 'created_at' or 'updated_at' is null, then it will through this error.

How to Solve ?
First of all, you need to store the data in those two columns using Laravel carbon.
Eg:

$user = new User();
$user->created_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->updated_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->save();

That's All, I hope it will work

Happy Coding....

ContentLicense: CC BY-SA 4.0


问:
Flutter: How to display a short text file from assets on screen of phone?
I have ckecked all the answers about reading and writing file in Flutter. None of them answers the question of how to display a text file on the screen of the phone.

All I want to do is to have a function/method to call with the filename as input, which will display a short text file from my assets directory on a new screen on the phone that I have navigated to. The file is correctly placed in assets and mentioned in the yaml file. I have seen the suggestion to use:

```<code>Future loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}
</code>```

but I don't know how to use it and what code to use to display a file on the screen.

答:
First this code to have a new screen and call your code:

```<code>child:
FlatButton(
  onPressed: () {
    Navigator.pushNamed(context, '/indled');
    setState(() {
      ReadFile(fileName: 'myfile.txt');
      print('Button 1 got pressed');
    });
    },
    ......
</code>```

It prints Button 1 got pressed on console and goes fine to new screen indled, which has the code:

```<code>class Indled extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Indledning'),
  ),
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      Expanded(
        child: Container(
          padding: EdgeInsets.all(8.0),
          child: Text('Indledning 2'),
</code>```

It prints 'Indledning 2' on the screen as a test, but nothing more happens. I have your code as the following in a separate file:

```<code>class ReadFile {
ReadFile({this.fileName});

final String fileName;

Future<void> readMyFile() async {
Directory directory = await      getApplicationDocumentsDirectory();
var _localFilePath = (directory.path + "myfile.txt");

if (FileSystemEntity.typeSync(_localFilePath) ==
    FileSystemEntityType.file) {
  final myFile = await _localFile(_localFilePath);
  List<String> linesAsList = myFile.readAsLinesSync();

  for (var i = 0; i < linesAsList.length; i++) {
    //print("Line No: " + i.toString() + "\n");
    print(linesAsList[i]);
  }
}
}

Future<File> _localFile(String myPath) async {
return File(myPath);
}
}
</code>```

On the line: List linesAsList = await myFile.readAsLinesSync();
I get a warning on await:  Await only futures
so I took out await. But same result if await is included.

I have tried to put fileName instead of "my file.txt" in your code, but same result.

Body:
I have ckecked all the answers about reading and writing file in Flutter. None of them answers the question of how to display a text file on the screen of the phone.

All I want to do is to have a function/method to call with the filename as input, which will display a short text file from my assets directory on a new screen on the phone that I have navigated to. The file is correctly placed in assets and mentioned in the yaml file. I have seen the suggestion to use:

Future loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}

but I don't know how to use it and what code to use to display a file on the screen.

Body:
First this code to have a new screen and call your code:

child:
FlatButton(
  onPressed: () {
    Navigator.pushNamed(context, '/indled');
    setState(() {
      ReadFile(fileName: 'myfile.txt');
      print('Button 1 got pressed');
    });
    },
    ......

It prints Button 1 got pressed on console and goes fine to new screen indled, which has the code:

class Indled extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Indledning'),
  ),
  body: Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      Expanded(
        child: Container(
          padding: EdgeInsets.all(8.0),
          child: Text('Indledning 2'),

It prints 'Indledning 2' on the screen as a test, but nothing more happens. I have your code as the following in a separate file:

class ReadFile {
ReadFile({this.fileName});

final String fileName;

Future<void> readMyFile() async {
Directory directory = await      getApplicationDocumentsDirectory();
var _localFilePath = (directory.path + "myfile.txt");

if (FileSystemEntity.typeSync(_localFilePath) ==
    FileSystemEntityType.file) {
  final myFile = await _localFile(_localFilePath);
  List<String> linesAsList = myFile.readAsLinesSync();

  for (var i = 0; i < linesAsList.length; i++) {
    //print("Line No: " + i.toString() + "\n");
    print(linesAsList[i]);
  }
}
}

Future<File> _localFile(String myPath) async {
return File(myPath);
}
}

On the line: List linesAsList = await myFile.readAsLinesSync();
I get a warning on await:  Await only futures
so I took out await. But same result if await is included.

I have tried to put fileName instead of "my file.txt" in your code, but same result.


问:
In jQuery uploadify show the images as thumbnails BEFORE the upload by the user's filepath
I'd like to make an uploadify upload to my server, and make thumbnails from the user's images on the fly.

I just need the filepath for each upload. However the only parameter i found in the Javascript is the substringed filename.

Instead of ohmygoditsantaclaus.jpg I want the full path like C:/Etc/Etcetera/Daddy/ohmygoditsantaclaus.jpg. If i have this, i can make a div container easily put the image to it, and resize it with CSS.

Thanks for the help. PS: I used Uploadify v1.6.2

Here is the jQuery Uploadify v.1.6.2 and the Uploader.FLA i currently using.

答: This would be a major security problem, and for all I know, this won't and should not work.</p>


问:
Detecting whether a GPS coordinate falls within a polygon on a map
As stated in the title, the goal is to have a way for detecting whether a given GPS coordinate falls inside a polygon or not.

The polygon itself can be either convex or concave. It's defined as a set of edge vectors and a known point within that polygon. Each edge vector is further defined by four coordinates which are the latitudes and longitudes of respective tip points and a bearing relative to the starting point.

There are a couple of questions similar to this one here on StackOverflow but they describe the solution only in general terms and for a 2D plane, whereas I am looking for an existing implementation that supports polygons defined by latitude/longitude pairs in WGS 84.

What API-s or services are out there for doing such collision tests?

答:
JavaScript Version -

{
const PI = 3.14159265;
const TWOPI = 2*PI;
function isCoordinateInsidePitch(latitude, longitude, latArray, longArray)
{
       let angle=0;
       let p1Lat;
       let p1Long;
       let p2Lat;
       let p2Long;
       let n = latArray.length;

       for (let i = 0; i < n; i++) {
          p1Lat = latArray[i] - latitude;
          p1Long = longArray[i] - longitude;
          p2Lat = latArray[(i+1)%n] - latitude;
          p2Long = longArray[(i+1)%n] - longitude;
          angle += angle2D(p1Lat,p1Long,p2Lat,p2Long);
       }

       return !(Math.abs(angle) < PI);
}

function angle2D(y1, x1, y2, x2)
{
   let dtheta,theta1,theta2;

   theta1 = Math.atan2(y1,x1);
   theta2 = Math.atan2(y2,x2);
   dtheta = theta2 - theta1;
   while (dtheta > PI)
      dtheta -= TWOPI;
   while (dtheta < -PI)
      dtheta += TWOPI;

   return dtheta;
}

function isValidCoordinate(latitude,longitude)
{
    return (
    latitude !== '' && longitude !== '' && !isNaN(latitude)
     && !isNaN(longitude) && latitude > -90 &&
     latitude < 90 && longitude > -180 && longitude < 180
     )
}
let latArray = [32.10458, 32.10479, 32.1038, 32.10361];
let longArray = [34.86448, 34.86529, 34.86563, 34.86486];
// true
console.log(isCoordinateInsidePitch(32.104447, 34.865108,latArray, longArray));
// false
// isCoordinateInsidePitch(32.104974, 34.864576,latArray, longArray);
// true
// isValidCoordinate(0, 0)
// true
// isValidCoordinate(32.104974, 34.864576)
}```

ContentLicense: CC BY-SA 2.5


问:
Why login page is blinking after login in Angular?
My issue is that after login I navigate my page to dashboard page and the URL seems to be http://localhost:4200/home but when I change my URL to http://localhost:4200 it shows me default Login page for some second and then after redirect to http://localhost:4200/home.

at time of login I used to generate the cookies and I want that login page should not display at all when cookies is available.

on app-routing.module.ts i have tried writing as

```<code>const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent },
 ];
</code>```

on AuthGuard I have written code as

```<code>export class AuthGuard implements CanActivate {

constructor(
private router: Router,
private Cookie: CookieService,
private commonser: CommonService
 ) { }
 readonly LocalStName = require('proxy.config.json');
 GetlocalStoragePermissison: any = [];

 async canActivate(
 next: ActivatedRouteSnapshot,
 state: RouterStateSnapshot): Promise<boolean> {
 if (this.Cookie.getCookie('usertoken')) {
   if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
  }
  if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
    for (const a of CommonService.GlobalVar) {
      if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
    }
  }
   return false;
  } else {
     this.router.navigate(['/login']);
      return false;
   }
 }
}
</code>```

the this.commonser.getuserpermisison(); code is as below

```<code>async getuserpermisison() {
const data: any = await this.service.getuserpermisison();
if (data.length > 0) {
  data.push({
    isactive: 1,
    permissionid: null,
    permissionname: 'home',
    permissions: [2],
    total: 2,
    upmid: null
  }
  );
}
CommonService.GlobalVar = [];
this.SetlocalStoragePermissison = [];
for (const userper of data) {
  userper.permissionname = userper.permissionname.toLowerCase();
  if (userper.total > 0) {
    this.SetlocalStoragePermissison.push(Object.assign({}, userper));
  }
}
CommonService.GlobalVar = this.SetlocalStoragePermissison;
}
</code>```

on login.component.ts after login click below code is written

```<code>onSubmit(form: NgForm) {
  this.submitted = true;
  if (form.invalid) {
   return;
 }
this.service.userlogin(form.value.Username, sha512.sha512(form.value.Password)).subscribe(
  async (data: any) => {
    this.Cookie.setCookie('usertoken', data.Token, 1);
    await this.appmethod.getuserpermisison();
    await this.appmethod.getdetails();
    await this.appmethod.callingmethod();
  }, (err: HttpErrorResponse) => {
    if (err.error.message != null) {
      this.commonser.openSnackBarError(err.error.message, 'X');
    } else {
      this.commonser.openSnackBarError(err.message.toString(), 'X');
    }
  });
}
</code>```

The situation is that once I do successful login it redirect to home page and the URL is as http://localhost:4200/home but when I place URL http://localhost:4200 it doesn't show login page, instead it directly redirect to home page

答:
Wrap the macro tasks inside the setTimeout function. Because based on the javascript tasks rules, if condition after the await this.commonser.getuserpermisison(); won't wait for the asynchronous task gets completed.

```<code>if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
    await setTimeout(() => {
      if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
      for (const a of CommonService.GlobalVar) {
        if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
      }
    }
    return false;
    }, 1000);
}
</code>```

Body:
My issue is that after login I navigate my page to dashboard page and the URL seems to be http://localhost:4200/home but when I change my URL to http://localhost:4200 it shows me default Login page for some second and then after redirect to http://localhost:4200/home.

at time of login I used to generate the cookies and I want that login page should not display at all when cookies is available.

on app-routing.module.ts i have tried writing as

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent },
 ];

on AuthGuard I have written code as

export class AuthGuard implements CanActivate {

constructor(
private router: Router,
private Cookie: CookieService,
private commonser: CommonService
 ) { }
 readonly LocalStName = require('proxy.config.json');
 GetlocalStoragePermissison: any = [];

 async canActivate(
 next: ActivatedRouteSnapshot,
 state: RouterStateSnapshot): Promise<boolean> {
 if (this.Cookie.getCookie('usertoken')) {
   if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
  }
  if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
    for (const a of CommonService.GlobalVar) {
      if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
    }
  }
   return false;
  } else {
     this.router.navigate(['/login']);
      return false;
   }
 }
}

the this.commonser.getuserpermisison(); code is as below

async getuserpermisison() {
const data: any = await this.service.getuserpermisison();
if (data.length > 0) {
  data.push({
    isactive: 1,
    permissionid: null,
    permissionname: 'home',
    permissions: [2],
    total: 2,
    upmid: null
  }
  );
}
CommonService.GlobalVar = [];
this.SetlocalStoragePermissison = [];
for (const userper of data) {
  userper.permissionname = userper.permissionname.toLowerCase();
  if (userper.total > 0) {
    this.SetlocalStoragePermissison.push(Object.assign({}, userper));
  }
}
CommonService.GlobalVar = this.SetlocalStoragePermissison;
}

on login.component.ts after login click below code is written

onSubmit(form: NgForm) {
  this.submitted = true;
  if (form.invalid) {
   return;
 }
this.service.userlogin(form.value.Username, sha512.sha512(form.value.Password)).subscribe(
  async (data: any) => {
    this.Cookie.setCookie('usertoken', data.Token, 1);
    await this.appmethod.getuserpermisison();
    await this.appmethod.getdetails();
    await this.appmethod.callingmethod();
  }, (err: HttpErrorResponse) => {
    if (err.error.message != null) {
      this.commonser.openSnackBarError(err.error.message, 'X');
    } else {
      this.commonser.openSnackBarError(err.message.toString(), 'X');
    }
  });
}

The situation is that once I do successful login it redirect to home page and the URL is as http://localhost:4200/home but when I place URL http://localhost:4200 it doesn't show login page, instead it directly redirect to home page

Body:
Wrap the macro tasks inside the setTimeout function. Because based on the javascript tasks rules, if condition after the await this.commonser.getuserpermisison(); won't wait for the asynchronous task gets completed.

if (CommonService.GlobalVar === undefined || CommonService.GlobalVar.length === 0) {
    await this.commonser.getuserpermisison();
    await setTimeout(() => {
      if (CommonService.GlobalVar !== undefined && CommonService.GlobalVar.length > 0) {
      for (const a of CommonService.GlobalVar) {
        if (state.url.replace('/', '').toLowerCase() === a.permissionname) {
        return true;
      }
      }
    }
    return false;
    }, 1000);
}


问:
Reading an XML array to python dict
I am trying to read an array from an XML data file with the shown structure.
By using How do I parse XML in Python? I received the following without my array.

```<code><event id="1" settings="183" digitizer="LoremID" timestamp="42">
 <triggershift samples="0"></triggershift>
 <trace channel="0">2 4 1 2 1 23 5 4 2 4 2
 </trace>
</event>
</code>```

Output:

```<code>{'id': '1',
'settings': '183',
'digitizer': 'LoremID',
'timestamp': '42',
'triggershift': {'samples': '0'},
'trace': {'channel': '0'}}
</code>```

Does anyone have ideas on how to read both the settings and the array?

Thanks in advance.

答:
Code:

```<code>import xml.etree.ElementTree as ET

content = """<event id="1" settings="183" digitizer="LoremID" timestamp="42">
 <triggershift samples="0"></triggershift>
 <trace channel="0">2 4 1 2 1 23 5 4 2 4 2</trace>
</event>"""

root = ET.fromstring(content)
settings = {**root.attrib}
for el in root:
    settings[el.tag] = {**el.attrib}
    if el.text:
        array = el.text.split(" ")
        settings[el.tag]["value"] = array
</code>```

Output:

```<code>{
    "id": "1",
    "settings": "183",
    "digitizer": "LoremID",
    "timestamp": "42",
    "triggershift": {
        "samples": "0"
    },
    "trace": {
        "channel": "0",
        "value": [
            "2",
            "4",
            "1",
            "2",
            "1",
            "23",
            "5",
            "4",
            "2",
            "4",
            "2"
        ]
    }
}
</code>```

Upd.

If you want to convert array elements to int, you can use map():

```<code>settings[el.tag]["value"] = list(map(int, array))
</code>```

Title: Reading an XML array to python dict

Body:
I am trying to read an array from an XML data file with the shown structure.
By using How do I parse XML in Python? I received the following without my array.

<event id="1" settings="183" digitizer="LoremID" timestamp="42">
 <triggershift samples="0"></triggershift>
 <trace channel="0">2 4 1 2 1 23 5 4 2 4 2
 </trace>
</event>

Output:

{'id': '1',
'settings': '183',
'digitizer': 'LoremID',
'timestamp': '42',
'triggershift': {'samples': '0'},
'trace': {'channel': '0'}}

Does anyone have ideas on how to read both the settings and the array?

Thanks in advance.

Body:
Code:

import xml.etree.ElementTree as ET

content = """<event id="1" settings="183" digitizer="LoremID" timestamp="42">
 <triggershift samples="0"></triggershift>
 <trace channel="0">2 4 1 2 1 23 5 4 2 4 2</trace>
</event>"""

root = ET.fromstring(content)
settings = {**root.attrib}
for el in root:
    settings[el.tag] = {**el.attrib}
    if el.text:
        array = el.text.split(" ")
        settings[el.tag]["value"] = array

Output:

{
    "id": "1",
    "settings": "183",
    "digitizer": "LoremID",
    "timestamp": "42",
    "triggershift": {
        "samples": "0"
    },
    "trace": {
        "channel": "0",
        "value": [
            "2",
            "4",
            "1",
            "2",
            "1",
            "23",
            "5",
            "4",
            "2",
            "4",
            "2"
        ]
    }
}

Upd.

If you want to convert array elements to int, you can use map():

settings[el.tag]["value"] = list(map(int, array))


问:
Opening UIDatePicker under UITextView
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

```<code>datePicker = UIDatePicker
</code>```

and

```<code>inputTextfield = UITextField
</code>```

myCode:

```<code>//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }
</code>```

答:
```<code>let dateFormatter = DateFormatter()
let locale = NSLocale.current
var datePicker : UIDatePicker!
let toolBar = UIToolbar()

func doDatePicker() {
    // DatePicker
    self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: UIScreen.main.bounds.height - 200.0, width: UIScreen.main.bounds.width, height: 200))
    self.datePicker?.backgroundColor = UIColor.white
    self.datePicker?.datePickerMode = UIDatePickerMode.dateAndTime
    datePicker.center = view.center
    view.addSubview(self.datePicker)
    // ToolBar
    toolBar.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 240.0, width: UIScreen.main.bounds.width, height: 44.0)
    toolBar.barStyle = .default
    toolBar.isTranslucent = true
    toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
    toolBar.sizeToFit()
    // Adding Button ToolBar
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneClick))
    let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelClick))
    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: true)
    self.view.addSubview(toolBar)
    self.toolBar.isHidden = false
}

@objc func doneClick() {
    let dateFormatter1 = DateFormatter()
    dateFormatter1.dateStyle = .medium
    dateFormatter1.timeStyle = .none
    //self.datePicker.resignFirstResponder()
    datePicker.isHidden = true
    self.toolBar.isHidden = true
}

@objc func cancelClick() {
    datePicker.isHidden = true
    self.toolBar.isHidden = true
}
</code>```

Title: Opening UIDatePicker under UITextView

Body:
I am writing an app, where when clicking on a UITexView an UIDatePicker opens. I want the UIDatePicker to pop up underneath the UITextView and not to come up as the keyboard from the bottom.

I am just starting with IOS app development and I hope someone can help me.

datePicker = UIDatePicker

and

inputTextfield = UITextField

myCode:

//Function to create the datepicker
func createDatePicker(){
            //create instance of the datepicker
            datePicker = UIDatePicker()
            //sets format, so only day month and year can be selected
            //datePicker?.datePickerMode = .date
            datePicker?.backgroundColor = .white
            datePicker?.addTarget(self, action: #selector(ViewController.dateChanged(datePicker:)), for: .valueChanged)
            //to limit the datepicker, you can not pick a date older than yesterday
            let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
            datePicker?.minimumDate = yesterday
            datePicker?.minuteInterval = 30
            let loc = Locale(identifier: "de")
            datePicker?.locale = loc

            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gesturRecognizer:)))

            view.addGestureRecognizer(tapGesture)

            inputTextfield.inputView = datePicker

            //create a toolbar
            let toolbar = UIToolbar()
            toolbar.sizeToFit()

            //add done button to the toolbar
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneClicked))
            toolbar.setItems([doneButton], animated: true)

            inputTextfield.inputAccessoryView = toolbar
        }

        //function to select a date
        @objc func dateChanged(datePicker: UIDatePicker){

            //selected date by the user
            let dateFormate = DateFormatter()
            //Jonas das ist vllt für dich relevant, man kann es so verändern wie man will
            dateFormate.dateFormat = "MM/dd/yyyy"
            inputTextfield.text = dateFormate.string(from: datePicker.date)
        }

        //function to close the datepicker, when tapping on the inputText again -handler method
        @objc func viewTapped(gesturRecognizer: UITapGestureRecognizer){
            view.endEditing(true)
        }

        //function to close the datepicker when clicking on the done button
        @objc func doneClicked(){
            self.view.endEditing(true)
        }


问:
Print a List of All Tests in a Rails App
Is there an easy ruby or rails command to get a list of all the tests in an application?  I use Shoulda primarily, but if there's a ruby solution regardless of test suite that would work too.</p>

答:
I think you need this. It's what the "rails test" command does</p>

```<code>tests = Rake::FileList["test/**/*_test.rb"]
</code>```

Body:
I think you need this. It's what the "rails test" command does

tests = Rake::FileList["test/**/*_test.rb"]


问:
call in BATCH doesnt work
I have created file called a.bat

```<code>call echo. > outfile
call dup.bat file1 outfile 7
call MORE file2 >> outfile
call dup.bat file1 outfile 10
</code>```

when I execute it the output is

```<code>C:\>a
C:\>call echo.  1>outfile
C:\>call dup.bat file1 outfile 7
C:\>
</code>```

I don't understand why it stops the excution after executing the first batch

the batch is an answer to this question
how to do loop in Batch?

the dup.bat

```<code>@ECHO off
SET infile=%1
SET outfile=%2
SET times=%3

rem IF EXIST %outfile% DEL %outfile%
FOR /L %%i IN (1,1,%times%) DO (
    call MORE %infile% >> %outfile%
)
</code>```

Maybe some silent exception is being thrown? how to catch it?

Any ideas?

答:
I think it just works: execution does not stop, only echo stops!

Please check your output file outfile and verify its contents. The reason that you do not see the last two lines of a.bat is that dup.bat turns echo off…

Title: call in BATCH doesnt work

Body:
I have created file called a.bat

call echo. > outfile
call dup.bat file1 outfile 7
call MORE file2 >> outfile
call dup.bat file1 outfile 10

when I execute it the output is

C:\>a
C:\>call echo.  1>outfile
C:\>call dup.bat file1 outfile 7
C:\>

I don't understand why it stops the excution after executing the first batch

the batch is an answer to this question
how to do loop in Batch?

the dup.bat

@ECHO off
SET infile=%1
SET outfile=%2
SET times=%3

rem IF EXIST %outfile% DEL %outfile%
FOR /L %%i IN (1,1,%times%) DO (
    call MORE %infile% >> %outfile%
)

Maybe some silent exception is being thrown? how to catch it?

Any ideas?


问:
How to add objects to a private list with a method?
You can see the list i created is private and I want to be able to add objects to the list aswell as showing the user the list through methods AddBook() and ShowBooks().

```<code>public class Library
{
    private List<Book> Books = new List<Book>();

    public static void AddBook()
    {
    }

    public static void ShowBooks()
    {
        foreach (Book item in Books)
        //This foreach-loop doesn't work since its a private list.
        {
            Console.WriteLine("Books found");
        }
    }
}
</code>```

The loop doesnt work since "An object reference is required for the non-static field, method, or property" refering to the list.

答:
If you do not want to use static on the books collection do this:</p>

```<code>public class Library
{
    private List<Book> Books = new List<Book>();

    public void AddBook()
    {
    }

    public void ShowBooks()
    {
        var library = new Library();
        foreach (Book item in Books)
        {
            //This foreach-loop doesn't work since its a private list.
            library.Books.Add(item);
            Console.WriteLine("Books found");
        }
    }
}
</code>```

Body:
You can see the list i created is private and I want to be able to add objects to the list aswell as showing the user the list through methods AddBook() and ShowBooks().

public class Library
{
    private List<Book> Books = new List<Book>();

    public static void AddBook()
    {
    }

    public static void ShowBooks()
    {
        foreach (Book item in Books)
        //This foreach-loop doesn't work since its a private list.
        {
            Console.WriteLine("Books found");
        }
    }
}

The loop doesnt work since "An object reference is required for the non-static field, method, or property" refering to the list.

Body:
If you do not want to use static on the books collection do this:

public class Library
{
    private List<Book> Books = new List<Book>();

    public void AddBook()
    {
    }

    public void ShowBooks()
    {
        var library = new Library();
        foreach (Book item in Books)
        {
            //This foreach-loop doesn't work since its a private list.
            library.Books.Add(item);
            Console.WriteLine("Books found");
        }
    }
}


问:
Laravel Query Error - htmlspecialchars() expects parameter 1 to be string, object given
Am trying to get the total sum for amount from in table for a particular month, but I got this error:

htmlspecialchars() expects parameter 1 to be string, object given

'currentmonthbilling' => object(Builder),

The table name is billings

I have written the query

```<code> $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
            ->select(DB::raw("SUM(amount)"))
                        ->whereRaw('MONTH(created_at) = ?',[$currentMonth]);
</code>```

I want to get the total amount paid by everyone for the current month

答:
To get query result you must have to add get() at the end.

like:

```<code>$currentMonth = date('m');
$currentmonthbilling = DB::table("billings")
       ->select(DB::raw("SUM(amount) as total"))
       ->whereRaw('MONTH(created_at) = ?',[$currentMonth])
       ->get();
</code>```

Body:
Am trying to get the total sum for amount from in table for a particular month, but I got this error:

htmlspecialchars() expects parameter 1 to be string, object given

'currentmonthbilling' => object(Builder),

The table name is billings

I have written the query

 $currentMonth = date('m');
            $currentmonthbilling = DB::table("billings")
            ->select(DB::raw("SUM(amount)"))
                        ->whereRaw('MONTH(created_at) = ?',[$currentMonth]);

I want to get the total amount paid by everyone for the current month

Body:
To get query result you must have to add get() at the end.

like:

$currentMonth = date('m');
$currentmonthbilling = DB::table("billings")
       ->select(DB::raw("SUM(amount) as total"))
       ->whereRaw('MONTH(created_at) = ?',[$currentMonth])
       ->get();


问:
Confusion about start end index in binary search
Following is the binary search from this post. s means start index, e means end index. I think I understand them.

```<code>function bs(arr, tar) {
  let s = 0;
  let e = arr.length - 1;

  while(s <= e) {
    let m = Math.floor((s + e) / 2);

    if(tar === arr[m]) {
      return m;
    }

    if(tar > arr[m]) {
      s = m + 1; // follow index
    }

    if(tar < arr[m]) {
      e = m - 1; // follow index
    }
  }

  return -1;
}

let arr = [1, 2, 3, 4, 5, 6, 7];
let tar = 5;
let out = bs(arr, tar);
console.log(out);
</code>```

Sometimes I also see this version:

```<code>function bs(arr, tar) {
  let s = 0;
  let e = arr.length; // full len

  while(s < e) {
    let m = Math.floor((s + e) / 2);

    if(tar === arr[m]) {
      return m;
    }

    if(tar > arr[m]) {
      s = m + 1; // because s=0;
    }

    // end, exact index
    if(tar < arr[m]) {
      e = m; // not m-1, because arr.length???
    }
  }

  return -1;
}

let arr = [1, 2, 3, 4, 5, 6, 7];
let tar = 5;
let out = bs(arr, tar);
console.log(out);
</code>```

I think after a while, I get what the indexes mean.

答: Binary search need an ordered list to work, for example a list of numbers. The idea is to search an element in the right half and this is possible because this algorithm converge to one. Let's say that you have a list of 10(1, 10, 54, 70, 100, 110, 120, 130, 150, 200)numbers and you are looking for  120. You divide list into two halves and look for the middle element (100) is 120 greater than 100? Yes so the element is in the second half, now start point is middle position and end position is the end of the list, you go on until you have an element, the one you are looking for. Hope this was helpful </p>

Body:
Following is the binary search from this post. s means start index, e means end index. I think I understand them.

function bs(arr, tar) {
  let s = 0;
  let e = arr.length - 1;

  while(s <= e) {
    let m = Math.floor((s + e) / 2);

    if(tar === arr[m]) {
      return m;
    }

    if(tar > arr[m]) {
      s = m + 1; // follow index
    }

    if(tar < arr[m]) {
      e = m - 1; // follow index
    }
  }

  return -1;
}

let arr = [1, 2, 3, 4, 5, 6, 7];
let tar = 5;
let out = bs(arr, tar);
console.log(out);

Sometimes I also see this version:

function bs(arr, tar) {
  let s = 0;
  let e = arr.length; // full len

  while(s < e) {
    let m = Math.floor((s + e) / 2);

    if(tar === arr[m]) {
      return m;
    }

    if(tar > arr[m]) {
      s = m + 1; // because s=0;
    }

    // end, exact index
    if(tar < arr[m]) {
      e = m; // not m-1, because arr.length???
    }
  }

  return -1;
}

let arr = [1, 2, 3, 4, 5, 6, 7];
let tar = 5;
let out = bs(arr, tar);
console.log(out);

I think after a while, I get what the indexes mean.


问:
segmentation fault when calling fortran subroutine in C++
I am trying to call a Fortran subroutine in C++.

this is the subroutine start:

```<code>    subroutine fireballess(ear,ne,parames,ifl,photar,photer)
    integer ne,ifl
    real*4 ear(0:ne),parames(10),photar(ne),photer(ne)
</code>```

The subroutine works fine in Fortran, but when I try to call it in C++ I get a segmentation fault. Here is my code:

```<code>    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>

    using namespace std;

    extern "C" void fireballess_( double *fear, int fne,double* fparames, nt fifl, double *fphotar, double *fphoter);

    int main(int argc, char ** argv)
    {
            int ne,ifl;
            double *ear;
        double *parames;

        double *photar;
            double *photer;

        parames = new double[9];

            parames[0]=4.3;
           parames[1]=0.23;
           parames[2]=0.5;
           parames[3]=0.5;
           parames[4]=1.5;
           parames[5]=1.;
           parames[6]=1000.;
           parames[7]=2.15;
           parames[8]=3.;

        ne = 3;

            ear = new double[ne];
        ear[0] = 0.;
        ear[1] = 20.;
        ear[2] = 40.;
        ifl=2;

            photar = new double[ne];
            photer = new double[ne];

    // Check on variables initialization

        for (int i=0;i<=2;i++)    cout << ear[i] <<",";
        cout <<"    "<< ne<<"   ";
        for (int i=0;i<=8;i++)    cout << parames[i] <<",";
        cout <<"    "<< ifl <<" "<< photar[0] <<"   "<< photer[0] << endl;

            cout << "Calling a Fortran subroutine" << endl;
            cout << "===============================" << endl;

    // call to the subroutine -->segmentation fault
            fireballess_(ear,ne,parames,ifl,photar,photer);

        for (int i=0;i<=ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
        }

            delete[] ear;
            delete[] parames;
            delete[] photar;
            delete[] photer;
    }
</code>```

The program crashes on the call to the subroutine. I am not very experienced in C++ or Fortran coding, so I am not sure about what to do. So far I have checked the format of the variables passed to the subroutine was correct, and it looks so.

Thanks in advance for any help

---------EDIT------
after reading some comments I revised the code as follows, still getting the same segmentation fault error when the routine is invoked:

```<code>using namespace std;

extern "C" void fireballess_( std::vector<float> fear, int fne,std::vector<float> fparames, int fifl, std::vector<float> fphotar, std::vector<float> fphoter);

int main(int argc, char ** argv)
{
    int ne,ifl;
ifl=2;
ne = 3;
    std::vector<float> parames = {4.3,0.23,0.5,0.5,1.5,1.,1000.,2.15,3.};
std::vector<float> ear={0,20,40};
    std::vector<float> photar;
    std::vector<float> photer;

    cout << "Calling a Fortran subroutine" << endl;
    cout << "===============================" << endl;
        fireballess_(ear,ne,parames,ifl,photar,photer);

for (int i=0;i<ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
}

}
</code>```

答:
The modern way of calling Fortran functions from C and C++ code is via ISO_C_BINDING, see its tag wiki on SO. Without this interface there are some quirks like

all variables are passed by reference (pointer) to Fortran functions

when passing arrays you must also pass their lengths

...

This old quirky way of C/Fortran interoperation is described e.g. here.

Note that you can't pass std::vector or any other complex C++ object to a C or Fortran function and expect that it'll understand it. This will most likely not work, unless the function was designed to handle this. So you need to get actual low-level data (e.g. pointers to arrays) from these objects and pass them instead.

Body:
I am trying to call a Fortran subroutine in C++.

this is the subroutine start:

    subroutine fireballess(ear,ne,parames,ifl,photar,photer)
    integer ne,ifl
    real*4 ear(0:ne),parames(10),photar(ne),photer(ne)

The subroutine works fine in Fortran, but when I try to call it in C++ I get a segmentation fault. Here is my code:

    #include <stdlib.h>
    #include <stdio.h>
    #include <iostream>

    using namespace std;

    extern "C" void fireballess_( double *fear, int fne,double* fparames, nt fifl, double *fphotar, double *fphoter);

    int main(int argc, char ** argv)
    {
            int ne,ifl;
            double *ear;
        double *parames;

        double *photar;
            double *photer;

        parames = new double[9];

            parames[0]=4.3;
           parames[1]=0.23;
           parames[2]=0.5;
           parames[3]=0.5;
           parames[4]=1.5;
           parames[5]=1.;
           parames[6]=1000.;
           parames[7]=2.15;
           parames[8]=3.;

        ne = 3;

            ear = new double[ne];
        ear[0] = 0.;
        ear[1] = 20.;
        ear[2] = 40.;
        ifl=2;

            photar = new double[ne];
            photer = new double[ne];

    // Check on variables initialization

        for (int i=0;i<=2;i++)    cout << ear[i] <<",";
        cout <<"    "<< ne<<"   ";
        for (int i=0;i<=8;i++)    cout << parames[i] <<",";
        cout <<"    "<< ifl <<" "<< photar[0] <<"   "<< photer[0] << endl;

            cout << "Calling a Fortran subroutine" << endl;
            cout << "===============================" << endl;

    // call to the subroutine -->segmentation fault
            fireballess_(ear,ne,parames,ifl,photar,photer);

        for (int i=0;i<=ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
        }

            delete[] ear;
            delete[] parames;
            delete[] photar;
            delete[] photer;
    }

The program crashes on the call to the subroutine. I am not very experienced in C++ or Fortran coding, so I am not sure about what to do. So far I have checked the format of the variables passed to the subroutine was correct, and it looks so.

Thanks in advance for any help

---------EDIT------
after reading some comments I revised the code as follows, still getting the same segmentation fault error when the routine is invoked:

using namespace std;

extern "C" void fireballess_( std::vector<float> fear, int fne,std::vector<float> fparames, int fifl, std::vector<float> fphotar, std::vector<float> fphoter);

int main(int argc, char ** argv)
{
    int ne,ifl;
ifl=2;
ne = 3;
    std::vector<float> parames = {4.3,0.23,0.5,0.5,1.5,1.,1000.,2.15,3.};
std::vector<float> ear={0,20,40};
    std::vector<float> photar;
    std::vector<float> photer;

    cout << "Calling a Fortran subroutine" << endl;
    cout << "===============================" << endl;
        fireballess_(ear,ne,parames,ifl,photar,photer);

for (int i=0;i<ne;i++){
        cout << "ear = " <<ear[i-1]<< " - "<<ear[i] << endl;
        cout << "photar = " << photar[i] << endl;
        cout << "photer = " << photer[i] << endl << endl;
}

}


问:
Arrow key not working in component
I use the Gecko SDK, a component that allows you to view web pages.

I use this component to create an html editor.

This problem happens when going off editing web pages.

The problem is that the arrow keys and the tab does not work with my component. I tried to find an answer to this problem, but I didn't find one. I found a track here, but the function does not work.

Function Movement (dx, dy) does not exist. Thank you for helping me solve this problem.

```<code>Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin   dx: 0; dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    Case  wparam of
      VK_LEFT  : dx := -1;
      VK_RIGHT : dx :=  1;
      VK_UP    : dy := -1;
      VK_DOWN  : dy :=  1;
    end;
  end;
  IF (dy = 0) AND (Dx = 0) then Handled := false else
  begin
    handled := true;     // message traité
    Mouvement(dx, dy)    // exécution du tracé
  end;
end;
</code>```

答:
Add this to your component's class:

```<code>procedure HandleDlgCode(var Msg:TMessage); message WM_GETDLGCODE;
</code>```

and then in the implementation section:

```<code>procedure TComponentClass.HandleDlgCode(var Msg:TMessage);
var
  M: PMsg;
begin
  Msg.Result := DLGC_WANTALLKEYS or DLGC_WANTARROWS or DLGC_WANTCHARS or DLGC_HASSETSEL;
  if Msg.lParam <> 0 then
    begin
      M := PMsg(Msg.lParam);
      case M.message of
        WM_KEYDOWN, WM_KEYUP, WM_CHAR:
        begin
          Perform(M.message, M.wParam, M.lParam);
          Msg.Result := Msg.Result or DLGC_WANTMESSAGE;
        end;
      end;
    end
  else
    Msg.Result := Msg.Result or DLGC_WANTMESSAGE;
end;
</code>```

I've just copy-pasted this code from my own numeric editor, so it works.

Title: Arrow key not working in component

Body:
I use the Gecko SDK, a component that allows you to view web pages.

I use this component to create an html editor.

This problem happens when going off editing web pages.

The problem is that the arrow keys and the tab does not work with my component. I tried to find an answer to this problem, but I didn't find one. I found a track here, but the function does not work.

Function Movement (dx, dy) does not exist. Thank you for helping me solve this problem.

Procedure Tform1.TraiteMessages(Var msg : TMsg; Var Handled: boolean);
var
  dx, dy : integer;
begin   dx: 0; dy := 0;
  With msg do
  begin
    IF Message = WM_KEYDOWN then
    Case  wparam of
      VK_LEFT  : dx := -1;
      VK_RIGHT : dx :=  1;
      VK_UP    : dy := -1;
      VK_DOWN  : dy :=  1;
    end;
  end;
  IF (dy = 0) AND (Dx = 0) then Handled := false else
  begin
    handled := true;     // message traité
    Mouvement(dx, dy)    // exécution du tracé
  end;
end;

Body:
Add this to your component's class:

procedure HandleDlgCode(var Msg:TMessage); message WM_GETDLGCODE;

and then in the implementation section:

procedure TComponentClass.HandleDlgCode(var Msg:TMessage);
var
  M: PMsg;
begin
  Msg.Result := DLGC_WANTALLKEYS or DLGC_WANTARROWS or DLGC_WANTCHARS or DLGC_HASSETSEL;
  if Msg.lParam <> 0 then
    begin
      M := PMsg(Msg.lParam);
      case M.message of
        WM_KEYDOWN, WM_KEYUP, WM_CHAR:
        begin
          Perform(M.message, M.wParam, M.lParam);
          Msg.Result := Msg.Result or DLGC_WANTMESSAGE;
        end;
      end;
    end
  else
    Msg.Result := Msg.Result or DLGC_WANTMESSAGE;
end;

I've just copy-pasted this code from my own numeric editor, so it works.


问:
3rd party sync method freezing the UI in .NET 4.7.2 WPF
I have a .NET 4.7.2 application using WPF MVVM. I am connecting to a robot using the provided library from the manufacturer. Unfortunately, their method that connects to the robot stops for 30 seconds when the IP parameter is faulty and this essentially freezes the UI.

I decided to use async/await to fix this issue, based on this I figured it is an I/O-Bound problem, but since the method I use to connect to the robot is sync, I couldn't await it. In the examples I saw they usually used async libraries at the first place and I couldn't find how to solve this problem, when a sync method is provided by 3rd party is freezing my UI.

The first code snippet didn't work, my UI stopped for 30 seconds when I tried to connect.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await ConnectToFanuc(ip);

            return result;
        }

private Task<bool> ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return Task.FromResult(true);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }
```

<p>Eventually I got around it by using the CPU-Bound example (second code snippet), however, this is not really a CPU bound problem, hence I'm not sure if this would cause problems in the future.</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await Task.Run(() => ConnectToFanuc(ip));

            return result;
        }

private bool ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return true;
            }
            catch
            {
                return false;
            }
        }
</code>```

Is there a better way to solve this problem? Should I use something other than the async/await keywords?

答:
Using Task.Run to make asynchronous wrappers around synchronous methods is generally considered a bad practice unless you want to offload the current thread to prevent it from freezing while waiting for the synchronous method complete.

So since ConnectToFanuc is obviously not asynchronous in this case, it is a viable workaround to use await Task.Run to call it.

Please refer to this blog for more information about this.

Body:
I have a .NET 4.7.2 application using WPF MVVM. I am connecting to a robot using the provided library from the manufacturer. Unfortunately, their method that connects to the robot stops for 30 seconds when the IP parameter is faulty and this essentially freezes the UI.

I decided to use async/await to fix this issue, based on this I figured it is an I/O-Bound problem, but since the method I use to connect to the robot is sync, I couldn't await it. In the examples I saw they usually used async libraries at the first place and I couldn't find how to solve this problem, when a sync method is provided by 3rd party is freezing my UI.

The first code snippet didn't work, my UI stopped for 30 seconds when I tried to connect.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await ConnectToFanuc(ip);

            return result;
        }

private Task<bool> ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return Task.FromResult(true);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }

Eventually I got around it by using the CPU-Bound example (second code snippet), however, this is not really a CPU bound problem, hence I'm not sure if this would cause problems in the future.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await Task.Run(() => ConnectToFanuc(ip));

            return result;
        }

private bool ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return true;
            }
            catch
            {
                return false;
            }
        }

Is there a better way to solve this problem? Should I use something other than the async/await keywords?


问:
CSS transition width not working with flex
Layout:

```<code><div style={{ flex:1 }}>
    <div className="sideBarContainer">
         <div className="sideBar">
         <div className="sideBarExtra"> <--- conditional
    </div>
    <div className="content"></div>
</div>
</code>```

CSS:

```<code>.sideBarContainer {
    display: flex;
    flex-direction: row;
}
.sideBar {
    height: 100vh;
    min-width: 64px;
    z-index: 99;
}
.content {
    flex: 1;
    transition: width .3s linear;
}
</code>```

sideBarExtra conditionally renders using the react-tranisition-group CSSTransitionGroup component.

The sideBarExtra will slide in smoothly from left to right when it is rendered, and slide out right to left when it is removed.

The content div does not transition smoothly when sideBarExtra is added, it jumps to its spots.

Expected behaviour: content to smoothly slide to it's new width.

In the console dev tools I can see the content width being changed, but no transition animation is happening.

答:
.sideBarContainer {
    display: flex;
    flex-direction: row;
    width: 100%;
}
.sideBar {
    background: red;
    height: 100vh;
    min-width: 64px;
    z-index: 99;
}

.content {
    width: 10%;
    height: 100vh;
    background: yellow;
    transition: width .3s linear;
}
.content:hover {
  width: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display:flex;">
    <div class="sideBarContainer">
         <div class="sideBar">
         <div class="sideBarExtra"> </div>
    </div>
    <div class="content">Hover me</div>
</div></code>```

You can change the instant

```<code>.content {
    flex: 1;
    transition: width: .3s linear;
}
</code>```

to

```<code>.content {
    flex: 1;
    transition: width .3s linear;
}
</code>```

the transition does not take any : Colon here the above code

Answare 2

You can also set animation for flex property here the example:

.sideBarContainer {
    display: flex;
    flex-direction: row;
    width: 100%;
}
.sideBar {
    background: red;
    height: 100vh;
    min-width: 64px;
    z-index: 99;
    flex: 2;
    transition: flex .3s linear;
}

.content {
    flex: 1;
    height: 100vh;
    background: yellow;
    transition: flex .3s linear;
}
.sideBarContainer:hover .sideBar {
  flex: 1;
}
.sideBarContainer:hover .content {
  flex: 2 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display:flex;">
    <div class="sideBarContainer">
         <div class="sideBar">
         <div class="sideBarExtra"> </div>
    </div>
    <div class="content">Hover me</div>
</div></code>```

Body:
Layout:

 <--- conditional

CSS:

.sideBarContainer {
    display: flex;
    flex-direction: row;
}
.sideBar {
    height: 100vh;
    min-width: 64px;
    z-index: 99;
}
.content {
    flex: 1;
    transition: width .3s linear;
}

sideBarExtra conditionally renders using the react-tranisition-group CSSTransitionGroup component.

The sideBarExtra will slide in smoothly from left to right when it is rendered, and slide out right to left when it is removed.

The content div does not transition smoothly when sideBarExtra is added, it jumps to its spots.

Expected behaviour: content to smoothly slide to it's new width.

In the console dev tools I can see the content width being changed, but no transition animation is happening.

Body:
.sideBarContainer {
    display: flex;
    flex-direction: row;
    width: 100%;
}
.sideBar {
    background: red;
    height: 100vh;
    min-width: 64px;
    z-index: 99;
}

.content {
    width: 10%;
    height: 100vh;
    background: yellow;
    transition: width .3s linear;
}
.content:hover {
  width: 80%;
}

<div style="display:flex;">
    <div class="sideBarContainer">
         <div class="sideBar">
         <div class="sideBarExtra"> </div>
    </div>
    <div class="content">Hover me</div>
</div>

You can change the instant

.content {
    flex: 1;
    transition: width: .3s linear;
}

to

.content {
    flex: 1;
    transition: width .3s linear;
}

the transition does not take any : Colon here the above code

Answare 2

You can also set animation for flex property here the example:

.sideBarContainer {
    display: flex;
    flex-direction: row;
    width: 100%;
}
.sideBar {
    background: red;
    height: 100vh;
    min-width: 64px;
    z-index: 99;
    flex: 2;
    transition: flex .3s linear;
}

.content {
    flex: 1;
    height: 100vh;
    background: yellow;
    transition: flex .3s linear;
}
.sideBarContainer:hover .sideBar {
  flex: 1;
}
.sideBarContainer:hover .content {
  flex: 2 0 auto;
}

<div style="display:flex;">
    <div class="sideBarContainer">
         <div class="sideBar">
         <div class="sideBarExtra"> </div>
    </div>
    <div class="content">Hover me</div>
</div>


问:
How to pass Bean shell processor variable in to HTTP Request body data in jmeter
I need to pass the Date format variable data from Bean shell processor to http request body

Below is my code and json where I passed variable data but it is not working

```<code>import java.text.SimpleDateFormat;
import java.util.Date;

Date enrolmentDate = new Date();
enrolmentDate.setDate(enrolmentDate.getDate());//+ ${__Random(1,50,)});
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = df.format(enrolmentDate);
vars.put("StartDate",formattedDate);
log.info("########################"+formattedDate);
</code>```

Below is the Http Request Body data

```<code>{
"articleId":""${ArticleId}",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
</code>```

When i run it Start date and end date is shown as ${formattedDate}, what will be the solution?

and in my JSON body data i want to send Start and End Date like "27/05/2019 14:34 "

Below is the Request I got

```<code>PUT data:
{
"articleId":"7694b207-936b-40b9-9c80-4b8097e67da1",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}
</code>```

答:
Change your request body to

```<code>{
"articleId":""${ArticleId}",
"startDate":"${StartDate}",
"endDate":"${Carttodates}"
}
</code>```

The reason why this is required is because you are storing the date in "StartDate" variable in beanshell. Hence, you should use "StartDate" to access the value later in HTTP.
The other option is to store the value in "formattedDate" variable in beanshell and then you do not need to change it in HTTP request body.

Body:
I need to pass the Date format variable data from Bean shell processor to http request body

Below is my code and json where I passed variable data but it is not working

import java.text.SimpleDateFormat;
import java.util.Date;

Date enrolmentDate = new Date();
enrolmentDate.setDate(enrolmentDate.getDate());//+ ${__Random(1,50,)});
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String formattedDate = df.format(enrolmentDate);
vars.put("StartDate",formattedDate);
log.info("########################"+formattedDate);

Below is the Http Request Body data

{
"articleId":""${ArticleId}",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}

When i run it Start date and end date is shown as ${formattedDate}, what will be the solution?

and in my JSON body data i want to send Start and End Date like "27/05/2019 14:34 "

Below is the Request I got

PUT data:
{
"articleId":"7694b207-936b-40b9-9c80-4b8097e67da1",
"startDate":"${formattedDate}",
"endDate":"${Carttodates}"
}

Body:
Change your request body to

{
"articleId":""${ArticleId}",
"startDate":"${StartDate}",
"endDate":"${Carttodates}"
}

The reason why this is required is because you are storing the date in "StartDate" variable in beanshell. Hence, you should use "StartDate" to access the value later in HTTP.
The other option is to store the value in "formattedDate" variable in beanshell and then you do not need to change it in HTTP request body.


问:
window.open(url, name, features) under IE
This is regarding JavaScript method window.open(url, name, features).
If the url is relative or under the same domain of the current page, the parameter features will be ignored by IE.

Example: http://statcomp.ats.ucla.edu/WebTools/JavaTools/popup.htm.

This happens in IE8/9 at least.
Why? Is there any workaround?

Thanks a lot, Xiao

答:
The only time you use px for a client side web thing is in CSS.

That should be: height=400,width=400.


问:
Write log file to AppData with log4net Asp.net Core 2.2 not working
I'm trying to write log file to AppData location, but it doesn't work. I've tried with env%{AppData}, env%{APPDATA}, %APPDATA%, ${AppData}, ${APPDATA} but no one works. If I use C:\Temp it does work though.

I use Asp.Net Core 2.2. and log4net 2.08.

Any suggestions?

```<code><?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>
  <appender name="console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
  <appender name="file" type="log4net.Appender.RollingFileAppender">
    <file value="${AppData}\MyApp\MyLogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
</log4net>
</code>```

答:
For anyone with the same problems I had:

Nuget (Install):

```<code>log4net
Microsoft.Extensions.Options.ConfigurationExtensions
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Logging.Debug
Microsoft.Extensions.Logging.Log4Net.AspNetCore
</code>```

AssemblyInfo.cs:

```<code>[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
</code>```

appsettings.json:

```<code>"Log4NetConfigFile": {
    "Name": "log4net.config"
  },
</code>```

Program.cs

```<code>using Microsoft.Extensions.Logging; //Had to write manually

public static void Main(string[] args)
{
    var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
    log4net.GlobalContext.Properties["LogPath"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp");
    log4net.Config.XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging((webHostBuilderContext, loggingBuilder) =>
    {
        loggingBuilder.AddLog4Net();
    })
    .UseStartup<Startup>();
}
</code>```

Set log4net.config to Copy to Output directory: Copy Always

log4net.config:

```<code><?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>
  <appender name="console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
  <appender name="file" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="%property{LogPath}\MyLogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
</log4net>
</code>```

HomeController.cs

```<code>private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));

public HomeController()
{
    log.Info("Starting GenerateDebugLog method...");
}
</code>```

Body:
I'm trying to write log file to AppData location, but it doesn't work. I've tried with env%{AppData}, env%{APPDATA}, %APPDATA%, ${AppData}, ${APPDATA} but no one works. If I use C:\Temp it does work though.

I use Asp.Net Core 2.2. and log4net 2.08.

Any suggestions?

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>
  <appender name="console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
  <appender name="file" type="log4net.Appender.RollingFileAppender">
    <file value="${AppData}\MyApp\MyLogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
</log4net>

Body:
For anyone with the same problems I had:

Nuget (Install):

log4net
Microsoft.Extensions.Options.ConfigurationExtensions
Microsoft.Extensions.Logging.Console
Microsoft.Extensions.Logging.Debug
Microsoft.Extensions.Logging.Log4Net.AspNetCore

AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

appsettings.json:

"Log4NetConfigFile": {
    "Name": "log4net.config"
  },

Program.cs

using Microsoft.Extensions.Logging; //Had to write manually

public static void Main(string[] args)
{
    var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
    log4net.GlobalContext.Properties["LogPath"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApp");
    log4net.Config.XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

    CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging((webHostBuilderContext, loggingBuilder) =>
    {
        loggingBuilder.AddLog4Net();
    })
    .UseStartup<Startup>();
}

Set log4net.config to Copy to Output directory: Copy Always

log4net.config:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="console" />
    <appender-ref ref="file" />
  </root>
  <appender name="console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
  <appender name="file" type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString" value="%property{LogPath}\MyLogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="5" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5level %date{dd-mm-yyyy HH:mm:ss} %logger [%thread] - %message %exception%newline" />
    </layout>
  </appender>
</log4net>

HomeController.cs

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));

public HomeController()
{
    log.Info("Starting GenerateDebugLog method...");
}


答:
The problem is that your List-instance is non-static, while your methods are. You either have to change your List to be static, or you methods to be non static. Following good OO Design, I would suggest you remove the static modifier from your methods. I also applied a readonly modifier to your List and changed It to be ICollection, as you do not seem to need indexed access. And also applied some common naming patterns.</p>

```<code>public class Library
{
    private readonly ICollection<Book> _books = new List<Book>();

    public void AddBook(Book book)
    {
        _books.Add(book);
    }

    public void ShowBooks()
    {
        foreach (Book item in _books)
        {
            Console.WriteLine("Books found");
        }
    }
}
</code>```

Title: How to add objects to a private list with a method?

Body:
The problem is that your List-instance is non-static, while your methods are. You either have to change your List to be static, or you methods to be non static. Following good OO Design, I would suggest you remove the static modifier from your methods. I also applied a readonly modifier to your List and changed It to be ICollection, as you do not seem to need indexed access. And also applied some common naming patterns.

public class Library
{
    private readonly ICollection<Book> _books = new List<Book>();

    public void AddBook(Book book)
    {
        _books.Add(book);
    }

    public void ShowBooks()
    {
        foreach (Book item in _books)
        {
            Console.WriteLine("Books found");
        }
    }
}


问:
PHP code in viewing a pdf file from a mysql database
How to view .pdf file in a webpage using PHP? The pdf file is in a mysql database. Thanks.</p>

答:
If you echo the contents from the database to the browser and provide the appropriate content type through HTTP headers you're done!</p>

```<code><?php

header('Content-type: application/pdf');
echo $pdf_from_database;
</code>```

Body:
If you echo the contents from the database to the browser and provide the appropriate content type through HTTP headers you're done!

<?php

header('Content-type: application/pdf');
echo $pdf_from_database;


问:
Efficiently matching Words against a sorted Vocabulary in Python
On one hand, I have an alphabetically sorted noun vocabulary (#7000)

```<code>aardvark
abacus
abbey
abbreviation
abdomen
ability
abnormal
</code>```

On the other hand I have a set of words (#1E6)

```<code>['Hello', 'airport', 'really', 'sorry', 'to', 'hear', 'this'...]
</code>```

What is the most efficient way to find out if a word is present in the vocabulary, and the index?

I could simply use lists/arrays and compare strings, but this does not take advantage of the alphabetic sorting of the vocabulary

答:
You can use bisect in order to take advantage of the sorted vocabulary:

In [1]: d = ["aardvark", "abacus", "abbey", "abbreviation"]
In [2]: w = ['Hello', 'airport', 'really', 'sorry', 'to', 'hear', 'this', "aardvark"]
In [3]: for wd in w:
    ...:     try:
    ...:         index = bisect.bisect_left(d, wd)
    ...:         found = d[index]
    ...:         if found == wd:
    ...:             print(f"{wd} found at index {index}")
    ...:     except IndexError:
    ...:         pass
    ...:
aardvark found at index 0
```

Another option would be to use a dictionary, and search for word in set or dictionary.get(word) for the index - You can read my answer here for details about dict implementation in CPython.

Body:
On one hand, I have an alphabetically sorted noun vocabulary (#7000)

aardvark
abacus
abbey
abbreviation
abdomen
ability
abnormal

On the other hand I have a set of words (#1E6)

['Hello', 'airport', 'really', 'sorry', 'to', 'hear', 'this'...]

What is the most efficient way to find out if a word is present in the vocabulary, and the index?

I could simply use lists/arrays and compare strings, but this does not take advantage of the alphabetic sorting of the vocabulary

Body:
You can use bisect in order to take advantage of the sorted vocabulary:

In [1]: d = ["aardvark", "abacus", "abbey", "abbreviation"]
In [2]: w = ['Hello', 'airport', 'really', 'sorry', 'to', 'hear', 'this', "aardvark"]
In [3]: for wd in w:
    ...:     try:
    ...:         index = bisect.bisect_left(d, wd)
    ...:         found = d[index]
    ...:         if found == wd:
    ...:             print(f"{wd} found at index {index}")
    ...:     except IndexError:
    ...:         pass
    ...:
aardvark found at index 0

Another option would be to use a dictionary, and search for word in set or dictionary.get(word) for the index - You can read my answer here for details about dict implementation in CPython.


问:
Getting string from label visible at runtime
I want to get the string which is visible at my label and having line break mode .byClipping .
My real string is :-
 "This way your API interface will be nice and pretty, you’re not exposing the internals of your class to the world. If you have constants that are used in lots of classes all over the app then it makes sense to have a separate .h and .m file just for defining these constants."

but at run time i am getting :-
"This way your API interface will be nice and pretty, you’re not exposing the internals of your class to the world. If you have constants"

i want to get the below string in a variable at runtime.

答:
I am not sure if this is natively doable. The closest idea I have is to test the string size and removing/adding characters. Check if the following works for you:

```<code>func findTextActuallyVisibleInLabel(_ label: UILabel) -> String? {
    guard let originalText = label.text else { return nil }
    var text = originalText

    let labelSize = label.bounds
    guard labelSize.height > 0 else { return text }

    let bounds: CGRect = CGRect(x: 0.0, y: 0.0, width: labelSize.width, height: CGFloat.infinity)

    while !text.isEmpty && label.textRect(forBounds: bounds, limitedToNumberOfLines: label.numberOfLines).height > labelSize.height {
        text.removeLast()
        label.text = text
    }
    label.text = originalText

    return text
}
</code>```

This seems to do its job in my case more or less. If I use wrapping that ends text with ... the result is incorrect.
Also some optimization may be nice; currently I just use the full string and start subtracting character by character. Maybe a bisection would be nicer here.

I do still use original label so it should take all possible parameters into account like wrapping, font size, lines... I modify the actual text on the label which is then reset to original.

Possibly view animations should be disabled while this operation is in progress.

Body:
I am not sure if this is natively doable. The closest idea I have is to test the string size and removing/adding characters. Check if the following works for you:

func findTextActuallyVisibleInLabel(_ label: UILabel) -> String? {
    guard let originalText = label.text else { return nil }
    var text = originalText

    let labelSize = label.bounds
    guard labelSize.height > 0 else { return text }

    let bounds: CGRect = CGRect(x: 0.0, y: 0.0, width: labelSize.width, height: CGFloat.infinity)

    while !text.isEmpty && label.textRect(forBounds: bounds, limitedToNumberOfLines: label.numberOfLines).height > labelSize.height {
        text.removeLast()
        label.text = text
    }
    label.text = originalText

    return text
}

This seems to do its job in my case more or less. If I use wrapping that ends text with ... the result is incorrect.
Also some optimization may be nice; currently I just use the full string and start subtracting character by character. Maybe a bisection would be nicer here.

I do still use original label so it should take all possible parameters into account like wrapping, font size, lines... I modify the actual text on the label which is then reset to original.

Possibly view animations should be disabled while this operation is in progress.


问:
How debug placeholder pseudo element in firefox?
I have CSS code like this:

```<code>:-moz-placeholder,::-moz-placeholder {
    color:    #999;
    /*some additional font styling*/
}
</code>```

I can click "Inspect element" and see all style information about element. But where I can see all CSS rules that has applied to element placeholder?

答: Just to give an updated answer for anyone still coming to this page, in FireFox v66, you can reveal pseudo-element styles simply by clicking on the expand icon in the styles panel when inspecting an element in the Developer Tools- see screenshot:

Body:
I have CSS code like this:

:-moz-placeholder,::-moz-placeholder {
    color:    #999;
    /*some additional font styling*/
}

I can click "Inspect element" and see all style information about element. But where I can see all CSS rules that has applied to element placeholder?


问:
How do I insert values of different type to columns in my table?
The question title might sound ridiculous, but I would explain what I want to do with example table below:

```<code>+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+
</code>```

Now would like to insert more values to attrname and attrvalue columns ONLY, in which the values correspond to the following:

```<code>+----------------+-------------------------+
|    attrname    |        attrvalue        |
+----------------+-------------------------+
| measurand      | 38.7                    |
| sonometerClass | 2                       |
| name           | London Street           |
| longitude      | -8.603257               |
| latitude       | 41.183778               |
| dateObserved   | 2016-05-24T18:38:15.00Z |
+----------------+-------------------------+
</code>```

How do I achieve this in SQL? I really don't mind keep all other columns with the values as they are(i.e. repeating their values).

EDIT

While I acknowledge the answer by Gordon Linoff, it wouldn't solve my problem because these values are actually read from a csv file of the form:

```<code>measurand,sonometerClass,name,longitude,latitude,dateObserved
38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z
</code>```

The values are not coming directly from user input, but read from the csv file whose form is as above.

EDIT-2:

I understand I would use postgres copy command, in fact I'm  using postgres copy_from in the python script.
My specific problem is reading the values from the csv file  such that for each line of the csv file, values are inserted into attrvalue column with corresponding attrname updated, so that:

```<code>For line1: 38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
</code>```

I get the following correspondance(attrname set to like):

```<code>measurand = 38.7
sonometerClass = 2
name = London Street
longitude = -8.603257
latitude = 41.183778
dateObserved = 2016-05-24T18:38:15.00Z
</code>```

Similarly,

```<code>For line2: 90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
</code>```

I get the following:

```<code>measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z
</code>```

All other columns remain as they are.

答:
You can insert records using columns specific query like below:
insert into table_name (attrname, attrvalue) values ("dateObserved", "2016-05-24T18:38:15.00Z");

Here, replace values with the expected what you want to insert.
Note: Make sure this query will be executed when there is no primary key on this table. If primary key exists on any column, we need to add that column also with unique value

Body:
The question title might sound ridiculous, but I would explain what I want to do with example table below:

+------------+------------+----------------+----------+-------------------------+
|  recvtime  | entitytype |    attrname    | attrtype |        attrvalue        |
+------------+------------+----------------+----------+-------------------------+
| 2019-05-27 | Noise      | measurand      | Number   | 51.7                    |
| 2019-05-27 | Noise      | sonometerClass | Text     | 1                       |
| 2019-05-27 | Noise      | name           | Text     | City Centre             |
| 2019-05-27 | Noise      | longitude      | Number   | -8.65915                |
| 2019-05-27 | Noise      | latitude       | Number   | 41.1591                 |
| 2019-05-27 | Noise      | dateObserved   | DateTime | 2016-05-24T18:38:15.00Z |
+------------+------------+----------------+----------+-------------------------+

Now would like to insert more values to attrname and attrvalue columns ONLY, in which the values correspond to the following:

+----------------+-------------------------+
|    attrname    |        attrvalue        |
+----------------+-------------------------+
| measurand      | 38.7                    |
| sonometerClass | 2                       |
| name           | London Street           |
| longitude      | -8.603257               |
| latitude       | 41.183778               |
| dateObserved   | 2016-05-24T18:38:15.00Z |
+----------------+-------------------------+

How do I achieve this in SQL? I really don't mind keep all other columns with the values as they are(i.e. repeating their values).

EDIT

While I acknowledge the answer by Gordon Linoff, it wouldn't solve my problem because these values are actually read from a csv file of the form:

measurand,sonometerClass,name,longitude,latitude,dateObserved
38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z
90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z
59.3,0,City Campus,-8.594866,41.178031,2014-08-12T16:10:10.00Z
64.5,1,ABC Beach,-8.607085,41.15001,2015-10-11T16:10:10.00Z

The values are not coming directly from user input, but read from the csv file whose form is as above.

EDIT-2:

I understand I would use postgres copy command, in fact I'm  using postgres copy_from in the python script.
My specific problem is reading the values from the csv file  such that for each line of the csv file, values are inserted into attrvalue column with corresponding attrname updated, so that:

For line1: 38.7,2,London Street,-8.603257,41.183778,2016-05-24T18:38:15.00Z

I get the following correspondance(attrname set to like):

measurand = 38.7
sonometerClass = 2
name = London Street
longitude = -8.603257
latitude = 41.183778
dateObserved = 2016-05-24T18:38:15.00Z

Similarly,

For line2: 90.4,1,Hospital de S. Joao,-8.603257,41.183778,2014-07-12T6:18:15.00Z

I get the following:

measurand = 90.4
sonometerClass = 1
name = Hospital de S. Joao
longitude = -8.603257
latitude = 41.183778
dateObserved = 2014-07-12T6:18:15.00Z

All other columns remain as they are.


问:
Need to find turn around time
I'm calculating TAT. I have 3 params like Current Date, TAT period and List of Holidays(Date).

```<code>    static List<DateTime> Holidates = new List<DateTime>();
    static DateTime StartDate = DateTime.Now;
    static void Main(string[] args)
    {
        Holidates.Add(DateTime.Now.AddDays(20));
        Holidates.Add(DateTime.Now.AddDays(10));
        Holidates.Add(DateTime.Now.AddDays(3));

        TatDueDateCalculator(DateTime.Now, 10, Holidates);
    }

    private static DateTime TatDueDateCalculator(DateTime AssignDate, int TatPeriod, List<DateTime> Holidays)
    {
        DateTime dueDate = AssignDate.AddDays(TatPeriod);

        int holiDayCount = Holidays.FindAll(x => x >= AssignDate && x <= AssignDate.AddDays(30)).Where(y => dueDate >= AssignDate && dueDate <= y).Count();

        if (holiDayCount > 0)
            dueDate = dueDate.AddDays(holiDayCount);

        return dueDate;
    }
</code>```

TatDueDateCalculator() need to return dueDate.

Followings are the cases:

Continuous Holidays

List<DateTime>Holiday contains only one matching dueDate, but having greater values in the List.

For eg.

DueDate is "2019-05-13", Holiday List contains following dates.
"2019-05-10","2019-05-13","2019-05-12". In this case i have getting 2 TAT. But expected is 1

答:
The following code yields the expected result (according to you example in the comments). It also accounts for holidays which are initially after the first due date.</p>

```<code>static void Main(string[] args)
{
    var holidays = new List<DateTime>()
    {
        new DateTime(2019,05,03),
        new DateTime(2019,05,04),
        new DateTime(2019,05,06),
        new DateTime(2019,05,10),
    };
    int tatPeriod = 5;
    var assignDate = new DateTime(2019, 05, 01);
    var dueDate = Enumerable.Range(0, tatPeriod + holidays.Count)
                            .Select(offset => assignDate.AddDays(offset))
                            .Except(holidays)
                            .ElementAt(tatPeriod - 1);

    Console.WriteLine(dueDate);
    Console.Read();
}
</code>```

Title: Need to find turn around time

Body:
I'm calculating TAT. I have 3 params like Current Date, TAT period and List of Holidays(Date).

    static List<DateTime> Holidates = new List<DateTime>();
    static DateTime StartDate = DateTime.Now;
    static void Main(string[] args)
    {
        Holidates.Add(DateTime.Now.AddDays(20));
        Holidates.Add(DateTime.Now.AddDays(10));
        Holidates.Add(DateTime.Now.AddDays(3));

        TatDueDateCalculator(DateTime.Now, 10, Holidates);
    }

    private static DateTime TatDueDateCalculator(DateTime AssignDate, int TatPeriod, List<DateTime> Holidays)
    {
        DateTime dueDate = AssignDate.AddDays(TatPeriod);

        int holiDayCount = Holidays.FindAll(x => x >= AssignDate && x <= AssignDate.AddDays(30)).Where(y => dueDate >= AssignDate && dueDate <= y).Count();

        if (holiDayCount > 0)
            dueDate = dueDate.AddDays(holiDayCount);

        return dueDate;
    }

TatDueDateCalculator() need to return dueDate.

Followings are the cases:

Continuous Holidays

List<DateTime>Holiday contains only one matching dueDate, but having greater values in the List.

For eg.

DueDate is "2019-05-13", Holiday List contains following dates.
"2019-05-10","2019-05-13","2019-05-12". In this case i have getting 2 TAT. But expected is 1

Body:
The following code yields the expected result (according to you example in the comments). It also accounts for holidays which are initially after the first due date.

static void Main(string[] args)
{
    var holidays = new List<DateTime>()
    {
        new DateTime(2019,05,03),
        new DateTime(2019,05,04),
        new DateTime(2019,05,06),
        new DateTime(2019,05,10),
    };
    int tatPeriod = 5;
    var assignDate = new DateTime(2019, 05, 01);
    var dueDate = Enumerable.Range(0, tatPeriod + holidays.Count)
                            .Select(offset => assignDate.AddDays(offset))
                            .Except(holidays)
                            .ElementAt(tatPeriod - 1);

    Console.WriteLine(dueDate);
    Console.Read();
}


问:
How to add an outline/stroke around a material-ui icon?
How to add a color outline around the material-ui icons?
Have this

Look more like this?

I've tried stroke and webkit-stroke and no luck on anything. It put a border around the whole invisible box.

答:
Using Material-UI with React the way to go, in theory, should be setting the property stroke and stroke-width directly to the imported heart icon. But as you said, it will create an awkward border around the whole svg tag.
Then, you should be able to extract the  definition of the heart from the dom and use the more general SvgIcon component Material-UI provides.

So, to reach your goal, instead of:

```<code>import { Favorite } from '@material-ui/icons';
export default () => <Favorite stroke={"white"} stroke-width={1}/>
</code>```

I would go for:

```<code>import SvgIcon from '@material-ui/core/SvgIcon';
export default () => (
  <SvgIcon>
    <path
      d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
      stroke="white"
      strokeWidth={1}
    />
  </SvgIcon>
);
</code>```

Body:
Using Material-UI with React the way to go, in theory, should be setting the property stroke and stroke-width directly to the imported heart icon. But as you said, it will create an awkward border around the whole svg tag.
Then, you should be able to extract the  definition of the heart from the dom and use the more general SvgIcon component Material-UI provides.

So, to reach your goal, instead of:

import { Favorite } from '@material-ui/icons';
export default () => <Favorite stroke={"white"} stroke-width={1}/>

I would go for:

import SvgIcon from '@material-ui/core/SvgIcon';
export default () => (
  <SvgIcon>
    <path
      d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
      stroke="white"
      strokeWidth={1}
    />
  </SvgIcon>
);