问:
Cannot modify header information - headers already sent by (output started at 22

Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 33

Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 34

Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 35

Notice: Undefined index: ubkuser in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 36

Notice: Undefined index: ubklogin in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 37

Notice: Undefined index: ubktahun in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 38 SMK NEGERI 25
  Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 49

the code

```<code><?php
if(isset($_POST['userz'], $_POST['passz'])) {
        include "../../config/server.php";

        require("../../config/fungsi_thn.php");

    $libpath1="up/";
    $js_path="um/";
    $um_path="um/";
    $docroot="";
    $toroot="";

    include_once $um_path."um412_func_inc_v.03.php";
    include_once $um_path."um412_func_inc_v.03_add2.php";
        $userz = mysql_real_escape_string($_REQUEST['userz']);
        $passz = mysql_real_escape_string($_REQUEST['passz']);
        $passz = md5($passz);
        $loginz = mysql_real_escape_string($_REQUEST['login']);
        if($loginz == "admin"){$peran = "1";} else {$peran="0";}
        $sq="select * from cbt_user where Username = '$userz' and Password = '$passz' and login = '$peran'";
        echo $sq;
        $hs=mysql_query($sq);
        $sqladmin = mysql_num_rows($hs);
     //exit;
        if($sqladmin>0){
                    //if(!isset($_COOKIE['ubkuser'], $_COOKIE['ubklogin'])){
        $sqltahun = mysql_query("select * from cbt_setid where XStatus = '1'");
        $st = mysql_fetch_array($sqltahun);
        $tahunz = $st['XKodeAY'];
                        setcookie('ubkuser',$userz);
                        setcookie('ubklogin',$loginz);
                        setcookie('ubktahun',$tahunz);
                        $_COOKIE['ubkuser']==$userz;
                        $_COOKIE['ubklogin']==$loginz;
                        $_COOKIE['ubktahun']==$tahunz;

                        //setting namauser
                        $namasek=carifield("select xsekolah from cbt_admin");
                        extractRecord($sq);
                        echo $Nama;
                        //exit;
                        if ($namasek!=$Nama) {
                            mysql_query("update cbt_admin set xsekolah='$Nama'");
                            //exit;
                        }
                        header("Location: ../pages/?");
                    //}

        } else { header("Location: login.php"); }
} else {

    header("Location: login.php");

}

?>
</code>```

答:
header("Location: login.php"); is called after you send content (maybe an error in your includes), you should put this one before any showed contents.

I see you do that :
echo $Nama;
It's the kind of thing that makes a headers already sent by error...

Body:
Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 33

Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 34

Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 35

Notice: Undefined index: ubkuser in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 36

Notice: Undefined index: ubklogin in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 37

Notice: Undefined index: ubktahun in
  E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 38 SMK NEGERI 25
  Warning: Cannot modify header information - headers already sent by
  (output started at
  E:\xampp\htdocs\kntl\panel\pages\um\um412_func_inc_v.03_add2.php:633)
  in E:\xampp\htdocs\kntl\panel\pages\ceklogin.php on line 49

the code

<?php
if(isset($_POST['userz'], $_POST['passz'])) {
        include "../../config/server.php";

        require("../../config/fungsi_thn.php");

    $libpath1="up/";
    $js_path="um/";
    $um_path="um/";
    $docroot="";
    $toroot="";

    include_once $um_path."um412_func_inc_v.03.php";
    include_once $um_path."um412_func_inc_v.03_add2.php";
        $userz = mysql_real_escape_string($_REQUEST['userz']);
        $passz = mysql_real_escape_string($_REQUEST['passz']);
        $passz = md5($passz);
        $loginz = mysql_real_escape_string($_REQUEST['login']);
        if($loginz == "admin"){$peran = "1";} else {$peran="0";}
        $sq="select * from cbt_user where Username = '$userz' and Password = '$passz' and login = '$peran'";
        echo $sq;
        $hs=mysql_query($sq);
        $sqladmin = mysql_num_rows($hs);
     //exit;
        if($sqladmin>0){
                    //if(!isset($_COOKIE['ubkuser'], $_COOKIE['ubklogin'])){
        $sqltahun = mysql_query("select * from cbt_setid where XStatus = '1'");
        $st = mysql_fetch_array($sqltahun);
        $tahunz = $st['XKodeAY'];
                        setcookie('ubkuser',$userz);
                        setcookie('ubklogin',$loginz);
                        setcookie('ubktahun',$tahunz);
                        $_COOKIE['ubkuser']==$userz;
                        $_COOKIE['ubklogin']==$loginz;
                        $_COOKIE['ubktahun']==$tahunz;

                        //setting namauser
                        $namasek=carifield("select xsekolah from cbt_admin");
                        extractRecord($sq);
                        echo $Nama;
                        //exit;
                        if ($namasek!=$Nama) {
                            mysql_query("update cbt_admin set xsekolah='$Nama'");
                            //exit;
                        }
                        header("Location: ../pages/?");
                    //}

        } else { header("Location: login.php"); }
} else {

    header("Location: login.php");

}

?>


来源: stackexchange

问:
Why does my PHP email come without HTML and utf-8?
I have a contact form and want to format the output email in HTML and use charset utf-8 as I need some special character. I have following code, but it's not working.
Edit: The email is sent, but without html and utf-8.</p>

```<code><?php
if ($_POST["email"]<>'') {
    $ToEmail = 'contact@domain.com';
    $EmailSubject = 'Email Subject';
    $mailheader = 'From: donotreply@domain.com' . "\r\n" .
        'Reply-To:' .$_POST["email"]. "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        'MIME-Version: 1.0'."\r\n".
        'Content-Type: text/html; charset=utf-8'."\r\n".
    $MESSAGE_BODY .= "<b>Navn:</b> ".$_POST["name"]."\r\n";
    $MESSAGE_BODY .= "<b>Telefon:</b> ".$_POST["telephone"]."\r\n";
    $MESSAGE_BODY .= "<b>Email:</b> ".$_POST["email"]."\r\n\r\n";
    $MESSAGE_BODY .= "".nl2br($_POST["message"])."\r\n";
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
</code>```

答:
I found that the only thing that was wrong was the order of the code. By moving 'X-Mailer: PHP/' . phpversion(); below Content-Type the mail is encoded correct.

This is how I fixed it:

$mailheader = 'From: donotreply@domain.com' . "\r\n" .
        'Reply-To:' .$_POST["email"]. "\r\n" .
        'MIME-Version: 1.0'."\r\n".
        'Content-Type: text/html; charset=utf-8'."\r\n".
        'X-Mailer: PHP/' . phpversion();

ContentLicense: CC BY-SA 3.0

Body:
I have a contact form and want to format the output email in HTML and use charset utf-8 as I need some special character. I have following code, but it's not working.
Edit: The email is sent, but without html and utf-8.

<?php
if ($_POST["email"]<>'') {
    $ToEmail = 'contact@domain.com';
    $EmailSubject = 'Email Subject';
    $mailheader = 'From: donotreply@domain.com' . "\r\n" .
        'Reply-To:' .$_POST["email"]. "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        'MIME-Version: 1.0'."\r\n".
        'Content-Type: text/html; charset=utf-8'."\r\n".
    $MESSAGE_BODY .= "Navn: ".$_POST["name"]."\r\n";
    $MESSAGE_BODY .= "Telefon: ".$_POST["telephone"]."\r\n";
    $MESSAGE_BODY .= "Email: ".$_POST["email"]."\r\n\r\n";
    $MESSAGE_BODY .= "".nl2br($_POST["message"])."\r\n";
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>


问:
Why is the extended method not over-riding the parent method
I need to be able to run a child method from the parent class.
I am calling the child function $this->getPlan, but it is not calling the child plan, but only the parent one. I thought an extended class over-rides the function.
Here is my code

```<code>class logon{
    public function getPlan(){}
    public function __construct(){
    }
    public function checkWorks(){
        $this->getPlan();
    }
}

class plan extends logon{
    function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}
$logon = new logon();
$plan = new plan();

$logon->checkWorks();
</code>```

However if I call the code from the parent constructor like this, it calls my child method.

```<code>public function __construct(){
      $this->getPlan();
    }
</code>```

I don't want to use an abstract class to do this, as there is a good reason for this.
Can anyone tell me why my parent method is not being over-ridden by the child class?

答:
You are calling logon method:

```<code>$logon->checkWorks();
</code>```

but getPlan in logon class is empty. You need to call child class (Plan):

```<code>$plan->checkWorks();
</code>```

Body:
I need to be able to run a child method from the parent class.
I am calling the child function $this->getPlan, but it is not calling the child plan, but only the parent one. I thought an extended class over-rides the function.
Here is my code

class logon{
    public function getPlan(){}
    public function __construct(){
    }
    public function checkWorks(){
        $this->getPlan();
    }
}

class plan extends logon{
    function __construct(){
        parent::__construct();
    }
    public function getPlan(){
        echo "test";
    }
}
$logon = new logon();
$plan = new plan();

$logon->checkWorks();

However if I call the code from the parent constructor like this, it calls my child method.

public function __construct(){
      $this->getPlan();
    }

I don't want to use an abstract class to do this, as there is a good reason for this.
Can anyone tell me why my parent method is not being over-ridden by the child class?

Body:
You are calling logon method:

$logon->checkWorks();

but getPlan in logon class is empty. You need to call child class (Plan):

$plan->checkWorks();


问:
Importing Excel data into C# without first row becoming column names?
I am trying to import data from excel into a datatable using c#. Here is the code I use to do so...

```<code>string ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;" +
                    "Extended Properties=\"Excel 8.0;HRD=No;IMEX=1;\"";
OleDbDataAdapter SheetAdapter = new OleDbDataAdapter("select * from ["Sheet1"]", conn);
System.Data.DataTable excelData = new System.Data.DataTable();
SheetAdapter.Fill(excelData);
excelData.TableName = "excelData";

foreach (DataRow row in excelData.Rows)
{
   ProcessDataRow(row);
}
</code>```

When I look at the datatable while debugging the first row of data has become the tables column names. I don't understand why this is happening when I put HDR=No into the connection string. Is there a way to force the DataTable to not take the first row as column names?

答: The code sample you provided has HRD=No instead of HDR=No

ContentLicense: CC BY-SA 2.5

Body:
I am trying to import data from excel into a datatable using c#. Here is the code I use to do so...

string ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;" +
                    "Extended Properties=\"Excel 8.0;HRD=No;IMEX=1;\"";
OleDbDataAdapter SheetAdapter = new OleDbDataAdapter("select * from ["Sheet1"]", conn);
System.Data.DataTable excelData = new System.Data.DataTable();
SheetAdapter.Fill(excelData);
excelData.TableName = "excelData";

foreach (DataRow row in excelData.Rows)
{
   ProcessDataRow(row);
}

When I look at the datatable while debugging the first row of data has become the tables column names. I don't understand why this is happening when I put HDR=No into the connection string. Is there a way to force the DataTable to not take the first row as column names?


问:
Showing Greeting Message in Javascript
How can I display a greeting message according to the time of the day in javascript?</p>

```<code>var greetdate=new Date()
var hours=greetdate.getHours()

document.write('<h2>Hello! Good Morning! Have a nice day.</h2>')

document.write('<h2>Good Noon Visitor! </h2>')

//MESSAGE FOR AFTERNOON
document.write('<h2>Good Afternoon! </h2>')

//MESSAGE FOR EVENING (6pm-8pm)
document.write('<h2>Good Evening! </h2>')

//MESSAGE FOR NIGHT (9pm-11pm)
document.write('<h2>Good Night! </h2>')

//MESSAGE FOR LATE NIGHT (12pm-4am)
document.write('<h2>Wow! You`re still awake. Working Late?</h2>')
</code>```

答:
var now = new Date();
var hours = now.getHours();

var greetings = [
   {"tod": "latenight",
    "greet": "Wow! You`re still awake. Working Late?",
    "test": hours >= 24 || hours <= 4
  },
  {"tod":"night",
    "greet": "Good Night!",
    "test": hours >= 21 || hours <= 11
  },
  {"tod":"evening",
    "greet": "Good Evening!",
    "test": hours >= 18 && hours <= 20
  },
  {"tod":"afternoon",
    "greet": "Good Afternoon!",
    "test": hours >= 13 && hours <= 17
  },
  {"tod":"noon",
    "greet": "Good Noon Visitor!",
    "test": hours == 12
  },
  {"tod":"morning",
    "greet": "Hello! Good Morning! Have a nice day.",
    "test": hours >= 5 && hours <= 11
  }
];

var message = document.getElementById("message");
message.innerHTML = greetings.find(el=>el.test).greet;
message.className = greetings.find(el=>el.test).tod;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2.latenight {
  color: purple;
  background: #ccf;
}

h2.night {
  color: silver;
  background: #000;
}

h2.evening {
  color: navy;
  background: #eee;
}

h2.afternoon {
  color: red;
  background: #ffdede;
}

h2.noon {
  color: cyan;
  background: goldenrod;
}

h2.morning {
  color: blue;
  background: #ffe;
}</code>```

```

The code avoids using document.write which is generally regarded as a bad practice (see discussion here).  The script sets the content of a pair of H2 tags and their style according to the time of day.  Now that the code is self-documenting it is uncluttered by any comments.  Note, that the objects are in descending order according to value of the time of day ("tod") property to assure accurate testing.

The array applies its find method to each of its elements until a true result occurs. The callback for find() consists of an arrow function which returns the result of an object's test property.  When true, find() in turn returns that element, thereby facilitating setting the content.  This same technique also aids in styling the H2 tag.

Title: Showing Greeting Message in Javascript

Body:
How can I display a greeting message according to the time of the day in javascript?

var greetdate=new Date()
var hours=greetdate.getHours()

document.write('
Hello! Good Morning! Have a nice day.
')

document.write('
Good Noon Visitor!
')

//MESSAGE FOR AFTERNOON
document.write('
Good Afternoon!
')

//MESSAGE FOR EVENING (6pm-8pm)
document.write('
Good Evening!
')

//MESSAGE FOR NIGHT (9pm-11pm)
document.write('
Good Night!
')

//MESSAGE FOR LATE NIGHT (12pm-4am)
document.write('
Wow! You`re still awake. Working Late?
')

Body:
var now = new Date();
var hours = now.getHours();

var greetings = [
   {"tod": "latenight",
    "greet": "Wow! You`re still awake. Working Late?",
    "test": hours >= 24 || hours <= 4
  },
  {"tod":"night",
    "greet": "Good Night!",
    "test": hours >= 21 || hours <= 11
  },
  {"tod":"evening",
    "greet": "Good Evening!",
    "test": hours >= 18 && hours <= 20
  },
  {"tod":"afternoon",
    "greet": "Good Afternoon!",
    "test": hours >= 13 && hours <= 17
  },
  {"tod":"noon",
    "greet": "Good Noon Visitor!",
    "test": hours == 12
  },
  {"tod":"morning",
    "greet": "Hello! Good Morning! Have a nice day.",
    "test": hours >= 5 && hours <= 11
  }
];

var message = document.getElementById("message");
message.innerHTML = greetings.find(el=>el.test).greet;
message.className = greetings.find(el=>el.test).tod;

h2.latenight {
  color: purple;
  background: #ccf;
}

h2.night {
  color: silver;
  background: #000;
}

h2.evening {
  color: navy;
  background: #eee;
}

h2.afternoon {
  color: red;
  background: #ffdede;
}

h2.noon {
  color: cyan;
  background: goldenrod;
}

h2.morning {
  color: blue;
  background: #ffe;
}

<div>
  <h2 id="message" class="bla"></h2>
</div>

The code avoids using document.write which is generally regarded as a bad practice (see discussion here).  The script sets the content of a pair of H2 tags and their style according to the time of day.  Now that the code is self-documenting it is uncluttered by any comments.  Note, that the objects are in descending order according to value of the time of day ("tod") property to assure accurate testing.

The array applies its find method to each of its elements until a true result occurs. The callback for find() consists of an arrow function which returns the result of an object's test property.  When true, find() in turn returns that element, thereby facilitating setting the content.  This same technique also aids in styling the H2 tag.


问:
Trouble connecting react-native with redux
I am trying to create a counter with react-native and redux, but i'm getting the error Expected a component class, got [object Object].

This is my index.android.js

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';

import Root from './src/containers/Root';
import configureStore from './configureStore';

export default class CounterReactNativeRedux extends Component {
  render() {
    return (<Root store={configureStore()} />)
  }
}

AppRegistry.registerComponent('CounterReactNativeRedux', () => CounterReactNativeRedux);
```

My code can be found here.

Found answers about this saying that it might be because of the class name not being capitalize but this is not the case.

Anyone any idea?

答:
Look inside of your Counter.js. You have used div tags there which do not exist in React Native.

So import View tag from React Native and use that.

```<code>import {View} from 'react-native'

const Counter = ({ value }) => (
  <View>{value}</View>
);
</code>```

Body:
I am trying to create a counter with react-native and redux, but i'm getting the error Expected a component class, got [object Object].

This is my index.android.js

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';

import Root from './src/containers/Root';
import configureStore from './configureStore';

export default class CounterReactNativeRedux extends Component {
  render() {
    return (<Root store={configureStore()} />)
  }
}

AppRegistry.registerComponent('CounterReactNativeRedux', () => CounterReactNativeRedux);

My code can be found here.

Found answers about this saying that it might be because of the class name not being capitalize but this is not the case.

Anyone any idea?

Body:
Look inside of your Counter.js. You have used div tags there which do not exist in React Native.

So import View tag from React Native and use that.

import {View} from 'react-native'

const Counter = ({ value }) => (
  <View>{value}</View>
);


问:
GD Library extension not available with this PHP installation Ubuntu Nginx
I am using Laravel web framework on my ubuntu 14.04 server and Nginx web server, I have this error when I try to upload a file using Laravel to the server.
my upload directory is on the public/uploads folder that has 777 permission.

答:
In my case under Archlinux:

```<code>pacman -S php-gd
</code>```

php-gd

then in your php.ini for me in /etc/php/php.ini uncomment line ;extension=gd.so by removing semicolon.

Don't forget to restart the server.

ContentLicense: CC BY-SA 4.0

Body:
In my case under Archlinux:

pacman -S php-gd

php-gd

then in your php.ini for me in /etc/php/php.ini uncomment line ;extension=gd.so by removing semicolon.

Don't forget to restart the server.


问:
"Reverse" these math trig (3d game world) operations
I'm doing a mod for a game and I'm not very good with trigonometry and can't figure out how to do this despite of many attempts.

I have a vehicle in the 3D World at some position with some facing angle (z angle). I also have an object right next to it, and have it's XYZ position and rotations. I want to attach the object to the vehicle, but to attach it I need to specify the offsets relative to the vehicle, not real world pos.
This is the "vehicle coord system":
vehicle attachment coords

But that's not the problem. I already have this code which does it:

```<code>new Float:ofx, Float:ofy, Float:ofz, Float:ofangle;
new Float:attachX, Float:attachY;
new Float:vehX, Float:vehY, Float:vehZ, Float:vehAngle;

GetVehiclePos(vehicleid, vehX, vehY, vehZ); // get vehicle XYZ pos
GetVehicleZAngle(vid, vehAngle); // get vehicle facing angle
ofx = x-vehX; // x = object's real world XYZ, vehX - vehicle's XYZ. Calculate            real world offset between object and vehicle
ofy = y-vehY;
ofz = z-vehZ;
ofangle = rz-vehAngle;
// calculate attach offsets relative to vehicle (see image above)
attachX = ofx*floatcos(vehAngle, degrees) +  ofy*floatsin(vehAngle, degrees);
attachY = -ofx*floatsin(vehAngle, degrees)+ ofy*floatcos(vehAngle, degrees);

AttachObjectToVehicle(objectid, vehicleid, attachX, attachY, ofz, rx, ry, ofangle); // attach object with calculated X, Y and angle
</code>```

And this works great, but what I want to do now, is to "reverse" this.
I want to calculate object's real world position (so it will be in the exactly same place as it is now, but not attached)
So I have this:

```<code>    new Float:vehX, Float:vehY, Float:vehZ, Float:vehAngle;
GetVehiclePos(vehicleid, vehX, vehY, vehZ);
GetVehicleAngle(vehicleid, vehAngle);

new Float:objAttachX, Float:objAttachY, Float:objAttachZ, Float:objAttachRotX, Float:objAttachRotY, Float:ObjAttachRotZ);
GetAttachedObjectOffsets(objectid, objAttachX, objAttachY, objAttachZ);
GetAttachedObjectRotation(objectid, objAttachRotX, objAttachRotY, objAttachRotZ);
// now, using current vehicle position and the object's attachment offsets, somehow calculate the objects position in real world.
</code>```

I would be glad if someone could help me in this, I guess it's really simple but I can't figure it out.

答:
Forget about the trigonometry. All you have to do is solve a system of 2 linear equations with 2 unknowns (and 2 parameters, c and s):
X =  x * c + y * s
Y = -x * s + y * c
equivalent to (multiplying by s and c respectively):
s X =  s c x + s^2 y
c Y = -s c x + c^2 y.
Adding:
s X + c Y = s^2 y + c^2 y = y [cos^2 + sin^2 = 1]
Likewise for x:
c X =  c^2 x + s c y
s Y = -s^2 x + s c y,
yielding:
c X - s Y = c^2 x + s^2 x = x</p>

Body:
I'm doing a mod for a game and I'm not very good with trigonometry and can't figure out how to do this despite of many attempts.

I have a vehicle in the 3D World at some position with some facing angle (z angle). I also have an object right next to it, and have it's XYZ position and rotations. I want to attach the object to the vehicle, but to attach it I need to specify the offsets relative to the vehicle, not real world pos.
This is the "vehicle coord system":
vehicle attachment coords

But that's not the problem. I already have this code which does it:

new Float:ofx, Float:ofy, Float:ofz, Float:ofangle;
new Float:attachX, Float:attachY;
new Float:vehX, Float:vehY, Float:vehZ, Float:vehAngle;

GetVehiclePos(vehicleid, vehX, vehY, vehZ); // get vehicle XYZ pos
GetVehicleZAngle(vid, vehAngle); // get vehicle facing angle
ofx = x-vehX; // x = object's real world XYZ, vehX - vehicle's XYZ. Calculate            real world offset between object and vehicle
ofy = y-vehY;
ofz = z-vehZ;
ofangle = rz-vehAngle;
// calculate attach offsets relative to vehicle (see image above)
attachX = ofx*floatcos(vehAngle, degrees) +  ofy*floatsin(vehAngle, degrees);
attachY = -ofx*floatsin(vehAngle, degrees)+ ofy*floatcos(vehAngle, degrees);

AttachObjectToVehicle(objectid, vehicleid, attachX, attachY, ofz, rx, ry, ofangle); // attach object with calculated X, Y and angle

And this works great, but what I want to do now, is to "reverse" this.
I want to calculate object's real world position (so it will be in the exactly same place as it is now, but not attached)
So I have this:

    new Float:vehX, Float:vehY, Float:vehZ, Float:vehAngle;
GetVehiclePos(vehicleid, vehX, vehY, vehZ);
GetVehicleAngle(vehicleid, vehAngle);

new Float:objAttachX, Float:objAttachY, Float:objAttachZ, Float:objAttachRotX, Float:objAttachRotY, Float:ObjAttachRotZ);
GetAttachedObjectOffsets(objectid, objAttachX, objAttachY, objAttachZ);
GetAttachedObjectRotation(objectid, objAttachRotX, objAttachRotY, objAttachRotZ);
// now, using current vehicle position and the object's attachment offsets, somehow calculate the objects position in real world.

I would be glad if someone could help me in this, I guess it's really simple but I can't figure it out.


问:
Admob Not enough space to show ad with ConstraintLayout
I just changed my activity into fragment but now my ads no longer show because:

W/Ads: Not enough space to show ad. Needs 360x50 dp, but only has 344x496 dp.

I do not understand why it tells me not enough space whereas if I set the values myself (what I do not want to do) this working and ad is displayed on just over half.

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Score.FragmentScore"
    android:fitsSystemWindows="true">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintHorizontal_bias="0.5">

        <TableLayout
            android:id="@+id/tableau"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:background="@color/white"
            android:stretchColumns="*" />
    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="65dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:clickable="true"
        android:src="@drawable/ic_plus"
        app:backgroundTint="@android:color/holo_red_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginBottom="0dp" />

</android.support.constraint.ConstraintLayout>
</code>```

答:
Check your parent layout. Based from your logs, "Needs 360x50 dp, but only has 344x496 dp". You are missing 16dp you might have assigned some margin somewhere in your layout.

I cannot see any margins set in the layout that you pasted so I assume that you are adding your fragment to another layout. Check if it has any margins. ConstraintLayout sometimes set margins to added views. Here is an example:

```<code><android.support.design.widget.CoordinatorLayout
    android:id="@+id/fragment_container"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginEnd="0dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="0dp"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/main_toolbar"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1">
</android.support.design.widget.CoordinatorLayout>
</code>```

You will have to change the margins to 0dp so that your code will work.

Body:
I just changed my activity into fragment but now my ads no longer show because:

W/Ads: Not enough space to show ad. Needs 360x50 dp, but only has 344x496 dp.

I do not understand why it tells me not enough space whereas if I set the values myself (what I do not want to do) this working and ad is displayed on just over half.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Score.FragmentScore"
    android:fitsSystemWindows="true">

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/adView"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintHorizontal_bias="0.5">

        <TableLayout
            android:id="@+id/tableau"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:background="@color/white"
            android:stretchColumns="*" />
    </ScrollView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="65dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:clickable="true"
        android:src="@drawable/ic_plus"
        app:backgroundTint="@android:color/holo_red_light"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginBottom="0dp" />

</android.support.constraint.ConstraintLayout>

Body:
Check your parent layout. Based from your logs, "Needs 360x50 dp, but only has 344x496 dp". You are missing 16dp you might have assigned some margin somewhere in your layout.

I cannot see any margins set in the layout that you pasted so I assume that you are adding your fragment to another layout. Check if it has any margins. ConstraintLayout sometimes set margins to added views. Here is an example:

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/fragment_container"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginEnd="0dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="0dp"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/main_toolbar"
    tools:layout_constraintBottom_creator="1"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1">
</android.support.design.widget.CoordinatorLayout>

You will have to change the margins to 0dp so that your code will work.


问:
urllib.Request remove Content-Type header
I want to remove the content-type header from a POST request. I have tried setting the header to ''

```<code>try:
    from urllib.request import Request, urlopen
except ImportError:
    from urllib2 import Request, urlopen

url = 'https://httpbin.org/post'
test_data = 'test'

req = Request(url, test_data.encode(), headers={'Content-Type': ''})
req.get_method = lambda: 'POST'
print(urlopen(req).read().decode())
</code>```

But this sends:

```<code>{
  // ...
  "headers": {
     "Content-Type": "", // ...
  }
  // ...
}
</code>```

What I would like it to do is send no Content-Type at all, instead of a blank one. By default, it is application/x-www-form-urlencoded.

This can easily be acheived with requests:

```<code>print(requests.post(url, test_data).text)
</code>```

But this is a script I need to distribute, so cannot have dependencies. I need it to have no Content-Type at all, since the server is very picky, so I cannot use text/plain or application/octet-stream.

答:
You can specify custom handler:

```<code>try:
    from urllib.request import Request, urlopen, build_opener, BaseHandler
except ImportError:
    from urllib2 import Request, urlopen, build_opener, BaseHandler

url = 'https://httpbin.org/post'
test_data = 'test'

class ContentTypeRemover(BaseHandler):
    def http_request(self, req):
        if req.has_header('Content-type'):
            req.remove_header('Content-type')
        return req
    https_request = http_request

opener = build_opener(ContentTypeRemover())
req = Request(url, test_data.encode())
print(opener.open(req).read().decode())
</code>```

Another (hacky) way: monkey-patching the request object to pretend there's Content-type header already there; prevents AbstractHTTPHandler to default Content-Type header.

```<code>req = Request(url, test_data.encode())
req.has_header = lambda header_name: (header_name == 'Content-type' or
                                      Request.has_header(req, header_name))
print(urlopen(req).read().decode())
</code>```

Body:
I want to remove the content-type header from a POST request. I have tried setting the header to ''

try:
    from urllib.request import Request, urlopen
except ImportError:
    from urllib2 import Request, urlopen

url = 'https://httpbin.org/post'
test_data = 'test'

req = Request(url, test_data.encode(), headers={'Content-Type': ''})
req.get_method = lambda: 'POST'
print(urlopen(req).read().decode())

But this sends:

{
  // ...
  "headers": {
     "Content-Type": "", // ...
  }
  // ...
}

What I would like it to do is send no Content-Type at all, instead of a blank one. By default, it is application/x-www-form-urlencoded.

This can easily be acheived with requests:

print(requests.post(url, test_data).text)

But this is a script I need to distribute, so cannot have dependencies. I need it to have no Content-Type at all, since the server is very picky, so I cannot use text/plain or application/octet-stream.

Body:
You can specify custom handler:

try:
    from urllib.request import Request, urlopen, build_opener, BaseHandler
except ImportError:
    from urllib2 import Request, urlopen, build_opener, BaseHandler

url = 'https://httpbin.org/post'
test_data = 'test'

class ContentTypeRemover(BaseHandler):
    def http_request(self, req):
        if req.has_header('Content-type'):
            req.remove_header('Content-type')
        return req
    https_request = http_request

opener = build_opener(ContentTypeRemover())
req = Request(url, test_data.encode())
print(opener.open(req).read().decode())

Another (hacky) way: monkey-patching the request object to pretend there's Content-type header already there; prevents AbstractHTTPHandler to default Content-Type header.

req = Request(url, test_data.encode())
req.has_header = lambda header_name: (header_name == 'Content-type' or
                                      Request.has_header(req, header_name))
print(urlopen(req).read().decode())


问:
What is relvar - relational variable?
I am reading an introductory book on database systems and the authour introdiced the term: relational variable - relvar.

It says that the relvar is a container for the actual relation.

What is it meant by container? Is this a pysical concept, like a place on disk? Is this more of an logical concept, so that container is just an umbrella term for metadata and relation?

答:
A relation variable can be contrasted with a relation value. These concepts are analogous to simple algebraic variables like x, and values like 5.

A relation variable is a symbol that can reference different values at different times - hence the term variable, since its value can vary. For example, I might have a relation Employee which holds information about the people working for me at any given time.

A relation value is a particular state. Values don't vary. When we say the value of a variable changes, we actually mean that the variable is assigned a new value, which may be derived from the old value.

These are logical concepts. Container is an informal term which is accessible to a lay audience. However, it shouldn't be taken too literally. Variables and values can be implemented or represented in a variety of ways in physical systems.

Title: What is relvar - relational variable?


问:
Processing NLTK Stanford POS Tagger output
Im working with NLTK Stanford Pos Tagger with my own model to tag line of sentences in text file. The output of my tagger is like :

```<code>sentences = [((Word,WordTag),....(Word,WordTag)]
</code>```

Im processing Indonesian language, Im doing 2 step after doing Pos tag :

Stop Word Removal

Stemming

I've got a list of stopword in text file(stopword.txt), and Stem the sentence.
So far I have done the tagging part. I dont have any ideas how to filter the word in sentences  and remove the word if they in stopword.txt and stem the word in sentences

So far, i've tried this code to remove the word but still not removing the word and its word tag:

```<code>stopWords = getStopWordList('id_stopword.txt')
filtered_sentences = [w for w in sentences if not w in stopWords]
    filtered_sentences = []
    for w in sentences:
        if w not in stopWords:
            filtered_sentences.append(w)
</code>```

答:
I have to assume that your function getStopWordList() correctly returns a list of strings. (Have you verified that?)

The code you posted won't run because it has indentation errors. But the indented bit doesn't matter because you don't need it. It clearly just repeats the logic of the line before it. So I've just ignored it.

To do the filtering you need to change this:

```<code>filtered_sentences = [w for w in sentences if not w in stopWords]
</code>```

to this:

```<code>filtered_sentences = [(w,t) for (w,t) in sentences if not w in stopWords]
</code>```

Body:
Im working with NLTK Stanford Pos Tagger with my own model to tag line of sentences in text file. The output of my tagger is like :

sentences = [((Word,WordTag),....(Word,WordTag)]

Im processing Indonesian language, Im doing 2 step after doing Pos tag :

Stop Word Removal

Stemming

I've got a list of stopword in text file(stopword.txt), and Stem the sentence.
So far I have done the tagging part. I dont have any ideas how to filter the word in sentences  and remove the word if they in stopword.txt and stem the word in sentences

So far, i've tried this code to remove the word but still not removing the word and its word tag:

stopWords = getStopWordList('id_stopword.txt')
filtered_sentences = [w for w in sentences if not w in stopWords]
    filtered_sentences = []
    for w in sentences:
        if w not in stopWords:
            filtered_sentences.append(w)

Body:
I have to assume that your function getStopWordList() correctly returns a list of strings. (Have you verified that?)

The code you posted won't run because it has indentation errors. But the indented bit doesn't matter because you don't need it. It clearly just repeats the logic of the line before it. So I've just ignored it.

To do the filtering you need to change this:

filtered_sentences = [w for w in sentences if not w in stopWords]

to this:

filtered_sentences = [(w,t) for (w,t) in sentences if not w in stopWords]


问:
Yahoo Finance API .get_historical() not working python
So I recently downloaded the yahoo_finance API and its version 1.4.0. I got it a few days ago, and the .get_historical() was working fine. Now however, it doesn't. Heres what its doing:

```<code>import yahoo_finance as yf

apple=yf.Share('AAPL')
apple_price=apple.get_price()

print apple.get_historical('2016-02-15', '2016-04-29')
</code>```

The error I get is:YQLResponseMalformedError: Response malformed. Is there a bug in the API or am I forgetting something?

答:
The Yahoo Stock Price API doesn't work anymore, which a lot of modules are based on, unfortunately.

Alternatively, you could use Google's API
https://www.google.com/finance/getprices?q=1101&x=TPE&i=86400&p=3d&f=d,c,h,l,o,v

```<code>q=1101 is the stock quote
x=TPE is the exchange (List of Exchanges here: https://www.google.com/googlefinance/disclaimer/ )
i=86400 interval in seconds (86400 sec = 1 day)
p=3d data since how long ago
f= fields of data (d=date, c=close, h=high, l=low, o=open, v=volume)
</code>```

Data would look like this:

```<code>EXCHANGE%3DTPE
MARKET_OPEN_MINUTE=540
MARKET_CLOSE_MINUTE=810
INTERVAL=86400
COLUMNS=DATE,CLOSE,HIGH,LOW,OPEN,VOLUME
DATA=
TIMEZONE_OFFSET=480
a1496295000,24.4,24.75,24.35,24.75,11782000
1,24.5,24.5,24.3,24.4,10747000
</code>```

a1496295000 is the Unix timestamp of first row of data

the second row 1 is the interval offset from first row (offset 1 day)

Body:
So I recently downloaded the yahoo_finance API and its version 1.4.0. I got it a few days ago, and the .get_historical() was working fine. Now however, it doesn't. Heres what its doing:

import yahoo_finance as yf

apple=yf.Share('AAPL')
apple_price=apple.get_price()

print apple.get_historical('2016-02-15', '2016-04-29')

The error I get is:YQLResponseMalformedError: Response malformed. Is there a bug in the API or am I forgetting something?

Body:
The Yahoo Stock Price API doesn't work anymore, which a lot of modules are based on, unfortunately.

Alternatively, you could use Google's API
https://www.google.com/finance/getprices?q=1101&x=TPE&i=86400&p=3d&f=d,c,h,l,o,v

q=1101 is the stock quote
x=TPE is the exchange (List of Exchanges here: https://www.google.com/googlefinance/disclaimer/ )
i=86400 interval in seconds (86400 sec = 1 day)
p=3d data since how long ago
f= fields of data (d=date, c=close, h=high, l=low, o=open, v=volume)

Data would look like this:

EXCHANGE%3DTPE
MARKET_OPEN_MINUTE=540
MARKET_CLOSE_MINUTE=810
INTERVAL=86400
COLUMNS=DATE,CLOSE,HIGH,LOW,OPEN,VOLUME
DATA=
TIMEZONE_OFFSET=480
a1496295000,24.4,24.75,24.35,24.75,11782000
1,24.5,24.5,24.3,24.4,10747000

a1496295000 is the Unix timestamp of first row of data

the second row 1 is the interval offset from first row (offset 1 day)


问:
Passing multi parameters from view to controller using array
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

```<code>@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{

    <input type="checkbox" name="U1">Choice one</input>
    <input type="checkbox" name="U2">Choice two</input>
    <input type="checkbox" name="U3">Choice three</input>
    <input type="checkbox" name="U4">Choice four</input>

....

<input type="checkbox" name="U55">Choice fifty five</input>

<button type="submit">Send</button>
                               }
</code>```

Controller:

```<code>[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}
</code>```

How can I send all of parameters (checkboxes) using an array to my controller. I appriciate all your solutions.

答:
Dynamically you can do it like bellow code:

```<code>@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{

    <input type="checkbox" name="answer[]" value="@dynamicValue">@dynamicValue</input>

    <button type="submit">Send</button>
}
</code>```

and

```<code>[HttpPost]
public async Task<ActionResult> User(string[] answer)
{

}
</code>```

Body:
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{

    <input type="checkbox" name="U1">Choice one</input>
    <input type="checkbox" name="U2">Choice two</input>
    <input type="checkbox" name="U3">Choice three</input>
    <input type="checkbox" name="U4">Choice four</input>

....

<input type="checkbox" name="U55">Choice fifty five</input>

<button type="submit">Send</button>
                               }

Controller:

[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}

How can I send all of parameters (checkboxes) using an array to my controller. I appriciate all your solutions.

Body:
Dynamically you can do it like bellow code:

@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{

    <input type="checkbox" name="answer[]" value="@dynamicValue">@dynamicValue</input>

    <button type="submit">Send</button>
}

and

[HttpPost]
public async Task<ActionResult> User(string[] answer)
{

}


问:
Tortoise SVN logging without committing
I normally make multiple small edits to my source code, but I don't want to commit just yet, since the changes are rather trivial. The current method I'm using right now is to log the changes in a text file, then copying the contents into the log when committing.

Is it possible when using Tortoise SVN (or any other SVN tool) to attach log messages to the copy I'm currently working on as I'm editing, then when committing, the log messages are automatically attached to the commit, so I don't have to remember all the changes I've made so far?

答:
What's wrong with using a diff tool and reviewing your changes before commit?

If you can't remember the reason for changes, or work them out from the code, then isn't that a clue that you need to commit more often? Commits are cheap and quick, and if the changes are logically related in a revision, it makes reverting and merging (in the future) much easier.

Title: Tortoise SVN logging without committing


问:
return new object of same type as child object in overwritten method
I have a virtual super class with several child classes. In the following is a simple example of my situation:

```<code>(*Super class*)
class virtual super = object(self : 'self)
 method virtual generateNewOne : X
end;;

(*Child class one*)
class subOne = object(self)
 inherit super

 method subOneMethod x =
  x+2;

 method generateNewOne =
  let a = new subOne in
  a
 end;;

(*Child class two*)
class subTwo = object(self)
 inherit super

 method subTwoMethod x =
  x+3;

 method generateNewOne =
  let b = new subTwo in
  b
 end;;
</code>```

My question is:

What do i have to insert for the X as type of the generateNewOne method?

My first thought was of type self, but as far as i tried it did not work, because the new objects do not have self type but subOne or subTwo.

答:
You can replace X with super. In that case, generateNewOne of subOne has to return a super as well. Which can be achieved with a coercion:

```<code>method generateNewOne =
  let a = new subOne in
  (a :> super)
</code>```

Similarly for subTwo.

If you really insist on generateNewOne to return a subOne or subTwo, then subOne, subTwo and super will be incompatible types, neither being a subtype of another. The reason is that they have mutually different return types of generateNewOne (To be more precise, we do not know that of super per se, because X is not yet specified. But we do know for sure, that super will be incompatible with at least one of subOne and subTwo.). In that case you cannot use inheritance, because inheritance implies that the type of generateNewOne remains the same.

Body:
I have a virtual super class with several child classes. In the following is a simple example of my situation:

(*Super class*)
class virtual super = object(self : 'self)
 method virtual generateNewOne : X
end;;

(*Child class one*)
class subOne = object(self)
 inherit super

 method subOneMethod x =
  x+2;

 method generateNewOne =
  let a = new subOne in
  a
 end;;

(*Child class two*)
class subTwo = object(self)
 inherit super

 method subTwoMethod x =
  x+3;

 method generateNewOne =
  let b = new subTwo in
  b
 end;;

My question is:

What do i have to insert for the X as type of the generateNewOne method?

My first thought was of type self, but as far as i tried it did not work, because the new objects do not have self type but subOne or subTwo.

Body:
You can replace X with super. In that case, generateNewOne of subOne has to return a super as well. Which can be achieved with a coercion:

method generateNewOne =
  let a = new subOne in
  (a :> super)

Similarly for subTwo.

If you really insist on generateNewOne to return a subOne or subTwo, then subOne, subTwo and super will be incompatible types, neither being a subtype of another. The reason is that they have mutually different return types of generateNewOne (To be more precise, we do not know that of super per se, because X is not yet specified. But we do know for sure, that super will be incompatible with at least one of subOne and subTwo.). In that case you cannot use inheritance, because inheritance implies that the type of generateNewOne remains the same.


问:
how to calculate geomatic average value with nans?
I would like to calculate the geometric mean of some data (including NaN), how can I do it?

I know how to calculate the mean value with NaNs, we can use the following code:

```<code>import numpy as np
M = np.nanmean(data, axis=2).
</code>```

So how to do it with geomean?

答:
You could use the identity (I only found it in the german Wikipedia but there are probably other sources as well):

This identity can be constructed using the "logarithm rules" on the normal definition of the geometric mean:

The base a can be chosen arbitarly, so you could use np.log (and np.exp as inverse operation):

```<code>import numpy as np

def nangmean(arr, axis=None):
    arr = np.asarray(arr)
    inverse_valids = 1. / np.sum(~np.isnan(arr), axis=axis)  # could be a problem for all-nan-axis
    rhs = inverse_valids * np.nansum(np.log(arr), axis=axis)
    return np.exp(rhs)
</code>```

And it seems to work:

```<code>>>> l = [[1, 2, 3], [1, np.nan, 3], [np.nan, 2, np.nan]]

>>> nangmean(l)
1.8171205928321397

>>> nangmean(l, axis=1)
array([ 1.81712059,  1.73205081,  2.        ])

>>> nangmean(l, axis=0)
array([ 1.,  2.,  3.])
</code>```

In NumPy 1.10 also np.nanprod was added, so you could also use the normal definition:

```<code>import numpy as np

def nangmean(arr, axis=None):
    arr = np.asarray(arr)
    valids = np.sum(~np.isnan(arr), axis=axis)
    prod = np.nanprod(arr, axis=axis)
    return np.power(prod, 1. / valids)
</code>```

Body:
I would like to calculate the geometric mean of some data (including NaN), how can I do it?

I know how to calculate the mean value with NaNs, we can use the following code:

import numpy as np
M = np.nanmean(data, axis=2).

So how to do it with geomean?

Body:
You could use the identity (I only found it in the german Wikipedia but there are probably other sources as well):

This identity can be constructed using the "logarithm rules" on the normal definition of the geometric mean:

The base a can be chosen arbitarly, so you could use np.log (and np.exp as inverse operation):

import numpy as np

def nangmean(arr, axis=None):
    arr = np.asarray(arr)
    inverse_valids = 1. / np.sum(~np.isnan(arr), axis=axis)  # could be a problem for all-nan-axis
    rhs = inverse_valids * np.nansum(np.log(arr), axis=axis)
    return np.exp(rhs)

And it seems to work:

>>> l = [[1, 2, 3], [1, np.nan, 3], [np.nan, 2, np.nan]]

>>> nangmean(l)
1.8171205928321397

>>> nangmean(l, axis=1)
array([ 1.81712059,  1.73205081,  2.        ])

>>> nangmean(l, axis=0)
array([ 1.,  2.,  3.])

In NumPy 1.10 also np.nanprod was added, so you could also use the normal definition:

import numpy as np

def nangmean(arr, axis=None):
    arr = np.asarray(arr)
    valids = np.sum(~np.isnan(arr), axis=axis)
    prod = np.nanprod(arr, axis=axis)
    return np.power(prod, 1. / valids)


问:
how to get latest JRE version in command prompt if windows has more than one JRE version
I am trying get the latest JRE installed in windows using dir command. I Have JRE 1.6 and 1.8 installed on my Windows but I need to get whatever the latest version installed in windows (even in future it may change to 1.8 to 2.0*). Can any one please help on this.

答:
Try this batch for win7</p>

```<code>@echo off

@echo off
rem http://technet.microsoft.com/en-us/library/bb490890.aspx
SETLOCAL EnableDelayedExpansion
:: findJDK.bat

rem start:-> Run a command in a separate process, or run a file with its default associated application
rem REGEDIT.EXE: -> Export to a (.REG) file:
rem REGEDIT.EXE [ /L:system | /R:user ] /E exportfile.REG "registry_key"

start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit"

rem TYPE: -> Display text file content in console
rem FIND: -> Search files or standard output

rem reserved key words regarding reg-key -> "JavaHome" "MicroVersion" "RuntimeLib"
rem | Reads the output from one command and writes it to the input of another command. Also known as a pipe.

type reg1.txt | find "JavaHome" > reg2.txt

if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg2.txt) do (
  set JavaTemp=%%~x
  echo Regedit: JAVA_HOME path : !JavaTemp!
)

if errorlevel 1 goto ERROR
echo.
set JAVA_HOME=%JavaTemp%
set JAVA_HOME=%JAVA_HOME:\\=\%
echo JAVA_HOME was found to be %JAVA_HOME%

start /w regedit /e reg3.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment"
type reg3.txt | find "RuntimeLib" > reg4.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg4.txt) do (
  set JavaTemp=%%~x
  echo Regedit: JRE_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JRE_HOME=%JavaTemp%
set JRE_HOME=%JRE_HOME:\\=\%
echo JRE_HOME was found to be %JRE_HOME%
goto END
:ERROR
echo A reg1.txt is: & type reg1.txt
echo B reg2.txt is: & type reg2.txt
echo
:END
echo END

pause
</code>```

Body:
Try this batch for win7

@echo off

@echo off
rem http://technet.microsoft.com/en-us/library/bb490890.aspx
SETLOCAL EnableDelayedExpansion
:: findJDK.bat

rem start:-> Run a command in a separate process, or run a file with its default associated application
rem REGEDIT.EXE: -> Export to a (.REG) file:
rem REGEDIT.EXE [ /L:system | /R:user ] /E exportfile.REG "registry_key"

start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit"

rem TYPE: -> Display text file content in console
rem FIND: -> Search files or standard output

rem reserved key words regarding reg-key -> "JavaHome" "MicroVersion" "RuntimeLib"
rem | Reads the output from one command and writes it to the input of another command. Also known as a pipe.

type reg1.txt | find "JavaHome" > reg2.txt

if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg2.txt) do (
  set JavaTemp=%%~x
  echo Regedit: JAVA_HOME path : !JavaTemp!
)

if errorlevel 1 goto ERROR
echo.
set JAVA_HOME=%JavaTemp%
set JAVA_HOME=%JAVA_HOME:\\=\%
echo JAVA_HOME was found to be %JAVA_HOME%

start /w regedit /e reg3.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment"
type reg3.txt | find "RuntimeLib" > reg4.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg4.txt) do (
  set JavaTemp=%%~x
  echo Regedit: JRE_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JRE_HOME=%JavaTemp%
set JRE_HOME=%JRE_HOME:\\=\%
echo JRE_HOME was found to be %JRE_HOME%
goto END
:ERROR
echo A reg1.txt is: & type reg1.txt
echo B reg2.txt is: & type reg2.txt
echo
:END
echo END

pause


问:
Detect if a generic type is open?
I have a bunch of regular, closed and opened types in my assembly. I have a query that I'm trying to rule out the open types from it

```<code>class Foo { } // a regular type
class Bar<T, U> { } // an open type
class Moo : Bar<int, string> { } // a closed type

var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => ???);
types.Foreach(t => ConsoleWriteLine(t.Name)); // should *not* output "Bar`2"
</code>```

Upon debugging the generic arguments of an open type, I found that their FullName is null (as well as other things like the DeclaringMethod) - So this could be one way:

```<code>    bool IsOpenType(Type type)
    {
        if (!type.IsGenericType)
            return false;
        var args = type.GetGenericArguments();
        return args[0].FullName == null;
    }

    Console.WriteLine(IsOpenType(typeof(Bar<,>)));            // true
    Console.WriteLine(IsOpenType(typeof(Bar<int, string>)));  // false
</code>```

Is there a built-in way to know if a type is open? if not, is there a better way to do it? Thanks.

答:
Type.IsGenericTypeDefinition is not technically the correct property to rule out open types. It will however work just fine in your case (and indeed in most other cases).

That being said, a type can be open without being a generic type definition. In the more general case, e.g. in a public method that accepts a Type parameter, what you really want is Type.ContainsGenericParameters.

For full details see the answer to this question:
 Difference between Type.IsGenericTypeDefinition and Type.ContainsGenericParameters

TL;DR: The latter is recursive, while the former is not, and can thus be "fooled" by constructing a generic type that has a generic type definition as at least one of its generic type parameters.

Title: Detect if a generic type is open?

Body:
I have a bunch of regular, closed and opened types in my assembly. I have a query that I'm trying to rule out the open types from it

class Foo { } // a regular type
class Bar<T, U> { } // an open type
class Moo : Bar<int, string> { } // a closed type

var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => ???);
types.Foreach(t => ConsoleWriteLine(t.Name)); // should *not* output "Bar`2"

Upon debugging the generic arguments of an open type, I found that their FullName is null (as well as other things like the DeclaringMethod) - So this could be one way:

    bool IsOpenType(Type type)
    {
        if (!type.IsGenericType)
            return false;
        var args = type.GetGenericArguments();
        return args[0].FullName == null;
    }

    Console.WriteLine(IsOpenType(typeof(Bar<,>)));            // true
    Console.WriteLine(IsOpenType(typeof(Bar<int, string>)));  // false

Is there a built-in way to know if a type is open? if not, is there a better way to do it? Thanks.


问:
Why is Zend Framework so popular?
I'm not a troll and my goal isn't to start a flame war; neither do I mean to disrespect the authors of the Zend Framework: there is a lot of fine work in it. But... I have a job to get done and I'm having a hard time reconciling the popularity of ZF against the reality of building apps with it. I would really like to know from others why they use Zend Framework.

I am fairly new to the PHP world but I've done a lot of programming in many languages. After reading many tutorials and building a couple of apps in it, some core Zend Framework facilities feel like alpha code to me. For me the following fundamental weaknesses, among others, would seem too overwhelming to consider deploying apps with it -  but over and over again ZF is suggested as one of the, if not the leading framework.

First let me say I find the much of ZF to be workable. Routing works pretty much as it should, the Layout facility is serviceable (though very different from templating systems such as JSP/ASP), as is the cache facility, etc. There seems to be a tendency in the community to stuff a lot of modeling (e.g. validation) and view logic (e.g. $this->headScript() - why should my controller have to care which js file my view requires?) into controllers but could be a matter of usage and not necessarily the framework's fault.

Now for a couple of really serious (IMO) weaknesses I've experienced in my short time with it. I shudder to imagine the other areas I will discover in the future if I continue to build with it.

1. Form Layout

Many people seem to be unhappy with the lack of control over form layout. How can you have a popular framework where constructing a simple form requires so much discussion?
Question 1 and question 2.

2. Authentication/Authorization

No one really seems to understand how to simply perform routine authentication/authorization. People [including yours truly] struggle with implementing simple access control. Further, the approach seems to lean on serialization for persistence, rather than traditional database storage of users and permissions.
A confusing example, a proposal to enhance the facility, a tutorial - part I,
and part II. This is too much work guys!

Are my perceived weaknesses not real or somehow not a problem? Why or why not? Why did you choose Zend Framework (or not)? Are there other areas that you've found to be so painful that you want to dump ZF for a different approach? Thanks for your opinions.

答:
I use ZF for a few reasons:
The host of nifty classes, lazy loading of classes, stand-alone usage of classes, and clean clear source. The first time I used it I needed to build an ACL system - a very big complex one. Zend_Acl helped tremendously.

I think ZF needs to work on it's docs and db classes. The db classes problems have a lot to do with PHP itself. So maybe it's some thing Zend wants to look into.

The OP is new to PHP. I agree PHP has it's flaws such as the arbitrary naming of functions, but generally it does make sense for HTTP and doesn't hide reality from you.

Title: Why is Zend Framework so popular?


问:
Wordpress Woocommerce custom field
I'm trying to create custom field in woo-commerce (not interested in plugins) in single product and variable product ( custom field price should change according to selected variable option) as that client should be able to enter price as show in 1st picture and customer could be able check the option.

My Requirement

```<code>// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woocom_general_product_data_custom_field' );

function woocom_general_product_data_custom_field() {
  // Create a custom text field

  // Text Field
  woocommerce_wp_text_input(
    array(
      'id' => '_text_field',
      'label' => __( 'Enter your choose', 'woocommerce' ),
      'placeholder' => 'Custom text field',
      'desc_tip' => 'true',
      'description' => __( 'Enter the custom value here.', 'woocommerce' )
    )
  );

  // Number Field
  woocommerce_wp_text_input(
    array(
      'id' => '_number_field',
      'label' => __( 'Enter your number', 'woocommerce' ),
      'placeholder' => '',
      'description' => __( 'Enter the custom value here.', 'woocommerce' ),
      'type' => 'number',
      'custom_attributes' => array(
         'step' => 'any',
         'min' => '15'
      )
    )
  );

  // Checkbox
  woocommerce_wp_checkbox(
    array(
      'id' => '_checkbox',
      'label' => __('Select', 'woocommerce' ),
      'description' => __( 'Check me!', 'woocommerce' )
    )
  );

  // Select
  woocommerce_wp_select(
    array(
      'id' => '_select',
      'label' => __( 'option', 'woocommerce' ),
      'options' => array(
         '1' => __( 'Custom Option 1', 'woocommerce' ),
         '2' => __( 'Custom Option 2', 'woocommerce' ),
        '3' => __( 'Custom Option 3', 'woocommerce' )
      )
    )
  );

  // Textarea
  woocommerce_wp_textarea_input(
     array(
       'id' => '_textarea',
       'label' => __( 'Description', 'woocommerce' ),
       'placeholder' => '',
       'description' => __( 'Enter the custom value here.', 'woocommerce' )
     )
 );

}

// Hook to save the data value from the custom fields
add_action( 'woocommerce_process_product_meta', 'woocom_save_general_proddata_custom_field' );

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_top_category_desc', 1 );
    function woocommerce_template_top_category_desc (){
 $terms = get_the_terms( $post->ID, 'wc-attibute-class' );
if ( !empty($terms)) {
        $term = array_pop($terms);
                $text= get_field('txt-field', $term);
                if (!empty($text)) {
                echo $text;
                }
}
        }

/** Hook callback function to save custom fields information */
function woocom_save_general_proddata_custom_field( $post_id ) {
  // Save Text Field
  $text_field = $_POST['_text_field'];
  if( ! empty( $text_field ) ) {
     update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );
  }

  // Save Number Field
  $number_field = $_POST['_number_field'];
  if( ! empty( $number_field ) ) {
     update_post_meta( $post_id, '_number_field', esc_attr( $number_field ) );
  }
  // Save Textarea
  $textarea = $_POST['_textarea'];
  if( ! empty( $textarea ) ) {
     update_post_meta( $post_id, '_textarea', esc_html( $textarea ) );
  }

  // Save Select
  $select = $_POST['_select'];
  if( ! empty( $select ) ) {
     update_post_meta( $post_id, '_select', esc_attr( $select ) );
  }

  // Save Checkbox
  $checkbox = isset( $_POST['_checkbox'] ) ? 'yes' : 'no';
  update_post_meta( $post_id, '_checkbox', $checkbox );

  // Save Hidden field
  $hidden = $_POST['_hidden_field'];
  if( ! empty( $hidden ) ) {
     update_post_meta( $post_id, '_hidden_field', esc_attr( $hidden ) );
  }
}
</code>```

I have tried some woocommerce custom plugin but it didn't solve my requirement as I have 25 above custom filed to be created and plugin seems to be very lengthy process for my work

My output is in picture 2 which I got from coding for not as my requirement

My output

答: I know you are not interested in plugins, but I highly recommend ACF plugin for custom fields. Check it out, it will save you a lot of time.</p>

Title: Wordpress Woocommerce custom field

Body:
I'm trying to create custom field in woo-commerce (not interested in plugins) in single product and variable product ( custom field price should change according to selected variable option) as that client should be able to enter price as show in 1st picture and customer could be able check the option.

My Requirement

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woocom_general_product_data_custom_field' );

function woocom_general_product_data_custom_field() {
  // Create a custom text field

  // Text Field
  woocommerce_wp_text_input(
    array(
      'id' => '_text_field',
      'label' => __( 'Enter your choose', 'woocommerce' ),
      'placeholder' => 'Custom text field',
      'desc_tip' => 'true',
      'description' => __( 'Enter the custom value here.', 'woocommerce' )
    )
  );

  // Number Field
  woocommerce_wp_text_input(
    array(
      'id' => '_number_field',
      'label' => __( 'Enter your number', 'woocommerce' ),
      'placeholder' => '',
      'description' => __( 'Enter the custom value here.', 'woocommerce' ),
      'type' => 'number',
      'custom_attributes' => array(
         'step' => 'any',
         'min' => '15'
      )
    )
  );

  // Checkbox
  woocommerce_wp_checkbox(
    array(
      'id' => '_checkbox',
      'label' => __('Select', 'woocommerce' ),
      'description' => __( 'Check me!', 'woocommerce' )
    )
  );

  // Select
  woocommerce_wp_select(
    array(
      'id' => '_select',
      'label' => __( 'option', 'woocommerce' ),
      'options' => array(
         '1' => __( 'Custom Option 1', 'woocommerce' ),
         '2' => __( 'Custom Option 2', 'woocommerce' ),
        '3' => __( 'Custom Option 3', 'woocommerce' )
      )
    )
  );

  // Textarea
  woocommerce_wp_textarea_input(
     array(
       'id' => '_textarea',
       'label' => __( 'Description', 'woocommerce' ),
       'placeholder' => '',
       'description' => __( 'Enter the custom value here.', 'woocommerce' )
     )
 );

}

// Hook to save the data value from the custom fields
add_action( 'woocommerce_process_product_meta', 'woocom_save_general_proddata_custom_field' );

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_top_category_desc', 1 );
    function woocommerce_template_top_category_desc (){
 $terms = get_the_terms( $post->ID, 'wc-attibute-class' );
if ( !empty($terms)) {
        $term = array_pop($terms);
                $text= get_field('txt-field', $term);
                if (!empty($text)) {
                echo $text;
                }
}
        }

/** Hook callback function to save custom fields information */
function woocom_save_general_proddata_custom_field( $post_id ) {
  // Save Text Field
  $text_field = $_POST['_text_field'];
  if( ! empty( $text_field ) ) {
     update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );
  }

  // Save Number Field
  $number_field = $_POST['_number_field'];
  if( ! empty( $number_field ) ) {
     update_post_meta( $post_id, '_number_field', esc_attr( $number_field ) );
  }
  // Save Textarea
  $textarea = $_POST['_textarea'];
  if( ! empty( $textarea ) ) {
     update_post_meta( $post_id, '_textarea', esc_html( $textarea ) );
  }

  // Save Select
  $select = $_POST['_select'];
  if( ! empty( $select ) ) {
     update_post_meta( $post_id, '_select', esc_attr( $select ) );
  }

  // Save Checkbox
  $checkbox = isset( $_POST['_checkbox'] ) ? 'yes' : 'no';
  update_post_meta( $post_id, '_checkbox', $checkbox );

  // Save Hidden field
  $hidden = $_POST['_hidden_field'];
  if( ! empty( $hidden ) ) {
     update_post_meta( $post_id, '_hidden_field', esc_attr( $hidden ) );
  }
}

I have tried some woocommerce custom plugin but it didn't solve my requirement as I have 25 above custom filed to be created and plugin seems to be very lengthy process for my work

My output is in picture 2 which I got from coding for not as my requirement

My output


问:
Bundling data files with PyInstaller (--onefile)
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

If I do --onedir it works all works very well.
When I use --onefile, it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.

I've looked in the temp-dir generated when running the EXE (\Temp\_MEI95642\ for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.

This is what I've added to the .spec file

```<code>a.datas += [('images/icon.ico', 'D:\\[workspace]\\App\\src\\images\\icon.ico',  'DATA'),
('images/loaderani.gif','D:\\[workspace]\\App\\src\\images\\loaderani.gif','DATA')]
</code>```

I should add that I have tried not putting them in subfolders as well, didn't make a difference.

Edit: Marked newer answer as correct due to PyInstaller update.

答:
All of the other answers use the current working directory in the case where the application is not PyInstalled (i.e. sys._MEIPASS is not set). That is wrong, as it prevents you from running your application from a directory other than the one where your script is.

A better solution:

```<code>import sys
import os

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)
</code>```

Body:
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

If I do --onedir it works all works very well.
When I use --onefile, it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.

I've looked in the temp-dir generated when running the EXE (\Temp\_MEI95642\ for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.

This is what I've added to the .spec file

a.datas += [('images/icon.ico', 'D:\\[workspace]\\App\\src\\images\\icon.ico',  'DATA'),
('images/loaderani.gif','D:\\[workspace]\\App\\src\\images\\loaderani.gif','DATA')]

I should add that I have tried not putting them in subfolders as well, didn't make a difference.

Edit: Marked newer answer as correct due to PyInstaller update.

Body:
All of the other answers use the current working directory in the case where the application is not PyInstalled (i.e. sys._MEIPASS is not set). That is wrong, as it prevents you from running your application from a directory other than the one where your script is.

A better solution:

import sys
import os

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)


问:
Is there any way to perform a batched request in Asp.net core?
We have an API built using ASP.Net Core, and we would like to consolidate multiple requests into one HTTP requests for performance reasons.

In previous versions of asp.net you could allow for batch requests via the DefaultHttpBatchHandler.

Unfortunately, no such thing seems to exist in Asp.net Core.

Is anyone aware of any way to do HTTP batches in core?

答:
Not sure I understand? Do you mean 1 exposed endpoint that makes multiple calls?

Can you not have 1 API action that just creates multiple Tasks (that will run in parallel), waits for them all to complete then return all response data (combined or separated as required)?


问:
Finding all numbers in a array with top frequency?
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

```<code>8 => 2
1 => 2
9 => 2
</code>```

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

```<code>    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }
</code>```

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

```<code>    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }
</code>```

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

答:
this should help you . a perfectly optimised code and guess what ? It works in O(N) .</p>

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Test {
public static void main(String[] args) {
    int[] A = { 1, 8, 7, 8, 9, 2, 1, 9, 6, 4, 3, 5, 4, 4, 4, 4, 4 };
    Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
    for (int i : A) {
        if (map.containsKey(i)) {
            map.put(i, map.get(i) + 1);
        } else {
            map.put(i, 1);
        }
    }
    System.out.println(sortByValue(map));
    List<Integer> keys = new ArrayList<Integer>(sortByValue(map).keySet());
    int maximumPossibleFrequency = map.get(keys.get(keys.size() - 1));
    for (int i = keys.size() - 1; i >= 0; i--) {
        if (map.get(keys.get(i)) < maximumPossibleFrequency) {
            break;
        } else {
            System.out.println(keys.get(i) + " => " + map.get(keys.get(i)));
        }
    }
}

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> unsortMap) {

    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortMap.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }

    return result;

}
}
</code>```

Body:
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

Body:
this should help you . a perfectly optimised code and guess what ? It works in O(N) .

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Test {
public static void main(String[] args) {
    int[] A = { 1, 8, 7, 8, 9, 2, 1, 9, 6, 4, 3, 5, 4, 4, 4, 4, 4 };
    Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
    for (int i : A) {
        if (map.containsKey(i)) {
            map.put(i, map.get(i) + 1);
        } else {
            map.put(i, 1);
        }
    }
    System.out.println(sortByValue(map));
    List<Integer> keys = new ArrayList<Integer>(sortByValue(map).keySet());
    int maximumPossibleFrequency = map.get(keys.get(keys.size() - 1));
    for (int i = keys.size() - 1; i >= 0; i--) {
        if (map.get(keys.get(i)) < maximumPossibleFrequency) {
            break;
        } else {
            System.out.println(keys.get(i) + " => " + map.get(keys.get(i)));
        }
    }
}

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> unsortMap) {

    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(unsortMap.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }

    return result;

}
}


问:
How do i get "sed" to delete everything else but email address.
how do i get "sed" to delete everything else but email address. </p>

```<code>db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
</code>```

答:
The following will work no matter where the email address is in the line but only if there is one email address per line.  If there are more than one it's going to only show the last one in the line.  It also won't touch lines that don't have valid email addresses in them

```<code>sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/'
</code>```

Input

```<code>$ cat dbdump
this line with no valid @ email address is untouched
::: a0$...aucvkDt86 ::: joesmith@gmail.com
::: a0$... foo@example.com db dump: someusername :::
</code>```

Output

```<code>$  sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/' ./dbdump
this line with no valid @ email address is untouched
joesmith@gmail.com
foo@example.com
</code>```

Body:
how do i get "sed" to delete everything else but email address.

db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com

Body:
The following will work no matter where the email address is in the line but only if there is one email address per line.  If there are more than one it's going to only show the last one in the line.  It also won't touch lines that don't have valid email addresses in them

sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/'

Input

$ cat dbdump
this line with no valid @ email address is untouched
::: a0$...aucvkDt86 ::: joesmith@gmail.com
::: a0$... foo@example.com db dump: someusername :::

Output

$  sed 's/^.* \([^@ ]\+@[^ ]\+\) \?.*$/\1/' ./dbdump
this line with no valid @ email address is untouched
joesmith@gmail.com
foo@example.com


问:
How can I read a "ctrl+q" input from user using opencv and Python?
I am using:-

```<code>key=cv2.waitKey(1) #& 0xFF
    if key== ord('q'):
        ....................
</code>```

but I need the input from user to be ctrl+q

Thanks

答:
@WalidAhmed, Ctrl+Anykey interprets as single key if you use cv::waitKeyEx(). In example,

std::cout << cv::waitKey() << std::endl;
std::cout << cv::waitKey() << std::endl;
```

<p>Gives <code>227, 113</code> (<code>Ctrl</code> code, <code>q</code> code) both in combo and if they pressed separately. But</p>

<pre class="lang-cpp prettyprint-override"><code>std::cout << cv::waitKeyEx() << std::endl;
std::cout << cv::waitKeyEx() << std::endl;
</code>```

produces 65507, 113 when keys pressed separately and 65507, 262257 in case of combination.

Sorry for C++ code, I hope you can simply reproduce it in Python. And please note that this approach is sensitive to language layout of your keyboard (i.e. mine is English-Russian and Q key has Й character in russian layout that gives 263882 code of Ctrl + Й combination). Also  I've tested it in Ubuntu. So codes might be different for the different operation systems.

Body:
I am using:-

key=cv2.waitKey(1) #& 0xFF
    if key== ord('q'):
        ....................

but I need the input from user to be ctrl+q

Thanks

Body:
@WalidAhmed, Ctrl+Anykey interprets as single key if you use cv::waitKeyEx(). In example,

std::cout << cv::waitKey() << std::endl;
std::cout << cv::waitKey() << std::endl;

Gives 227, 113 (Ctrl code, q code) both in combo and if they pressed separately. But

std::cout << cv::waitKeyEx() << std::endl;
std::cout << cv::waitKeyEx() << std::endl;

produces 65507, 113 when keys pressed separately and 65507, 262257 in case of combination.

Sorry for C++ code, I hope you can simply reproduce it in Python. And please note that this approach is sensitive to language layout of your keyboard (i.e. mine is English-Russian and Q key has Й character in russian layout that gives 263882 code of Ctrl + Й combination). Also  I've tested it in Ubuntu. So codes might be different for the different operation systems.


问:
How to get the user "Name" using Swift?
I'm trying to create an app that when the user open the first view it will provide with a nice greeting.

For example depending on the time of the day it would say "Good Morning/Afternoon/Night - User Name".

How do I get the name that the User has on his iPhone? I need the name that is on Settings > General > About _ NAME?

答:
```<code>let benutzerGeraeteName = UIDevice.current.name
        print("Hallo, \(benutzerGeraeteName)")
</code>```

Title: How to get the user "Name" using Swift?


问:
Do compilers usually emit vector (SIMD) instructions when not explicitly told to do so?
C++17 adds extensions for parallelism to the standard library (e.g. std::sort(std::execution::par_unseq, arr, arr + 1000), which will allow the sort to be done with multiple threads and with vector instructions).

I noticed that Microsoft's experimental implementation mentions that the VC++ compiler lacks support to do vectorization over here, which surprises me - I thought that modern C++ compilers are able to reason about the vectorizability of loops, but apparently the VC++ compiler/optimizer is unable to generate SIMD code even if explicitly told to do so.  The seeming lack of automatic vectorization support contradicts the answers for this 2011 question on Quora, which suggests that compilers will do vectorization where possible.

Maybe, compilers will only vectorize very obvious cases such as a std::array<int, 4>, and no more than that, thus C++17's explicit parallelization would be useful.

Hence my question: Do current compilers automatically vectorize my code when not explicitly told to do so?  (To make this question more concrete, let's narrow this down to Intel x86 CPUs with SIMD support, and the latest versions of GCC, Clang, MSVC, and ICC.)

As an extension: Do compilers for other languages do better automatic vectorization (maybe due to language design) (so that the C++ standards committee decides it necessary for explicit (C++17-style) vectorization)?

答:
The best compiler for automatically spotting SIMD style vectorisation (when told it can generate opcodes for the appropriate instruction sets of course) is the Intel compiler in my experience (which can generate code to do dynamic dispatch depending on the actual CPU if required), closely followed by GCC and Clang, and MSVC last (of your four).

This is perhaps unsurprising I realise - Intel do have a vested interest in helping developers exploit the latest features they've been adding to their offerings.

I'm working quite closely with Intel and while they are keen to demonstrate how their compiler can spot auto-vectorisation, they also very rightly point out using their compiler also allows you to use pragma simd constructs to further show the compiler assumptions that can or can't be made (that are unclear from a purely syntactic level), and hence allow the compiler to further vectorise the code without resorting to intrinsics.

This, I think, points at the issue with hoping that the compiler (for C++ or another language) will do all the vectorisation work... if you have simple vector processing loops (eg multiply all the elements in a vector by a scalar) then yes, you could  expect that 3 of the 4 compilers would spot that.

But for more complicated code, the vectorisation gains that can be had come not from simple loop unwinding and combining iterations, but from actually using a different or tweaked algorithm, and that's going to hard if not impossible for a compiler to do completely alone. Whereas if you understand how vectorisation might be applied to an algorithm, and you can structure your code to allow the compiler to see the opportunities do so, perhaps with pragma simd constructs or OpenMP, then you may get the results you want.

Vectorisation comes when the code has a certain mechanical sympathy for the underlying CPU and memory bus - if you have that then I think the Intel compiler will be your best bet. Without it, changing compilers may make little difference.

Can I recommend Matt Godbolt's Compiler Explorer as a way to actually test this - put your c++ code in there and look at what different compilers actually generate? Very handy... it doesn't include older version of MSVC (I think it currently supports VC++ 2017 and later versions) but will show you what different versions of ICC, GCC, Clang and others can do with code...


问:
Firebase 10.0.: InternalFirebaseAuth.FIREBASE_AUTH_API is not available on this device
I am developping an Android application using Firebase Authentication (using Google account) and I recently experience the following exception every time I try to connect:

com.google.firebase.FirebaseApiNotAvailableException: API:
  InternalFirebaseAuth.FIREBASE_AUTH_API is not available on this
  device.
  at com.google.firebase.zza.zzz(Unknown Source)
                                                                            at com.google.android.gms.internal.zzzq$zzd.zzy(Unknown Source)
                                                                            at com.google.android.gms.internal.zzaap$zza.zzC(Unknown Source)
                                                                            at
  com.google.android.gms.internal.zzaap$zza.onConnectionFailed(Unknown
  Source)
                                                                            at com.google.android.gms.internal.zzaap$zzb$1.run(Unknown Source)
                                                                            at android.os.Handler.handleCallback(Handler.java:730)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                            at android.os.Looper.loop(Looper.java:176)
                                                                            at android.os.HandlerThread.run(HandlerThread.java:61)

I'm quite surprised since the authentication worked very well until a few days ago...

I use firebase 10.0.1.

Do someone have ever experienced this error and resolved it?

答: Maybe your emulator doesn't have google play</p>


问:
IoException error when save button is selected
Beloew is my code which i want to save some info the user key in to be saved to the file, how come i keep encountering Ioexception error after i debug and click on the save button..pls kindly adv..thks!!! i guess it has something to do with the filefolder but have absolutely no idea..</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ASSISNMENTTT
{
    public partial class Registeration : Form
    {
        public Registeration()
        {
            InitializeComponent();
        }

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
    }
}
</code>```

答: Most likely you are on Win7 or Vista and have no access to the c:\ drive.</p>

Body:
Beloew is my code which i want to save some info the user key in to be saved to the file, how come i keep encountering Ioexception error after i debug and click on the save button..pls kindly adv..thks!!! i guess it has something to do with the filefolder but have absolutely no idea..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ASSISNMENTTT
{
    public partial class Registeration : Form
    {
        public Registeration()
        {
            InitializeComponent();
        }

        private void Btn_Save_Click(object sender, EventArgs e)
        {
            // This is the button labeled "Save" in the program.
            //
            File.WriteAllText("C:\\demo.txt", Tb_Admin.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Name.Text);
            File.WriteAllText("C:\\demo.txt", Tb_Gender.Text);
        }
    }
}