问:
c++ dereference pointed object and pass into a function as reference, value is changed
Dear experienced c++ expert:

In recent coding process, there is a trick problem associated with reference and
dereference operation.

```<code>typedef io::SequenceDataAccess<DNA_N>     read_access_type;
</code>```

here is class constructor:

```<code>AlignmentData( // ignored some arguments
              const io::SequenceDataHost*   read_data_batch
             )
{
read_access_type read_data_access( *read_data_batch );
......
}
</code>```

in a debug session, I set a breakpoint at the function body(the unique line), the
value of read_data_batch(a pointer) is 0x7fff9a0489a0, and print the other state info:

```<code>(gdb) print read_data_batch
$7 = (const bxtbio::io::SequenceDataHost *) **0x7fff9a0489a0**
(gdb) print *read_data_batch
$8 = (bxtbio::io::SequenceData) {<bxtbio::io::SequenceData> =
{<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::DNA_N,
m_n_seqs = 250, m_n_segments = 0, m_name_stream_len = 16392,
m_sequence_stream_len = 25000, m_sequence_stream_words = 3125,
......
</code>```

but when I step into the constructor of class SequenceDataAccess,

shown as below:

```<code>NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data):m_data(data)
</code>```

the argument data's state:

```<code>(gdb) print &data
$9 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*,
unsigned int const*, char const*, char const*> *) **0x7fffa0aacb50**

(gdb) print data
$10 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*, unsigned int const*, char const*, char const*> &) @0x7fffa0aacb50: {<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::PROTEIN, m_n_seqs = 0, m_n_segments = 0, m_name_stream_len = 0, m_sequence_stream_len = 0, m_sequence_stream_words = 0, m_has_qualities = 0, .......
</code>```

My Questions:

shouldn't data has the same address as the  read_data_batch which is
passed in the copy-constructor?

why are the data member's values all changed? What are the possible
reasons?

this code is running in a multiple threads environment.

Thanks.

Here is a small invoke chain code excerpt:

```<code>// file1.cpp
void MapSpliceWorker::align(io::HostOutputBatchSE *cpu_batch)
{
    log_info(stderr, "MapSpliceWorker::align called cpu_batch.count = %d\n",cpu_batch->count);

    for (uint32 c = 0; c < cpu_batch->count; c++) {
        AlignmentData alignment = get(*cpu_batch, c);   // Here is the entrypoint invocation
    }
}

// file2.cpp
AlignmentData get(HostOutputBatchSE& batch, const uint32 aln_id)
{
    const uint32 read_id = batch.read_ids.size() ?
                           batch.read_ids[ aln_id ] : aln_id;
   // construct a AlignmentData object and return
    return AlignmentData(&batch.alignments[aln_id],
                         batch.mapq[aln_id],
                         aln_id,
                         read_id,
                         batch.read_data,
                         &batch.cigar,
                         &batch.mds);
}
// file3.h
struct AlignmentData
{
    AlignmentData(const Alignment*              _aln,
                  const uint32                  _mapq,
                  const uint32                  _aln_id,
                  const uint32                  _read_id,
                  const io::SequenceDataHost*   read_data_batch,
                  const HostCigarArray*         cigar_array,
                  const HostMdsArray*           mds_array)
        : valid(true),
          aln(_aln),
          aln_id(_aln_id),
          read_id(_read_id),
          mapq(_mapq),
          read_data_batch_p(read_data_batch),
          cigar_array_p(cigar_array),
          mds_array_p(mds_array)
    {
        read_access_type read_data_access( *read_data_batch );   // up to now, read_data_batch has valid states
    }
};

// file4. h
template <
    Alphabet  SEQUENCE_ALPHABET_T,
    typename  SequenceDataT = ConstSequenceDataView>
struct SequenceDataAccess
{
    /// constructor
    NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data)
: m_data( data )   // here the data's states is cleaned and the address is not same as read_data_batch in previous context.
    {
      #if !defined(NVBIO_DEVICE_COMPILATION) || defined(NVBIO_CUDA_DEBUG)
        assert( m_data.m_alphabet == SEQUENCE_ALPHABET );
        // failed by this assert
      #endif
    }
}
</code>```

答:
It looks like your program invoked Undefined Behaviour.

If some piece of the program writes out-of-bounds (corrupting heap or stack) the results are unpredictable.

Whenever you see inexplicable things like this in your code, you should be thinking of UB elsewhere.

You could...

Start with minimal code and gradually add code until the problem appears¹

use a memory checker/instrumenter (valgrind, rational purify)

use sanitizers (much the same effects, eg. -fsanitize=address,undefined for GCC/clang)

Keep in mind that debugging optimized code can be disorienting because the compiler may re-arranges code out-of-order and optimize variables out.

Using a debug (unoptimized) build can help, BUT you might not see the UB then

¹ This approach is haphazard, because UB means you might not see the problem when it exists (it's undefined: It might just appear to execute normally)

Body:
Dear experienced c++ expert:

In recent coding process, there is a trick problem associated with reference and
dereference operation.

typedef io::SequenceDataAccess<DNA_N>     read_access_type;

here is class constructor:

AlignmentData( // ignored some arguments
              const io::SequenceDataHost*   read_data_batch
             )
{
read_access_type read_data_access( *read_data_batch );
......
}

in a debug session, I set a breakpoint at the function body(the unique line), the
value of read_data_batch(a pointer) is 0x7fff9a0489a0, and print the other state info:

(gdb) print read_data_batch
$7 = (const bxtbio::io::SequenceDataHost *) **0x7fff9a0489a0**
(gdb) print *read_data_batch
$8 = (bxtbio::io::SequenceData) {<bxtbio::io::SequenceData> =
{<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::DNA_N,
m_n_seqs = 250, m_n_segments = 0, m_name_stream_len = 16392,
m_sequence_stream_len = 25000, m_sequence_stream_words = 3125,
......

but when I step into the constructor of class SequenceDataAccess,

shown as below:

NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data):m_data(data)

the argument data's state:

(gdb) print &data
$9 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*,
unsigned int const*, char const*, char const*> *) **0x7fffa0aacb50**

(gdb) print data
$10 = (const bxtbio::io::SequenceDataViewCore<unsigned int const*, unsigned int const*, char const*, char const*> &) @0x7fffa0aacb50: {<bxtbio::io::SequenceDataInfo> = {m_alphabet = bxtbio::PROTEIN, m_n_seqs = 0, m_n_segments = 0, m_name_stream_len = 0, m_sequence_stream_len = 0, m_sequence_stream_words = 0, m_has_qualities = 0, .......

My Questions:

shouldn't data has the same address as the  read_data_batch which is
passed in the copy-constructor?

why are the data member's values all changed? What are the possible
reasons?

this code is running in a multiple threads environment.

Thanks.

Here is a small invoke chain code excerpt:

// file1.cpp
void MapSpliceWorker::align(io::HostOutputBatchSE *cpu_batch)
{
    log_info(stderr, "MapSpliceWorker::align called cpu_batch.count = %d\n",cpu_batch->count);

    for (uint32 c = 0; c < cpu_batch->count; c++) {
        AlignmentData alignment = get(*cpu_batch, c);   // Here is the entrypoint invocation
    }
}

// file2.cpp
AlignmentData get(HostOutputBatchSE& batch, const uint32 aln_id)
{
    const uint32 read_id = batch.read_ids.size() ?
                           batch.read_ids[ aln_id ] : aln_id;
   // construct a AlignmentData object and return
    return AlignmentData(&batch.alignments[aln_id],
                         batch.mapq[aln_id],
                         aln_id,
                         read_id,
                         batch.read_data,
                         &batch.cigar,
                         &batch.mds);
}
// file3.h
struct AlignmentData
{
    AlignmentData(const Alignment*              _aln,
                  const uint32                  _mapq,
                  const uint32                  _aln_id,
                  const uint32                  _read_id,
                  const io::SequenceDataHost*   read_data_batch,
                  const HostCigarArray*         cigar_array,
                  const HostMdsArray*           mds_array)
        : valid(true),
          aln(_aln),
          aln_id(_aln_id),
          read_id(_read_id),
          mapq(_mapq),
          read_data_batch_p(read_data_batch),
          cigar_array_p(cigar_array),
          mds_array_p(mds_array)
    {
        read_access_type read_data_access( *read_data_batch );   // up to now, read_data_batch has valid states
    }
};

// file4. h
template <
    Alphabet  SEQUENCE_ALPHABET_T,
    typename  SequenceDataT = ConstSequenceDataView>
struct SequenceDataAccess
{
    /// constructor
    NVBIO_HOST_DEVICE NVBIO_FORCEINLINE
SequenceDataAccess(const SequenceDataT& data)
: m_data( data )   // here the data's states is cleaned and the address is not same as read_data_batch in previous context.
    {
      #if !defined(NVBIO_DEVICE_COMPILATION) || defined(NVBIO_CUDA_DEBUG)
        assert( m_data.m_alphabet == SEQUENCE_ALPHABET );
        // failed by this assert
      #endif
    }
}


来源: stackexchange

问:
Can you create an initialize method for DLL?
I need to create a service, but the service needs to be in a already existing Class Library file and also the new service needs to start running after the Class Library is installed.
Is there a way to create an Init() method or other way to start service inside in Class Library?
The project supports max .NET 3.5

Sorry if it sounds dumb, i'm new to the Class Library stuff

答:
No, class libraries don't support initialization like this.

Note that the library wouldn't even be loaded until it's first used anyway. You could write a type initializer for some appropriate type, and make that start the service - but personally I'd make it explicit if at all possible. (Doing lots of work in type initializers can lead to difficult-to-diagnose issues.)

ContentLicense: CC BY-SA 3.0


问:
Change language after POST
I was following this tutorial to use multiple languages on my site, but i'm trying to switch language after POST, but actually the language switch happens when clicked on POST button twice.

This code is called out in the beginning of page.

```<code><?php
if (!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'ENG';
    require "lang/ENG.php";
}
else {
    $language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
    switch($language) {
        case "EST":
            require "lang/EST.php";
            break;
        case "ENG":
            require "lang/ENG.php";
            break;
        default:
            require "lang/ENG.php";
    }
}
?>
</code>```

This code is called out when form is submitted:

```<code>if(isset($_POST['selectlang'])){
    $lang = $_POST['country'];
    //Change language??
}
</code>```

If i click POST button twice, the language is switched, but not on the first try. What do i need to change?

Edit #2: Adding modified HTML now based on answers:

```<code><?php
include('connection.php');
?>
<?php
if (!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'ENG';
    require "lang/ENG.php";
}
else {
    $language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
    switch($language) {
        case "EST":
            require "lang/EST.php";
            break;
        case "ENG":
            require "lang/ENG.php";
            break;
        default:
            require "lang/ENG.php";
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $lang['reklamatsioon_title'];?></title>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="css/logo-nav.css" rel="stylesheet">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>
    <!-- Navigation -->
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="reklamatsioon.php">
                    <img src="logo.png" alt="">
                </a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li>
                        <a href="#"><?php echo $lang['link1'];?></a>
                    </li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container -->
    </nav>

    <!-- Page Content -->
    <div class="container">
        <div class="row">
            <form action="" method="post" class="form-horizontal" role="form">
                <div class="form-group">
                    <label for="selector" class="col-sm-3 col-lg-3 control-label">Pick language</label>
                    <div class="col-sm-9 col-lg-9">
                        <span id="selector" class="input-group-btn">
                            <select id="country" name="riik" class="form-control">
                                <option <?php if($_POST['riik'] == "EST"){ echo "selected='selected'"; }?> value="EST">Eesti</option>
                                <option <?php if($_POST['riik'] == "ENG"){ echo "selected='selected'"; }?> value="ENG">English</option>
                                <option <?php if($_POST['riik'] == "FIN"){ echo "selected='selected'"; }?> value="FIN">Suomi</option>
                                <option <?php if($_POST['riik'] == "SWE"){ echo "selected='selected'"; }?> value="SWE">Rootsi</option>
                                <option <?php if($_POST['riik'] == "NOR"){ echo "selected='selected'"; }?> value="NOR">Norra</option>
                            </select>
                        </span>
                        <span class="input-group-btn">
                            <button class="btn btn-primary" name="selectlang" type="submit">Choose language!</button>
                        </span>
                    </div>
                </div>
            </form>
        </div>
        <?php
            if(isset($_POST['selectlang'])){
                $lang = $_POST['riik'];
                $_SESSION['lang'] = $lang;
                //Show code form and terms and conditions url!
                echo "<div class='row'>";
                    echo "<form action='' method='post' class='form-horizontal' role='form'>";
                        echo "<div class='form-group'>";
                            echo "<label for='code' class='col-sm-3 control-label'>"."Code"."</label>";
                            echo "<div class='col-sm-6'>";
                                echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus>";
                                echo "<span class='help-block'></span>";
                            echo "</div>";
                            echo "</div>";
                            echo "<div class='form-group'>";
                                echo "<div class='col-sm-6 col-sm-offset-3'>";
                                    echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
                                echo "</div>";
                            echo "</div>";
                    echo "</form>";
                echo "</div>";
            }

            if(isset($_POST["gobutton"])){
                $codeVal = $_POST['code'];
                $brokenCode = false;
                if(strlen($codeVal) < 9){
                    $codeQuery = mysql_query("SELECT clientNumber FROM client WHERE clientNumber = '$codeVal'",$connection) or die(mysql_error());
                    if (mysql_num_rows($codeQuery) == 1){
                        header('location: ankeet.php?code='.$codeVal);
                    }
                    else {
                        $brokenCode = true;
                    }
                }
                else {
                    $brokenCode = true;
                }
                if ($brokenCode){
                    echo "<div class='row'>";
                        echo "<form action='' method='post' class='form-horizontal' role='form'>";
                            echo "<div class='form-group'>";
                                echo "<label for='code' class='col-sm-3 control-label'>"."Code"."</label>";
                                echo "<div class='col-sm-6'>";
                                    echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus value='".$codeVal."'>";
                                    echo "<span class='help-block'></span>";
                                echo "</div>";
                                echo "</div>";
                                echo "<div class='alert alert-danger col-sm-6 col-sm-offset-3'>Such code does not exist!</div>";
                                echo "<div class='form-group'>";
                                    echo "<div class='col-sm-6 col-sm-offset-3'>";
                                        echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
                                    echo "</div>";
                                echo "</div>";
                        echo "</form>";
                    echo "</div>";
                }

            }
        ?>
    </div>
    <!-- /.container -->

    <!-- jQuery -->
    <script src="js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>

</body>

</html>
</code>```

答:
First you need:

```<code>if (isset($_POST['country'])) {
    $_SESSION['lang'] = $_POST['country'];
}
</code>```

So the language can be switched.

Then you need to load your settings.

```<code>$language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
switch($language) {
    case "DE":
        require "lang/de.php";
        break;
    case "ENG":
    default:
        require "lang/eng.php";
}
</code>```

That way nothing, that you dont want can happen

There are several other things you could optimize but for now that should solve your problem.

You should NEVER require or include a file based on a variable that can be set by the website user!

Edit:

I have seen your posted code now: It can not work because you first include your file and switch the session value later on. At that time the file has already been loaded. You need to do things in the correct order, just think of it like that:

1) initialize request

2) make configurations

3) output html code

Edit again:

There are so many bad practices in your code, that i actually dont know where to start.

1) Dont include user input unfiltered in SQL queries, that way you can be attacked by anyone with minimal knowledge. And people will try - believe me. You have to escape values, that are used in sql queries. It would be much better to use parameter binding, please google "php mysql pdo parameter binding"

2) When rendering your options, you should consider using a loop to avoid repeating yourself, please google "DRY dont repeat yourself"

3) you can not send a http header after you printed output already. That does not work due to the nature of the http protocol. First the headers are sent to the browser, followed by the content, basically it looks like:

```<code>HeaderLineOne: HeaderValue
HeaderLineTwo: HeaderValue

Content
</code>```

3) You should really handle the request first and output your code later on. So put your php logic on top of the file (handle input, configure etc) and output your response at the end. That way you can react properly and dont mix up your view with your logic. Basically like:

```<code><?php

// bootstrap application
require_once "connection.php";
require_once "other_include.php";

// configure
$language = "ENG";
if (isset($_SESSION['language'])) {
    $language = $_SESSION['language'];
}

// allow user override for language
if (isset($_POST['country'])) {
    $language = $_POST['country'];
    // make change persistent
    $_SESSION['language'] = $language;
}

// include translation labels
switch($language) {
    case "DE":
        require "lang/de.php";
        break;
    case "ENG":
    default:
        require "lang/eng.php";
}

// handle user request
if (isset($_POST['someValue'])) {
    // handle user input, make database calls etc
    // this is where your logic goes
}

// finally render response
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title><?= $lang['title'] ?></title>
</head>
<body>
    <h1><?= $lang['title'] ?>
</body>
</html>
</code>```

Title: Change language after POST

Body:
I was following this tutorial to use multiple languages on my site, but i'm trying to switch language after POST, but actually the language switch happens when clicked on POST button twice.

This code is called out in the beginning of page.

<?php
if (!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'ENG';
    require "lang/ENG.php";
}
else {
    $language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
    switch($language) {
        case "EST":
            require "lang/EST.php";
            break;
        case "ENG":
            require "lang/ENG.php";
            break;
        default:
            require "lang/ENG.php";
    }
}
?>

This code is called out when form is submitted:

if(isset($_POST['selectlang'])){
    $lang = $_POST['country'];
    //Change language??
}

If i click POST button twice, the language is switched, but not on the first try. What do i need to change?

Edit #2: Adding modified HTML now based on answers:

<?php
include('connection.php');
?>
<?php
if (!isset($_SESSION['lang'])){
    $_SESSION['lang'] = 'ENG';
    require "lang/ENG.php";
}
else {
    $language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
    switch($language) {
        case "EST":
            require "lang/EST.php";
            break;
        case "ENG":
            require "lang/ENG.php";
            break;
        default:
            require "lang/ENG.php";
    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title><?php echo $lang['reklamatsioon_title'];?></title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/logo-nav.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        <?php echo $lang['link1'];?>

            <form action="" method="post" class="form-horizontal" role="form">

                    Pick language

                            <select id="country" name="riik" class="form-control">
                                <option <?php if($_POST['riik'] == "EST"){ echo "selected='selected'"; }?> value="EST">Eesti</option>
                                <option <?php if($_POST['riik'] == "ENG"){ echo "selected='selected'"; }?> value="ENG">English</option>
                                <option <?php if($_POST['riik'] == "FIN"){ echo "selected='selected'"; }?> value="FIN">Suomi</option>
                                <option <?php if($_POST['riik'] == "SWE"){ echo "selected='selected'"; }?> value="SWE">Rootsi</option>
                                <option <?php if($_POST['riik'] == "NOR"){ echo "selected='selected'"; }?> value="NOR">Norra</option>
                            </select>

                            <button class="btn btn-primary" name="selectlang" type="submit">Choose language!</button>

            </form>

        <?php
            if(isset($_POST['selectlang'])){
                $lang = $_POST['riik'];
                $_SESSION['lang'] = $lang;
                //Show code form and terms and conditions url!
                echo "
";
                    echo "<form action='' method='post' class='form-horizontal' role='form'>";
                        echo "
";
                            echo ""."Code"."";
                            echo "
";
                                echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus>";
                                echo "";
                            echo "
";
                            echo "
";
                            echo "
";
                                echo "
";
                                    echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
                                echo "
";
                            echo "
";
                    echo "</form>";
                echo "
";
            }

            if(isset($_POST["gobutton"])){
                $codeVal = $_POST['code'];
                $brokenCode = false;
                if(strlen($codeVal) < 9){
                    $codeQuery = mysql_query("SELECT clientNumber FROM client WHERE clientNumber = '$codeVal'",$connection) or die(mysql_error());
                    if (mysql_num_rows($codeQuery) == 1){
                        header('location: ankeet.php?code='.$codeVal);
                    }
                    else {
                        $brokenCode = true;
                    }
                }
                else {
                    $brokenCode = true;
                }
                if ($brokenCode){
                    echo "
";
                        echo "<form action='' method='post' class='form-horizontal' role='form'>";
                            echo "
";
                                echo ""."Code"."";
                                echo "
";
                                    echo "<input type='number' id='code' name='code' placeholder='Code' class='form-control' autofocus value='".$codeVal."'>";
                                    echo "";
                                echo "
";
                                echo "
";
                                echo "
Such code does not exist!
";
                                echo "
";
                                    echo "
";
                                        echo "<button type='submit' class='btn btn-primary btn-block' name='gobutton'>Continue to form</button>";
                                    echo "
";
                                echo "
";
                        echo "</form>";
                    echo "
";
                }

            }
        ?>

Body:
First you need:

if (isset($_POST['country'])) {
    $_SESSION['lang'] = $_POST['country'];
}

So the language can be switched.

Then you need to load your settings.

$language = (isset($_SESSION['lang'])) ? $_SESSION['lang'] : "ENG";
switch($language) {
    case "DE":
        require "lang/de.php";
        break;
    case "ENG":
    default:
        require "lang/eng.php";
}

That way nothing, that you dont want can happen

There are several other things you could optimize but for now that should solve your problem.

You should NEVER require or include a file based on a variable that can be set by the website user!

Edit:

I have seen your posted code now: It can not work because you first include your file and switch the session value later on. At that time the file has already been loaded. You need to do things in the correct order, just think of it like that:

1) initialize request

2) make configurations

3) output html code

Edit again:

There are so many bad practices in your code, that i actually dont know where to start.

1) Dont include user input unfiltered in SQL queries, that way you can be attacked by anyone with minimal knowledge. And people will try - believe me. You have to escape values, that are used in sql queries. It would be much better to use parameter binding, please google "php mysql pdo parameter binding"

2) When rendering your options, you should consider using a loop to avoid repeating yourself, please google "DRY dont repeat yourself"

3) you can not send a http header after you printed output already. That does not work due to the nature of the http protocol. First the headers are sent to the browser, followed by the content, basically it looks like:

HeaderLineOne: HeaderValue
HeaderLineTwo: HeaderValue

Content

3) You should really handle the request first and output your code later on. So put your php logic on top of the file (handle input, configure etc) and output your response at the end. That way you can react properly and dont mix up your view with your logic. Basically like:

<?php

// bootstrap application
require_once "connection.php";
require_once "other_include.php";

// configure
$language = "ENG";
if (isset($_SESSION['language'])) {
    $language = $_SESSION['language'];
}

// allow user override for language
if (isset($_POST['country'])) {
    $language = $_POST['country'];
    // make change persistent
    $_SESSION['language'] = $language;
}

// include translation labels
switch($language) {
    case "DE":
        require "lang/de.php";
        break;
    case "ENG":
    default:
        require "lang/eng.php";
}

// handle user request
if (isset($_POST['someValue'])) {
    // handle user input, make database calls etc
    // this is where your logic goes
}

// finally render response
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title><?= $lang['title'] ?></title>
</head>
<body>
    <h1><?= $lang['title'] ?>
</body>
</html>


问:
Efficiency in swapping array elements vs Array indices
I have a quick question: I know that the complexity of both snippets is same. Yet, I want to know which one is comparatively better and why? This is the selection sort code:

This is what I wrote:

```<code>            for (int i = 0; i < n - 1; i++)
            {
                for (int j = i + 1; j <= n - 1; j++)
                {
                    if (a[j] < a[i])
                    {
                        int temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }
</code>```

This is what my friend wrote:

```<code>            for (int i = 0; i < n - 1; i++)
            {
                int iMin = i;
                for (int j = i + 1; j <= n - 1; j++)
                {
                    if (a[j] < a[i])
                    {
                        iMin = j;
                    }
                    int temp = a[i];
                    a[i] = a[iMin];
                    a[iMin] = temp;
                }
            }
</code>```

答:
Your code is slightly faster because you make swaps only when a[j] < a[i], whereas your friend's code is always making a swap. So, in most cases, your code will make less swaps.

The complexity of both codes are indeed the same, but your "constants" are smaller, so your code is faster.

Body:
I have a quick question: I know that the complexity of both snippets is same. Yet, I want to know which one is comparatively better and why? This is the selection sort code:

This is what I wrote:

            for (int i = 0; i < n - 1; i++)
            {
                for (int j = i + 1; j <= n - 1; j++)
                {
                    if (a[j] < a[i])
                    {
                        int temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }

This is what my friend wrote:

            for (int i = 0; i < n - 1; i++)
            {
                int iMin = i;
                for (int j = i + 1; j <= n - 1; j++)
                {
                    if (a[j] < a[i])
                    {
                        iMin = j;
                    }
                    int temp = a[i];
                    a[i] = a[iMin];
                    a[iMin] = temp;
                }
            }


问:
lexicographicMode in asyncio bulkCmd
While using Asynchronous pysnmp bulkCmd with asyncio, if requested OID have many values (like 1.3.6.1.2.1.17.4.3.1.2 that show MAC address learned by Cisco switch) or if using several OIDs in one request, I have problem that total number of OIDs in response limited by MTU/MSS of network, which means that not all OIDs received.

This problem can control if using lexicographicMode in Synchronous  bulkCmd, but Asynchronous bulkCmd generator haven`t that options.

It is possible to use getNext but it is significantly reducing performance because of increasing total number of packet (one request/response per OID).
Is there way to control that all "sub oid" received in response using Asynchronous bulkCmd ?

答:
Could you use the maxRepetitions parameter to limit the number of response OIDs per each requested OID? It's 50 in this example.

I believe the lexicographicMode option is designed to stop walking the MIB once the initial prefix goes out of scope. So it has only indirect influence over message size what makes it unreliable for the purpose.

Title: lexicographicMode in asyncio bulkCmd


问:
Ruby extend for object class
Why for this code I have folowing error?

```<code>module ForExtend
  def print
    print "ForExtend print method!"
  end
end

class A
end

a = A.new

class << a
  extend ForExtend
end

a.print
</code>```

Result:

```<code>private method `print' called for #<A:0x005607b26811f8>
(repl):16:in `<main>'
</code>```

In what class/eigenclass lays method print in this case? And how can I access it?

答:
As for why you get the error for calling a private method - there is Kernel#print and Kernel is included in Object, hence objects by default have a private #print method.

As for where this method lies in this case - it's a class method of the singleton class on a:

```<code>a.singleton_class.print
</code>```

As for how to extend the module for a, check @mudasobwa's answer.

Also note that even if you resolve this, you will get an error for calling #print with wrong number of arguments as you redefined it to take no arguments, but call it with one. To call the original implementation when overwriting the method, use super.

Title: Ruby extend for object class

Body:
Why for this code I have folowing error?

module ForExtend
  def print
    print "ForExtend print method!"
  end
end

class A
end

a = A.new

class << a
  extend ForExtend
end

a.print

Result:

private method `print' called for #
(repl):16:in `'

In what class/eigenclass lays method print in this case? And how can I access it?

Body:
As for why you get the error for calling a private method - there is Kernel#print and Kernel is included in Object, hence objects by default have a private #print method.

As for where this method lies in this case - it's a class method of the singleton class on a:

a.singleton_class.print

As for how to extend the module for a, check @mudasobwa's answer.

Also note that even if you resolve this, you will get an error for calling #print with wrong number of arguments as you redefined it to take no arguments, but call it with one. To call the original implementation when overwriting the method, use super.


问:
How to enable disable sup tag in javascript
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

```<code>  <label>code<sup id="star" disabled>*</sup></label>
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no
</code>```

my javascript:

```<code> function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }
</code>```

i tried this but no change in view. any ideas?

答:
$(document).ready(function() {
    $('input[type=radio][name=yes]').change(function() {
        if (this.id == 'yes') {
         $('#star').hide();
        }
        else if (this.id == 'no') {
            $('#star').show();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>code<span id="star" >*</span></label>
      Add to electronic
      <input type="radio" name="yes" id="yes"/>yes
      <input type="radio" name="yes"
         id="no"/>no</code>```

use this

Body:
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

  code*
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no

my javascript:

 function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }

i tried this but no change in view. any ideas?

Body:
$(document).ready(function() {
    $('input[type=radio][name=yes]').change(function() {
        if (this.id == 'yes') {
         $('#star').hide();
        }
        else if (this.id == 'no') {
            $('#star').show();
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>code<span id="star" >*</span></label>
      Add to electronic
      <input type="radio" name="yes" id="yes"/>yes
      <input type="radio" name="yes"
         id="no"/>no

use this


问:
Add or Remove multiple records without manual comparision
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

```<code>PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)
</code>```

Book:

```<code>BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)
</code>```

PersonBook:

```<code>Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)
</code>```

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

```<code>Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);
</code>```

Here I give a simple condition:

```<code>Context.PersonBook.Where(m => m.PersonId == PersonId)
</code>```

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

答:
Not really an answer to your question but you could use the EF n-m relationships feature.

In your case the configuration should be

```<code>modelBuilder.Entity<Person>()
    .HasMany<Book>(user => user.OwnedBooks)
    .WithMany(book => book.Owners)
    .Map(mapping =>
    {
        mapping.MapLeftKey("PersonId");
        mapping.MapRightKey("BookId");
        mapping.ToTable("PersonBook");
    });
</code>```

Using this configuration EF will create and handle the junction table (your PersonBook table) for you. If you enable automatic migration you will see that EF creates the table with 2 fields and a primary key on the 2 fields.

EDIT

Using these classes

```<code>public class Person
{
    public Person()
    {
        OwnedBooks = new List<Book>();
    }

    [Column("PersonId")]
    public int Id { get; set; }
    [MaxLength(50)]
    public string FirstName { get; set; }
    [MaxLength(50)]
    public string LastName { get; set; }

    public ICollection<Book> OwnedBooks { get; set; }
}

public class Book
{
    public Book()
    {
        Owners = new List<Person>();
    }

    [Column("BookId")]
    public int Id { get; set; }
    [Column("BookName")]
    [MaxLength(50)]
    public string Name { get; set; }
    [MaxLength(50)]
    public string Isbn { get; set; }
    [MaxLength(50)]
    public string Author { get; set; }

    public ICollection<Person> Owners { get; set; }
}
</code>```

with the above configuration (I think that you have to use fluent interface to configure m-n relationship) you obtain this model

```<code>ExecuteNonQuery==========
CREATE TABLE [Books] (
 [BookId] int not null identity(1,1)
, [BookName] varchar(50) null
, [Isbn] varchar(50) null
, [Author] varchar(50) null
);
ALTER TABLE [Books] ADD CONSTRAINT [PK_Books_e63a83c6] PRIMARY KEY ([BookId])
ExecuteNonQuery==========
CREATE TABLE [People] (
 [PersonId] int not null identity(1,1)
, [FirstName] varchar(50) null
, [LastName] varchar(50) null
);
ALTER TABLE [People] ADD CONSTRAINT [PK_People_e63a83c6] PRIMARY KEY ([PersonId])
ExecuteNonQuery==========
CREATE TABLE [PersonBook] (
 [PersonId] int not null
, [BookId] int not null
);
ALTER TABLE [PersonBook] ADD CONSTRAINT [PK_PersonBook_e63a83c6] PRIMARY KEY ([PersonId], [BookId])
ExecuteNonQuery==========
CREATE INDEX [IX_PersonId] ON [PersonBook] ([PersonId])
ExecuteNonQuery==========
CREATE INDEX [IX_BookId] ON [PersonBook] ([BookId])
ExecuteNonQuery==========
ALTER TABLE [PersonBook] ADD CONSTRAINT [FK_PersonBook_People_PersonId] FOREIGN KEY ([PersonId]) REFERENCES [People] ([PersonId])
ExecuteNonQuery==========
ALTER TABLE [PersonBook] ADD CONSTRAINT [FK_PersonBook_Books_BookId] FOREIGN KEY ([BookId]) REFERENCES [Books] ([BookId])
</code>```

Then I make some random insert/delete statements

```<code>Book book = new Book()
{
    Author = "Niccolò Ammaniti",
    Name = "Branchie"
};

book.Owners.Add(new Person() { FirstName = "Mastero" });
book.Owners.Add(new Person() { FirstName = "bubi" });

context.Books.Add(book);
context.SaveChanges();
</code>```

These are the queries that EF generates

```<code>ExecuteDbDataReader==========
insert into [Books]([BookName], [Isbn], [Author])
values (@p0, null, @p1);
select [BookId]
from [Books]
where [BookId] = @@identity
@p0 = Branchie
@p1 = Niccolò Ammaniti
ExecuteDbDataReader==========
insert into [People]([FirstName], [LastName])
values (@p0, null);
select [PersonId]
from [People]
where [PersonId] = @@identity
@p0 = Mastero
ExecuteDbDataReader==========
insert into [People]([FirstName], [LastName])
values (@p0, null);
select [PersonId]
from [People]
where [PersonId] = @@identity
@p0 = bubi
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 1
@p1 = 1
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 2
@p1 = 1
</code>```

Then update/delete (from Junction table but for us is transparent)

```<code>book = new Book()
{
    Author = "Niccolò Ammaniti",
    Name = "Come Dio comanda"
};

Person person = context.People.Single(_ => _.FirstName == "bubi");
person.OwnedBooks.Add(book);

context.SaveChanges();

book.Owners.Remove(person);
context.SaveChanges();
</code>```

And these are the queries

```<code>ExecuteDbDataReader==========
SELECT TOP 2
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [People] AS [Extent1]
WHERE 'bubi' = [Extent1].[FirstName]
ExecuteDbDataReader==========
insert into [Books]([BookName], [Isbn], [Author])
values (@p0, null, @p1);
select [BookId]
from [Books]
where [BookId] = @@identity
@p0 = Come Dio comanda
@p1 = Niccolò Ammaniti
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 2
@p1 = 2
ExecuteNonQuery==========
delete from [PersonBook]
where (([PersonId] = @p0) and ([BookId] = @p1))
@p0 = 2
@p1 = 2
</code>```

You can download this code (and other insteresting configurations) from here

https://github.com/bubibubi/JetEntityFrameworkProvider/tree/master/JetEntityFrameworkProvider.Test/Model60_StackOverflow_m2n_Person_Book

They are tests for the Microsoft Access (Jet) Entity Framework provider but is very simple to adapt them for SQL Server.

Body:
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)

Book:

BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)

PersonBook:

Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);

Here I give a simple condition:

Context.PersonBook.Where(m => m.PersonId == PersonId)

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

Body:
Not really an answer to your question but you could use the EF n-m relationships feature.

In your case the configuration should be

modelBuilder.Entity<Person>()
    .HasMany<Book>(user => user.OwnedBooks)
    .WithMany(book => book.Owners)
    .Map(mapping =>
    {
        mapping.MapLeftKey("PersonId");
        mapping.MapRightKey("BookId");
        mapping.ToTable("PersonBook");
    });

Using this configuration EF will create and handle the junction table (your PersonBook table) for you. If you enable automatic migration you will see that EF creates the table with 2 fields and a primary key on the 2 fields.

EDIT

Using these classes

public class Person
{
    public Person()
    {
        OwnedBooks = new List<Book>();
    }

    [Column("PersonId")]
    public int Id { get; set; }
    [MaxLength(50)]
    public string FirstName { get; set; }
    [MaxLength(50)]
    public string LastName { get; set; }

    public ICollection<Book> OwnedBooks { get; set; }
}

public class Book
{
    public Book()
    {
        Owners = new List<Person>();
    }

    [Column("BookId")]
    public int Id { get; set; }
    [Column("BookName")]
    [MaxLength(50)]
    public string Name { get; set; }
    [MaxLength(50)]
    public string Isbn { get; set; }
    [MaxLength(50)]
    public string Author { get; set; }

    public ICollection<Person> Owners { get; set; }
}

with the above configuration (I think that you have to use fluent interface to configure m-n relationship) you obtain this model

ExecuteNonQuery==========
CREATE TABLE [Books] (
 [BookId] int not null identity(1,1)
, [BookName] varchar(50) null
, [Isbn] varchar(50) null
, [Author] varchar(50) null
);
ALTER TABLE [Books] ADD CONSTRAINT [PK_Books_e63a83c6] PRIMARY KEY ([BookId])
ExecuteNonQuery==========
CREATE TABLE [People] (
 [PersonId] int not null identity(1,1)
, [FirstName] varchar(50) null
, [LastName] varchar(50) null
);
ALTER TABLE [People] ADD CONSTRAINT [PK_People_e63a83c6] PRIMARY KEY ([PersonId])
ExecuteNonQuery==========
CREATE TABLE [PersonBook] (
 [PersonId] int not null
, [BookId] int not null
);
ALTER TABLE [PersonBook] ADD CONSTRAINT [PK_PersonBook_e63a83c6] PRIMARY KEY ([PersonId], [BookId])
ExecuteNonQuery==========
CREATE INDEX [IX_PersonId] ON [PersonBook] ([PersonId])
ExecuteNonQuery==========
CREATE INDEX [IX_BookId] ON [PersonBook] ([BookId])
ExecuteNonQuery==========
ALTER TABLE [PersonBook] ADD CONSTRAINT [FK_PersonBook_People_PersonId] FOREIGN KEY ([PersonId]) REFERENCES [People] ([PersonId])
ExecuteNonQuery==========
ALTER TABLE [PersonBook] ADD CONSTRAINT [FK_PersonBook_Books_BookId] FOREIGN KEY ([BookId]) REFERENCES [Books] ([BookId])

Then I make some random insert/delete statements

Book book = new Book()
{
    Author = "Niccolò Ammaniti",
    Name = "Branchie"
};

book.Owners.Add(new Person() { FirstName = "Mastero" });
book.Owners.Add(new Person() { FirstName = "bubi" });

context.Books.Add(book);
context.SaveChanges();

These are the queries that EF generates

ExecuteDbDataReader==========
insert into [Books]([BookName], [Isbn], [Author])
values (@p0, null, @p1);
select [BookId]
from [Books]
where [BookId] = @@identity
@p0 = Branchie
@p1 = Niccolò Ammaniti
ExecuteDbDataReader==========
insert into [People]([FirstName], [LastName])
values (@p0, null);
select [PersonId]
from [People]
where [PersonId] = @@identity
@p0 = Mastero
ExecuteDbDataReader==========
insert into [People]([FirstName], [LastName])
values (@p0, null);
select [PersonId]
from [People]
where [PersonId] = @@identity
@p0 = bubi
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 1
@p1 = 1
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 2
@p1 = 1

Then update/delete (from Junction table but for us is transparent)

book = new Book()
{
    Author = "Niccolò Ammaniti",
    Name = "Come Dio comanda"
};

Person person = context.People.Single(_ => _.FirstName == "bubi");
person.OwnedBooks.Add(book);

context.SaveChanges();

book.Owners.Remove(person);
context.SaveChanges();

And these are the queries

ExecuteDbDataReader==========
SELECT TOP 2
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [People] AS [Extent1]
WHERE 'bubi' = [Extent1].[FirstName]
ExecuteDbDataReader==========
insert into [Books]([BookName], [Isbn], [Author])
values (@p0, null, @p1);
select [BookId]
from [Books]
where [BookId] = @@identity
@p0 = Come Dio comanda
@p1 = Niccolò Ammaniti
ExecuteNonQuery==========
insert into [PersonBook]([PersonId], [BookId])
values (@p0, @p1);

@p0 = 2
@p1 = 2
ExecuteNonQuery==========
delete from [PersonBook]
where (([PersonId] = @p0) and ([BookId] = @p1))
@p0 = 2
@p1 = 2

You can download this code (and other insteresting configurations) from here

https://github.com/bubibubi/JetEntityFrameworkProvider/tree/master/JetEntityFrameworkProvider.Test/Model60_StackOverflow_m2n_Person_Book

They are tests for the Microsoft Access (Jet) Entity Framework provider but is very simple to adapt them for SQL Server.


问:
Improving Python user defined max function
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

```<code>def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'
</code>```

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.

答:
```<code>>>> def umax(array):
    global biggest
    for num in array:
        if num > biggest:
            biggest = num

>>> biggest = int()
>>> nums = (1, 9, 6, 4, 5, 3, 2, 7, 0)
>>> umax(nums)
>>> biggest
9
</code>```

Body:
I am new to programming and am trying to understand how to "think" more programmatically in Python. I wrote a function that returns the largest element in an array without using max:

def max_userdefined(array):
    """
    Finds largest value of nonempty array of numbers in O(n)
    :param: list/tuple of values
    :return: max value
    """
    try:
        assert isinstance(array, list or tuple)
        result = array[0]
        for element in array:
            if element > result:
                result = element
        return result
    except IndexError:
        return 'Please pass in a nonempty array'
    except AssertionError:
        return 'Please pass in a list or tuple'
    except TypeError:
        return 'Please make sure elements of array are all floats or ints'

How can I improve the above code? Open to any criticism or if anyone can recommend a good Pythonic style guide.


问:
Django1.8 and Mongoengine NameError: name 'IntegerField' is not defined
I am using mongoengine with Django 1.8 and my project needs to connect to one instances of MongoDB while another with sql.But i am getting this error-

command prompt-

```<code>python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_from_command_line(sys.argv)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/var/www/html/admin_python/admin_app/models.py", line 212, in <module>
    class location(Document):
  File "/var/www/html/admin_python/admin_app/models.py", line 213, in location
    user_id = IntegerField(blank=True, null=True)
NameError: name 'IntegerField' is not defined
</code>```

my setting.py file-

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

}

from mongoengine import connect
connect(
db='pom',
username='admin',
password='root',
host='mongodb://admin:root@localhost'
)
</code>```

so First i decided to complete all work related to mongodb then i will move on to sql.This is the code for model of mongodb database

my model.py file -

```<code>class location(Document):
        user_id = IntegerField(blank=True, null=True)
        name = CharField(max_length=100)
        loc_lon = FloatField(blank=True, null=True)
        timestamp = IntegerField(blank=True, null=True)
        activity = StringField()
        lot_lat = FloatField(blank=True, null=True)
        batter_status = StringField()
        address = StringField()
        date_created = DateTimeField(auto_now_add=True)
</code>```

and plz can someone refer any MongoEngine and Django1.8 tutorial ....

答:
```<code>timestamp = IntField(blank=True, null=True)
</code>```

but its better to use

```<code>timestamp = DateTimeField(blank=True, null=True)
</code>```

as its a timestamp

Body:
I am using mongoengine with Django 1.8 and my project needs to connect to one instances of MongoDB while another with sql.But i am getting this error-

command prompt-

python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_from_command_line(sys.argv)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/var/www/html/admin_python/admin_app/models.py", line 212, in <module>
    class location(Document):
  File "/var/www/html/admin_python/admin_app/models.py", line 213, in location
    user_id = IntegerField(blank=True, null=True)
NameError: name 'IntegerField' is not defined

my setting.py file-

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    },

}

from mongoengine import connect
connect(
db='pom',
username='admin',
password='root',
host='mongodb://admin:root@localhost'
)

so First i decided to complete all work related to mongodb then i will move on to sql.This is the code for model of mongodb database

my model.py file -

class location(Document):
        user_id = IntegerField(blank=True, null=True)
        name = CharField(max_length=100)
        loc_lon = FloatField(blank=True, null=True)
        timestamp = IntegerField(blank=True, null=True)
        activity = StringField()
        lot_lat = FloatField(blank=True, null=True)
        batter_status = StringField()
        address = StringField()
        date_created = DateTimeField(auto_now_add=True)

and plz can someone refer any MongoEngine and Django1.8 tutorial ....

Body:
timestamp = IntField(blank=True, null=True)

but its better to use

timestamp = DateTimeField(blank=True, null=True)

as its a timestamp


问:
why assert_equal() in Ruby on Rails sometimes seem to compare by Identity and sometimes by value?
it was very weird that yesterday, I was do an integration test in Rails and

```<code>assert_equal array_of_obj1, array_of_obj2     # obj1 from db, obj2 created in test
</code>```

and it failed.  The values shown inside the array and objects were identical.  If I change the test to

```<code>assert array_of_obj1 == array_of_obj2
</code>```

Then it will pass.

But today, the first  test actually passed.  What reason could it be?  Is assert_equal always using == or .equal? in Rails 2.2 or 2.3.5?

答:
assert_equal does always use the == method. This behavior is from the Ruby core and is not overridden or changed in Rails.  You can read the documentation for assert_equal here.

However, it should be noted that the == method behaves differently depending on which object it is called on.

For example, an Object == method compares actual object identity. However, a String == method compares the values of the string.

ContentLicense: CC BY-SA 2.5

Body:
it was very weird that yesterday, I was do an integration test in Rails and

assert_equal array_of_obj1, array_of_obj2     # obj1 from db, obj2 created in test

and it failed.  The values shown inside the array and objects were identical.  If I change the test to

assert array_of_obj1 == array_of_obj2

Then it will pass.

But today, the first  test actually passed.  What reason could it be?  Is assert_equal always using == or .equal? in Rails 2.2 or 2.3.5?

ContentLicense: CC BY-SA 4.0


问:
I have a query reguarding publishing android game in google play?
I know how to publish an normal application in (Google Play Developer Console). I want to know how to publish a game in (Google Play Developer Console) which is implementing Game Services. My game application is running well and Game Service is working properly.But now I am confused about debug sha1 debug key and sha1 release key.
and do I have to linked my game with both debug and release sha1 keys?

答:
I think you're referring to release certificate and debug certificate which you need to keep.

You should create two client IDs, one with the release certificate
  fingerprint and another with the debug certificate fingerprint. Make
  sure to use the same package name for both. This allows Google Play
  games services to recognize calls from your linked APKs that are
  signed with either certificate. For more information about certificate
  signing for Android, see Signing Your
  Application.

When all is setup, move to Testing and Publishing Game Changes.


问:
How can I create a table within a PDF using Python?
i'm having trouble on making a basic pdf document with a table in it in python, and i'm wondering how i can get my table to show on the PDF, because i'm unsure on how it's not showing, here's the code for reference.</p>

```<code>import time
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, inch, landscape, letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

doc = SimpleDocTemplate("code challenge1.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
Story=[]

formatted_time = time.ctime()
full_name = "Mike Driscoll"
address_parts = ["411 State St.", "Marshalltown, IA 50158"]

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
ptext = '<font size=12>%s</font>' % formatted_time

Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 12))

data = [
["Activity", "Times/wk”, "Time of day", "Description"],
["B", "01", "ABCD", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"],
["E", "02", "CDEF", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"],
["E", "03", "SDFSDF", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"],
["e", "04", "SDFSDF", "DDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"],
["x", "05", "GHJGHJGHJ", "EEEEEEEEEEEEEE EEEEEEEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEE"],
]

style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
                       ('TEXTCOLOR',(1,1),(-2,-2),colors.red),
                       ('VALIGN',(0,0),(0,-1),'TOP'),
                       ('TEXTCOLOR',(0,0),(0,-1),colors.blue),
                       ('ALIGN',(0,-1),(-1,-1),'CENTER'),
                       ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ])

s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
data2 = [[Paragraph(cell, s) for cell in row] for row in data]
t=Table(data2)
t.setStyle(style)

Story.append(t)
ptext = '<font size=12>I wanted to code ever since I was young, and have done mods for videogames I liked and played. It’s been my childhood dream to create worlds and stories, and coding is the best way to script events the way you want them to go. While this may not be exactly what I’m looking for, I think it’ll give me an accurate experience of what that life is like.</font>'
Story.append(Paragraph(ptext, styles["Justify"]))

doc.build(Story)
</code>```

答:
It's just a typo - you used ” instead of " in line 26 (right double quotation mark instead of regular quotation mark).

Here's how the document looks like after fixing this:

Body:
i'm having trouble on making a basic pdf document with a table in it in python, and i'm wondering how i can get my table to show on the PDF, because i'm unsure on how it's not showing, here's the code for reference.

import time
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, inch, landscape, letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

doc = SimpleDocTemplate("code challenge1.pdf",pagesize=letter,
                        rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)
Story=[]

formatted_time = time.ctime()
full_name = "Mike Driscoll"
address_parts = ["411 State St.", "Marshalltown, IA 50158"]

styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
ptext = '%s' % formatted_time

Story.append(Paragraph(ptext, styles["Normal"]))
Story.append(Spacer(1, 12))

data = [
["Activity", "Times/wk”, "Time of day", "Description"],
["B", "01", "ABCD", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"],
["E", "02", "CDEF", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"],
["E", "03", "SDFSDF", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"],
["e", "04", "SDFSDF", "DDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"],
["x", "05", "GHJGHJGHJ", "EEEEEEEEEEEEEE EEEEEEEEEEEEEEEEE EEEEEEEEEEEEEEEEEEEE"],
]

style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'),
                       ('TEXTCOLOR',(1,1),(-2,-2),colors.red),
                       ('VALIGN',(0,0),(0,-1),'TOP'),
                       ('TEXTCOLOR',(0,0),(0,-1),colors.blue),
                       ('ALIGN',(0,-1),(-1,-1),'CENTER'),
                       ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
                       ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ])

s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
data2 = [[Paragraph(cell, s) for cell in row] for row in data]
t=Table(data2)
t.setStyle(style)

Story.append(t)
ptext = 'I wanted to code ever since I was young, and have done mods for videogames I liked and played. It’s been my childhood dream to create worlds and stories, and coding is the best way to script events the way you want them to go. While this may not be exactly what I’m looking for, I think it’ll give me an accurate experience of what that life is like.'
Story.append(Paragraph(ptext, styles["Justify"]))

doc.build(Story)


问:
Connecting to MySQL from Laravel
I set up a database called cms which I can connect to if I ssh as the root user and I can manipulate the database just fine. I also can connect with MySQL Workbench. However, when it comes to connecting through Laravel 5.4, it will not let me connect to MySQL to run a migration. I have the same credentials in my .env file as I do in MySQL Workbench, but still no connection. Any ideas?

Below is what I have in my .env file

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cms
DB_USERNAME=root
DB_PASSWORD=
</code>```

答:
Via SSH you are able to connect to MySQL as root without a password, because that is the default behavior. It allows the local Linux root user to login as root on MySQL with no password.

When you want to connect not locally (via SSH) but instead via TCP/IP or a socket using the PHP mysql library, then you need to setup a user for that.

Here is how to do it:

1) Log in via SSH as you normally did, and with root access MySQL

2) Create a user:

```<code>CREATE USER 'laravel'@'%' IDENTIFIED BY 'ENTER-PASSWORD-HERE';
</code>```

3) Grant permissions to that user on your database:

```<code>GRANT ALL PRIVILEGES ON cms.* TO 'laravel'@'%';
</code>```

4) Flush permissions so that everything reloads:

```<code>FLUSH PRIVILEGES;
</code>```

5) Now exit SSH and edit your .env file like this:

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cms
DB_USERNAME=laravel
DB_PASSWORD=ENTER-PASSWORD-HERE
</code>```

Of course, please change the placeholder "ENTER-PASSWORD-HERE" to something of your preference.

You should now be able to connect from your application.

Title: Connecting to MySQL from Laravel

Body:
I set up a database called cms which I can connect to if I ssh as the root user and I can manipulate the database just fine. I also can connect with MySQL Workbench. However, when it comes to connecting through Laravel 5.4, it will not let me connect to MySQL to run a migration. I have the same credentials in my .env file as I do in MySQL Workbench, but still no connection. Any ideas?

Below is what I have in my .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cms
DB_USERNAME=root
DB_PASSWORD=

Body:
Via SSH you are able to connect to MySQL as root without a password, because that is the default behavior. It allows the local Linux root user to login as root on MySQL with no password.

When you want to connect not locally (via SSH) but instead via TCP/IP or a socket using the PHP mysql library, then you need to setup a user for that.

Here is how to do it:

1) Log in via SSH as you normally did, and with root access MySQL

2) Create a user:

CREATE USER 'laravel'@'%' IDENTIFIED BY 'ENTER-PASSWORD-HERE';

3) Grant permissions to that user on your database:

GRANT ALL PRIVILEGES ON cms.* TO 'laravel'@'%';

4) Flush permissions so that everything reloads:

FLUSH PRIVILEGES;

5) Now exit SSH and edit your .env file like this:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cms
DB_USERNAME=laravel
DB_PASSWORD=ENTER-PASSWORD-HERE

Of course, please change the placeholder "ENTER-PASSWORD-HERE" to something of your preference.

You should now be able to connect from your application.


问:
Nothing is being printed out from a Flink Patterned Stream
I have this code below:

```<code>import java.util.Properties

import com.google.gson._
import com.typesafe.config.ConfigFactory
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.cep.scala.CEP
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010
import org.apache.flink.streaming.util.serialization.SimpleStringSchema

object WindowedWordCount {
  val configFactory = ConfigFactory.load()
  def main(args: Array[String]) = {
    val brokers = configFactory.getString("kafka.broker")
    val topicChannel1 = configFactory.getString("kafka.topic1")

    val props = new Properties()
    ...

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

    val dataStream = env.addSource(new FlinkKafkaConsumer010[String](topicChannel1, new SimpleStringSchema(), props))

    val partitionedInput = dataStream.keyBy(jsonString => {
      val jsonParser = new JsonParser()
      val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
      jsonObject.get("account")
    })

    val priceCheck = Pattern.begin[String]("start").where({jsonString =>
      val jsonParser = new JsonParser()
      val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
      jsonObject.get("account").toString == "iOS"})

    val pattern = CEP.pattern(partitionedInput, priceCheck)

    val newStream = pattern.select(x =>
      x.get("start").map({str =>
        str
      })
    )

    newStream.print()

    env.execute()
  }
}
</code>```

For some reason in the above code at the newStream.print() nothing is being printed out. I am positive that there is data in Kafka that matches the pattern that I defined above but for some reason nothing is being printed out.

Can anyone please help me spot an error in this code?

EDIT:

```<code>class TimestampExtractor extends AssignerWithPeriodicWatermarks[String] with Serializable {

  override def extractTimestamp(e: String, prevElementTimestamp: Long) = {
    val jsonParser = new JsonParser()
    val context = jsonParser.parse(e).getAsJsonObject.getAsJsonObject("context")
    Instant.parse(context.get("serverTimestamp").toString.replaceAll("\"", "")).toEpochMilli
  }

  override def getCurrentWatermark(): Watermark = {
    new Watermark(System.currentTimeMillis())
  }
}
</code>```

I saw on the flink doc that you can just return prevElementTimestamp in the extractTimestamp method (if you are using Kafka010) and new Watermark(System.currentTimeMillis) in the getCurrentWatermark method.

But I don't understand what prevElementTimestamp is or why one would return new Watermark(System.currentTimeMillis) as the WaterMark and not something else. Can you please elaborate on why we do this on how WaterMark and EventTime work together please?

答:
You do setup your job to work in EventTime, but you do not provide  timestamp and watermark extractor.

For more on working in event time see those docs. If you want to use the kafka embedded timestamps this docs may help you.

In EventTime the CEP library buffers events upon watermark arrival so to properly handle out-of-order events. In your case there are no watermarks generated, so the events are buffered infinitly.

Edit:

For the prevElementTimestamp I think the docs are pretty clear:

There is no need to define a timestamp extractor when using the timestamps from Kafka. The previousElementTimestamp argument of the extractTimestamp() method contains the timestamp carried by the Kafka message.

Since Kafka 0.10.x Kafka messages can have embedded timestamp.

Generating Watermark as new Watermark(System.currentTimeMillis) in this case is not a good idea. You should create Watermark based on your knowledge of the data. For information on how Watermark and EventTime work together I could not be more clear than the docs

Body:
I have this code below:

import java.util.Properties

import com.google.gson._
import com.typesafe.config.ConfigFactory
import org.apache.flink.cep.scala.pattern.Pattern
import org.apache.flink.cep.scala.CEP
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer010
import org.apache.flink.streaming.util.serialization.SimpleStringSchema

object WindowedWordCount {
  val configFactory = ConfigFactory.load()
  def main(args: Array[String]) = {
    val brokers = configFactory.getString("kafka.broker")
    val topicChannel1 = configFactory.getString("kafka.topic1")

    val props = new Properties()
    ...

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

    val dataStream = env.addSource(new FlinkKafkaConsumer010[String](topicChannel1, new SimpleStringSchema(), props))

    val partitionedInput = dataStream.keyBy(jsonString => {
      val jsonParser = new JsonParser()
      val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
      jsonObject.get("account")
    })

    val priceCheck = Pattern.begin[String]("start").where({jsonString =>
      val jsonParser = new JsonParser()
      val jsonObject = jsonParser.parse(jsonString).getAsJsonObject()
      jsonObject.get("account").toString == "iOS"})

    val pattern = CEP.pattern(partitionedInput, priceCheck)

    val newStream = pattern.select(x =>
      x.get("start").map({str =>
        str
      })
    )

    newStream.print()

    env.execute()
  }
}

For some reason in the above code at the newStream.print() nothing is being printed out. I am positive that there is data in Kafka that matches the pattern that I defined above but for some reason nothing is being printed out.

Can anyone please help me spot an error in this code?

EDIT:

class TimestampExtractor extends AssignerWithPeriodicWatermarks[String] with Serializable {

  override def extractTimestamp(e: String, prevElementTimestamp: Long) = {
    val jsonParser = new JsonParser()
    val context = jsonParser.parse(e).getAsJsonObject.getAsJsonObject("context")
    Instant.parse(context.get("serverTimestamp").toString.replaceAll("\"", "")).toEpochMilli
  }

  override def getCurrentWatermark(): Watermark = {
    new Watermark(System.currentTimeMillis())
  }
}

I saw on the flink doc that you can just return prevElementTimestamp in the extractTimestamp method (if you are using Kafka010) and new Watermark(System.currentTimeMillis) in the getCurrentWatermark method.

But I don't understand what prevElementTimestamp is or why one would return new Watermark(System.currentTimeMillis) as the WaterMark and not something else. Can you please elaborate on why we do this on how WaterMark and EventTime work together please?


问:
Change foreach loop by for loop
I am creating a Fingerprint Verification System in which I have to match fingerprints using records in database.  I have used foreach loop to to so but it is taking almost 40 seconds for only 350 records.  I want to speed it up.  I want my foreach loop to convert into for loop but I am facing some difficulties in initializing the for loop.  Here is my code.

foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + tt.Key.ToString();
    }));
    temp = new DPFP.Template(tt.Value);

    Verificator = new DPFP.Verification.Verification();
    featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
    if (featuresForVerification != null)
    {
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        Verificator.Verify(featuresForVerification, temp, ref result);

        #region UI Envoke
        this.Invoke(new Function(delegate()
        {
            if (result.Verified)
            {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + tt.Key.ToString());
            }
            else
            {
                //MessageBox.Show("No Match");
            }
        }));
        #endregion
    }
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value += 1;
    }));
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
}
```

I am confused at the first line foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic).  Can someone tell me how I can iterate through every item in Dictionary object profileDic using a for loop.  I am not sure how to get KeyValuePair<decimal, MemoryStream> tt in profileDic when using a for loop.

答: Instead of changing it to Foreach Loop from For Loop, You might actually want to add like Exit For or Break; in c# once you already find the result.</p>

Title: Change foreach loop by for loop

Body:
I am creating a Fingerprint Verification System in which I have to match fingerprints using records in database.  I have used foreach loop to to so but it is taking almost 40 seconds for only 350 records.  I want to speed it up.  I want my foreach loop to convert into for loop but I am facing some difficulties in initializing the for loop.  Here is my code.

foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic)
{
    this.Invoke(new Function(delegate()
    {
        textBox1.Text += "\n" + tt.Key.ToString();
    }));
    temp = new DPFP.Template(tt.Value);

    Verificator = new DPFP.Verification.Verification();
    featuresForVerification = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification);
    if (featuresForVerification != null)
    {
        DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
        Verificator.Verify(featuresForVerification, temp, ref result);

        #region UI Envoke
        this.Invoke(new Function(delegate()
        {
            if (result.Verified)
            {
                MessageBox.Show("FAR " + result.FARAchieved + "\n" + tt.Key.ToString());
            }
            else
            {
                //MessageBox.Show("No Match");
            }
        }));
        #endregion
    }
    this.Invoke(new Function(delegate()
    {
        progressBar1.Value += 1;
    }));
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
}

I am confused at the first line foreach (KeyValuePair<decimal, MemoryStream> tt in profileDic).  Can someone tell me how I can iterate through every item in Dictionary object profileDic using a for loop.  I am not sure how to get KeyValuePair<decimal, MemoryStream> tt in profileDic when using a for loop.


问:
How to rotate 4 (or more) images, fading between each one?
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

```<code><img src="/images/image-1.jpg" id="featureImg1" />
<img src="/images/image-2.jpg" id="featureImg2" style="display:none;" />
<img src="/images/image-3.jpg" id="featureImg3" style="display:none;" />
<img src="/images/image-4.jpg" id="featureImg4" style="display:none;" />
</code>```

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.

答: I'd highly recommend the jQuery Cycle plugin. It may do more than you're looking for in this case, but it's well structured and easy to setup. There's also a lightweight version called jQuery Cycle Lite which just supports fade transitions.</p>

OwnerDisplayName: Darryl Hein

Body:
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.

OwnerDisplayName: Taeram


问:
How to fix NotOfficeXmlFileException in java Apache POI?
I'm trying to create a new excel file with just "hello" in it.
Here's my code:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author kamal
 */
public class JavaApplication4 {
    private static String dir = "";
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            JFileChooser jc = new JFileChooser();
                        jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int output = jc.showOpenDialog(null);
            if(output == JFileChooser.APPROVE_OPTION){
                File f = jc.getSelectedFile();
                String directory = f.getAbsolutePath();
                setDir(directory);
            }

            FileOutputStream out = new FileOutputStream(new File(getDir()+"\\Book2.xlsx"));
            FileInputStream in = new FileInputStream(new File(getDir()+"\\Book2.xlsx"));

           org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(in);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

           sheet.createRow(0).createCell(0).setCellValue("hello");

            workbook.write(out);
            workbook.close();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * @return the dir
     */
    public static String getDir() {
        return dir;
    }

    /**
     * @param dir the dir to set
     */
    public static void setDir(String directory) {
        dir = directory;
    }

}
</code>```

..And when I run it I get the following error:

Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
    at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
    at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
    at javaapplication4.JavaApplication4.main(JavaApplication4.java:46)
C:\Users\kamal\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 7 seconds)
```

I looked up this code in youtube and it's same but i'm not sure why am i getting the error? Can you help me with this?

答:
I think the most likely explanations are that either the file is corrupt, or it is an older format spreadsheet file that XSSFWorkbook does not understand.

It is unlikely anyone can give you a definite diagnosis without looking at the file itself.

Body:
I'm trying to create a new excel file with just "hello" in it.
Here's my code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author kamal
 */
public class JavaApplication4 {
    private static String dir = "";
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            // TODO code application logic here
            JFileChooser jc = new JFileChooser();
                        jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int output = jc.showOpenDialog(null);
            if(output == JFileChooser.APPROVE_OPTION){
                File f = jc.getSelectedFile();
                String directory = f.getAbsolutePath();
                setDir(directory);
            }

            FileOutputStream out = new FileOutputStream(new File(getDir()+"\\Book2.xlsx"));
            FileInputStream in = new FileInputStream(new File(getDir()+"\\Book2.xlsx"));

           org.apache.poi.ss.usermodel.Workbook workbook = new XSSFWorkbook(in);
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

           sheet.createRow(0).createCell(0).setCellValue("hello");

            workbook.write(out);
            workbook.close();

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            Logger.getLogger(JavaApplication4.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * @return the dir
     */
    public static String getDir() {
        return dir;
    }

    /**
     * @param dir the dir to set
     */
    public static void setDir(String directory) {
        dir = directory;
    }

}

..And when I run it I get the following error:

Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
    at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
    at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
    at javaapplication4.JavaApplication4.main(JavaApplication4.java:46)
C:\Users\kamal\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 7 seconds)

I looked up this code in youtube and it's same but i'm not sure why am i getting the error? Can you help me with this?


问:
Hide errors and warnings from console
In PHP and other languages there are ways to suppress error/warning messages.

Is there a way in javascript or jquery to prevent errors and warnings from being written to the console log?

答:
you just simply add some chunk of code into the script it will works.!
Chrome:

```<code>console._commandLineAPI.clear();
</code>```

Safari:

```<code>console._inspectorCommandLineAPI.clear();
</code>```

You can create your own variable, which works in both:

```<code>if (typeof console._commandLineAPI !== 'undefined') {
    console.API = console._commandLineAPI;
} else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
    console.API = console._inspectorCommandLineAPI;
} else if (typeof console.clear !== 'undefined') {
    console.API = console;
}
</code>```

After that, you can simply use

```<code>console.API.clear().
</code>```

Title: Hide errors and warnings from console

Body:
you just simply add some chunk of code into the script it will works.!
Chrome:

console._commandLineAPI.clear();

Safari:

console._inspectorCommandLineAPI.clear();

You can create your own variable, which works in both:

if (typeof console._commandLineAPI !== 'undefined') {
    console.API = console._commandLineAPI;
} else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
    console.API = console._inspectorCommandLineAPI;
} else if (typeof console.clear !== 'undefined') {
    console.API = console;
}

After that, you can simply use

console.API.clear().


问:
How to draw a round image with PDFsharp
I am using PDFsharp to make a PDF file, and have succeeded to put an image on my page.

```<code>        byte[] imgBytes = interview.Application.CandidateImage.ImageBinary.ToArray();
        Stream stream = new MemoryStream(imgBytes);
        MemoryStream strm = new MemoryStream();
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        img.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

        XImage xfoto = XImage.FromGdiPlusImage(img);

        gfx.DrawImage(xfoto, 30, 130, 300, 300);
</code>```

This gets the binary image data and the DrawImage will draw this image retrieved from the stream.

The thing is, I want to make the image round just as if I used img-circle class on HTML. Is there a function for this with PDFsharp? If not, how can I do this?

EDIT:

```<code>    void DrawClipPath(XGraphics gfx, PdfPage page)
    {

        XGraphicsPath path = new XGraphicsPath();
        path.AddEllipse((page.Width / 2) - 150, (page.Height / 2) - 120, 300, 300);
        gfx.Save();
        gfx.IntersectClip(path);

        // Draw a beam of dotted lines
        XPen pen = XPens.DarkRed.Clone();
        pen.DashStyle = XDashStyle.Dot;
        for (double r = 0; r <= 90; r += 0.5)
            gfx.DrawLine(pen, 0, 0, 250 * Math.Cos(r / 90 * Math.PI), 250 * Math.Sin(r / 90 * Math.PI));

        gfx.Restore();

    }
</code>```

答:
You can set a circle as a clip path and then draw the image. You have to save the graphic state (XGraphics.Save) before setting the clip path and then restore it (XGraphics.Restore) after you drew all the objects that needed to be clipped.

EDIT: I'm not familiar with PDFSharp API but the code would look something like this:

```<code>gfx.Save();
XGraphicsPath clipPath = new XGraphicsPath();
clipPath.AddEllipse(30, 130, 300, 300);
gfx.IntersectClip(clipPath);
gfx.DrawImage(xfoto, 30, 130, 300, 300);
gfx.Restore();
</code>```

Title: How to draw a round image with PDFsharp

Body:
I am using PDFsharp to make a PDF file, and have succeeded to put an image on my page.

        byte[] imgBytes = interview.Application.CandidateImage.ImageBinary.ToArray();
        Stream stream = new MemoryStream(imgBytes);
        MemoryStream strm = new MemoryStream();
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        img.Save(strm, System.Drawing.Imaging.ImageFormat.Png);

        XImage xfoto = XImage.FromGdiPlusImage(img);

        gfx.DrawImage(xfoto, 30, 130, 300, 300);

This gets the binary image data and the DrawImage will draw this image retrieved from the stream.

The thing is, I want to make the image round just as if I used img-circle class on HTML. Is there a function for this with PDFsharp? If not, how can I do this?

EDIT:

    void DrawClipPath(XGraphics gfx, PdfPage page)
    {

        XGraphicsPath path = new XGraphicsPath();
        path.AddEllipse((page.Width / 2) - 150, (page.Height / 2) - 120, 300, 300);
        gfx.Save();
        gfx.IntersectClip(path);

        // Draw a beam of dotted lines
        XPen pen = XPens.DarkRed.Clone();
        pen.DashStyle = XDashStyle.Dot;
        for (double r = 0; r <= 90; r += 0.5)
            gfx.DrawLine(pen, 0, 0, 250 * Math.Cos(r / 90 * Math.PI), 250 * Math.Sin(r / 90 * Math.PI));

        gfx.Restore();

    }

Body:
You can set a circle as a clip path and then draw the image. You have to save the graphic state (XGraphics.Save) before setting the clip path and then restore it (XGraphics.Restore) after you drew all the objects that needed to be clipped.

EDIT: I'm not familiar with PDFSharp API but the code would look something like this:

gfx.Save();
XGraphicsPath clipPath = new XGraphicsPath();
clipPath.AddEllipse(30, 130, 300, 300);
gfx.IntersectClip(clipPath);
gfx.DrawImage(xfoto, 30, 130, 300, 300);
gfx.Restore();


问:
Global Js not working in Dynamicaly created Component Angular 2
I am creating a chat app using angular 2 .
angular-cli: 1.0.0-beta.28.3

My chat boxes are loading dynamically .

I am using material design lite for design.
I have included material design lite js file in index.html which should work globally in all components.

But the material design lite js is only workng in app.component
not in the dynamically generated component.

My component hierarchyis:

-- App Component
       -- Connection Component
           -- ChatRoom Component

The App Component and Connection Component gets loaded on app start.
The ChatRoom Component loads dynamically on button click.

答: You should use Angular Material instead of material design lite. Angular material gives all the components which are available in other material design libraries but can be integrated with Angular with ease.</p>