问:
password_verify using password_hash error to store user in session at login
I'm having a issue with password_hash, when i login i want to bring the user logged in Session, but do not work when i use password verify, the ECHO return nothing. How i can solve this? Thanks
This is my code:

```<code>    <?php
session_start();
include_once("../Backend/conexao_db.php");

if((isset($_POST['txt_usuario'])) && (isset($_POST['txt_senha']))) {
    $usuario = mysqli_real_escape_string($conn, $_POST['txt_usuario']);
    $pass = mysqli_real_escape_string($conn, $_POST['txt_senha']);
    $passwordhash = password_hash($pass, PASSWORD_DEFAULT);

    $result_usuario = "SELECT * FROM tbl_Usuario WHERE email = '$usuario' && senha = '$pass'";
    $resultado_usuario = mysqli_query($conn, $result_usuario);
    if ($resultado = mysqli_fetch_assoc($resultado_usuario)) {
        if (password_verify($pass, $passwordhash)) {

        $_SESSION['usuarioId'] = $resultado['id'];
        if ($_SESSION['empresaID'] == "") {
            echo $_SESSION['usuarioId'];

            } else {

            }

        }
    }
}
</code>```

This code work perfectly when i not use password_verify.

答:
What your'e doing there is useless, because you're testing the password hash you just created for matching with itself. This would always be true.

Without knowing your Session-Variables I would guess that if ($_SESSION['empresaID'] == "") is causing your error, unless you set it elsewhere.

But to improve your code:

You should store the hash in the database and test the result for a match with the inputted password.
Goal of this procedure is that you don't have to store the password in plaintext in your database.

Also, please use prepared statements to prevent SQL-injection. In my example I used PDO.

With prepared statements you can avoid mysqli_real_escape_string - it would change the password if there are any special characters in it.

```<code>if((!empty($_POST['txt_usuario'])) && (!empty($_POST['txt_senha']))) {
  $usuario = $_POST['txt_usuario'];
  $pass = $_POST['txt_senha'];

  // returns a connection to pdo
  $conn = Database::connectPDO();
  $stmt = $conn->prepare('SELECT * FROM tbl_Usuario WHERE email = :email');
  $stmt->bindParam(':email', $usuario);

  if($stmt->execute()) {
    while($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
      if(password_verify($pass, $user['senha'])) {
         echo 'success';
       }
     }
  }
}
</code>```

So, if you're adding an user, you should store the password hashed in the database for this function to work:

```<code>if((!empty($_POST['txt_usuario'])) && (!empty($_POST['txt_senha']))) {
  $usuario = $_POST['txt_usuario'];
  $pass = $_POST['txt_senha'];

  $hashedPassword = password_hash($pass, PASSWORD_DEFAULT);

  $conn = Database::connectPDO();
  $stmt = $conn->prepare('INSERT INTO tbl_Usuario (email, senha) VALUES (:email, : senha)');
  $stmt->bindParam(':email', $usuario);
  $stmt->bindParam(':senha', $hashedPassword);

  if($stmt->execute()) {
    echo 'successfully registered';
  }
}
</code>```

Body:
I'm having a issue with password_hash, when i login i want to bring the user logged in Session, but do not work when i use password verify, the ECHO return nothing. How i can solve this? Thanks
This is my code:

    <?php
session_start();
include_once("../Backend/conexao_db.php");

if((isset($_POST['txt_usuario'])) && (isset($_POST['txt_senha']))) {
    $usuario = mysqli_real_escape_string($conn, $_POST['txt_usuario']);
    $pass = mysqli_real_escape_string($conn, $_POST['txt_senha']);
    $passwordhash = password_hash($pass, PASSWORD_DEFAULT);

    $result_usuario = "SELECT * FROM tbl_Usuario WHERE email = '$usuario' && senha = '$pass'";
    $resultado_usuario = mysqli_query($conn, $result_usuario);
    if ($resultado = mysqli_fetch_assoc($resultado_usuario)) {
        if (password_verify($pass, $passwordhash)) {

        $_SESSION['usuarioId'] = $resultado['id'];
        if ($_SESSION['empresaID'] == "") {
            echo $_SESSION['usuarioId'];

            } else {

            }

        }
    }
}

This code work perfectly when i not use password_verify.

Body:
What your'e doing there is useless, because you're testing the password hash you just created for matching with itself. This would always be true.

Without knowing your Session-Variables I would guess that if ($_SESSION['empresaID'] == "") is causing your error, unless you set it elsewhere.

But to improve your code:

You should store the hash in the database and test the result for a match with the inputted password.
Goal of this procedure is that you don't have to store the password in plaintext in your database.

Also, please use prepared statements to prevent SQL-injection. In my example I used PDO.

With prepared statements you can avoid mysqli_real_escape_string - it would change the password if there are any special characters in it.

if((!empty($_POST['txt_usuario'])) && (!empty($_POST['txt_senha']))) {
  $usuario = $_POST['txt_usuario'];
  $pass = $_POST['txt_senha'];

  // returns a connection to pdo
  $conn = Database::connectPDO();
  $stmt = $conn->prepare('SELECT * FROM tbl_Usuario WHERE email = :email');
  $stmt->bindParam(':email', $usuario);

  if($stmt->execute()) {
    while($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
      if(password_verify($pass, $user['senha'])) {
         echo 'success';
       }
     }
  }
}

So, if you're adding an user, you should store the password hashed in the database for this function to work:

if((!empty($_POST['txt_usuario'])) && (!empty($_POST['txt_senha']))) {
  $usuario = $_POST['txt_usuario'];
  $pass = $_POST['txt_senha'];

  $hashedPassword = password_hash($pass, PASSWORD_DEFAULT);

  $conn = Database::connectPDO();
  $stmt = $conn->prepare('INSERT INTO tbl_Usuario (email, senha) VALUES (:email, : senha)');
  $stmt->bindParam(':email', $usuario);
  $stmt->bindParam(':senha', $hashedPassword);

  if($stmt->execute()) {
    echo 'successfully registered';
  }
}


来源: stackexchange

问:
How to finish an android application?
I need to finish an android application. For that i wrote

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}
</code>```

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

答:
Please read first this post from Google Android Developer Advocate Reto Meier :
When to Include an Exit Button in Android Apps (Hint: Never)

What is th symptom that make you want to add an exit button ? If you need to clear the activity stack and always restart with a specific Activity, maybe you just have to tweak your activity manifest declaration with attributes like : android:clearTaskOnLaunch

ContentLicense: CC BY-SA 3.0

Title: How to finish an android application?

Body:
I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

ContentLicense: CC BY-SA 2.5


问:
Checkbox in MVC 5 ASP.net
I made a "Availability" option in my database, this is set as a "bit". When I made a controller on my generated model, it came out as a dropdownlist with 2 values: true and false. I don't want this to be a dropdown list but a checkbox. I've googled all around and couldnt find an easy fix for this. Any of you have an idea how to do this? My code looks like this:</p>

```<code><div class="form-group">
        @Html.LabelFor(model => model.Beschikbaar, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="checkbox">
                @Html.EditorFor(model => model.Beschikbaar)
                @Html.ValidationMessageFor(model => model.Beschikbaar, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
</code>```

答:
```<code><div class="form-group">
   @Html.LabelFor(model => model.Beschikbaar, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
        <div class="checkbox">
           @Html.CheckBoxFor(model => model.Beschikbaar)
           @Html.ValidationMessageFor(model => model.Beschikbaar, "", new { @class = "text-danger" })
         </div>
     </div>
</div>
</code>```

Title: Checkbox in MVC 5 ASP.net

Body:
I made a "Availability" option in my database, this is set as a "bit". When I made a controller on my generated model, it came out as a dropdownlist with 2 values: true and false. I don't want this to be a dropdown list but a checkbox. I've googled all around and couldnt find an easy fix for this. Any of you have an idea how to do this? My code looks like this:

        @Html.LabelFor(model => model.Beschikbaar, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Beschikbaar)
                @Html.ValidationMessageFor(model => model.Beschikbaar, "", new { @class = "text-danger" })


问:
jQuery image error handling for media queries
I have images loaded depending on screen size using media queries. I would like to handle the error if any using jQuery. A text message will show when the image failed.

My code so far:

```<code><div class="container">
<div class="row">
    <div class="col-xs-12">
        <img class="img-responsive center-block" id="notice_banner" alt="" src="css/images/banner.png"/>
    </div>
    <div class="col-xs-12">
        <p id="altText" style="display: none">
            This is a text!
        </p>
    </div>
</div>
</code>```

CSS code:

```<code>/* xs */
img {
content:url("images/small_banner.png");
}
/* md */
@media (min-width: 768px) {
img {
    content:url("images/large_banner.png");
}
}
</code>```

javascript code:

```<code>$(document).ready(function() {
$("img").on("error", function() {
    $("#altText").show();
});
});
</code>```

The problem now is that it can detect the error from the original src attribute, but not when the images are coming from media queries.

Anyone has any idea how to solve this?

答:
As I mentioned in a comment, content is not fully supported outside of the pseudo-elements :before and :after (as far as I know, only Chrome supports it for any element). And on top of that, there's another problem with doing things this way: CSS errors do not trigger JS events, so if an image linked in CSS fails, JS will not detect it.

One solution would be to listen to the resize event, and if the window size goes through a threshold used in a media query, perform one action or another (e.g. change the src of the image). In this case, as the change happened within JS, you would be able to read it.

For example, something like this:

$(document).ready(function() {

  $("img").on("error", function() {
    $("#altText").show();
  });

  function resizeActions() {
    var windowWidth = $(window).width();
    if (windowWidth < 768) {
      $("#notice_banner").attr("src", "//placehold.it/100x100");
    } else if (windowWidth >= 768) {
      $("#notice_banner").attr("src", "fake-url-path");
    } // else if ...

  };

  // execute on load and on window resize
  $(window).resize(resizeActions);
  resizeActions();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <img class="img-responsive center-block" id="notice_banner" alt="" src="//placehold.it/200x200" />
    </div>
    <div class="col-xs-12">
      <p id="altText" style="display: none">
        This is a text!
      </p>
    </div>
  </div></code>```

Body:
I have images loaded depending on screen size using media queries. I would like to handle the error if any using jQuery. A text message will show when the image failed.

My code so far:

            This is a text!

CSS code:

/* xs */
img {
content:url("images/small_banner.png");
}
/* md */
@media (min-width: 768px) {
img {
    content:url("images/large_banner.png");
}
}

javascript code:

$(document).ready(function() {
$("img").on("error", function() {
    $("#altText").show();
});
});

The problem now is that it can detect the error from the original src attribute, but not when the images are coming from media queries.

Anyone has any idea how to solve this?

Body:
As I mentioned in a comment, content is not fully supported outside of the pseudo-elements :before and :after (as far as I know, only Chrome supports it for any element). And on top of that, there's another problem with doing things this way: CSS errors do not trigger JS events, so if an image linked in CSS fails, JS will not detect it.

One solution would be to listen to the resize event, and if the window size goes through a threshold used in a media query, perform one action or another (e.g. change the src of the image). In this case, as the change happened within JS, you would be able to read it.

For example, something like this:

$(document).ready(function() {

  $("img").on("error", function() {
    $("#altText").show();
  });

  function resizeActions() {
    var windowWidth = $(window).width();
    if (windowWidth < 768) {
      $("#notice_banner").attr("src", "//placehold.it/100x100");
    } else if (windowWidth >= 768) {
      $("#notice_banner").attr("src", "fake-url-path");
    } // else if ...

  };

  // execute on load and on window resize
  $(window).resize(resizeActions);
  resizeActions();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <img class="img-responsive center-block" id="notice_banner" alt="" src="//placehold.it/200x200" />
    </div>
    <div class="col-xs-12">
      <p id="altText" style="display: none">
        This is a text!
      </p>
    </div>
  </div>


问:
tanf() function returns wrong value in iOS
I got a problem, but can't find the error. I'm trying to calculate the tangent of an angle. I tried both in radians and in degree, i got wrong answer. My code:

```<code>CGFloat tiltAngleDegrees = tiltAngle * 180.0f / M_PI - 90.0f; // in degrees
NSLog(@"Tan Angle: %f", tanf(tiltAngleDegrees));
</code>```

I tried for Angle:-6.027872

I got answer: 0.261010

Answer that i calculated on calculator: -0.105596

I thought it was going to be a simple task, but i hit a wall - can't find what's going wrong. I hope some of you can point me in the right direction.

Thanks.

答:
tanf requires radians.

Simply do:

```<code>float tangent = tanf(-6.027872);
</code>```

The result will be 0.261009.

This is the correct result.

A result of -0.105596 for -6.027872 means that you entered -6.027872 as degrees in your calculator. Put your calculator in radians mode and then you will see the correct result of 0.261009 just as you do with this tanf function.

Body:
I got a problem, but can't find the error. I'm trying to calculate the tangent of an angle. I tried both in radians and in degree, i got wrong answer. My code:

CGFloat tiltAngleDegrees = tiltAngle * 180.0f / M_PI - 90.0f; // in degrees
NSLog(@"Tan Angle: %f", tanf(tiltAngleDegrees));

I tried for Angle:-6.027872

I got answer: 0.261010

Answer that i calculated on calculator: -0.105596

I thought it was going to be a simple task, but i hit a wall - can't find what's going wrong. I hope some of you can point me in the right direction.

Thanks.

Body:
tanf requires radians.

Simply do:

float tangent = tanf(-6.027872);

The result will be 0.261009.

This is the correct result.

A result of -0.105596 for -6.027872 means that you entered -6.027872 as degrees in your calculator. Put your calculator in radians mode and then you will see the correct result of 0.261009 just as you do with this tanf function.


问:
storing data on iOS device using react native
I am new to React Native and trying to create a simple iOS app. The app has a button on clicking which I need to store the timestamp of the click on the device in a file.

I know that React Native has an API called AsyncStorage but I am getting errors while using this. I copied the code from some site on the net.

Can someone please guide me to use this API?

This is my entire code:

```<code>import React, {Component} from 'react';
import { StyleSheet, Text, View, TextInput, AsyncStorage } from 'react-native';

export default class App extends Component{
  state = {
    'name': ''

}

  componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({'name': value}))

  setName = (value) => {
    AsyncStorage.setItem('name': value);
    this.setState({'name': value});
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput style = {styles.textInput} autoCapitalize = 'none'
               onChangeText = {this.setName}/>
        <Text>
          {this.state.name}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
   },
   textInput: {
      margin: 15,
      height: 35,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
});
</code>```

As for the error, when I launch the code on iOS, I am getting a red screen. There is no syntax error that I can see.

Thanks in advance.

答:
Hard to say without more detail the exact problem you're facing, but I assume some of the following might help you?

Ah I see you posted some code. You will need a constructor that defines your state as well. Added it in my code below.

Please note I'm not an expert. Forgive any errors

```<code>import {
  AsyncStorage,
} from 'react-native';

class myComponent extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  componentDidMount() {
    this._loadInitialState().done();
  }

  _someFunction() {
    var myData = 123;
    saveItemLocally('data', myData);
  }

  async _loadInitialState() {
    try {
      // get localy stored data
      var dataStored = await AsyncStorage.getItem('data');
      if (dataStored!==null) {
        this.setState({
          data: dataStored
        });
      }
    } catch (error) {
      //didn't get locally stored data
      console.log(error.message);
    }
  } // end _loadinitialstate

  render () {
    //your render function
    return (
    );
  }
} // end of your component

async function saveItemLocally(item, value) {
  try {
    await AsyncStorage.setItem(item, value);
  } catch (error) {
    console.log('AsyncStorage error: ' + error.message);
  }
}
</code>```

Body:
I am new to React Native and trying to create a simple iOS app. The app has a button on clicking which I need to store the timestamp of the click on the device in a file.

I know that React Native has an API called AsyncStorage but I am getting errors while using this. I copied the code from some site on the net.

Can someone please guide me to use this API?

This is my entire code:

import React, {Component} from 'react';
import { StyleSheet, Text, View, TextInput, AsyncStorage } from 'react-native';

export default class App extends Component{
  state = {
    'name': ''

}

  componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({'name': value}))

  setName = (value) => {
    AsyncStorage.setItem('name': value);
    this.setState({'name': value});
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput style = {styles.textInput} autoCapitalize = 'none'
               onChangeText = {this.setName}/>
        <Text>
          {this.state.name}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
   },
   textInput: {
      margin: 15,
      height: 35,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
});

As for the error, when I launch the code on iOS, I am getting a red screen. There is no syntax error that I can see.

Thanks in advance.

Body:
Hard to say without more detail the exact problem you're facing, but I assume some of the following might help you?

Ah I see you posted some code. You will need a constructor that defines your state as well. Added it in my code below.

Please note I'm not an expert. Forgive any errors

import {
  AsyncStorage,
} from 'react-native';

class myComponent extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  componentDidMount() {
    this._loadInitialState().done();
  }

  _someFunction() {
    var myData = 123;
    saveItemLocally('data', myData);
  }

  async _loadInitialState() {
    try {
      // get localy stored data
      var dataStored = await AsyncStorage.getItem('data');
      if (dataStored!==null) {
        this.setState({
          data: dataStored
        });
      }
    } catch (error) {
      //didn't get locally stored data
      console.log(error.message);
    }
  } // end _loadinitialstate

  render () {
    //your render function
    return (
    );
  }
} // end of your component

async function saveItemLocally(item, value) {
  try {
    await AsyncStorage.setItem(item, value);
  } catch (error) {
    console.log('AsyncStorage error: ' + error.message);
  }
}


问:
make a session user have a automatic code input
when a user logs in, I want a input type text to be already filled with some pre-determined letter...

how can I make that possible?

答:
You can do it in two ways:-

You can give control from the Admin area, so that the Administrator has the full control. This can be possible by providing a list drop down with all the recommended alphabets, in the Settings section of your Admin area, and let the Admin choose her preferred alphabet & store it in the database. Then you can retrieve it from the database & show it in the front-end when any user logs in.

When the user logs in, you can generate a random letter, using the PHP function "rand()".

One simple code snippet for the second solution will be:-

```<code><?php
// This function considers both the cases for each of the letters.
function randLetter() {
    $int = rand(0, 51);
    $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $rand_letter = $a_z[$int];
    return $rand_letter;
}

/**
 * This function considers only one specific cases for each of the letters.
 */
function randSpecificCaseLetter($lower_case = TRUE) {
    if ($lower_case) {
        $letter = chr(rand(97, 122));
    }
    else {
        $letter = chr(rand(65, 90));
    }

    return $letter;
}
?>
</code>```

Hope it helps.

Body:
You can do it in two ways:-

You can give control from the Admin area, so that the Administrator has the full control. This can be possible by providing a list drop down with all the recommended alphabets, in the Settings section of your Admin area, and let the Admin choose her preferred alphabet & store it in the database. Then you can retrieve it from the database & show it in the front-end when any user logs in.

When the user logs in, you can generate a random letter, using the PHP function "rand()".

One simple code snippet for the second solution will be:-

<?php
// This function considers both the cases for each of the letters.
function randLetter() {
    $int = rand(0, 51);
    $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $rand_letter = $a_z[$int];
    return $rand_letter;
}

/**
 * This function considers only one specific cases for each of the letters.
 */
function randSpecificCaseLetter($lower_case = TRUE) {
    if ($lower_case) {
        $letter = chr(rand(97, 122));
    }
    else {
        $letter = chr(rand(65, 90));
    }

    return $letter;
}
?>

Hope it helps.


问:
Printing IP address of Nic card to bash using script
currently I am working on a school assignment on Linux using Vim where I have to write a script that displays the user that is currently logged in, the time and date, and list only the IP address of the Nic card. I have everything working except for the IP address part. If anyone could help I would appreciate it greatly.

Edit to include the code I have at the moment.

```<code>#!/bin/bash
Time=$(date)
IP=$(ifconfig ens33)
echo "The following user is currently logged in $USER"
echo ""
echo "The current time is $Time"
echo ""
echo "The IP information is $IP"
</code>```

答:
You can filter the result of ifconfig using awk like this (IPv4):

```<code>$ ifconfig ens33 | awk '/inet addr/{print substr($2, 6)}'
</code>```

Result:

10.10.xx.xx

inet addr: represents IPv4 address.

inet6 addr: represents IPv6 address.

Body:
currently I am working on a school assignment on Linux using Vim where I have to write a script that displays the user that is currently logged in, the time and date, and list only the IP address of the Nic card. I have everything working except for the IP address part. If anyone could help I would appreciate it greatly.

Edit to include the code I have at the moment.

#!/bin/bash
Time=$(date)
IP=$(ifconfig ens33)
echo "The following user is currently logged in $USER"
echo ""
echo "The current time is $Time"
echo ""
echo "The IP information is $IP"

Body:
You can filter the result of ifconfig using awk like this (IPv4):

$ ifconfig ens33 | awk '/inet addr/{print substr($2, 6)}'

Result:

10.10.xx.xx

inet addr: represents IPv4 address.

inet6 addr: represents IPv6 address.


问:
.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList
when I share my app to other one then my app crash but when I run my app direct fron studio then app run properly but I have seen all solution but nothing works for me.

java.lang.RuntimeException: Unable to get provider
  com.google.firebase.provider.FirebaseInitProvider:
  java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.amit.workoutdocent-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.amit.workoutdocent-1/lib/arm,
  /vendor/lib, /system/lib]]
                                                                                at
  android.app.ActivityThread.installProvider(ActivityThread.java:6948)
                                                                                at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:6540)
                                                                                at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:6480)
                                                                                at android.app.ActivityThread.access$1800(ActivityThread.java:230)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1888)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
                                                                                Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.firebase.provider.FirebaseInitProvider" on path:
  DexPathList[[zip file
  "/data/app/com.example.amit.workoutdocent-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.amit.workoutdocent-1/lib/arm,
  /vendor/lib, /system/lib]]
                                                                                at
  dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                                                at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                                                at
  android.app.ActivityThread.installProvider(ActivityThread.java:6933)
                                                                                at
  android.app.ActivityThread.installContentProviders(ActivityThread.java:6540)
                                                                                at
  android.app.ActivityThread.handleBindApplication(ActivityThread.java:6480)
                                                                                at android.app.ActivityThread.access$1800(ActivityThread.java:230)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1888)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:7409)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

答:
if your minSdkVersion is set to 20 or lower, then you have to use the multidex support library as:

module-level.gradle ---

```<code>android {
defaultConfig {
    ...
    minSdkVersion 15
    targetSdkVersion 26
    multiDexEnabled true
}
...
}

dependencies {
 compile 'com.android.support:multidex:1.0.1'
}
</code>```

and in your Application class

```<code>public class MyApplication extends SomeOtherApplication {
@Override
protected void attachBaseContext(Context base) {
 super.attachBaseContext(base);
 MultiDex.install(this);
}
}
</code>```

Body:
if your minSdkVersion is set to 20 or lower, then you have to use the multidex support library as:

module-level.gradle ---

android {
defaultConfig {
    ...
    minSdkVersion 15
    targetSdkVersion 26
    multiDexEnabled true
}
...
}

dependencies {
 compile 'com.android.support:multidex:1.0.1'
}

and in your Application class

public class MyApplication extends SomeOtherApplication {
@Override
protected void attachBaseContext(Context base) {
 super.attachBaseContext(base);
 MultiDex.install(this);
}
}


问:
Install Ruby Using RVM on Virtual Machine Running Debian Failed Silently
I've successfully installed a Debian guest operating system on a Vista host using VirtualBox. I'm trying to follow this tutorial(http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you) to install RVM and Ruby. It appears to install ruby successfully, but the terminal will not recognise ruby at all.

Here is the terminal output:

```<code>user@debian:~$ rvm install 1.9.2
/home/user/.rvm/rubies/ruby-1.9.2-p136, this may take a while depending on your cpu(s)...

ruby-1.9.2-p136 - #fetching
ruby-1.9.2-p136 - #downloading ruby-1.9.2-p136, this may take a while depending on your connection...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100 8612k  100 8612k    0     0   200k      0  0:00:42  0:00:42 --:--:--  328k
ruby-1.9.2-p136 - #extracting ruby-1.9.2-p136 to /home/user/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #extracted to /home/user/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #configuring
ruby-1.9.2-p136 - #compiling
ruby-1.9.2-p136 - #installing
ruby-1.9.2-p136 - updating #rubygems for /home/user/.rvm/gems/ruby-1.9.2-p136@global
ruby-1.9.2-p136 - updating #rubygems for /home/user/.rvm/gems/ruby-1.9.2-p136
ruby-1.9.2-p136 - adjusting #shebangs for (gem).
ruby-1.9.2-p136 - #importing default gemsets (/home/user/.rvm/gemsets/)
Install of ruby-1.9.2-p136 - #complete
user@debian:~$ ruby -v
bash: ruby: command not found
</code>```

I have no idea what went wrong or how to proceed here. I'd appreciate any insight anyone could offer.

Thanks

答: If you want to make this stick between shell sessions: rvm use --default 1.9.2

Body:
I've successfully installed a Debian guest operating system on a Vista host using VirtualBox. I'm trying to follow this tutorial(http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you) to install RVM and Ruby. It appears to install ruby successfully, but the terminal will not recognise ruby at all.

Here is the terminal output:

user@debian:~$ rvm install 1.9.2
/home/user/.rvm/rubies/ruby-1.9.2-p136, this may take a while depending on your cpu(s)...

ruby-1.9.2-p136 - #fetching
ruby-1.9.2-p136 - #downloading ruby-1.9.2-p136, this may take a while depending on your connection...
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100 8612k  100 8612k    0     0   200k      0  0:00:42  0:00:42 --:--:--  328k
ruby-1.9.2-p136 - #extracting ruby-1.9.2-p136 to /home/user/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #extracted to /home/user/.rvm/src/ruby-1.9.2-p136
ruby-1.9.2-p136 - #configuring
ruby-1.9.2-p136 - #compiling
ruby-1.9.2-p136 - #installing
ruby-1.9.2-p136 - updating #rubygems for /home/user/.rvm/gems/ruby-1.9.2-p136@global
ruby-1.9.2-p136 - updating #rubygems for /home/user/.rvm/gems/ruby-1.9.2-p136
ruby-1.9.2-p136 - adjusting #shebangs for (gem).
ruby-1.9.2-p136 - #importing default gemsets (/home/user/.rvm/gemsets/)
Install of ruby-1.9.2-p136 - #complete
user@debian:~$ ruby -v
bash: ruby: command not found

I have no idea what went wrong or how to proceed here. I'd appreciate any insight anyone could offer.

Thanks


问:
Date.getTime() in Java returning different time in different server
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

```<code>public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}
</code>```

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!

答:
You get these different values, because the time difference between your server in the US and the one in India is 9h 30.

This has nothing to do with floating points, but with time zones.

One way to solve this problem is to work always within the same time zone (e.g. India)

Body:
I need to calculate a value that is based on dates. So I'm parsing the date first using date format class and then i'm using getTime() to get milliseconds. With those milliseconds i'll calculate some value. But getTime() is returning different values in different servers. We develop here in India, where i'm getting correct value but in US server i'm getting different value.

Scenario:

public class Test {

    public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String now = "11/03/2018";

        Date UsualDateformat = sdf.parse(now);

        System.out.println(UsualDateformat.getTime());
    }
}

Above is a sample code, but my actual code is a rule in a drl file (drools).
This program returns
"1541183400000" which i convert to date is "Sat 3 November 2018 00:00:00".,
but in US server im getting "1541217600000" equal to date "Sat 3 November 2018 09:30:00".
So when i use this value i'm getting marginal decimal point formatting issue.
How to resolve this issue?

Thanks in advance!


问:
Speed up Image Feature Extraction
It's the program of import multiple images and extract feature.
The problem is that it's too slow
I think it's because there's so many for loop.

For example

```<code>for q in range(0, height-32 , 32):
  for w in range(0 , width-32 ,32):
   for j in range(0,64,8):
       for n in range(0,64,8):
</code>```

How can I change my code to speed up?

```<code>import numpy as np
from scipy.fftpack import dct
from PIL import Image
import glob
import matplotlib.pyplot as plt

def image_open(path):
    image_list = []
    #for filename in glob.glob('path/*.jpg'):
    for filename in glob.glob(path+'/*.jpg'):
     im=Image.open(filename)
     image_list.append(im)

    return image_list

path = 'C:\\Users\\LG\\PycharmProjects\\photo'

images = image_open(path)

for i in range(0, len(images)):
 box3 = (0,0,256,256)
 a = images[i].crop(box3)

 (y,cb,cr) = a.split()
 width , height = y.size
 y.show()

 for q in range(0, height-32 , 32):
  for w in range(0 , width-32 ,32):

     for j in range(0,64,8):
       for n in range(0,64,8):

     print(w/32)
</code>```

答:
Not sure why you are using so many loops so I’d suggest you try to improve that as best as you can first.

After that, look into threads. Threading

If the number of images being consumed is low, you could run the operation on each image on a separate thread.

Title: Speed up Image Feature Extraction

Body:
It's the program of import multiple images and extract feature.
The problem is that it's too slow
I think it's because there's so many for loop.

For example

for q in range(0, height-32 , 32):
  for w in range(0 , width-32 ,32):
   for j in range(0,64,8):
       for n in range(0,64,8):

How can I change my code to speed up?

import numpy as np
from scipy.fftpack import dct
from PIL import Image
import glob
import matplotlib.pyplot as plt

def image_open(path):
    image_list = []
    #for filename in glob.glob('path/*.jpg'):
    for filename in glob.glob(path+'/*.jpg'):
     im=Image.open(filename)
     image_list.append(im)

    return image_list

path = 'C:\\Users\\LG\\PycharmProjects\\photo'

images = image_open(path)

for i in range(0, len(images)):
 box3 = (0,0,256,256)
 a = images[i].crop(box3)

 (y,cb,cr) = a.split()
 width , height = y.size
 y.show()

 for q in range(0, height-32 , 32):
  for w in range(0 , width-32 ,32):

     for j in range(0,64,8):
       for n in range(0,64,8):

     print(w/32)


问:
jQuery can't catch the parent element
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

```<code><button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">\
            <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
    </img>\
 </button>\
</code>```

and here is my jquery code that access the span element

```<code>$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });
</code>```

How can i do this right.

答:
I have closed the image and made the span as sibling of parent;

In this code snippet I have provided both jquery approach and pure js approach. Hope this helps.

//jquery approach
console.log($(".postID").siblings('.test').attr("src"));

//pure js
console.log(document.getElementsByClassName("postID")[0].previousElementSibling.getAttribute('src'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
<img class="test" src="http://cdn3-www.dogtime.com/assets/uploads/gallery/goldador-dog-breed-pictures/puppy-1.jpg"/>
  <span class="postID" id=' + idPost + '>' + likesPost + '</span>
 </button></code>```

Title: jQuery can't catch the parent element

Body:
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

<button type="button" class="buttonLike">\
    \
            ' + likesPost + '\
    \
 </button>\

and here is my jquery code that access the span element

$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });

How can i do this right.

Body:
I have closed the image and made the span as sibling of parent;

In this code snippet I have provided both jquery approach and pure js approach. Hope this helps.

//jquery approach
console.log($(".postID").siblings('.test').attr("src"));

//pure js
console.log(document.getElementsByClassName("postID")[0].previousElementSibling.getAttribute('src'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
<img class="test" src="http://cdn3-www.dogtime.com/assets/uploads/gallery/goldador-dog-breed-pictures/puppy-1.jpg"/>
  <span class="postID" id=' + idPost + '>' + likesPost + '</span>
 </button>


问:
Selectively copy [non-blank cells only] in random column order from one sheet to another
I have a specific need to copy cells from one sheet to another sheet whereby not the entire row is copied. Only data in specific columns in the one sheet needs to be copied to specific columns in the other sheet. Copying does not happen row by row but cell by cell and not in the same order as presented in either sheet . E.g. Copy ROW "A" in Sheet 1 to ROW "D" in Sheet 2.

The code I have here works great except I would like to ONLY copy cells in rows WITH DATA and SKIP the rows with BLANK cells. I would like some help adding a line of code that precedes the copy-functions ("D" to "X", "O" to "Z", etc.) to skip the rows with blank cells.

```<code>Sub Test()

Dim i As Long
Dim ii As Long
Dim i3 As Long
Dim LastRow As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set wb = ThisWorkbook
Set sht1 = wb.Sheets("DataValues")
Set sht2 = wb.Sheets("BEN")

Sheets("BEN").Select
Range("C192:P220").ClearContents

'Find the last row (in column X) with data in sheet ("DATAValues"). (LIMIT data to COLUMN Z)
LastRow = sht1.Range("Z9:Z37").Find("*", SearchDirection:=xlPrevious).Row

'Start copying data values in "BEN" starting at ROW "192" (due to other data located above)
ii = 192

'This is the beginning of the loop !!!
'Start at row 9 in DATAVALUES to last row with data

For i = 9 To LastRow

    'First activity
    'This is a MUST HAVE for my application

    sht2.Range("D" & ii) = sht1.Range("X" & i).Value
    sht2.Range("O" & ii) = sht1.Range("Z" & i).Value
    sht2.Range("K" & ii) = sht1.Range("AB" & i).Value
    sht2.Range("M" & ii) = sht1.Range("AD" & i).Value

    ii = ii + 1

Next i

End Sub
</code>```

答:
Add the following test to skip empty cells (and those resulting in 0 or "")

```<code>If Not IsEmpty(sht1.Range("Z" & i)) And sht1.Range("Z" & i) <> 0  And sht1.Range("Z" & i) <> vbNullString
</code>```

See below

```<code>Option Explicit

Sub Test()

    Dim i As Long
    Dim ii As Long
    Dim i3 As Long
    Dim LastRow As Long
    Dim wb As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet

    Set wb = ThisWorkbook
    Set sht1 = wb.Sheets("DataValues")
    Set sht2 = wb.Sheets("BEN")

    With Sheets("BEN")

        .Range("C192:P220").ClearContents

        'Find the last row (in column X) with data in sheet ("DATAValues"). (LIMIT data to COLUMN Z)
        LastRow = sht1.Range("Z9:Z37").Find("*", SearchDirection:=xlPrevious).Row
        'Start copying data values in "BEN" starting at ROW "192" (due to other data located above)
        ii = 192

        'This is the beginning of the loop !!!
        'Start at row 9 in DATAVALUES to last row with data

        For i = 9 To LastRow

            'First activity
            'This is a MUST HAVE for my application
            If Not IsEmpty(sht1.Range("Z" & i)) And _
               sht1.Range("Z" & i) <> 0 And _
               sht1.Range("Z" & i) <> vbNullString Then

                sht2.Range("D" & ii) = sht1.Range("X" & i).Value
                sht2.Range("O" & ii) = sht1.Range("Z" & i).Value
                sht2.Range("K" & ii) = sht1.Range("AB" & i).Value
                sht2.Range("M" & ii) = sht1.Range("AD" & i).Value

            ii = ii + 1

            End If

        Next i

    End With

End Sub
</code>```

Body:
I have a specific need to copy cells from one sheet to another sheet whereby not the entire row is copied. Only data in specific columns in the one sheet needs to be copied to specific columns in the other sheet. Copying does not happen row by row but cell by cell and not in the same order as presented in either sheet . E.g. Copy ROW "A" in Sheet 1 to ROW "D" in Sheet 2.

The code I have here works great except I would like to ONLY copy cells in rows WITH DATA and SKIP the rows with BLANK cells. I would like some help adding a line of code that precedes the copy-functions ("D" to "X", "O" to "Z", etc.) to skip the rows with blank cells.

Sub Test()

Dim i As Long
Dim ii As Long
Dim i3 As Long
Dim LastRow As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet

Set wb = ThisWorkbook
Set sht1 = wb.Sheets("DataValues")
Set sht2 = wb.Sheets("BEN")

Sheets("BEN").Select
Range("C192:P220").ClearContents

'Find the last row (in column X) with data in sheet ("DATAValues"). (LIMIT data to COLUMN Z)
LastRow = sht1.Range("Z9:Z37").Find("*", SearchDirection:=xlPrevious).Row

'Start copying data values in "BEN" starting at ROW "192" (due to other data located above)
ii = 192

'This is the beginning of the loop !!!
'Start at row 9 in DATAVALUES to last row with data

For i = 9 To LastRow

    'First activity
    'This is a MUST HAVE for my application

    sht2.Range("D" & ii) = sht1.Range("X" & i).Value
    sht2.Range("O" & ii) = sht1.Range("Z" & i).Value
    sht2.Range("K" & ii) = sht1.Range("AB" & i).Value
    sht2.Range("M" & ii) = sht1.Range("AD" & i).Value

    ii = ii + 1

Next i

End Sub

Body:
Add the following test to skip empty cells (and those resulting in 0 or "")

If Not IsEmpty(sht1.Range("Z" & i)) And sht1.Range("Z" & i) <> 0  And sht1.Range("Z" & i) <> vbNullString

See below

Option Explicit

Sub Test()

    Dim i As Long
    Dim ii As Long
    Dim i3 As Long
    Dim LastRow As Long
    Dim wb As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet

    Set wb = ThisWorkbook
    Set sht1 = wb.Sheets("DataValues")
    Set sht2 = wb.Sheets("BEN")

    With Sheets("BEN")

        .Range("C192:P220").ClearContents

        'Find the last row (in column X) with data in sheet ("DATAValues"). (LIMIT data to COLUMN Z)
        LastRow = sht1.Range("Z9:Z37").Find("*", SearchDirection:=xlPrevious).Row
        'Start copying data values in "BEN" starting at ROW "192" (due to other data located above)
        ii = 192

        'This is the beginning of the loop !!!
        'Start at row 9 in DATAVALUES to last row with data

        For i = 9 To LastRow

            'First activity
            'This is a MUST HAVE for my application
            If Not IsEmpty(sht1.Range("Z" & i)) And _
               sht1.Range("Z" & i) <> 0 And _
               sht1.Range("Z" & i) <> vbNullString Then

                sht2.Range("D" & ii) = sht1.Range("X" & i).Value
                sht2.Range("O" & ii) = sht1.Range("Z" & i).Value
                sht2.Range("K" & ii) = sht1.Range("AB" & i).Value
                sht2.Range("M" & ii) = sht1.Range("AD" & i).Value

            ii = ii + 1

            End If

        Next i

    End With

End Sub


问:
Can you avoid unboxing in a memoizing generic method?
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

```<code>public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

答:
I'm willing to bet (OK, I also have the advantage of having the source code...) that in most cases this code is called as per you your examples in your reply

```<code>Get("Site.Twitter.AccountName", "")
</code>```

or

```<code>Get("Site.Twitter.AccountName", 77)
</code>```

In which case you are using generic type inference. But there is another, simpler, thing that would compile there... don't use generics. I expect there are only a few scenarios here; so write a few classes / method-overloads - one for string, one for int, etc.

```<code>string Get(string key, string defaultValue) {...}
int Get(string key, int defaultValue) {...}
bool Get(string key, bool defaultValue) {...}
</code>```

Sure, there will be a little duplication, but the compiler will be able to optimise for each individual scenario - no boxing. You could even (if you choose) replace the Convert.ChangeType with something like int.Parse (for the T = int case).

Another option (given your examples) is to make the memoized object generic:

```<code>public MySpecialValue<T> {
    T val;
    bool valSet = false;

    T GetValue() {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return val;
     }

     public string DatabaseValue { get; set; }
}
</code>```

and push the <T> code up a level, so that is done in a cast.

Body:
I have a generic method I use to memoize conversions of string values in the db to an actual converted value.

public MySpecialValue {
    object val;
    bool valSet = false;

    T GetValue<T> () {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return (T)val;
     }

     public string DatabaseValue { get; set; }
}

The trouble is that during initialization I do not know what type the data in the database is, its only on first call that I can make this decision.

Is there any way to structure it in such a way that it is not forced to unbox value types that are cached? (without changing the signature of the containing class)

Body:
I'm willing to bet (OK, I also have the advantage of having the source code...) that in most cases this code is called as per you your examples in your reply

Get("Site.Twitter.AccountName", "")

or

Get("Site.Twitter.AccountName", 77)

In which case you are using generic type inference. But there is another, simpler, thing that would compile there... don't use generics. I expect there are only a few scenarios here; so write a few classes / method-overloads - one for string, one for int, etc.

string Get(string key, string defaultValue) {...}
int Get(string key, int defaultValue) {...}
bool Get(string key, bool defaultValue) {...}

Sure, there will be a little duplication, but the compiler will be able to optimise for each individual scenario - no boxing. You could even (if you choose) replace the Convert.ChangeType with something like int.Parse (for the T = int case).

Another option (given your examples) is to make the memoized object generic:

public MySpecialValue<T> {
    T val;
    bool valSet = false;

    T GetValue() {
         if (!valSet)
         {
                val = (T)Convert.ChangeType(DatabaseValue, typeof(T));
                valSet = true;
         }
         return val;
     }

     public string DatabaseValue { get; set; }
}

and push the <T> code up a level, so that is done in a cast.


问:
Occasionally not getting output from processes running in parallel
I'm trying to get the output from several process that are running in parallel. As soon as each process is done I want to print its output to the console. Unfortunatelly none of the popular approaches work.

Using the TaskCompletionSource

With TaskCompletionSource the output can arrive asynchronously when the Exited event is called but it's often missing because the execution does not wait for the buffers to flush. Adding a Task.Delay for a few (hundred) milliseconds doesn't seem right and also does not always work.

Using WaitForExit

The isssue with WaitForExit is that it indeed works in parallel but it waits for all processes to finish. Only then you can print their results so you don't see any progress until they all exited.

In order to demonstrate it I created a demo application. It calls a misspelled ipconfig. If you run it a few times in LINQPad you'll see at some point that this line will kick-in informing you that there was no output.

```<code>if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
</code>```

Here's the test application reproducing the issue. It's intentional that ipconfig is mispelled to provoke the Output problem.

```<code>void Main()
{
    var testCount = 30;

    var tasks = Enumerable.Range(0, testCount).Select(i => Task.Run(() => RunTestProcess()));

    Task.WaitAll(tasks.ToArray());

    Console.WriteLine("Done!");

}

private static object _consoleSyncLock = new object();
private static volatile int counter = 0;

public static async Task RunTestProcess()
{

    var stopwatch = Stopwatch.StartNew();
    var result = await CmdExecutor.Execute("ipconfigf", $"", "/Q", "/C");

    lock (_consoleSyncLock)
    {
        var temp = new
        {
            OutputLength = result.Output.Length,
            ErrorLength = result.Error.Length,
            Thread.CurrentThread.ManagedThreadId,
            stopwatch.Elapsed,
            Counter = counter++
        };

        if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
    }
}

public class CmdExecutor
{
    public static Task<CmdResult> Execute(string fileName, string arguments, params string[] cmdSwitches)
    {
        Console.WriteLine(nameof(Execute) + " - " + Thread.CurrentThread.ManagedThreadId);

        if (cmdSwitches == null) throw new ArgumentNullException(nameof(cmdSwitches));
        if (fileName == null) throw new ArgumentNullException(nameof(fileName));
        if (arguments == null) throw new ArgumentNullException(nameof(arguments));

        arguments = $"{string.Join(" ", cmdSwitches)} {fileName} {arguments}";
        var startInfo = new ProcessStartInfo("cmd", arguments)
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };

        var tcs = new TaskCompletionSource<CmdResult>();

        var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
        {
            var output = new StringBuilder();
            var error = new StringBuilder();

            process.OutputDataReceived += (sender, e) =>
            {
                output.AppendLine(e.Data);
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                error.AppendLine(e.Data);
            };

            process.Exited += (sender, e) =>
            {
                tcs.SetResult(new CmdResult
                {
                    Arguments = arguments,
                    Output = output.ToString(),
                    Error = error.ToString(),
                    ExitCode = process.ExitCode
                });
                process.Dispose();
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
    }
}

[Serializable]
public class CmdResult
{
    public string Arguments { get; set; }
    public string Output { get; set; }
    public string Error { get; set; }
    public int ExitCode { get; set; }
}
</code>```

I don't consider this code working because it does not do what it should be doing. This is, showing the entire output of each process as soon as it's finished.

I'm curious what can be done to solve this? I don't want to simply run processes in parallel, I already can do it but I'm interested in their ouput.

答:
To me, the error seems to be that there is the assumption that either OutputDataReceived or ErrorDataReceived will have been called at least once prior to the process.Exited - this will leave both the output and error StringBuilders empty if the process exits before the callbacks are complete.

By adding a second TaskCompletionSource to monitor the presence of at least one of the error / data callbacks, I am able to reliably always get at least one of the data callbacks invoked.

I've also changed the StringBuilders to ConcurrentBags to be safe - I'm not 100% sure of the threading used in the callbacks:

```<code>var tcsGotData = new TaskCompletionSource<bool>();
var output = new ConcurrentBag<string>();
var error = new ConcurrentBag<string>();

process.OutputDataReceived += (sender, e) =>
{
    output.Add(e.Data);
    tcsGotData.TrySetResult(true);
};

process.ErrorDataReceived += (sender, e) =>
{
    error.Add(e.Data);
    tcsGotData.TrySetResult(true);
};

process.Exited += (sender, e) =>
{
    tcsGotData.Task.Wait(); // You might want to put a timeout here, though ...
    tcs.SetResult(new CmdResult
    {
        Arguments = arguments,
        Output = string.Join("", output),
        Error = string.Join("", error),
        ExitCode = process.ExitCode
    });
    process.Dispose();
};
</code>```

Body:
I'm trying to get the output from several process that are running in parallel. As soon as each process is done I want to print its output to the console. Unfortunatelly none of the popular approaches work.

Using the TaskCompletionSource

With TaskCompletionSource the output can arrive asynchronously when the Exited event is called but it's often missing because the execution does not wait for the buffers to flush. Adding a Task.Delay for a few (hundred) milliseconds doesn't seem right and also does not always work.

Using WaitForExit

The isssue with WaitForExit is that it indeed works in parallel but it waits for all processes to finish. Only then you can print their results so you don't see any progress until they all exited.

In order to demonstrate it I created a demo application. It calls a misspelled ipconfig. If you run it a few times in LINQPad you'll see at some point that this line will kick-in informing you that there was no output.

if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();

Here's the test application reproducing the issue. It's intentional that ipconfig is mispelled to provoke the Output problem.

void Main()
{
    var testCount = 30;

    var tasks = Enumerable.Range(0, testCount).Select(i => Task.Run(() => RunTestProcess()));

    Task.WaitAll(tasks.ToArray());

    Console.WriteLine("Done!");

}

private static object _consoleSyncLock = new object();
private static volatile int counter = 0;

public static async Task RunTestProcess()
{

    var stopwatch = Stopwatch.StartNew();
    var result = await CmdExecutor.Execute("ipconfigf", $"", "/Q", "/C");

    lock (_consoleSyncLock)
    {
        var temp = new
        {
            OutputLength = result.Output.Length,
            ErrorLength = result.Error.Length,
            Thread.CurrentThread.ManagedThreadId,
            stopwatch.Elapsed,
            Counter = counter++
        };

        if (temp.OutputLength == 0 && temp.ErrorLength == 0) temp.Dump();
    }
}

public class CmdExecutor
{
    public static Task<CmdResult> Execute(string fileName, string arguments, params string[] cmdSwitches)
    {
        Console.WriteLine(nameof(Execute) + " - " + Thread.CurrentThread.ManagedThreadId);

        if (cmdSwitches == null) throw new ArgumentNullException(nameof(cmdSwitches));
        if (fileName == null) throw new ArgumentNullException(nameof(fileName));
        if (arguments == null) throw new ArgumentNullException(nameof(arguments));

        arguments = $"{string.Join(" ", cmdSwitches)} {fileName} {arguments}";
        var startInfo = new ProcessStartInfo("cmd", arguments)
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
        };

        var tcs = new TaskCompletionSource<CmdResult>();

        var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
        {
            var output = new StringBuilder();
            var error = new StringBuilder();

            process.OutputDataReceived += (sender, e) =>
            {
                output.AppendLine(e.Data);
            };

            process.ErrorDataReceived += (sender, e) =>
            {
                error.AppendLine(e.Data);
            };

            process.Exited += (sender, e) =>
            {
                tcs.SetResult(new CmdResult
                {
                    Arguments = arguments,
                    Output = output.ToString(),
                    Error = error.ToString(),
                    ExitCode = process.ExitCode
                });
                process.Dispose();
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            return tcs.Task;
        }
    }
}

[Serializable]
public class CmdResult
{
    public string Arguments { get; set; }
    public string Output { get; set; }
    public string Error { get; set; }
    public int ExitCode { get; set; }
}

I don't consider this code working because it does not do what it should be doing. This is, showing the entire output of each process as soon as it's finished.

I'm curious what can be done to solve this? I don't want to simply run processes in parallel, I already can do it but I'm interested in their ouput.

Body:
To me, the error seems to be that there is the assumption that either OutputDataReceived or ErrorDataReceived will have been called at least once prior to the process.Exited - this will leave both the output and error StringBuilders empty if the process exits before the callbacks are complete.

By adding a second TaskCompletionSource to monitor the presence of at least one of the error / data callbacks, I am able to reliably always get at least one of the data callbacks invoked.

I've also changed the StringBuilders to ConcurrentBags to be safe - I'm not 100% sure of the threading used in the callbacks:

var tcsGotData = new TaskCompletionSource<bool>();
var output = new ConcurrentBag<string>();
var error = new ConcurrentBag<string>();

process.OutputDataReceived += (sender, e) =>
{
    output.Add(e.Data);
    tcsGotData.TrySetResult(true);
};

process.ErrorDataReceived += (sender, e) =>
{
    error.Add(e.Data);
    tcsGotData.TrySetResult(true);
};

process.Exited += (sender, e) =>
{
    tcsGotData.Task.Wait(); // You might want to put a timeout here, though ...
    tcs.SetResult(new CmdResult
    {
        Arguments = arguments,
        Output = string.Join("", output),
        Error = string.Join("", error),
        ExitCode = process.ExitCode
    });
    process.Dispose();
};


问:
How to calculate (statistical) power function vs. sample size in python?
How can this be done in python?

Calculate sample size for a given power and alpha?

Calculate power for a given sample size and alpha?

Note:
I am totally confused :( with the functions that python gives for (statistical) power function calculation.

Can someone help me to make an order here?

There are two functions under statsmodels:

```<code>from statsmodels.stats.power import ttest_power, tt_ind_solve_power()
</code>```

We have:

```<code>tt_ind_solve_power(effect_size=effect_size, alpha=alpha, power=0.8, ratio=1, alternative='two-sided')
</code>```

And we have also:

```<code>ttest_power(0.2, nobs=sampleSize, alpha=alpha, alternative='two-sided')
</code>```

There is also this peice of code:

```<code>import statsmodels.stats.api as sms
es = sms.proportion_effectsize(prop1, prop2, method='normal')
n = sms.NormalIndPower().solve_power(es, power=0.9, alpha=0.05, ratio=2)
</code>```

I found this example somewhere but it does NOT explain what are prop1 and prop2!

Each one is giving me different values.

thanks

答:
As an answer to the question above, I wrote this function that calculates power vs. sample size.

When calling the tt_ind_solve_power you need to leave one parameter as None in order to be calculated. In my example below i keep power as None.

I hope that someone will find it useful, any improvements are welcome.

```<code>from statsmodels.stats.power import  tt_ind_solve_power
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

def test_ttest_power_diff(mean, std, sample1_size=None, alpha=0.05, desired_power=0.8, mean_diff_percentages=[0.1, 0.05]):
    '''
    calculates the power function for a given mean and std. the function plots a graph showing the comparison between desired mean differences
    :param mean: the desired mean
    :param std: the std value
    :param sample1_size: if None, it is assumed that both samples (first and second) will have same size. The function then will
    walk through possible sample sizes (up to 100, hardcoded).
    If this value is not None, the function will check different alternatives for sample 2 sizes up to sample 1 size.
    :param alpha: alpha default value is 0.05
    :param desired_power: will use this value in order to mark on the graph
    :param mean_diff_percentages: iterable list of percentages. A line per value will be calculated and plotted.
    :return: None
    '''
    fig, ax = plt.subplots()
    for mean_diff_percent in mean_diff_percentages:
        mean_diff = mean_diff_percent * mean
        effect_size = mean_diff / std

        print('Mean diff: ', mean_diff)
        print('Effect size: ', effect_size)

        powers = []

        max_size  = sample1_size
        if sample1_size is None:
            max_size = 100

        sizes = np.arange(1, max_size, 2)
        for sample2_size in sizes:
            if(sample1_size is None):
                n = tt_ind_solve_power(effect_size=effect_size, nobs1=sample2_size, alpha=alpha, ratio=1.0, alternative='two-sided')
                print('tt_ind_solve_power(alpha=', alpha, 'sample2_size=', sample2_size, '): sample size in *second* group: {:.5f}'.format(n))
            else:
                n = tt_ind_solve_power(effect_size=effect_size, nobs1=sample1_size, alpha=alpha, ratio=(1.0*sample2_size/sample1_size), alternative='two-sided')
                print('tt_ind_solve_power(alpha=', alpha, 'sample2_size=', sample2_size, '): sample size *each* group: {:.5f}'.format(n))

            powers.append(n)

        try: # mark the desired power on the graph
            z1 = interp1d(powers, sizes)
            results = z1(desired_power)

            plt.plot([results], [desired_power], 'gD')
        except Exception as e:
            print("Error: ", e)
            #ignore

        plt.title('Power vs. Sample Size')
        plt.xlabel('Sample Size')
        plt.ylabel('Power')

        plt.plot(sizes, powers, label='diff={:2.0f}%'.format(100*mean_diff_percent)) #, '-gD')

    plt.legend()
    plt.show()
</code>```

As an example, if you call this function with mean=10 and std=2 you will get this plot:

Body:
How can this be done in python?

Calculate sample size for a given power and alpha?

Calculate power for a given sample size and alpha?

Note:
I am totally confused :( with the functions that python gives for (statistical) power function calculation.

Can someone help me to make an order here?

There are two functions under statsmodels:

from statsmodels.stats.power import ttest_power, tt_ind_solve_power()

We have:

tt_ind_solve_power(effect_size=effect_size, alpha=alpha, power=0.8, ratio=1, alternative='two-sided')

And we have also:

ttest_power(0.2, nobs=sampleSize, alpha=alpha, alternative='two-sided')

There is also this peice of code:

import statsmodels.stats.api as sms
es = sms.proportion_effectsize(prop1, prop2, method='normal')
n = sms.NormalIndPower().solve_power(es, power=0.9, alpha=0.05, ratio=2)

I found this example somewhere but it does NOT explain what are prop1 and prop2!

Each one is giving me different values.

thanks

Body:
As an answer to the question above, I wrote this function that calculates power vs. sample size.

When calling the tt_ind_solve_power you need to leave one parameter as None in order to be calculated. In my example below i keep power as None.

I hope that someone will find it useful, any improvements are welcome.

from statsmodels.stats.power import  tt_ind_solve_power
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

def test_ttest_power_diff(mean, std, sample1_size=None, alpha=0.05, desired_power=0.8, mean_diff_percentages=[0.1, 0.05]):
    '''
    calculates the power function for a given mean and std. the function plots a graph showing the comparison between desired mean differences
    :param mean: the desired mean
    :param std: the std value
    :param sample1_size: if None, it is assumed that both samples (first and second) will have same size. The function then will
    walk through possible sample sizes (up to 100, hardcoded).
    If this value is not None, the function will check different alternatives for sample 2 sizes up to sample 1 size.
    :param alpha: alpha default value is 0.05
    :param desired_power: will use this value in order to mark on the graph
    :param mean_diff_percentages: iterable list of percentages. A line per value will be calculated and plotted.
    :return: None
    '''
    fig, ax = plt.subplots()
    for mean_diff_percent in mean_diff_percentages:
        mean_diff = mean_diff_percent * mean
        effect_size = mean_diff / std

        print('Mean diff: ', mean_diff)
        print('Effect size: ', effect_size)

        powers = []

        max_size  = sample1_size
        if sample1_size is None:
            max_size = 100

        sizes = np.arange(1, max_size, 2)
        for sample2_size in sizes:
            if(sample1_size is None):
                n = tt_ind_solve_power(effect_size=effect_size, nobs1=sample2_size, alpha=alpha, ratio=1.0, alternative='two-sided')
                print('tt_ind_solve_power(alpha=', alpha, 'sample2_size=', sample2_size, '): sample size in *second* group: {:.5f}'.format(n))
            else:
                n = tt_ind_solve_power(effect_size=effect_size, nobs1=sample1_size, alpha=alpha, ratio=(1.0*sample2_size/sample1_size), alternative='two-sided')
                print('tt_ind_solve_power(alpha=', alpha, 'sample2_size=', sample2_size, '): sample size *each* group: {:.5f}'.format(n))

            powers.append(n)

        try: # mark the desired power on the graph
            z1 = interp1d(powers, sizes)
            results = z1(desired_power)

            plt.plot([results], [desired_power], 'gD')
        except Exception as e:
            print("Error: ", e)
            #ignore

        plt.title('Power vs. Sample Size')
        plt.xlabel('Sample Size')
        plt.ylabel('Power')

        plt.plot(sizes, powers, label='diff={:2.0f}%'.format(100*mean_diff_percent)) #, '-gD')

    plt.legend()
    plt.show()

As an example, if you call this function with mean=10 and std=2 you will get this plot:


问:
How to search for a value in Mysql all tables without specifying the table name and column name?
```<code>SELECT @sqlText = @sqlText + ' SELECT * FROM ' + QUOTENAME(name) + CHAR(13) FROM sys.tables
</code>```

答:
You can't search like that. You can write a query as</p>

```<code>SELECT * FROM tablename
WHERE MATCH(`col1`, `col2`, `col3`) AGAINST ('$searchword')
</code>```

Body:
You can't search like that. You can write a query as

SELECT * FROM tablename
WHERE MATCH(`col1`, `col2`, `col3`) AGAINST ('$searchword')


问:
How to configure phpunit located in vendor/bin directory?
I'm trying to set the database for the tests I'm going to run but I have one problem:

I can't run phpunit because I have an older version.

I've already read all posts related to upgrade phpunit in a global context but I've failed doing that. I tried everything and I just couldn't upgrade phpunit globally so I started to use vendor/bin/phpunit instead and everything works fine. Now that led me to a second problem:

How can I set the database where I am going to run my tests?

I know I need to set all the information about the database in the phpunit.xml file but the one that is in the base path works only for the global phpunit version. So where can I set the database information for the vendor/bin phunit version?

答:
As others have said ./vendor/bin/phpunit should read the phpunit.xml file if you running things from your app root path. To help with testing you can explicitly say what config file you need, like:

vendor/bin/phpunit -c ./phpunit.xml

but if the file is in the current directory you in its not needed, perhaps just double check that.


问:
SQL Row_Number() increase only when the value = 1 for a specific column
I am having some trouble generating row_number() in my SQL query as my expectation. I have this following output of my query-

Now, I want to add row number for all rows where row number will only increase when the value in C1 is = 1. Required output as below-

Any help will be appreciated. TIA

答:
Try this:</p>

```<code>SELECT C1,
       ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY (SELECT 100)) RN
FROM TableNAme
</code>```

Body:
Try this:

SELECT C1,
       ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY (SELECT 100)) RN
FROM TableNAme