问:
How do I set text-overflow to ellipsis in CSS grid layout?
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div></code>```

答:
Add overflow: hidden and white-space: nowrap when you used text-overflow

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div></code>```

Body:
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}

Left

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Right

  <content>
  </content>

Body:
Add overflow: hidden and white-space: nowrap when you used text-overflow

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

<div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div>


来源: stackexchange

问:
Not able to publish azure service to remote cluster
When i Am clicking Publish

It is showing Following Powershell Error:

答:
Finally Found the solution
Created a new azure cluster and deployed to it and it worked!</p>

ContentLicense: CC BY-SA 3.0


问:
Having bad requests in Paypal express checkput client side rest
I have laravel project and want to integrate paypal express checkout using client side rest. I have several problems.

Clicking on paypal button for making payment I have these errors:

```
POST https://c.paypal.com/v1/r/d/b/p1 400 (Bad Request)
POST https://c.paypal.com/v1/r/d/b/p2 400 (Bad Request)
GET https://c6.paypal.com/v1/r/d/b/p3?f=EC-19893223FU9150749&s=HERMES_SIGNIN 400 (Bad Request)
```

Also have this error:

Request listener already exists for xcomponent_delegate_ppcheckout on domain * for specified window

but I don't have listeners.js in my project

And last question. Do I need to have curl request to paypal api, if I am using client side rest.

This is my code.

```<code>  paypal.Button.render({
        env: 'sandbox', // sandbox | production
        client: {
        sandbox:    'AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R',
        production: 'EFPOKHzlSKXUGm9z615EopgdiqkKqVTfMayOzyadr06mWDe3NwaIKwBr7yZTpKZQbLisQ8WT5vIh2gyn'
    },
    commit: true,
    payment: function(actions) {
        return actions.payment.create({
            transactions: [
                {
                    amount: { total: '5', currency: 'USD' }
                }
            ]
        });
    },
    onAuthorize: function(data, actions) {
        return actions.payment.execute().then(function() {
            window.alert('Payment Complete!');
            console.log('The payment was authorized!');
            console.log('Payment ID = ',   data.paymentID);
            console.log('PayerID = ', data.payerID);
        });
    },
    onCancel: function(data) {
        console.log('The payment was cancelled!');
    }

}, '#paypal-button-container');
</code>```

I was looking on this tutorial:

https://github.com/paypal/paypal-checkout/blob/master/docs/paypal-rest-api.md

There are curl requests, but can anyone explain why do we need those curl request in client side case. Thanks a lot.

答:
I was seeing 400's and 401's too - not only in my own code, but in the live demo's on PayPal's site.

I contacted my account manager and sent some logs etc, and was told this is a sandbox issue and it should be fine on the production system. Indeed, switching to production the pop up opens successfully every time.

So it seems the advice for now is ignore the occasional failures on the sandbox, production works fine! I plan to do some final testing on the live system before rolling out the change.

You don't need any of the curl logic from that link for client side, the Javascript you've posted should be all you need. I'd recommend building off PayPal's samples here: https://developer.paypal.com/demo/checkout/#/pattern/client, and the REST API docs here in case any of the other JSON fields are useful: https://developer.paypal.com/docs/api/payments/#payment_create

Body:
I have laravel project and want to integrate paypal express checkout using client side rest. I have several problems.

Clicking on paypal button for making payment I have these errors:

POST https://c.paypal.com/v1/r/d/b/p1 400 (Bad Request)
POST https://c.paypal.com/v1/r/d/b/p2 400 (Bad Request)
GET https://c6.paypal.com/v1/r/d/b/p3?f=EC-19893223FU9150749&s=HERMES_SIGNIN 400 (Bad Request)

Also have this error:

Request listener already exists for xcomponent_delegate_ppcheckout on domain * for specified window

but I don't have listeners.js in my project

And last question. Do I need to have curl request to paypal api, if I am using client side rest.

This is my code.

  paypal.Button.render({
        env: 'sandbox', // sandbox | production
        client: {
        sandbox:    'AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R',
        production: 'EFPOKHzlSKXUGm9z615EopgdiqkKqVTfMayOzyadr06mWDe3NwaIKwBr7yZTpKZQbLisQ8WT5vIh2gyn'
    },
    commit: true,
    payment: function(actions) {
        return actions.payment.create({
            transactions: [
                {
                    amount: { total: '5', currency: 'USD' }
                }
            ]
        });
    },
    onAuthorize: function(data, actions) {
        return actions.payment.execute().then(function() {
            window.alert('Payment Complete!');
            console.log('The payment was authorized!');
            console.log('Payment ID = ',   data.paymentID);
            console.log('PayerID = ', data.payerID);
        });
    },
    onCancel: function(data) {
        console.log('The payment was cancelled!');
    }

}, '#paypal-button-container');

I was looking on this tutorial:

https://github.com/paypal/paypal-checkout/blob/master/docs/paypal-rest-api.md

There are curl requests, but can anyone explain why do we need those curl request in client side case. Thanks a lot.


问:
Opposite of cache prefetch hint
Is there a hint I can put in my code indicating that a line should be removed from cache? As opposed to a prefetch hint, which would indicate I will soon need a line. In my case, I know when I won't need a line for a while, so I want to be able to get rid of it to free up space for lines I do need.

答:
clflush, clflushopt

Invalidates from every level of the cache hierarchy in the cache coherence domain the cache line that contains the
  linear address specified with the memory operand. If that cache line contains modified data at any level of the
  cache hierarchy, that data is written back to memory.

They are not available on every CPU (in particular, clflushopt is only available on the 6th generation and later). To be certain, you should use CPUID to verify their availability:

The availability of CLFLUSH is indicated by the presence of the CPUID feature flag CLFSH
  (CPUID.01H:EDX[bit 19]).

The availability of CLFLUSHOPT is indicated by the presence of the CPUID feature flag CLFLUSHOPT
  (CPUID.(EAX=7,ECX=0):EBX[bit 23]).

If available, you should use clflushopt. It outperforms clflush when flushing buffers larger than 4KiB (64 lines).

This is the benchmark from Intel's Optimization Manual:

For informational purpose (assuming you are running in a privileged context), you can also use invd (as a nuke-from-orbit option). This:

Invalidates (flushes) the processor’s internal caches and issues a special-function bus cycle that directs external
  caches to also flush themselves. Data held in internal caches is not written back to main memory.

or wbinvd, which:

Writes back all modified cache lines in the processor’s internal cache to main memory and invalidates (flushes) the
  internal caches. The instruction then issues a special-function bus cycle that directs external caches to also write
  back modified data and another bus cycle to indicate that the external caches should be invalidated.

A future instruction that could make it into the ISA is club. Although this won't fit your need (because it doesn't necessarily invalidate the line), it's worth mentioning for completeness. This would:

Writes back to memory the cache line (if dirty) that contains the linear address specified with the memory
  operand from any level of the cache hierarchy in the cache coherence domain. The line may be retained in the
  cache hierarchy in non-modified state. Retaining the line in the cache hierarchy is a performance optimization
  (treated as a hint by hardware) to reduce the possibility of cache miss on a subsequent access. Hardware may
  choose to retain the line at any of the levels in the cache hierarchy, and in some cases, may invalidate the line
  from the cache hierarchy.

Title: Opposite of cache prefetch hint


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答: I'm not 100% familiar with C#, but I've seen implicit operators used to map one type to another before.  Can you create an implicit operator for the Enum type that allows you to use it as an int?</p>

ContentLicense: CC BY-SA 2.5

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

OwnerDisplayName: Matthew Brubaker


问:
how to run an oracle script using php
I've started a project where the user can either connect to a mySQL database or an oracle database. I got the mySQL part down but oracle is being a bit difficult. Standard queries work such as SELECT * FROM author, but when I try to load a script in order to create the schema I get invalid operation errors. I've tried using 'START' and '@' in various ways but to no avail. These commands work in the command line but not in php. I've tried the following:

```<code>else if($databaseType == "Oracle")
{
$c = oci_connect($username, $password, $server);
     if (!$c) {
       echo "Unable to connect: " . var_dump( oci_error() );
       die();
     }

    // Delete previous schema
    $s = oci_parse($c, "@/oracle/dropall");
    oci_execute($s, OCI_DEFAULT);

    // Create schema
    $s = oci_parse($c, "@/oracle/oracle");
    oci_execute($s, OCI_DEFAULT);

    // Create first trigger
    $s = oci_parse($c, "@/oracle/oracle_trigger1");
    oci_execute($s, OCI_DEFAULT);

    // Create second trigger
    $s = oci_parse($c, "@/oracle/oracle_trigger2");
    oci_execute($s, OCI_DEFAULT);

    // Populate the database
    $s = oci_parse($c, "@/oracle/oracle_populate");
    oci_execute($s, OCI_DEFAULT);

    // Commit to save changes...
    oci_commit($c);

    // Logoff from Oracle...
    oci_free_statement($s);
    oci_close($c);
}
</code>```

答:
OCI_PARSE

resource oci_parse ( resource $connection , string $sql_text )

It expecting a SQL statement instead of file name.

You want to try:

```<code> $s = oci_parse($c, file_get_contents('/oracle/dropall'));
</code>```

Title: how to run an oracle script using php

Body:
I've started a project where the user can either connect to a mySQL database or an oracle database. I got the mySQL part down but oracle is being a bit difficult. Standard queries work such as SELECT * FROM author, but when I try to load a script in order to create the schema I get invalid operation errors. I've tried using 'START' and '@' in various ways but to no avail. These commands work in the command line but not in php. I've tried the following:

else if($databaseType == "Oracle")
{
$c = oci_connect($username, $password, $server);
     if (!$c) {
       echo "Unable to connect: " . var_dump( oci_error() );
       die();
     }

    // Delete previous schema
    $s = oci_parse($c, "@/oracle/dropall");
    oci_execute($s, OCI_DEFAULT);

    // Create schema
    $s = oci_parse($c, "@/oracle/oracle");
    oci_execute($s, OCI_DEFAULT);

    // Create first trigger
    $s = oci_parse($c, "@/oracle/oracle_trigger1");
    oci_execute($s, OCI_DEFAULT);

    // Create second trigger
    $s = oci_parse($c, "@/oracle/oracle_trigger2");
    oci_execute($s, OCI_DEFAULT);

    // Populate the database
    $s = oci_parse($c, "@/oracle/oracle_populate");
    oci_execute($s, OCI_DEFAULT);

    // Commit to save changes...
    oci_commit($c);

    // Logoff from Oracle...
    oci_free_statement($s);
    oci_close($c);
}

Body:
OCI_PARSE

resource oci_parse ( resource $connection , string $sql_text )

It expecting a SQL statement instead of file name.

You want to try:

 $s = oci_parse($c, file_get_contents('/oracle/dropall'));


问:
PHP equivalent passwords hashing of the following .NET code
I don't really want to dump some code and expect answers but this is a pretty lengthy function that hashes a password in order to later compare it to the database-stored value.

I have seen posts where people wasted time trying to recreate what they could achieve with the md5() function in PHP.

For that reason, I'm wondering if someone with any encryption knowledge knows of a PHP equivalent to achieve the following effect in PHP:

```<code>    internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
        int derivedLength = passwordBytes.Length + saltBytes.Length;
        byte[] passwordSaltBytes = new byte[derivedLength];
        byte[] pbkdf2Bytes;
        string encryptedString;

        for (int i = 0; i < passwordBytes.Length; i++)
        {
            passwordSaltBytes[i] = passwordBytes[i];
        }

        for (int i = 0; i < saltBytes.Length; i++)
        {
            passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
        }

        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
        {
            pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
        }

        using (SHA512 sha512 = new SHA512Managed())
        {
            byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
            byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            encryptedString = Convert.ToBase64String(hashSaltBytes);
        }

        return encryptedString;
    }
</code>```

If it changes anything, I'm using Laravel...

Thank you for any guidance

I hate encryption :D

```<code>$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P@$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;

echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');
</code>```

答:
Read the PHP manual for password_hash and password_verify. I recommend using BCrypt as the algorithm.

http://php.net/manual/en/function.password-hash.php

http://php.net/manual/en/function.password-verify.php

It's not difficult at all! Good luck! :-)

Also, SHA-512 isn't all that secure. Read here: SHA1 vs md5 vs SHA256: which to use for a PHP login?

Body:
I don't really want to dump some code and expect answers but this is a pretty lengthy function that hashes a password in order to later compare it to the database-stored value.

I have seen posts where people wasted time trying to recreate what they could achieve with the md5() function in PHP.

For that reason, I'm wondering if someone with any encryption knowledge knows of a PHP equivalent to achieve the following effect in PHP:

    internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
        int derivedLength = passwordBytes.Length + saltBytes.Length;
        byte[] passwordSaltBytes = new byte[derivedLength];
        byte[] pbkdf2Bytes;
        string encryptedString;

        for (int i = 0; i < passwordBytes.Length; i++)
        {
            passwordSaltBytes[i] = passwordBytes[i];
        }

        for (int i = 0; i < saltBytes.Length; i++)
        {
            passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
        }

        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
        {
            pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
        }

        using (SHA512 sha512 = new SHA512Managed())
        {
            byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
            byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            encryptedString = Convert.ToBase64String(hashSaltBytes);
        }

        return encryptedString;
    }

If it changes anything, I'm using Laravel...

Thank you for any guidance

I hate encryption :D

$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P@$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;

echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');


问:
Should I use OOP when encapsulation is essentially ignored?
I am making a Mathematics web program which allows the user to compute and prove various quantities or statements, e.g. determinant of a matrix, intersection of sets, determine whether a given map is a homomorphism. I decided to write the code using the OOP paradigm (in PHP, to handle some of the super heavy computations that a user's browser might not appreciate), since I could easily declare sets as Set objects, matrices as Matrix objects, etc. and keep some of the messy details of determining things such as cardinality, determinants, etc. in the background. However, after getting knee-deep in code, I'm wondering if deciding on OOP was a mistake. Here's why.

I'll use my Matrix class as a simple example. Matrix has the following attributes:

name (type String) (stores name of this matrix)

size (type array) (stores # rows and # columns of this matrix)

entries (type array) (stores this matrix's entries)

is_invertible (type Boolean) (stores whether this matrix can be inverted)

determinant (type Int) (stores the determinant of this matrix)

transpose (type array) (stores the transpose of this matrix)

Creating a new matrix called A would be done like so:

$A = new Matrix("A");

Now, in a general math problem concerning matrices, it could be that we know the matrix's name, size, entries, whether it's invertible, its determinant, or its transpose, or any combination of the above. This means that all of these properties need to be accessible, and certainly any of these properties can be changed by the user, depending on what's given in the problem. (I can give examples of problems for any of these cases, if needed.)

The issue I'm having, then, is that this would break the encapsulation "rule" of OOP ("rule" in quotes since, from what I understand, it's not a hard-and-fast rule, just one that should be upheld to the greatest extent possible). I did some searching on when getters and setters should be used, or even IF they should be used (seems odd to me that they wouldn't, in an OOP setting...), but this did not seem to help me much, as I found many contradictory answers and case-specific opinions.

So, my overall questions are: when the user needs access to modify many (if not all) of an object's attributes, but a class-oriented design seems to be ideal for addressing the programming problem,

Is OOP the best way to structure the code, despite essentially ignoring encapsulation altogether?

Is there an alternative to OOP which allows high user access while maintaining the OO "flavor" (i.e. keeping sets, matrices, etc. as objects)

Is it ok to break the encapsulation rule altogether once in a while, if the problem calls for it? Or is that not in the spirit of OOP?

答:
What you are trying to do is not necessarily outside the scope of OOP. The thing is that you have a different model than what would usually be described in programming textbooks (where, for example, the values of the matrix would be always present and all of the functions could be simple methods). (Perhaps this is why the question was unfairly downvoted.) Nothing prevents you from storing values like "is_invertible" internally and implementing setter and getter methods. Doing this might make sense if you are trying to learn OOP. But I think other problems (see coding textbooks) might be easier for learning purposes. I see that a remote goal would be to capture some of mathematics as an OOP framework. But the whole mathematical universe is immensely richer than any fixed architecture (results like Gödel's theorem put a theoretical limit). You can only succeed in developing a framework for a very narrow application, for example solving certain equations. That's what symbolic algebra programs do: you can look at how, for example, SymPy or perhaps parts of Maple and Mathematica are implemented. In my view, the OOP paradigm can be both very useful and too restrictive / unnecessary depending on the task (you can certainly find more about shorcomings of OOP in Wikipedia or elsewhere). Also, your problem can be seen as writing a small programming language - in many of them you have sets, numbers, etc as objects.

You can use only rudimentary OOP or no OOP at all. You can use functional programming.

You should Google/read more about this on this or other sites. Is it OK to sometimes walk across the road when the red traffic light is on?


问:
VBA - Application.OnTime works overnight but not over weekend
I have a report I wish to run on Monday mornings, so the weekly reports are ready for when the office opens. The Macro runs a main report, saving different versions of it, and also opens and updates several Access databases.

I use Application.OnTime to automate this. I have been testing it for weeks and it works fine when I set it to run overnight (i.e. for the next day) but I have not been able to get it to work on Monday morning, when left from Friday afternoon.

Here is the timing code:

```<code>Private Sub Workbook_Open()

Application.OnTime TimeValue("05:00:00"), "Timer"

End Sub

Sub Timer()

If Weekday(Date) = vbMonday Then
Call MainMacro
Else
Exit Sub
End If

End Sub
</code>```

I run the Application.OnTime sub and then leave the workbook open.

Thanks

答:
Once the OnTime event has occurred, and your Timer subroutine has been called, and you have chosen to do nothing - that's the end.

You actually need to set a new OnTime event on Saturday, so it will run on Sunday, and then on Monday.

```<code>Private Sub Workbook_Open()
    Application.OnTime TimeValue("05:00:00"), "Timer"
End Sub

Sub Timer()
    If Weekday(Date) = vbMonday Then
        MainMacro
    Else
        Application.OnTime TimeValue("05:00:00"), "Timer"
    End If
End Sub
</code>```

Body:
I have a report I wish to run on Monday mornings, so the weekly reports are ready for when the office opens. The Macro runs a main report, saving different versions of it, and also opens and updates several Access databases.

I use Application.OnTime to automate this. I have been testing it for weeks and it works fine when I set it to run overnight (i.e. for the next day) but I have not been able to get it to work on Monday morning, when left from Friday afternoon.

Here is the timing code:

Private Sub Workbook_Open()

Application.OnTime TimeValue("05:00:00"), "Timer"

End Sub

Sub Timer()

If Weekday(Date) = vbMonday Then
Call MainMacro
Else
Exit Sub
End If

End Sub

I run the Application.OnTime sub and then leave the workbook open.

Thanks

Body:
Once the OnTime event has occurred, and your Timer subroutine has been called, and you have chosen to do nothing - that's the end.

You actually need to set a new OnTime event on Saturday, so it will run on Sunday, and then on Monday.

Private Sub Workbook_Open()
    Application.OnTime TimeValue("05:00:00"), "Timer"
End Sub

Sub Timer()
    If Weekday(Date) = vbMonday Then
        MainMacro
    Else
        Application.OnTime TimeValue("05:00:00"), "Timer"
    End If
End Sub


问:
Working with EventListener in Firebase for Android
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

```<code>String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);
</code>```

The above code results in error. To avoid this, I replaced the last line of code with

```<code>    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);
</code>```

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

答:
Your approach is wrong as the listener is updating the String CarBrand But since the code is not in sync and casing the Error. You need to update the code

```<code>private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            String CarBrand =
dataSnapshot.child("CarBrand").getValue(String.class);
            updateBrand(CarBrand);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
</code>```

you need to create a Function to update the value

```<code>/* updates the Car brand Text
   TODO:: You can do anystuff you want to do after anything gets
   updated
*/
public void updateBrand(String brand){
     mTextView.setText(CarBrand);
}
</code>```

NOTE : Put Listener on the Data you are actually looking for changes.

Body:
Consider, I store the following Key-Value pair in Firebase Database.

Key: "CarBrand" and Value: "Audi"

I read the Value for this Key from Firebase Database and display the Value in TextView. For this, I use an EventListener.

The problem I face with an EventListsner is since it runs on a separate thread, the TextView returns a NullPointerException even before the Value is fetched from Firebase.

To overcome the issue I have been using this dirty trick (using a Handler with 500 to 1000 ms delay). Can someone guide me the right way to fetch and display the Value in TextView or any other Views

PS: Apologies for this codeless Question

Thanks

EDIT: More the Code, better the question. The sample code is as follows

String CardBrand;

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            CarBrand = dataSnapshot.child("CarBrand").getValue(String.class);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());
mTextView.setText(CarBrand);

The above code results in error. To avoid this, I replaced the last line of code with

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTextView.setText(CarBrand);
        }
    }, 1000);

So this is what I have been doing. What would be the right way to display the Text in TextView in my Case?

Body:
Your approach is wrong as the listener is updating the String CarBrand But since the code is not in sync and casing the Error. You need to update the code

private ValueEventListener contentListener() {
    contentListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Pull Values for all available Keys
            String CarBrand =
dataSnapshot.child("CarBrand").getValue(String.class);
            updateBrand(CarBrand);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    };
    return contentListener;
}

dbContent.addListenerForSingleValueEvent(contentListener());

you need to create a Function to update the value

/* updates the Car brand Text
   TODO:: You can do anystuff you want to do after anything gets
   updated
*/
public void updateBrand(String brand){
     mTextView.setText(CarBrand);
}

NOTE : Put Listener on the Data you are actually looking for changes.


问:
ReactJS: How to get property in a component container?
I'm using a component in my JSX file and I'm passing a property value to this component like this:

anything.jsx

```<code>import Example from '/containers/example.js'

class Anything extends Component {
    render() {
        return (
            <Example type='article' />
        )
    }
}
</code>```

Below you see, that the component is filled with data via container. Now I need to get the property value in that container to pass it as a value for subscription.

The component has type value article. At the end I need to get this value in the subscription like Meteor.subscription('exampleDetail', mainID, 'article'). How do I pass that value?

Example component (components/example.jsx)

```<code>export default class Example extends Component {
    constructor(props) {
        super(props)
    }

    render() {
        const   { type } = this.props

        console.log(type);
    }
}
</code>```

Example container (containers/example.js)

```<code>import Example from '../components/example.jsx'

export default createContainer(() => {
    const   mainID       = Session.get('mainID'),
            // ??? How to get type value?
            subscription = Meteor.subscribe('exampleDetail', mainID, type)

    loading  = !subscription.ready()
    results  = Collection.find().fetch()

    return { results, loading }
}, Example)
</code>```

答: Try to change to createContainer((props) => { console.log(props)  ...}

Body:
I'm using a component in my JSX file and I'm passing a property value to this component like this:

anything.jsx

import Example from '/containers/example.js'

class Anything extends Component {
    render() {
        return (
            <Example type='article' />
        )
    }
}

Below you see, that the component is filled with data via container. Now I need to get the property value in that container to pass it as a value for subscription.

The component has type value article. At the end I need to get this value in the subscription like Meteor.subscription('exampleDetail', mainID, 'article'). How do I pass that value?

Example component (components/example.jsx)

export default class Example extends Component {
    constructor(props) {
        super(props)
    }

    render() {
        const   { type } = this.props

        console.log(type);
    }
}

Example container (containers/example.js)

import Example from '../components/example.jsx'

export default createContainer(() => {
    const   mainID       = Session.get('mainID'),
            // ??? How to get type value?
            subscription = Meteor.subscribe('exampleDetail', mainID, type)

    loading  = !subscription.ready()
    results  = Collection.find().fetch()

    return { results, loading }
}, Example)


问:
CORS not working even though OPTIONS returns HTTP 200
I am using chi and have setup cors as follows

```<code>func main() {
    r := chi.NewRouter()
    r.Use(render.SetContentType(render.ContentTypeJSON))
    r.Use(Cors)

    r.Post("/auth/login", Login)
    r.Route("/ec2", func(r chi.Router) {
        r.Use(Cors)
        r.Get("/", ListEc2)
    })

    http.ListenAndServe(":9000", r)
}
</code>```

My Cors middleware

```<code>func Cors(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Allow-Control-Allow-Origin", "*")
        w.Header().Set("Allow-Control-Allow-Methods", "*")
        w.Header().Set("Allow-Control-Allow-Headers", "*")
        w.Header().Set("Allow-Control-Allow-Credentials", "true")
        log.Printf("Should set headers")

        if r.Method == "OPTIONS" {
            log.Printf("Should return for OPTIONS")
            return
        }
        next.ServeHTTP(w, r)
    })
}
</code>```

In network tab it looks like:

答:
You just mistyped the header names:

```<code>w.Header().Set("Allow-Control-Allow-Origin", "*")
                ^^^^^
</code>```

Instead of Allow-Control there, you need Access-Control:

```<code>w.Header().Set("Access-Control-Allow-Origin", "*")
</code>```

…and same of course for the other three headers you’re setting there.

Body:
I am using chi and have setup cors as follows

func main() {
    r := chi.NewRouter()
    r.Use(render.SetContentType(render.ContentTypeJSON))
    r.Use(Cors)

    r.Post("/auth/login", Login)
    r.Route("/ec2", func(r chi.Router) {
        r.Use(Cors)
        r.Get("/", ListEc2)
    })

    http.ListenAndServe(":9000", r)
}

My Cors middleware

func Cors(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Allow-Control-Allow-Origin", "*")
        w.Header().Set("Allow-Control-Allow-Methods", "*")
        w.Header().Set("Allow-Control-Allow-Headers", "*")
        w.Header().Set("Allow-Control-Allow-Credentials", "true")
        log.Printf("Should set headers")

        if r.Method == "OPTIONS" {
            log.Printf("Should return for OPTIONS")
            return
        }
        next.ServeHTTP(w, r)
    })
}

In network tab it looks like:

Body:
You just mistyped the header names:

w.Header().Set("Allow-Control-Allow-Origin", "*")
                ^^^^^

Instead of Allow-Control there, you need Access-Control:

w.Header().Set("Access-Control-Allow-Origin", "*")

…and same of course for the other three headers you’re setting there.


问:
Execute LLVM IR code generated from Python code
Does anyone know if I can execute LLVM IR which is generated from Python code?

Using numba, llvm-lite we can have LLVM IR, but I am not sure if it is executable using clang or not?

答:
You can use lli tool which can be found in LLVM's bin folder.

Just do lli file.ll or lli file.bc.

Also see this question: Execute LLVM IR code generated from Rust/Python source code and this question: How to run LLVM interpreter with a shared library?.


问:
Python multiprocessing ImportError
I’m having trouble using python’s multiprocessing module. This is the first time I’ve tried using the module. I’ve tried simplifying my processing to the bare bones, but keep getting the same error. I’m using python 2.7.2, and Windows 7.

The script I’m trying to run is called learnmp.py, and the error message says that the problem is that it can't find module learnmp.

```<code>import multiprocessing

def doSomething():
    """worker function"""
    print 'something'
    return

if __name__ == '__main__':

    jobs = []
    for i in range(2):
        p = multiprocessing.Process(target=doSomething)
        jobs.append(p)
        p.start()
</code>```

The error is :

```<code>File “<string>”, line 1, in <module> File “C:\Python27\ArcGISx6410.1\lib\multiprocessing\forking.py”, line 373,
in main prepare(preparation_data) File “C:\Python27\ArcGISx6410.1\lib\multiprocessing\forking.py”, line 482,
in prepare file, path_name, etc = imp.find_module (main_name, dirs)
ImportError: No module named learnmp
</code>```

What’s causing the error, and how can I solve it?

EDIT: I still don't know what was causing the error, but changing the file name eliminated it.

答:
Microsoft Visual C++ 9.0 is required for some python modules to work in windows,so download below package it will work.

http://aka.ms/vcpython27

This package contains the compiler and set of system headers necessary for producing binary wheels for Python 2.7 packages.

Title: Python multiprocessing ImportError

Body:
I’m having trouble using python’s multiprocessing module. This is the first time I’ve tried using the module. I’ve tried simplifying my processing to the bare bones, but keep getting the same error. I’m using python 2.7.2, and Windows 7.

The script I’m trying to run is called learnmp.py, and the error message says that the problem is that it can't find module learnmp.

import multiprocessing

def doSomething():
    """worker function"""
    print 'something'
    return

if __name__ == '__main__':

    jobs = []
    for i in range(2):
        p = multiprocessing.Process(target=doSomething)
        jobs.append(p)
        p.start()

The error is :

File “<string>”, line 1, in <module> File “C:\Python27\ArcGISx6410.1\lib\multiprocessing\forking.py”, line 373,
in main prepare(preparation_data) File “C:\Python27\ArcGISx6410.1\lib\multiprocessing\forking.py”, line 482,
in prepare file, path_name, etc = imp.find_module (main_name, dirs)
ImportError: No module named learnmp

What’s causing the error, and how can I solve it?

EDIT: I still don't know what was causing the error, but changing the file name eliminated it.


问:
Trying to switch character unity 2d
I'm making a platformer where for different aspects of the level you have to change character. Each character is to have different properties and such. I wacthed this tutorial https://www.youtube.com/watch?v=vD5pW97-050 but this is basically just changing the sprite as both characters are part of the same gameobject with the same rigidbody and collider. I am using c# and would really love some help if anyone knew a solution. Here's my player controllers script, which includes the character switch script found in the tutorial. Any help would be appreciated thanks! </p>

```<code>using UnityEngine;
using System.Collections;

public class controller : MonoBehaviour
{
public float topSpeed = 15f;
bool facingRight = true;

bool grounded = false;

public Transform groundCheck;

float groundRadius = 0.2f;
GameObject Player, Player2;
int characterselect;

public float jumpForce = 700f;

public LayerMask whatIsGround;
void Start()
{
    characterselect = 1;
    Player = GameObject.Find("Player");
    Player2 = GameObject.Find("Player2");

}

void FixedUpdate()
{
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

    float move = Input.GetAxis("Horizontal");
    GetComponent<Rigidbody2D>().velocity = new Vector2(move * topSpeed, GetComponent<Rigidbody2D>().velocity.y);
    if (move > 0 && !facingRight)
        flip();
    else if (move < 0 && facingRight)
        flip();

}

void Update()
{
    if(grounded&& Input.GetKeyDown(KeyCode.Space))
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
    }
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (characterselect==1)
            {
                characterselect = 2;
            }
            else if (characterselect==2)
            {
                characterselect = 1;
            }
        }
        if (characterselect==1)
        {
            Player.SetActive(true);
            Player2.SetActive(false);
        }
        else if (characterselect==2)
        {
            Player.SetActive(false);
            Player2.SetActive(true);
        }
    }

}

void flip()
{
    facingRight = ! facingRight;

    Vector3 theScale = transform.localScale;

    theScale.x *= -1;

    transform.localScale = theScale;

}
</code>```

<p>}</p>

答:
Having a controller is a good start for this, but you got to think about how you different you want your characters to be. If they're going to be completely different, then think about a creating a "PlayerCharacter" interface that has functions for all possible commands for example

```<code>public interface IPlayerCharacter
{
    void DoActionA();
    void DoActionB();
}
</code>```

If you do not know what an interface is, it's basically a empty class that defines functions, but not yet creates code for them. Because of this you can very easily implement very different players. Because you can call the functions from an instance of this interface.

Then, add this component to your controller, and if you now switch from Player 1 to Player 2 It should probably be a bit like this

```<code>public class PlayerController_Jumper : MonoBehaviour, IPlayerCharacter
{
    // Does a jump
    void DoActionA()
    {
        rigidbody.AddVelocity(Vector3.Up, 100.0f);
    }
}
</code>```

Something that has to be done with Interfaces is that you HAVE to define all pre-defined functions, so it'll probably complain about this code because there's no DoActionB(). But lets disregard that for now.

Then Add to your controller something like "IPlayerController Jumper" and any other cool characters you're planning to make!

Title: Trying to switch character unity 2d

Body:
I'm making a platformer where for different aspects of the level you have to change character. Each character is to have different properties and such. I wacthed this tutorial https://www.youtube.com/watch?v=vD5pW97-050 but this is basically just changing the sprite as both characters are part of the same gameobject with the same rigidbody and collider. I am using c# and would really love some help if anyone knew a solution. Here's my player controllers script, which includes the character switch script found in the tutorial. Any help would be appreciated thanks!

using UnityEngine;
using System.Collections;

public class controller : MonoBehaviour
{
public float topSpeed = 15f;
bool facingRight = true;

bool grounded = false;

public Transform groundCheck;

float groundRadius = 0.2f;
GameObject Player, Player2;
int characterselect;

public float jumpForce = 700f;

public LayerMask whatIsGround;
void Start()
{
    characterselect = 1;
    Player = GameObject.Find("Player");
    Player2 = GameObject.Find("Player2");

}

void FixedUpdate()
{
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);

    float move = Input.GetAxis("Horizontal");
    GetComponent<Rigidbody2D>().velocity = new Vector2(move * topSpeed, GetComponent<Rigidbody2D>().velocity.y);
    if (move > 0 && !facingRight)
        flip();
    else if (move < 0 && facingRight)
        flip();

}

void Update()
{
    if(grounded&& Input.GetKeyDown(KeyCode.Space))
    {
        GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
    }
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (characterselect==1)
            {
                characterselect = 2;
            }
            else if (characterselect==2)
            {
                characterselect = 1;
            }
        }
        if (characterselect==1)
        {
            Player.SetActive(true);
            Player2.SetActive(false);
        }
        else if (characterselect==2)
        {
            Player.SetActive(false);
            Player2.SetActive(true);
        }
    }

}

void flip()
{
    facingRight = ! facingRight;

    Vector3 theScale = transform.localScale;

    theScale.x *= -1;

    transform.localScale = theScale;

}

}

Body:
Having a controller is a good start for this, but you got to think about how you different you want your characters to be. If they're going to be completely different, then think about a creating a "PlayerCharacter" interface that has functions for all possible commands for example

public interface IPlayerCharacter
{
    void DoActionA();
    void DoActionB();
}

If you do not know what an interface is, it's basically a empty class that defines functions, but not yet creates code for them. Because of this you can very easily implement very different players. Because you can call the functions from an instance of this interface.

Then, add this component to your controller, and if you now switch from Player 1 to Player 2 It should probably be a bit like this

public class PlayerController_Jumper : MonoBehaviour, IPlayerCharacter
{
    // Does a jump
    void DoActionA()
    {
        rigidbody.AddVelocity(Vector3.Up, 100.0f);
    }
}

Something that has to be done with Interfaces is that you HAVE to define all pre-defined functions, so it'll probably complain about this code because there's no DoActionB(). But lets disregard that for now.

Then Add to your controller something like "IPlayerController Jumper" and any other cool characters you're planning to make!


问:
Changing text and color randomly
I try to write a code that puts on the screen random texts and change the color sometimes( in loop 2).

I don't understand why my code loops just once. It seems that the show() function works by itself but the test() loop doesn't run well.

```<code><script type="text/javascript">//<![CDATA[
    window.onload=function(){
        button.addEventListener('mousedown', function (e) {
            test();
        });
}//]]>

function show() {
    b=makeid();
    document.getElementById("text").innerHTML = b;
}

function test() {
    var div = document.getElementById('text');
    for (i=0;i<5;i++) {b=makeid();
        document.getElementById("text").innerHTML = b;
        if (i==2) {div.style.color = '#000000';}
        setTimeout(function(){ show();},500);
        if (i==2) {div.style.color = '#CC0000';}
    }
}

function makeid() {
    var text = "";
    var possible =     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for( var i=0; i < 2; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

</script>
</head>
<body>
    <button id="button">click</button>
    <div>
        <span id="text"></span>
    </div>
</body>
</code>```

答:
Your Code is not sufficient for what you are trying to achieve

Issue with your code:-

You were calling show() function with a fixed timeout, so even though the function waits, all it's instances gets called at once after the same time period.

And you don't get to see the change in text with your eyes.

In case of color:-
You were always changing the color to same color, so it was always a single color in output.

I have achieved your requirement. Try this:-

 <button id="button">click</button>

```

Title: Changing text and color randomly

Body:
I try to write a code that puts on the screen random texts and change the color sometimes( in loop 2).

I don't understand why my code loops just once. It seems that the show() function works by itself but the test() loop doesn't run well.

    <button id="button">click</button>

Body:
Your Code is not sufficient for what you are trying to achieve

Issue with your code:-

You were calling show() function with a fixed timeout, so even though the function waits, all it's instances gets called at once after the same time period.

And you don't get to see the change in text with your eyes.

In case of color:-
You were always changing the color to same color, so it was always a single color in output.

I have achieved your requirement. Try this:-

<script type="text/javascript">

window.onload=function(){
 button.addEventListener('mousedown', function (e) {
 test();
});

}

function show()
{
 b=makeid();
 document.getElementById("text").innerHTML = b;

}

function test()
{
   var div = document.getElementById('text');
   var repeat = setInterval(function(){
        div.style.color = getRandomColor();
        show();
      },500);

   setTimeout(function(){clearInterval(repeat);},2500);
}

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++ ) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function makeid()
{
  var text = "";
  var possible =     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 for( var i=0; i < 2; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));
 return text;
}

</script>

</head>
<body>
 <button id="button">click</button>
 <div>
  <span id="text"></span>
 </div>
</body>


问:
Determining if all attributes on a javascript object are null or an empty string
What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string?  It should work for an arbitrary number of attributes.</p>

```<code>{'a':null, 'b':''} //should return true for this object
{'a':1, 'b':''} //should return false for this object
{'a':0, 'b':1} //should return false
{'a':'', 'b':''} //should return true
</code>```

答:
Based on adeneo's answer, I created a single line condition. Hope it will be helpful to someone.

```<code>var test = {
  "email": "test@test.com",
  "phone": "1234567890",
  "name": "Test",
  "mobile": "9876543210",
  "address": {
      "street": "",
      "city": "",
      "state": "",
      "country": "",
      "postalcode": "r"
  },
  "website": "www.test.com"
};

if (Object.keys(test.address).every(function(x) { return test.address[x]===''||test.address[x]===null;}) === false) {
   console.log('has something');
} else {
   console.log('nothing');
}
</code>```

You can test it https://jsfiddle.net/4uyue8tk/2/

ContentLicense: CC BY-SA 4.0

Body:
What is the most elegant way to determine if all attributes in a javascript object are either null or the empty string?  It should work for an arbitrary number of attributes.

{'a':null, 'b':''} //should return true for this object
{'a':1, 'b':''} //should return false for this object
{'a':0, 'b':1} //should return false
{'a':'', 'b':''} //should return true

Body:
Based on adeneo's answer, I created a single line condition. Hope it will be helpful to someone.

var test = {
  "email": "test@test.com",
  "phone": "1234567890",
  "name": "Test",
  "mobile": "9876543210",
  "address": {
      "street": "",
      "city": "",
      "state": "",
      "country": "",
      "postalcode": "r"
  },
  "website": "www.test.com"
};

if (Object.keys(test.address).every(function(x) { return test.address[x]===''||test.address[x]===null;}) === false) {
   console.log('has something');
} else {
   console.log('nothing');
}

You can test it https://jsfiddle.net/4uyue8tk/2/


问:
How to get response form Oracle using C#?
I'm new in Oracle and trying to execute the next SQL request using C#

```<code>try
{
    connection.Open();
    OracleCommand cmd = new OracleCommand();
    cmd.Connection = connection;
    cmd.CommandText = "select count(*) from agreements";
    cmd.CommandType = CommandType.Text;
    OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();
}
</code>```

I've read Oracle documentation, I've tried to use

var response = dr.GetString(0);

But it always returns exception

Specified cast is not valid.

Does somebody know how I can solve it ? Thanks for your answers!

答:
Given that you're querying count(*), you'd be better using ExecuteScalar rather than ExecuteReader(), for one thing. Next, the result will be an integer, which is why GetString() fails.

Change it to:

```<code>int count = (int) cmd.ExecuteScalar();
</code>```

(I'd also strongly advise using using statements for your connection, command, and any readers you'd normally create.)

Body:
I'm new in Oracle and trying to execute the next SQL request using C#

try
{
    connection.Open();
    OracleCommand cmd = new OracleCommand();
    cmd.Connection = connection;
    cmd.CommandText = "select count(*) from agreements";
    cmd.CommandType = CommandType.Text;
    OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();
}

I've read Oracle documentation, I've tried to use

var response = dr.GetString(0);

But it always returns exception

Specified cast is not valid.

Does somebody know how I can solve it ? Thanks for your answers!

Body:
Given that you're querying count(*), you'd be better using ExecuteScalar rather than ExecuteReader(), for one thing. Next, the result will be an integer, which is why GetString() fails.

Change it to:

int count = (int) cmd.ExecuteScalar();

(I'd also strongly advise using using statements for your connection, command, and any readers you'd normally create.)


问:
Docker swarm load balancing
Do we need to balance load via ngnix with swarm mode?

If so, why do we need to do that. Docker swarm balances load. I tested for simple application. It has several strategies for load balancing.

Even docker swarm balances load, why are there so many articles about load balancing with ngnix in swarm mode?

答:
The new feature in Docker 1.12 make Swarm a powerful platform, but this will be enhanced by taking advantage of open source NGINX and even more by using NGINX Plus. The ability of NGINX Plus to dynamically reconfigure the back-end containers to load balance using DNS, and the visibility provided by the Status API, make for a very powerful container solution.

There is this article which is very descriptive in explaining why is this so advantageous. Link here.

Hope this answers your question!

Title: Docker swarm load balancing


问:
UITextField should accept only positive integers and give alert message for rest
What Code I need to write to make my UITextField accept only positive integers(Whole numbers) other than setting keyboard Type to numbers only. And it should alert user when they input characters/fractions/Negative numbers/Special Characters. Kindly, Let me know. Thank you.</p>

答:
You can implement the UITextFieldDelegate method

```<code>-(BOOL)textFieldShouldReturn:(UITextField *)textField {}
</code>```

In it you can check the textField's text property and convert it to an NSNumber using the NSNumberFormatter class method numberFromString: and see if the intValue is positive.

Body:
You can implement the UITextFieldDelegate method

-(BOOL)textFieldShouldReturn:(UITextField *)textField {}

In it you can check the textField's text property and convert it to an NSNumber using the NSNumberFormatter class method numberFromString: and see if the intValue is positive.


问:
Laravel - Redirect with variable to twig page
I've made a mail function with an try/catch situation. It checks if the mail template exists, if not it needs to return redirect / back to the page with a message(return redirect('dashboard')->with('status', "Mail doesn't exists");)

Is it possible to redirect with a variable using a twig page? Or is there just something that I am doing wrong?

This is my mail function(DashboardController.php)

```<code> public function MailContact($date_id, $contact_id)
{
    try
    {
        $contact = Contact::find($contact_id);
        $date = Date::find($date_id);
        $mail = Mails::where('datetype_id', $date->datetype_id)->first();
        $html = $mail->html;

        Mail::to($contact->email)->send(new Anniversary($html));

        return redirect('dashboard');
        }
    catch(\Exception $ex )
    {
        return redirect('dashboard')->with("Mail doesn't exists");
    }
}
</code>```

This is the twig page('dashboard.twig')

```<code> <div class="box-body no-padding" style="width: 100%; padding-top:20px;">
  <ul class="telephoneKingList" style=" display: inline-block;
    width: 100%;">
        {% for dates in datestodayUser %}
           {% if dates is not empty %}
              <li data-id="{{ dates.id }}">
                 {{ dates.contact.fullname }}, {{ dates.contact.relation.company }} <br>
                 {{ dates.description }}<br>
                 {# Place where Error needs to be #}
                 <a role="button" id="edit-button" href="/dashboard/mail/{{ dates.id }}/{{ dates.contact.id }}" class="btn btn-primary btn-sm"><i class="fa fa-envelope"></i></a>
              </li>
              <hr>
           {% endif %}
           {% else %}
              <li>
                 Geen data beschikbaar.
              </li>
           {% endfor %}
  </ul>
</code>```

答:
You can do

```<code>return redirect('dashboard')->with(['message'=>"Mail doesn't exists"]);
</code>```

and then in your twig

{{message}} will give you the message

Body:
I've made a mail function with an try/catch situation. It checks if the mail template exists, if not it needs to return redirect / back to the page with a message(return redirect('dashboard')->with('status', "Mail doesn't exists");)

Is it possible to redirect with a variable using a twig page? Or is there just something that I am doing wrong?

This is my mail function(DashboardController.php)

 public function MailContact($date_id, $contact_id)
{
    try
    {
        $contact = Contact::find($contact_id);
        $date = Date::find($date_id);
        $mail = Mails::where('datetype_id', $date->datetype_id)->first();
        $html = $mail->html;

        Mail::to($contact->email)->send(new Anniversary($html));

        return redirect('dashboard');
        }
    catch(\Exception $ex )
    {
        return redirect('dashboard')->with("Mail doesn't exists");
    }
}

This is the twig page('dashboard.twig')

        {% for dates in datestodayUser %}
           {% if dates is not empty %}

                 {{ dates.contact.fullname }}, {{ dates.contact.relation.company }}

                 {{ dates.description }}

                 {# Place where Error needs to be #}

           {% endif %}
           {% else %}

                 Geen data beschikbaar.

           {% endfor %}

Body:
You can do

return redirect('dashboard')->with(['message'=>"Mail doesn't exists"]);

and then in your twig

{{message}} will give you the message


问:
Error while Restoring backup in SQL Server 2005
'Restore Failed' error is getting displayed when trying to restore the backup.

After searching here, it came to my knowledge that higher version of SQL Server (2014) database backups cannot be restored in earlier/lower/older(SQL Server 2005) version.

My query is that can I set the compatibility mode to that of 2005 and than take backup, will that work?

If not, are there any other possible tool or solutions because the backup is pretty big and takes 2-3 hours for back-up to get complete.

答:
A SQL 2014 database backup cannot be restored to a SQL 2005 database.
What you can do, is;

```<code> 1. script out all objects from the SQL 2014 database;
   1.1 right click database in Object Explorer
   1.2 select 'Tasks' -> 'Generate Scripts'.
   1.3 Enable everything, including 'script data'.
 2. Create a new database on SQL 2005
 3. Run all scripts on the new SQL 2005 database.
</code>```

However, as your database is pretty big, this will take a long time.
Especially scripting the data.

If you really need to do this, you could script out all tables, procedures etc., and create a data flow using e.g.SSIS to migrate the data into SQL 2005.

Edit;
another option I found (on this topic), but have not tested, is using third party tools,
'Create empty database on 2008 instance and use third party tools such as ApexSQL Diff and Data Diff to synchronize schema and tables.

Just use these (or any other on the market such as Red Gate, Idera, Dev Art, there are many similar) in trial mode to get the job done.'

Body:
A SQL 2014 database backup cannot be restored to a SQL 2005 database.
What you can do, is;

 1. script out all objects from the SQL 2014 database;
   1.1 right click database in Object Explorer
   1.2 select 'Tasks' -> 'Generate Scripts'.
   1.3 Enable everything, including 'script data'.
 2. Create a new database on SQL 2005
 3. Run all scripts on the new SQL 2005 database.

However, as your database is pretty big, this will take a long time.
Especially scripting the data.

If you really need to do this, you could script out all tables, procedures etc., and create a data flow using e.g.SSIS to migrate the data into SQL 2005.

Edit;
another option I found (on this topic), but have not tested, is using third party tools,
'Create empty database on 2008 instance and use third party tools such as ApexSQL Diff and Data Diff to synchronize schema and tables.

Just use these (or any other on the market such as Red Gate, Idera, Dev Art, there are many similar) in trial mode to get the job done.'


问:
Spring boot: Jersey ResourceConfig needs annotating?
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

```<code>@Component
public class JerseyExampleConfig extends ResourceConfig {
</code>```

The above is annotated with COMPONENT

```<code>@Configuration
public class JerseyExampleConfig extends ResourceConfig {
</code>```

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?

答:
The documentation suggests @Component:

To get started with Jersey 2.x just include the spring-boot-starter-jersey as a dependency and then you need one @Bean of type ResourceConfig in which you register all the endpoints:

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(Endpoint.class);
    }
}
```
</blockquote>

<p>The documentation also says the following:</p>

<blockquote>
  <p>You can also register an arbitrary number of beans implementing <code>ResourceConfigCustomizer</code> for more advanced customizations.</p>

  <p>All the registered endpoints should be <code>@Component</code>s with HTTP resource annotations (<code>@GET</code> etc.), e.g.</p>

  <pre class="lang-java prettyprint-override"><code>@Component
@Path("/hello")
public class Endpoint {

    @GET
    public String message() {
        return "Hello";
    }
}
</code>```

Since the Endpoint is a Spring @Component its lifecycle is managed by Spring and you can @Autowired dependencies and inject external configuration with @Value. The Jersey servlet will be registered and mapped to /* by default. You can change the mapping by adding @ApplicationPath to your ResourceConfig.

Body:
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

@Component
public class JerseyExampleConfig extends ResourceConfig {

The above is annotated with COMPONENT

@Configuration
public class JerseyExampleConfig extends ResourceConfig {

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?

Body:
The documentation suggests @Component:

To get started with Jersey 2.x just include the spring-boot-starter-jersey as a dependency and then you need one @Bean of type ResourceConfig in which you register all the endpoints:

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(Endpoint.class);
    }
}

The documentation also says the following:

You can also register an arbitrary number of beans implementing ResourceConfigCustomizer for more advanced customizations.

All the registered endpoints should be @Components with HTTP resource annotations (@GET etc.), e.g.

@Component
@Path("/hello")
public class Endpoint {

    @GET
    public String message() {
        return "Hello";
    }
}

Since the Endpoint is a Spring @Component its lifecycle is managed by Spring and you can @Autowired dependencies and inject external configuration with @Value. The Jersey servlet will be registered and mapped to /* by default. You can change the mapping by adding @ApplicationPath to your ResourceConfig.


问:
What is blocking the checking of the checkbox?
If you click the second orange "Заказ в 1 клик" button at this page you'll see the form with the checkbox at the bottom. How to figure out what script is blocking the checking of this chackbox?
May be it's due to this script:

```<code>$("#contactForm_oneclick").click( function(e){
        if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
            return false;
        }
    })
</code>```

but how to change it correct?

答:
You are correct about the snippet being the problem. The last part of your IF is stopping this checkbox from being ticked, below are a simple edit that should work.

```<code>$("#contactForm_oneclick").click( function(e){
    if(e.target.getAttribute('class') != 'addtocart_button') {
        return false;
    }
});
</code>```

Note: I can't find any good reason for the removed part to be there, but it could still affect other parts of the site that I don't know about. Check that your page works as intended before going live with the change.

EDIT: To answer your other question about how to find out what is blocking the checking of this checkbox I'd see this answer about finding all event-listeners attached to a specific DOM-element.

Body:
If you click the second orange "Заказ в 1 клик" button at this page you'll see the form with the checkbox at the bottom. How to figure out what script is blocking the checking of this chackbox?
May be it's due to this script:

$("#contactForm_oneclick").click( function(e){
        if(e.target.getAttribute('class') != 'addtocart_button' || e.target.getAttribute('id') == 'agree') {
            return false;
        }
    })

but how to change it correct?

Body:
You are correct about the snippet being the problem. The last part of your IF is stopping this checkbox from being ticked, below are a simple edit that should work.

$("#contactForm_oneclick").click( function(e){
    if(e.target.getAttribute('class') != 'addtocart_button') {
        return false;
    }
});

Note: I can't find any good reason for the removed part to be there, but it could still affect other parts of the site that I don't know about. Check that your page works as intended before going live with the change.

EDIT: To answer your other question about how to find out what is blocking the checking of this checkbox I'd see this answer about finding all event-listeners attached to a specific DOM-element.


问:
OData Data read- latest entry on top
I am using OData API to read data in my Fiori Application. The issue is, in Odata API, the latest data entry is at the end rather it should be at the top. How do i do that ie put my latest data on top. </p>

答:
You can use the $orderby to decide what order the data is returned in. See the docs for more info. This URL is an example of ordering (using the OData TripPin example service) that sorts by the LastName property:

```<code>http://services.odata.org/V4/TripPinServiceRW/People?$orderby=LastName
</code>```

We can use this same process to order by a DateTime value or an ID value to get your latest entries at the top. For example, here we order by the DateTimeOffset field StartsAt putting the latest entries first:

```<code>http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')/Trips?$orderby=StartsAt desc
</code>```

Title: OData Data read- latest entry on top

Body:
You can use the $orderby to decide what order the data is returned in. See the docs for more info. This URL is an example of ordering (using the OData TripPin example service) that sorts by the LastName property:

http://services.odata.org/V4/TripPinServiceRW/People?$orderby=LastName

We can use this same process to order by a DateTime value or an ID value to get your latest entries at the top. For example, here we order by the DateTimeOffset field StartsAt putting the latest entries first:

http://services.odata.org/V4/TripPinServiceRW/People('russellwhyte')/Trips?$orderby=StartsAt desc


问:
Excel VBA Userform, Update and delete database,
I'm very new to Excel VBA and I have found solutions to most my problem through Stackoverflow.com But still, there is a problem I've couldn't solve.
I am working on a multidimensional Userform to maintain our database. The Userform I'm working on containing option boxes, checkboxes, textboxes and combo boxes.
After long search and work, I fixed the search bottoms and they all are working. But I can not get the Update bottom and the Delete bottom to work.
I have uploaded the file, I would be grateful if anyone can help me out with this issue. </p>

```<code>Private Sub bt2_Click() 'Update shipment
Dim sonsat As Long, sor As String
If ListBox1.ListIndex = -1 Then
MsgBox "Choose an item", vbExclamation, ""
Exit Sub
End If

sor = MsgBox("Are your sure?", vbYesNo, "")
If sor = vbNo Then Exit Sub

lastrow = Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row
Sheets("logbook").Range("A1:A" & lastrow).Find(What:=ListBox1.Value,
LookIn:=xlValues, LookAt:=xlWhole).Activate
sonsat = ActiveCell.Row
Cells(sonsat, 1) = op1
Cells(sonsat, 2) = op2
Cells(sonsat, 3) = chb1
Cells(sonsat, 4) = chb2
Cells(sonsat, 5) = tb14
Cells(sonsat, 6) = tb1
Cells(sonsat, 7) = tb2
Cells(sonsat, 8) = tb3
Cells(sonsat, 9) = tb4
Cells(sonsat, 10) = tb5
Cells(sonsat, 11) = cb1
Cells(sonsat, 12) = tb6
Cells(sonsat, 13) = tb7
Cells(sonsat, 14) = tb8
Cells(sonsat, 15) = tb9
Cells(sonsat, 16) = cb2
Cells(sonsat, 17) = tb10
Cells(sonsat, 18) = tb11
Cells(sonsat, 19) = tb12
Cells(sonsat, 20) = cb3
Cells(sonsat, 21) = cb4
Cells(sonsat, 22) = tb13

MsgBox "Item Has Been Changed", vbInformation, ""
ListBox1.list = Sheets("logbook").Range("A1:V" &
Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row).Value

If Me.op1.Value = True Then
Cells(sonsat, 1).Value = "X"
Else
Cells(sonsat, 1).Value = "-"
End If

If Me.op2.Value = True Then
Cells(sonsat, 2).Value = "X"
Else
Cells(sonsat, 2).Value = "-"
End If

If Me.chb1.Value = True Then
Cells(sonsat, 3).Value = "X"
Else
Cells(sonsat, 3).Value = "-"
End If

If Me.chb2.Value = True Then
Cells(sonsat, 4) = "X"
Else
Cells(sonsat, 4) = "-"
End If
End Sub

Private Sub bt3_Click() 'delete shipmet
Dim sil As Long
Dim e, b, c, d As Integer

If ListBox1.ListIndex = -1 Then
MsgBox "Choose an entry", vbExclamation, ""
Exit Sub
End If

If ListBox1.ListIndex >= 0 Then
cevap = MsgBox("Entry will be deleted. ... Are you sure ?", vbYesNo, "")
If cevap = vbYes Then
Sheets("logbook").Range("A:A").Find(What:=ListBox1.Value).Activate
sil = ActiveCell.Row
Sheets("logbook").Rows(sil).Delete
End If
End If

For d = 1 To 2
Controls("op" & d) = False
Next

For c = 1 To 4
Controls("cb" & c) = "-"
Next

For b = 1 To 2
Controls("chb" & b) = False
Next

For e = 1 To 14
Controls("tb" & e) = ""
Next

ListBox1.list = Sheets("logbook").Range("A1:V" &
Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row).Value
End Sub
</code>```

答:
The following is based on the file you uploaded to Google Drive (as at 2017-06-08, 09:01 UK Time).

I lost a few controls when trying to open the workbook, perhaps our versions of Excel are too different for mine to cope with them. These were your date controls dtp2 and dtp3. I commented out code relating to these whenever they caused me trouble. Hopefully that doesn't negatively affect what follows ...

Main Suggestions

To get things to run at all I had to declare the lastrow variable and the cevap variable.

Your listbox1 is allowing multi-select. If you want to update just one row, you need to ensure that only one row is selected. Within the "Behaviour" section of the control properties, I'd change MultiSelect to 0 - fmMultiSelectSingle.

Because you were allowing multi-select, listbox1.value wasn't working. You have to do it differently when you allow multi-select (see here). But assuming you're okay with single-select, you don't need to worry about that.

When you use your Find ... Activate you'll then get a different error. Excel can't Activate the spreadsheet because Userform1 retains focus. You might be able to change that by making the form "non-modal", but I wouldn't. Instead, rather than, for example:

```<code>Sheets("logbook").Range("A1:A" & lastrow).Find(What:=ListBox1.Value, _
   LookIn:=xlValues, LookAt:=xlWhole).Activate
sonsat = ActiveCell.Row
</code>```

I'd do

```<code>sonsat = Sheets("logbook").Range("A1:A" &
   lastrow).Find(What:=ListBox1.Value, _
LookIn:=xlValues, LookAt:=xlWhole).Row
</code>```

Which avoid's the need to Activate. After that the code should run without complaining.

However, it still doesn't do what you want. The value of the listbox is based on your bound column, which you've set to the be first column. That value doesn't uniquely identify the row. As a result, when you run the update/delete the code updates/deletes the first matching row.

Minor Matters

There is currently nothing preventing the user selecting and updating/deleting the header row. Personally, I'd take them out of the listbox (start at A2 instead of A1) and add them as "column headings" in the form.

I'm guessing the title of the form should be "Data Entry Application" not "Data Entery Application".

Body:
I'm very new to Excel VBA and I have found solutions to most my problem through Stackoverflow.com But still, there is a problem I've couldn't solve.
I am working on a multidimensional Userform to maintain our database. The Userform I'm working on containing option boxes, checkboxes, textboxes and combo boxes.
After long search and work, I fixed the search bottoms and they all are working. But I can not get the Update bottom and the Delete bottom to work.
I have uploaded the file, I would be grateful if anyone can help me out with this issue.

Private Sub bt2_Click() 'Update shipment
Dim sonsat As Long, sor As String
If ListBox1.ListIndex = -1 Then
MsgBox "Choose an item", vbExclamation, ""
Exit Sub
End If

sor = MsgBox("Are your sure?", vbYesNo, "")
If sor = vbNo Then Exit Sub

lastrow = Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row
Sheets("logbook").Range("A1:A" & lastrow).Find(What:=ListBox1.Value,
LookIn:=xlValues, LookAt:=xlWhole).Activate
sonsat = ActiveCell.Row
Cells(sonsat, 1) = op1
Cells(sonsat, 2) = op2
Cells(sonsat, 3) = chb1
Cells(sonsat, 4) = chb2
Cells(sonsat, 5) = tb14
Cells(sonsat, 6) = tb1
Cells(sonsat, 7) = tb2
Cells(sonsat, 8) = tb3
Cells(sonsat, 9) = tb4
Cells(sonsat, 10) = tb5
Cells(sonsat, 11) = cb1
Cells(sonsat, 12) = tb6
Cells(sonsat, 13) = tb7
Cells(sonsat, 14) = tb8
Cells(sonsat, 15) = tb9
Cells(sonsat, 16) = cb2
Cells(sonsat, 17) = tb10
Cells(sonsat, 18) = tb11
Cells(sonsat, 19) = tb12
Cells(sonsat, 20) = cb3
Cells(sonsat, 21) = cb4
Cells(sonsat, 22) = tb13

MsgBox "Item Has Been Changed", vbInformation, ""
ListBox1.list = Sheets("logbook").Range("A1:V" &
Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row).Value

If Me.op1.Value = True Then
Cells(sonsat, 1).Value = "X"
Else
Cells(sonsat, 1).Value = "-"
End If

If Me.op2.Value = True Then
Cells(sonsat, 2).Value = "X"
Else
Cells(sonsat, 2).Value = "-"
End If

If Me.chb1.Value = True Then
Cells(sonsat, 3).Value = "X"
Else
Cells(sonsat, 3).Value = "-"
End If

If Me.chb2.Value = True Then
Cells(sonsat, 4) = "X"
Else
Cells(sonsat, 4) = "-"
End If
End Sub

Private Sub bt3_Click() 'delete shipmet
Dim sil As Long
Dim e, b, c, d As Integer

If ListBox1.ListIndex = -1 Then
MsgBox "Choose an entry", vbExclamation, ""
Exit Sub
End If

If ListBox1.ListIndex >= 0 Then
cevap = MsgBox("Entry will be deleted. ... Are you sure ?", vbYesNo, "")
If cevap = vbYes Then
Sheets("logbook").Range("A:A").Find(What:=ListBox1.Value).Activate
sil = ActiveCell.Row
Sheets("logbook").Rows(sil).Delete
End If
End If

For d = 1 To 2
Controls("op" & d) = False
Next

For c = 1 To 4
Controls("cb" & c) = "-"
Next

For b = 1 To 2
Controls("chb" & b) = False
Next

For e = 1 To 14
Controls("tb" & e) = ""
Next

ListBox1.list = Sheets("logbook").Range("A1:V" &
Sheets("logbook").Cells(Rows.count, 1).End(xlUp).Row).Value
End Sub

Body:
The following is based on the file you uploaded to Google Drive (as at 2017-06-08, 09:01 UK Time).

I lost a few controls when trying to open the workbook, perhaps our versions of Excel are too different for mine to cope with them. These were your date controls dtp2 and dtp3. I commented out code relating to these whenever they caused me trouble. Hopefully that doesn't negatively affect what follows ...

Main Suggestions

To get things to run at all I had to declare the lastrow variable and the cevap variable.

Your listbox1 is allowing multi-select. If you want to update just one row, you need to ensure that only one row is selected. Within the "Behaviour" section of the control properties, I'd change MultiSelect to 0 - fmMultiSelectSingle.

Because you were allowing multi-select, listbox1.value wasn't working. You have to do it differently when you allow multi-select (see here). But assuming you're okay with single-select, you don't need to worry about that.

When you use your Find ... Activate you'll then get a different error. Excel can't Activate the spreadsheet because Userform1 retains focus. You might be able to change that by making the form "non-modal", but I wouldn't. Instead, rather than, for example:

Sheets("logbook").Range("A1:A" & lastrow).Find(What:=ListBox1.Value, _
   LookIn:=xlValues, LookAt:=xlWhole).Activate
sonsat = ActiveCell.Row

I'd do

sonsat = Sheets("logbook").Range("A1:A" &
   lastrow).Find(What:=ListBox1.Value, _
LookIn:=xlValues, LookAt:=xlWhole).Row

Which avoid's the need to Activate. After that the code should run without complaining.

However, it still doesn't do what you want. The value of the listbox is based on your bound column, which you've set to the be first column. That value doesn't uniquely identify the row. As a result, when you run the update/delete the code updates/deletes the first matching row.

Minor Matters

There is currently nothing preventing the user selecting and updating/deleting the header row. Personally, I'd take them out of the listbox (start at A2 instead of A1) and add them as "column headings" in the form.

I'm guessing the title of the form should be "Data Entry Application" not "Data Entery Application".


问:
Doctrine : 2 leftJoin on same table, but different Join::WITH
i got a request with 2 leftJoin on the same table, with different alias :

```<code>$qb2->leftJoin('d2.groupeDossiers', 'gd',Join::WITH, 'gd.type = \'assure\'');
$qb2->leftJoin('d2.groupeDossiers', 'gdt',Join::WITH, 'gdt.type = \'tiers\'');
</code>```

But it seems there's conflicts. How could i do that leftJoin in a single request ?
Thank you !

答:
Without using Doctrine Relationships

If your relationship is like this :

```<code>/**
 * @ORM\OneToMany(targetEntity="GroupeDossier", mappedBy="test")
 */
private $groupeDossiers;
</code>```

And

```<code>/**
 * @ORM\ManyToOne(targetEntity="Test", inversedBy="groupeDossier")
 * @ORM\JoinColumn(name="id_test", referencedColumnName="id")
 */
private $test;
</code>```

The best way to return what you want is :

```<code>$qb2->select('MyBundle:Test','t');
$qb2->addSelect('gd');
$qb2->addSelect('gdt');
$qb2->leftJoin('MyBundle:GroupeDossiers', 'gd',Join::WITH, 'gd.type = \'assure\' AND gd.test = t');
$qb2->leftJoin('MyBundle:GroupeDossiers', 'gdt',Join::WITH, 'gdt.type = \'tiers\' AND gdt.test = t');
</code>```

But then, you should use getArrayResult() to get gd dans gdt

With Doctrine Relationships -- Quick and dirty

In your entity, do this :

```<code>/**
 * @ORM\OneToMany(targetEntity="GroupeDossier", mappedBy="test")
 */
private $groupeDossiers;

public function getGroupesDossierSeparated() {
    $result = ['assure'=>[], 'tiers'=>[]];
    foreach ($this->groupeDossiers as $d) {
        $result[$d->getType()][] = $d;
    }
    return $result;
}
</code>```

Then, just with $qb->leftJoin('d2.groupeDossiers') you can use getGroupesDossierSeparated() to get the data you want.

Body:
i got a request with 2 leftJoin on the same table, with different alias :

$qb2->leftJoin('d2.groupeDossiers', 'gd',Join::WITH, 'gd.type = \'assure\'');
$qb2->leftJoin('d2.groupeDossiers', 'gdt',Join::WITH, 'gdt.type = \'tiers\'');

But it seems there's conflicts. How could i do that leftJoin in a single request ?
Thank you !

Body:
Without using Doctrine Relationships

If your relationship is like this :

/**
 * @ORM\OneToMany(targetEntity="GroupeDossier", mappedBy="test")
 */
private $groupeDossiers;

And

/**
 * @ORM\ManyToOne(targetEntity="Test", inversedBy="groupeDossier")
 * @ORM\JoinColumn(name="id_test", referencedColumnName="id")
 */
private $test;

The best way to return what you want is :

$qb2->select('MyBundle:Test','t');
$qb2->addSelect('gd');
$qb2->addSelect('gdt');
$qb2->leftJoin('MyBundle:GroupeDossiers', 'gd',Join::WITH, 'gd.type = \'assure\' AND gd.test = t');
$qb2->leftJoin('MyBundle:GroupeDossiers', 'gdt',Join::WITH, 'gdt.type = \'tiers\' AND gdt.test = t');

But then, you should use getArrayResult() to get gd dans gdt

With Doctrine Relationships -- Quick and dirty

In your entity, do this :

/**
 * @ORM\OneToMany(targetEntity="GroupeDossier", mappedBy="test")
 */
private $groupeDossiers;

public function getGroupesDossierSeparated() {
    $result = ['assure'=>[], 'tiers'=>[]];
    foreach ($this->groupeDossiers as $d) {
        $result[$d->getType()][] = $d;
    }
    return $result;
}

Then, just with $qb->leftJoin('d2.groupeDossiers') you can use getGroupesDossierSeparated() to get the data you want.


问:
How to secure MongoDB with username and password
I want to set up user name & password authentication for my MongoDB instance, so that any remote access will ask for the user name & password.  I tried the tutorial from the MongoDB site and did following:

```<code>use admin
db.addUser('theadmin', '12345');
db.auth('theadmin','12345');
</code>```

After that, I exited and ran mongo again.  And I don't need password to access it. Even if I connect to the database remotely, I am not prompted for user name & password.

UPDATE Here is the solution I ended up using

```<code>1) At the mongo command line, set the administrator:

    use admin;
    db.addUser('admin','123456');

2) Shutdown the server and exit

    db.shutdownServer();
    exit

3) Restart mongod with --auth

  $ sudo ./mongodb/bin/mongod --auth --dbpath /mnt/db/

4) Run mongo again in 2 ways:

   i) run mongo first then login:

        $ ./mongodb/bin/mongo localhost:27017
        use admin
        db.auth('admin','123456');

  ii) run & login to mongo in command line.

        $ ./mongodb/bin/mongo localhost:27017/admin -u admin -p 123456
</code>```

The username & password will work the same way for mongodump and mongoexport.

答:
after you create new user, please don't forget to grant read/write/root permission to the user. you can try the

cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])

Body:
I want to set up user name & password authentication for my MongoDB instance, so that any remote access will ask for the user name & password.  I tried the tutorial from the MongoDB site and did following:

use admin
db.addUser('theadmin', '12345');
db.auth('theadmin','12345');

After that, I exited and ran mongo again.  And I don't need password to access it. Even if I connect to the database remotely, I am not prompted for user name & password.

UPDATE Here is the solution I ended up using

1) At the mongo command line, set the administrator:

    use admin;
    db.addUser('admin','123456');

2) Shutdown the server and exit

    db.shutdownServer();
    exit

3) Restart mongod with --auth

  $ sudo ./mongodb/bin/mongod --auth --dbpath /mnt/db/

4) Run mongo again in 2 ways:

   i) run mongo first then login:

        $ ./mongodb/bin/mongo localhost:27017
        use admin
        db.auth('admin','123456');

  ii) run & login to mongo in command line.

        $ ./mongodb/bin/mongo localhost:27017/admin -u admin -p 123456

The username & password will work the same way for mongodump and mongoexport.


问:
How to write a single query for the below scenario?
I am new to SQL and I am facing a problem in writing a query for one scenario. I have 3 tables:

Table 1 has actor names and movie-id's

```<code>Table1
Actor-ID  Actor-name    Movies_id
</code>```

Table 2 has movie-id's and corresponding movie names.

```<code>Table2
Movies_id   Movies_name
</code>```

Table 3 has movie-id's and corresponding revenue generated by the movies.

```<code>Table3
Movies_id   Revenue_generated
</code>```

I want to write a query to fetch data for the below scenario:
All the movies of any one actor which has earned more than 100 crores.

I haven't mention any data in the tables, so feel free to add data from your side.

答:
Data :

```<code>INSERT [dbo].[Table1] ([Actor_ID], [Actor_Name], [Movies_ID]) VALUES
(1, N'A1', 2),
(2, N'A2', 1),
(3, N'A3', 3),
(3, N'A3', 4),
(2, N'A2', 6)

INSERT [dbo].[Table2] ([Movies_ID], [Movies_Name]) VALUES
(1, N'M1'),
(2, N'M2'),
(3, N'M3')
(4, N'M4'),
(5, N'M5'),
(6, N'M6')

INSERT [dbo].[Table3] ([Movies_ID], [Revenue_generated]) VALUES
(1, 50),
(2, 100),
(3, 150),
(4, 75),
(5, 120),
(6, 115)
</code>```

query :

```<code>Select
a.Actor_name,
b.Movies_name,
c.Revenue_generated
from
Table1 a
inner join Table2 b on a.Movies_ID = b.Movies_ID
inner join Table3 c on b.Movies_ID = c.Movies_ID
where c.Revenue_generated > 100 AND a.Actor_Name= 'A1'
</code>```

replace 100 with desired value.

Body:
I am new to SQL and I am facing a problem in writing a query for one scenario. I have 3 tables:

Table 1 has actor names and movie-id's

Table1
Actor-ID  Actor-name    Movies_id

Table 2 has movie-id's and corresponding movie names.

Table2
Movies_id   Movies_name

Table 3 has movie-id's and corresponding revenue generated by the movies.

Table3
Movies_id   Revenue_generated

I want to write a query to fetch data for the below scenario:
All the movies of any one actor which has earned more than 100 crores.

I haven't mention any data in the tables, so feel free to add data from your side.

Body:
Data :

INSERT [dbo].[Table1] ([Actor_ID], [Actor_Name], [Movies_ID]) VALUES
(1, N'A1', 2),
(2, N'A2', 1),
(3, N'A3', 3),
(3, N'A3', 4),
(2, N'A2', 6)

INSERT [dbo].[Table2] ([Movies_ID], [Movies_Name]) VALUES
(1, N'M1'),
(2, N'M2'),
(3, N'M3')
(4, N'M4'),
(5, N'M5'),
(6, N'M6')

INSERT [dbo].[Table3] ([Movies_ID], [Revenue_generated]) VALUES
(1, 50),
(2, 100),
(3, 150),
(4, 75),
(5, 120),
(6, 115)

query :

Select
a.Actor_name,
b.Movies_name,
c.Revenue_generated
from
Table1 a
inner join Table2 b on a.Movies_ID = b.Movies_ID
inner join Table3 c on b.Movies_ID = c.Movies_ID
where c.Revenue_generated > 100 AND a.Actor_Name= 'A1'

replace 100 with desired value.


问:
A Fatal Error Occurred While Creating An Ssl Server Credential when connect to WCF RESTfull service
I get an event with message "A Fatal Error Occurred While Creating An Ssl Server Credential"
when try to use WCF RESTfull service on XP. On Windows 7 and windows server 2008 all works fine.
Any ideas?</p>

答: IIS 6 and IIS 7 credential versions would be where I would start looking. </p>


问:
How to select top 1 and ordered by date in Oracle SQL?
There is a clear answer how to select top 1:

```<code>select * from table_name where rownum = 1
</code>```

and how to order by date in descending order:

```<code>select * from table_name order by trans_date desc
</code>```

but they does not work togeather (rownum is not generated according to trans_date):

```<code>... where rownum = 1 order by trans_date desc
</code>```

The question is how to select top 1 also ordered by date?

答:
You can use window functions for that:

```<code>select t.*
from (
  select *,
         min(trans_date) over () as min_date,
         max(trans_date) over () as max_date
  from the_table
) t
where trans_date = min_date
   or trans_date = max_date;
</code>```

Another option would be to join on the derived table

```<code>select t1.*
from the_table
  join (
    select min(trans_date) over () as min_date,
           max(trans_date) over () as max_date
    from the_table
) t2 on t1.trans_date = t2.min_date
     or t1.trans_date = t2.max_date;
</code>```

Not sure which one would be faster, you need to check the execution plan

Body:
There is a clear answer how to select top 1:

select * from table_name where rownum = 1

and how to order by date in descending order:

select * from table_name order by trans_date desc

but they does not work togeather (rownum is not generated according to trans_date):

... where rownum = 1 order by trans_date desc

The question is how to select top 1 also ordered by date?

Body:
You can use window functions for that:

select t.*
from (
  select *,
         min(trans_date) over () as min_date,
         max(trans_date) over () as max_date
  from the_table
) t
where trans_date = min_date
   or trans_date = max_date;

Another option would be to join on the derived table

select t1.*
from the_table
  join (
    select min(trans_date) over () as min_date,
           max(trans_date) over () as max_date
    from the_table
) t2 on t1.trans_date = t2.min_date
     or t1.trans_date = t2.max_date;

Not sure which one would be faster, you need to check the execution plan


问:
Creating friendly URL's in Xampp
This is my non-friendly URL: localhost/website/users/?name=UserA

Now, i tried to create a friendly URL using .htaccess file.

This is everything in my .htaccess file:

```<code>ErrorDocument 404 /movies/error404.html  #For Error 404

RewriteEngine On
RewriteRule /website/users/(.*)$ /website/users/name=$1
</code>```

Now, When I open localhost/website/users/UserA it opens error 404 page.

Yes mod_rewrite is enabled

答:
Try this in your .htaccess file

```<code>#Options +FollowSymlinks
RewriteEngine On
RewriteRule    ^users/([0-9A-Za-z]+)/?$    users/index.php?name=$1    [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ErrorDocument 404 http://localhost/movies/error404.html
</code>```

In this cause the .htaccess file would be placed under the website directory root

Note: The requests are going to index.php file which is under the users directory if you have another filename then replace it with that one

Title: Creating friendly URL's in Xampp

Body:
This is my non-friendly URL: localhost/website/users/?name=UserA

Now, i tried to create a friendly URL using .htaccess file.

This is everything in my .htaccess file:

ErrorDocument 404 /movies/error404.html  #For Error 404

RewriteEngine On
RewriteRule /website/users/(.*)$ /website/users/name=$1

Now, When I open localhost/website/users/UserA it opens error 404 page.

Yes mod_rewrite is enabled

Body:
Try this in your .htaccess file

#Options +FollowSymlinks
RewriteEngine On
RewriteRule    ^users/([0-9A-Za-z]+)/?$    users/index.php?name=$1    [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ErrorDocument 404 http://localhost/movies/error404.html

In this cause the .htaccess file would be placed under the website directory root

Note: The requests are going to index.php file which is under the users directory if you have another filename then replace it with that one