问:
How to do custom list grouping based on variable?
Say I have a list that gets generated such as:

```<code>list_x = [0,1,2,3,4,5,6,7,8,9]
</code>```

Then I divide it up like this:

```<code>list_x = [01,23,45,67,89]
</code>```

with this list comprehension:

```<code>list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])
</code>```

How can I make this code so I can group it into a grouping based on `grp_count'

for example if group_count = 5:

```<code>list_x = [01234,56789]
</code>```

I know I have to insert multiple list_x[i+n] for each addition of grouping size somehow.

答:
As I said in a comment, there's no way to create a list of integers in Python that would display like [01234,56789] because Python doesn't show the value of integers with a leading zero like that. The closest you could get is [1234, 56789].

However you can create a list of strings with those digits in them like this:

```<code>def grouper(n, iterable):
    return zip(*[iter(iterable)]*n)

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 5
new_list = [''.join(map(str, g)) for g in grouper(grp_count, list_x)]
print(new_list)  #-> ['01234', '56789']
</code>```

Body:
Say I have a list that gets generated such as:

list_x = [0,1,2,3,4,5,6,7,8,9]

Then I divide it up like this:

list_x = [01,23,45,67,89]

with this list comprehension:

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 2
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)])

How can I make this code so I can group it into a grouping based on `grp_count'

for example if group_count = 5:

list_x = [01234,56789]

I know I have to insert multiple list_x[i+n] for each addition of grouping size somehow.

Body:
As I said in a comment, there's no way to create a list of integers in Python that would display like [01234,56789] because Python doesn't show the value of integers with a leading zero like that. The closest you could get is [1234, 56789].

However you can create a list of strings with those digits in them like this:

def grouper(n, iterable):
    return zip(*[iter(iterable)]*n)

list_x = [0,1,2,3,4,5,6,7,8,9]
grp_count = 5
new_list = [''.join(map(str, g)) for g in grouper(grp_count, list_x)]
print(new_list)  #-> ['01234', '56789']


来源: stackexchange

问:
search in laravel database with live results
I'm working with Laravel 5.4 and I have a list of users in admin panel I want to add search box in top of my users list to search them and I want to results be live (when typing words results shows) I guess should use Ajax for that(not sure!)

Let say this is my users list code:

```<code>@foreach ($users as $user)
  <td>{{ $user->first_name }}</td>
  <td>{{ $user->last_name }}</td>
  <td>{{ $user->username }}</td>
  <td>{{ $user->email }}</td>
@endforeach
</code>```

How can I get that search to work with it?

Should I install any plugin or just use Vue.Js or ...?

Thanks.

答:
you actually must use ajax technology for this ..
but only once .. let the angularJS or vue do the searching function ..
i actually wanted to post a snippet here but there's seems to be a bug .. so here's a sample you might wanna see ..</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm working with Laravel 5.4 and I have a list of users in admin panel I want to add search box in top of my users list to search them and I want to results be live (when typing words results shows) I guess should use Ajax for that(not sure!)

Let say this is my users list code:

@foreach ($users as $user)
  {{ $user->first_name }}
  {{ $user->last_name }}
  {{ $user->username }}
  {{ $user->email }}
@endforeach

How can I get that search to work with it?

Should I install any plugin or just use Vue.Js or ...?

Thanks.


问:
How to echo values from two indexed arrays in an alternating fashion?
I have this code:

```<code><?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>
</code>```

And it brings: 123567abcdef. How can I get 123abc567def?

答:
How about something like this:</p>

```<code>for ($i = 1; $i < yourendvariable; $i = i + 2) {
    echo "arrayname[i] arrayname2[i + 1]";
}
</code>```

Body:
I have this code:

<?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>

And it brings: 123567abcdef. How can I get 123abc567def?

Body:
How about something like this:

for ($i = 1; $i < yourendvariable; $i = i + 2) {
    echo "arrayname[i] arrayname2[i + 1]";
}


问:
Executing a sqlalchemy exists query
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

```<code>from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)
</code>```

The output of this program is:

```<code>I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>
</code>```

答:
Unless someone suggests a better answer, here's what I've come up with that works.  Having the DB count the matching records and send just the count to the python app.

```<code>from sqlalchemy import select, func   # more imports not in my example code above

s = select([func.count(1)]).select_from(person).where(person.c.name == "Bob")
print(s)
record_count = conn.execute(s).scalar()
print("Matching records: ", record_count)
</code>```

Example output:

```<code>SELECT count(:count_2) AS count_1
FROM person
WHERE person.name = :name_1
Matching records:  1
</code>```

Title: Executing a sqlalchemy exists query

Body:
I'm having trouble understanding how to execute a query to check and see if a matching record already exists in sqlalchemy.  Most of the examples I can find online seem to reference "session" and "query" objects that I don't have.

Here's a short complete program that illustrates my problem:

1. sets up in-memory sqlite db with "person" table.

2. inserts two records into the person table.

3. check if a particular record exists in the table.  This is where it barfs.

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.sql.expression import exists

engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()

person = Table('person', metadata,
                        Column('id', Integer, primary_key=True),
                        Column('name', String(255), nullable=False))

metadata.create_all(engine)
conn = engine.connect()

s = person.insert()
conn.execute(s, name="Alice")
conn.execute(s, name="Bob")

print("I can see the names in the table:")
s = person.select()
result = conn.execute(s)
print(result.fetchall())

print('This query looks like it should check to see if a matching record exists:')
s = person.select().where(person.c.name == "Bob")
s = exists(s)
print(s)

print("But it doesn't run...")
result = conn.execute(s)

The output of this program is:

I can see the names in the table:
[(1, 'Alice'), (2, 'Bob')]
This query looks like it should check to see if a matching record exists:
EXISTS (SELECT person.id, person.name
FROM person
WHERE person.name = :name_1)
But it doesn't run...
Traceback (most recent call last):
  File "/project_path/db_test/db_test_env/exists_example.py", line 30, in <module>
    result = conn.execute(s)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/project_path/db_test/db_test_env/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 265, in _execute_on_connection
    raise exc.ObjectNotExecutableError(self)
sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: <sqlalchemy.sql.selectable.Exists object at 0x105797438>

Body:
Unless someone suggests a better answer, here's what I've come up with that works.  Having the DB count the matching records and send just the count to the python app.

from sqlalchemy import select, func   # more imports not in my example code above

s = select([func.count(1)]).select_from(person).where(person.c.name == "Bob")
print(s)
record_count = conn.execute(s).scalar()
print("Matching records: ", record_count)

Example output:

SELECT count(:count_2) AS count_1
FROM person
WHERE person.name = :name_1
Matching records:  1


问:
How to use libssh's SCP with ssh::Session
I am using libssh's C++ wrapper (libsshpp.hpp) and I'm trying to call ssh_scp_new for an SCP routine by giving it my ssh::Session variable but I get the following error:

```<code>cannot convert ‘ssh::Session’ to ‘ssh_session {aka ssh_session_struct*}’ for argument ‘1’ to ‘ssh_scp_struct* ssh_scp_new(ssh_session, int, const char*)’
</code>```

I am able to get SCP working by completely not using the C++ ssh::Session class and going with the C example but obviously this is not my preferred workaround.  Looking at libsshpp.hpp I was able to find a getCSession() function but it is only privately accessible and I'm not sure how to use it (or if it's even what I think it is).

Here is my sample code:

```<code>#include <iostream>
#include <fstream>

#include <libssh/libsshpp.hpp>

int main()
{
  int port      = 22;
  int verbosity = SSH_LOG_PROTOCOL;

  ssh::Session session;

  try
  {
    session.setOption(SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
    session.setOption(SSH_OPTIONS_PORT,          &port);
    session.setOption(SSH_OPTIONS_USER,          "user");
    session.setOption(SSH_OPTIONS_HOST,          "host");

    session.connect();

    if (session.isServerKnown() != SSH_SERVER_KNOWN_OK)
    {
      if (session.writeKnownhost() != SSH_OK)
      {
        std::cout << "writeKnownHost failed" << std::endl;
      }
      else
      {
        session.connect();
      }
    }

    if (session.userauthPassword("password") !=
        SSH_AUTH_SUCCESS)
    {
      std::cout << "Authentication Error" << std::endl;
    }

    ssh_scp scp;
    int     rc;

    // error cannot convert ‘ssh::Session’ to ‘ssh_session {aka ssh_session_struct*}’
    scp = ssh_scp_new(session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
  }
  catch (ssh::SshException e)
  {
    std::cout << "Error during connection : ";
    std::cout << e.getError() << std::endl;
  }

  return 0;
}
</code>```

How do I SCP send or receive a file with libssh using C++ methods?

Thanks!

答:
As you can see the error. You have to decide to weather use ssh::Session class or ssh_session structure. The libssh library is a C library, and it has just a C++ wrapper (that may not contain all functionalities like in the original language)
Here is how to send connect and send files using libssh library (current stable version 0.7.3) according to official documentation.

Using ssh_session: (in C)
-use ssh_new() to create a ssh_session pointer.
-use int ssh_connect(ssh_session session) to connect.
-use *int ssh_options_set   (   ssh_session     session, enum ssh_options_e type,const void *   value )*    Take a look on this documentation http://api.libssh.org/stable/group__libssh__session.html#ga7a801b85800baa3f4e16f5b47db0a73d
-add your controls
-send file using ssh_scp_new(session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
-free the connection using ssh_free(ssh_session session)

```<code>//You can try this simple program (from official libssh tutorials)
#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>
int scp_write(ssh_session session)
{
    ssh_scp scp;
    int rc;
    scp = ssh_scp_new
        (session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
    if (scp == NULL)
    {
        fprintf(stderr, "Error allocating scp session: %s\n",         ssh_get_error(session));
        return SSH_ERROR;
    }
    rc = ssh_scp_init(scp);
    if (rc != SSH_OK)
    {
        fprintf(stderr, "Error initializing scp session: %s\n", ssh_get_error(session));
        ssh_scp_free(scp);
        return rc;
    }
    ssh_scp_close(scp);
    ssh_scp_free(scp);
    return SSH_OK;
}

int main(int argc, char* argv[])
    ssh_session my_ssh_session = ssh_new();
    if (my_ssh_session == NULL)
        return 1;
    scp_write(my_ssh_session );
    ssh_free(my_ssh_session);
    return 0;
}
</code>```

Using ssh::Session (in C++) well, no wrapper allows this currently :( .

Here is some useful examples for the use of libssh library. Hope it helps !
http://api.libssh.org/master/libssh_tutorial.html

Body:
I am using libssh's C++ wrapper (libsshpp.hpp) and I'm trying to call ssh_scp_new for an SCP routine by giving it my ssh::Session variable but I get the following error:

cannot convert ‘ssh::Session’ to ‘ssh_session {aka ssh_session_struct*}’ for argument ‘1’ to ‘ssh_scp_struct* ssh_scp_new(ssh_session, int, const char*)’

I am able to get SCP working by completely not using the C++ ssh::Session class and going with the C example but obviously this is not my preferred workaround.  Looking at libsshpp.hpp I was able to find a getCSession() function but it is only privately accessible and I'm not sure how to use it (or if it's even what I think it is).

Here is my sample code:

#include <iostream>
#include <fstream>

#include <libssh/libsshpp.hpp>

int main()
{
  int port      = 22;
  int verbosity = SSH_LOG_PROTOCOL;

  ssh::Session session;

  try
  {
    session.setOption(SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
    session.setOption(SSH_OPTIONS_PORT,          &port);
    session.setOption(SSH_OPTIONS_USER,          "user");
    session.setOption(SSH_OPTIONS_HOST,          "host");

    session.connect();

    if (session.isServerKnown() != SSH_SERVER_KNOWN_OK)
    {
      if (session.writeKnownhost() != SSH_OK)
      {
        std::cout << "writeKnownHost failed" << std::endl;
      }
      else
      {
        session.connect();
      }
    }

    if (session.userauthPassword("password") !=
        SSH_AUTH_SUCCESS)
    {
      std::cout << "Authentication Error" << std::endl;
    }

    ssh_scp scp;
    int     rc;

    // error cannot convert ‘ssh::Session’ to ‘ssh_session {aka ssh_session_struct*}’
    scp = ssh_scp_new(session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
  }
  catch (ssh::SshException e)
  {
    std::cout << "Error during connection : ";
    std::cout << e.getError() << std::endl;
  }

  return 0;
}

How do I SCP send or receive a file with libssh using C++ methods?

Thanks!

Body:
As you can see the error. You have to decide to weather use ssh::Session class or ssh_session structure. The libssh library is a C library, and it has just a C++ wrapper (that may not contain all functionalities like in the original language)
Here is how to send connect and send files using libssh library (current stable version 0.7.3) according to official documentation.

Using ssh_session: (in C)
-use ssh_new() to create a ssh_session pointer.
-use int ssh_connect(ssh_session session) to connect.
-use *int ssh_options_set   (   ssh_session     session, enum ssh_options_e type,const void *   value )*    Take a look on this documentation http://api.libssh.org/stable/group__libssh__session.html#ga7a801b85800baa3f4e16f5b47db0a73d
-add your controls
-send file using ssh_scp_new(session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
-free the connection using ssh_free(ssh_session session)

//You can try this simple program (from official libssh tutorials)
#include <libssh/libssh.h>
#include <stdlib.h>
#include <stdio.h>
int scp_write(ssh_session session)
{
    ssh_scp scp;
    int rc;
    scp = ssh_scp_new
        (session, SSH_SCP_WRITE | SSH_SCP_RECURSIVE, ".");
    if (scp == NULL)
    {
        fprintf(stderr, "Error allocating scp session: %s\n",         ssh_get_error(session));
        return SSH_ERROR;
    }
    rc = ssh_scp_init(scp);
    if (rc != SSH_OK)
    {
        fprintf(stderr, "Error initializing scp session: %s\n", ssh_get_error(session));
        ssh_scp_free(scp);
        return rc;
    }
    ssh_scp_close(scp);
    ssh_scp_free(scp);
    return SSH_OK;
}

int main(int argc, char* argv[])
    ssh_session my_ssh_session = ssh_new();
    if (my_ssh_session == NULL)
        return 1;
    scp_write(my_ssh_session );
    ssh_free(my_ssh_session);
    return 0;
}

Using ssh::Session (in C++) well, no wrapper allows this currently :( .

Here is some useful examples for the use of libssh library. Hope it helps !
http://api.libssh.org/master/libssh_tutorial.html


问:
Cannot find namespace Microsoft.Azure in Visual Studio Mac
I'm trying out to create a simple DocumentDb hello world program and am getting type or namespace name 'Azure' does not exist in namespace 'Microsoft'

using Microsoft.Azure

I added the DocumentDb library via Nuget.  Do I need to manually add a reference to it after I add the nuget package?  I thought using nuget automatically adds the project references.

答:
According to your another SO thread, it seems that you use the .net project not .net core project.

The .NET Framework provides a comprehensive programming model for building all kinds of applications on Windows, from mobile to web to desktop.

Please have a try to creat a .net core project.
We could get the Microsoft.Azure.DocumentDB.Core from nuget. I test creating a document on windows platform with .net core project. It works correctly on my side. I assume it should also work on Mac. The following is my demo code.

```<code> var endpointUrl = "https://documentdbnamespace.documents.azure.com:443/";
 var authorizationKey = "xxxxxxxxxx";
 var databaseId = "database";
 var collectionId = "collection"; //I use an existing collect

 using (_client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
    {
       var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
       var product = new Product
          {
             Id= Guid.NewGuid().ToString(),
             ProductId = "test"
          };
       Document created =  _client.CreateDocumentAsync(collectionLink, product).Result;
     }
</code>```

Product.cs Class :

```<code> public class Product
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        // used to set expiration policy
        [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
        public int? TimeToLive { get; set; }

        public string ProductId { get; set; }
        public DateTime DateStarted { get; set; }
    }
</code>```

We also could get more document example code from the document.

Body:
According to your another SO thread, it seems that you use the .net project not .net core project.

The .NET Framework provides a comprehensive programming model for building all kinds of applications on Windows, from mobile to web to desktop.

Please have a try to creat a .net core project.
We could get the Microsoft.Azure.DocumentDB.Core from nuget. I test creating a document on windows platform with .net core project. It works correctly on my side. I assume it should also work on Mac. The following is my demo code.

 var endpointUrl = "https://documentdbnamespace.documents.azure.com:443/";
 var authorizationKey = "xxxxxxxxxx";
 var databaseId = "database";
 var collectionId = "collection"; //I use an existing collect

 using (_client = new DocumentClient(new Uri(endpointUrl), authorizationKey))
    {
       var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
       var product = new Product
          {
             Id= Guid.NewGuid().ToString(),
             ProductId = "test"
          };
       Document created =  _client.CreateDocumentAsync(collectionLink, product).Result;
     }

Product.cs Class :

 public class Product
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }

        // used to set expiration policy
        [JsonProperty(PropertyName = "ttl", NullValueHandling = NullValueHandling.Ignore)]
        public int? TimeToLive { get; set; }

        public string ProductId { get; set; }
        public DateTime DateStarted { get; set; }
    }

We also could get more document example code from the document.


问:
PHP Paypal recurring payment
Hi
Can someone please explain me if "PayPal recurring payment" and "Paypal subscription" are the same thing?

Like I am working on a monthly membership payment integration with php and paypal. What I need to do is make this go on forever until the member decides to opt out. I am using this class found at www.micahcarrick.com/php-paypal-ipn-integration-class.html for the integration.

In the class you can mention like for how long you would like to make it as recurring payment but there are no options to make it go forever like a monthly subscription thing. Please help!

Many thanks in advance and I really appreciate your help :-))

答:
These are not the same thing. A standard PayPal account can create subscriptions but not recurring payments. If you plan to use IPN as your only integration, you need to create subscriptions, not recurring payments. You do not create them programmatically, you just generate a subscription link and the buyer creates the subscription on the PayPal website.

Recurring payments are part of one of the APIs accessible to PayPal Website Payments Pro accounts.

ContentLicense: CC BY-SA 2.5

Title: PHP Paypal recurring payment


问:
Unauthorized, The input authorization token can't serve the request
I am trying to obtain documentdbclient using the resourcetokens. I have a redis cluster with key as user identity and value as the resourcetoken.
I have a service that uses master key to generate resourcetokens for the user and updates them in Redis. I am using the below code to create resource token in my master service

```<code>  ResourceResponse<Permission> readPermissions = documentClient.readPermission("/dbs/customerdb/users/mobileuser/permissions/readperm", null);
        String accessToken=permission.getToken();
DocumentClient documentClient = new DocumentClient(HOST, MASTER_KEY,
                     ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
</code>```

Then i use below code to get resourcetoken and store it in redis

```<code>jedis.put("Client_1",readPermissions .getResource().getToken());
</code>```

Now, at client side when i try to create documentClient using the resourcetoken

```<code>DocumentClient manageClient = new DocumentClient(HOST,  jedis.get("Client_1"),ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
</code>```

I get logs stating unauthorized and following that the error

```<code>Unauthorized, The input authorization token can't serve the request
</code>```

I have created a user called mobileuser on database customerdb and permission with mode PermissionMode.Read on collection customers

I changed my code to be very sure that the tokens are not getting expired but still getting error

```<code>  java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get
</code>```

colls
dxhxakm3caa=
mon, 05 jun 2017 08:56:40 gmt

below id the code that i used to get the token

```<code>    ResourceResponse<Permission> permissions=documentClient.readPermission("/dbs/customerdd/users/mobileuser/permissions/readperm", null);
    System.out.println(permissions.getResource().getResourceLink());
    DocumentClient managedClient=new DocumentClient(HOST,permissions.getResource().getToken(), ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
    FeedResponse<Document> response = managedClient.queryDocuments(collection.getResource().getSelfLink(), "SELECT customers.source FROM customers where customers.source='direct-mail'", null);
    Iterator<Document> itr = response.getQueryIterator();
    while(itr.hasNext()){
        Document doc=itr.next();
        System.out.println(doc.get("source"));
    }
</code>```

Any pointer will be of a great help

答:
Unauthorized, The input authorization token can't serve the request

As far as I know, the default valid timespan of the resource token is one hour. And if the resource token expires, subsequent requests receive a 401 unauthorized exception, please make sure if the resource token is expired when you retrieve it from Redis cache.

Update:

If i use the overloaded constructor of DocumentClient and pass the PermissionFeed then it works

DocumentClient class has two constructors as below, and when you use new DocumentClient(HOST,  jedis.get("Client_1"),ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);, it seems that it recognizes jedis.get("Client_1") that you passed as a string and use the second constructor to initialize a new instance, which would be the cause of the issue.

Body:
I am trying to obtain documentdbclient using the resourcetokens. I have a redis cluster with key as user identity and value as the resourcetoken.
I have a service that uses master key to generate resourcetokens for the user and updates them in Redis. I am using the below code to create resource token in my master service

  ResourceResponse<Permission> readPermissions = documentClient.readPermission("/dbs/customerdb/users/mobileuser/permissions/readperm", null);
        String accessToken=permission.getToken();
DocumentClient documentClient = new DocumentClient(HOST, MASTER_KEY,
                     ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);

Then i use below code to get resourcetoken and store it in redis

jedis.put("Client_1",readPermissions .getResource().getToken());

Now, at client side when i try to create documentClient using the resourcetoken

DocumentClient manageClient = new DocumentClient(HOST,  jedis.get("Client_1"),ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);

I get logs stating unauthorized and following that the error

Unauthorized, The input authorization token can't serve the request

I have created a user called mobileuser on database customerdb and permission with mode PermissionMode.Read on collection customers

I changed my code to be very sure that the tokens are not getting expired but still getting error

  java.lang.IllegalStateException: com.microsoft.azure.documentdb.DocumentClientException: The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get

colls
dxhxakm3caa=
mon, 05 jun 2017 08:56:40 gmt

below id the code that i used to get the token

    ResourceResponse<Permission> permissions=documentClient.readPermission("/dbs/customerdd/users/mobileuser/permissions/readperm", null);
    System.out.println(permissions.getResource().getResourceLink());
    DocumentClient managedClient=new DocumentClient(HOST,permissions.getResource().getToken(), ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
    FeedResponse<Document> response = managedClient.queryDocuments(collection.getResource().getSelfLink(), "SELECT customers.source FROM customers where customers.source='direct-mail'", null);
    Iterator<Document> itr = response.getQueryIterator();
    while(itr.hasNext()){
        Document doc=itr.next();
        System.out.println(doc.get("source"));
    }

Any pointer will be of a great help


问:
How to centerize a UICollectionView cell after it has been loaded?
My code below to centerize it:-

```<code>- (void)centerUpNext:(NSIndexPath*)indexPath {
    //[super viewDidLayoutSubviews];
    [self.collectionView2 scrollToItemAtIndexPath:indexPath
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
</code>```

This is how I assign indexPath value:-

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath

    if(result == NSOrderedDescending)
        {
            NSLog(@"reminderTime is later than systemTime");
            self.upNextIndexPath = indexPath;
        }
</code>```

And I'll call it from viewWillAppear

```<code>-(void) viewWillAppear:(BOOL)animated
[self centerUpNext:self.upNextIndexPath];
</code>```

This is not working as intended. As I am unable to centerize the exact cell after the collectionview is loaded. Where and when should I call this method [self centerUpNext:self.upNextIndexPath]; ?

答:
I think using KVO is the best solution.

In viewDidLoad, you can add

```<code>[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:"contentSize"];
</code>```

And then:

```<code>- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqual: @"contentSize"]) {
        if ([change[NSKeyValueChangeNewKey] CGSizeValue].height != 0 && [change[NSKeyValueChangeNewKey] CGSizeValue].width != 0) {
        [self centerUpNext:self.upNextIndexPath];
    }
}
</code>```

}

Body:
My code below to centerize it:-

- (void)centerUpNext:(NSIndexPath*)indexPath {
    //[super viewDidLayoutSubviews];
    [self.collectionView2 scrollToItemAtIndexPath:indexPath
                                    atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

This is how I assign indexPath value:-

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath

    if(result == NSOrderedDescending)
        {
            NSLog(@"reminderTime is later than systemTime");
            self.upNextIndexPath = indexPath;
        }

And I'll call it from viewWillAppear

-(void) viewWillAppear:(BOOL)animated
[self centerUpNext:self.upNextIndexPath];

This is not working as intended. As I am unable to centerize the exact cell after the collectionview is loaded. Where and when should I call this method [self centerUpNext:self.upNextIndexPath]; ?

Body:
I think using KVO is the best solution.

In viewDidLoad, you can add

[self.collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:"contentSize"];

And then:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqual: @"contentSize"]) {
        if ([change[NSKeyValueChangeNewKey] CGSizeValue].height != 0 && [change[NSKeyValueChangeNewKey] CGSizeValue].width != 0) {
        [self centerUpNext:self.upNextIndexPath];
    }
}

}


问:
Swift 3.0 Placing a Annotation On MapView
I have my code set up such that a long press on the mapView will allow the user to drop a pin. I was wondering if there was a way that could allow the user to type in a title for the annotation, that way after pressing the annotation (once the pin is placed), the title would show up.   </p>

```<code>var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    let mapPress = UILongPressGestureRecognizer(target: self, action: #selector(AddressVC.addAnnotation(_:)))
    mapPress.minimumPressDuration = 1.5
    mapView.addGestureRecognizer(mapPress)
    }

func addAnnotation(_ recognizer: UIGestureRecognizer){
    let annotations = self.mapView.annotations
    self.mapView.removeAnnotations(annotations)
    let touchedAt = recognizer.location(in: self.mapView) // adds the location on the view it was pressed
    let newCoordinates : CLLocationCoordinate2D = mapView.convert(touchedAt, toCoordinateFrom: self.mapView) // will get coordinates

    let annotation = MKPointAnnotation()
    annotation.coordinate = newCoordinates
    self.mapView.addAnnotation(annotation)
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if (annotation is MKUserLocation) {
        //if annotation is not an MKPointAnnotation (eg. MKUserLocation),
        return nil
    }
    let identifier = "pinAnnotation"
    if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
        annotationView.annotation = annotation
        return annotationView
    } else {
        let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier: identifier)
        annotationView.isEnabled = true
        annotationView.canShowCallout = true

        return annotationView
    }
}
</code>```

答:
I suggest using an UIAlertController with a UITextField for the user to enter a name.

```<code>import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var map: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tap = UILongPressGestureRecognizer(target: self, action: #selector(self.createAnnotation))

        self.map.addGestureRecognizer(tap)
    }

    func createAnnotation(gesture: UILongPressGestureRecognizer){

        if gesture.state == .began {

            let point = gesture.location(in: self.map)

            let coordinate = self.map.convert(point, toCoordinateFrom: nil)

            let alertVC = UIAlertController(title: "Create Pin", message: "Enter a title for your pin.", preferredStyle: .alert)

            alertVC.addTextField { (textfield) in

                textfield.placeholder = "Enter a Title"

                textfield.autocapitalizationType = .words
            }

            alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            alertVC.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in

                guard

                    let textfield = alertVC.textFields?.first,

                    let text = textfield.text

                    else {

                        return
                }

                let pin = MKPointAnnotation()

                pin.title = text

                pin.coordinate = coordinate

                self.map.addAnnotation(pin)
            }))

            self.present(alertVC, animated: true, completion: nil)
        }
    }
}
</code>```

Body:
I have my code set up such that a long press on the mapView will allow the user to drop a pin. I was wondering if there was a way that could allow the user to type in a title for the annotation, that way after pressing the annotation (once the pin is placed), the title would show up.

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    let mapPress = UILongPressGestureRecognizer(target: self, action: #selector(AddressVC.addAnnotation(_:)))
    mapPress.minimumPressDuration = 1.5
    mapView.addGestureRecognizer(mapPress)
    }

func addAnnotation(_ recognizer: UIGestureRecognizer){
    let annotations = self.mapView.annotations
    self.mapView.removeAnnotations(annotations)
    let touchedAt = recognizer.location(in: self.mapView) // adds the location on the view it was pressed
    let newCoordinates : CLLocationCoordinate2D = mapView.convert(touchedAt, toCoordinateFrom: self.mapView) // will get coordinates

    let annotation = MKPointAnnotation()
    annotation.coordinate = newCoordinates
    self.mapView.addAnnotation(annotation)
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if (annotation is MKUserLocation) {
        //if annotation is not an MKPointAnnotation (eg. MKUserLocation),
        return nil
    }
    let identifier = "pinAnnotation"
    if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) {
        annotationView.annotation = annotation
        return annotationView
    } else {
        let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier: identifier)
        annotationView.isEnabled = true
        annotationView.canShowCallout = true

        return annotationView
    }
}

Body:
I suggest using an UIAlertController with a UITextField for the user to enter a name.

import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var map: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tap = UILongPressGestureRecognizer(target: self, action: #selector(self.createAnnotation))

        self.map.addGestureRecognizer(tap)
    }

    func createAnnotation(gesture: UILongPressGestureRecognizer){

        if gesture.state == .began {

            let point = gesture.location(in: self.map)

            let coordinate = self.map.convert(point, toCoordinateFrom: nil)

            let alertVC = UIAlertController(title: "Create Pin", message: "Enter a title for your pin.", preferredStyle: .alert)

            alertVC.addTextField { (textfield) in

                textfield.placeholder = "Enter a Title"

                textfield.autocapitalizationType = .words
            }

            alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            alertVC.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in

                guard

                    let textfield = alertVC.textFields?.first,

                    let text = textfield.text

                    else {

                        return
                }

                let pin = MKPointAnnotation()

                pin.title = text

                pin.coordinate = coordinate

                self.map.addAnnotation(pin)
            }))

            self.present(alertVC, animated: true, completion: nil)
        }
    }
}


问:
Check if password is valid in Keycloak from Spring Boot Application
My user is already loggedin with a valid token, but in some important operations (like confirm or cancel of a paid subscription), I want it to send the password along the other data, so the server validate it.
By now, my application has the users in a database, and it was easy to develop this way.

How can I check that user sent password correctly? Will I need to try to login with the username and password in my backend?

答:
Your backend should already be setup as a Keycloak Client so that it can pass tokens for validation / introspection.

If you enable "Direct Access Grants" it will allow the backend to directly pass and verify username and password credentials with Keycloak.


问:
import cvxopt.base: the specified module could not be found
I'm new to Python, just installed cvxopt module for my Python3.3 system (64 bit). The installation was successful, but when I typed "import cvxopt" in Python command line, it returned an error:

File "C:\Program Files
  (x86)\Python\lib\site-packages\cvxopt__init__.py", line 33, in
   import cvxopt.base ImportError: DLL load failed: The
  specified module could not be found.

Could anyone help me on this problem? Thanks a lot!

答: The package CVXOPT requires numpy+mkl, you can try uninstall the numpy package and reinstall numpy+mkl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy, then importing the CVXOPT, it will work.</p>


问:
Grid with different size squares next to, and on top of each other
I am trying to create something like so:

I am sure I am starting out wrong but I cannot see how else, plus I can't find anything online to help. My code so far is:

```<code><div class="container">
    <div class="one">
        one
    </div>
    <div class="two">
        two
    </div>
    <div class="three">
        three
    </div>
    <div class="four">
        four
    </div>
    <div class="five">
        five
    </div>
    <div class="six">
        six
    </div>
</div>
</code>```

And the css

```<code>.container {
  background-color: blue;
  display: flex;
}

.one {
  height: 400px;
  width: 30%;
  background-color: red;
}
.two {
  height: 250px;
  width: 35%;
  background-color: white;
}
.three {
  height: 400px;
  width: 35%;
  background-color: lightblue;
}
</code>```

The problem is that I cannot get the next set of divs to line up under correctly. Jsfiddle

答:
Solution1: Why not you use Bootstrap, Thanks.

```

<ul>
<li><strong>Solution2</strong>: Use <strong>Masonry Grid</strong>:</li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    width: 100%;
    max-width: 700px;
    margin: 2em auto;
}
.cols {
    -moz-column-count:3;
    -moz-column-gap: 3%;
    -moz-column-width: 30%;
    -webkit-column-count:3;
    -webkit-column-gap: 3%;
    -webkit-column-width: 30%;
    column-count: 3;
    column-gap: 3%;
    column-width: 30%;
}
.box {
    margin-bottom: 20px;
}
.box.one {
    height: 200px;
    background-color: #d77575;
}
.box.two {
    height: 300px;
    background-color: #dcbc4c;
}
.box.three {
    background-color: #a3ca3b;
    height: 400px;
}
.box.four {
    background-color: #3daee3;
    height: 500px;
}
.box.five {
    background-color: #bb8ed8;
    height: 600px;
}
.box.six {
    background-color: #baafb1;
    height: 200px;
}</code>```

```

Body:
I am trying to create something like so:

I am sure I am starting out wrong but I cannot see how else, plus I can't find anything online to help. My code so far is:

        one

        two

        three

        four

        five

        six

And the css

.container {
  background-color: blue;
  display: flex;
}

.one {
  height: 400px;
  width: 30%;
  background-color: red;
}
.two {
  height: 250px;
  width: 35%;
  background-color: white;
}
.three {
  height: 400px;
  width: 35%;
  background-color: lightblue;
}

The problem is that I cannot get the next set of divs to line up under correctly. Jsfiddle

Body:
Solution1: Why not you use Bootstrap, Thanks.

<div class="container-fluid">
    <div class="row">
        <div class="col-md-2">
        </div>
        <div class="col-md-5">
            <div class="row">
                <div class="col-md-12">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                </div>
            </div>
        </div>
        <div class="col-md-5">
        </div>
    </div>
    <div class="row">
        <div class="col-md-5">
            <div class="row">
                <div class="col-md-12">
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                </div>
                <div class="col-md-6">
                </div>
            </div>
        </div>
        <div class="col-md-5">
            <div class="row">
                <div class="col-md-12">
                </div>
            </div>
            <div class="row">
                <div class="col-md-12">
                </div>
            </div>
        </div>
        <div class="col-md-2">
        </div>
    </div>
</div>

Solution2: Use Masonry Grid:

#container {
    width: 100%;
    max-width: 700px;
    margin: 2em auto;
}
.cols {
    -moz-column-count:3;
    -moz-column-gap: 3%;
    -moz-column-width: 30%;
    -webkit-column-count:3;
    -webkit-column-gap: 3%;
    -webkit-column-width: 30%;
    column-count: 3;
    column-gap: 3%;
    column-width: 30%;
}
.box {
    margin-bottom: 20px;
}
.box.one {
    height: 200px;
    background-color: #d77575;
}
.box.two {
    height: 300px;
    background-color: #dcbc4c;
}
.box.three {
    background-color: #a3ca3b;
    height: 400px;
}
.box.four {
    background-color: #3daee3;
    height: 500px;
}
.box.five {
    background-color: #bb8ed8;
    height: 600px;
}
.box.six {
    background-color: #baafb1;
    height: 200px;
}

<div id="container" class="cols">
    <div class="box one"></div>
    <div class="box two"></div>
    <div class="box one"></div>
    <div class="box three"></div>
    <div class="box two"></div>
    <div class="box five"></div>
    <div class="box one"></div>
    <div class="box two"></div>
    <div class="box six"></div>
    <div class="box three"></div>
    <div class="box two"></div>
</div>


问:
Having two lists as a value to a single key: Dictionaries
Looking for a way to add two lists to a value in a dictionary for example if want to add two lists to a single value for example

For example this dictionary dict1 = {a: [], b:[], c:[]}

Would become dict1 = {a:([1,3,4,5,6],[1,2,3,4]),b:[],c:[]}

When you add the two lists [1,2,3,4,5,6] and [1,2,3,4] to the key a.
And if you were to print the key a you would get the two lists as output

Any help would be much appreciated

答:
you can also doing it in this way by adding two list [a]+[b]

Edit:  from the comment. Another better way [a,b]

```<code>dict1 = {'a': [], 'b':[], 'c':[]}
a = [1,2,3,4,5,6]
b = ['a','b']
dict1['a']=[a]+[b]
print(dict1)
</code>```

Body:
you can also doing it in this way by adding two list [a]+[b]

Edit:  from the comment. Another better way [a,b]

dict1 = {'a': [], 'b':[], 'c':[]}
a = [1,2,3,4,5,6]
b = ['a','b']
dict1['a']=[a]+[b]
print(dict1)


问:
How do you set text color of disabled form control button
I am trying to set the color of text in a control button to the same color of the control when it is disabled.
In other words... I don't want any text to show when button is disabled.

I don't know how else to phrase this question.

It is just important for the text not to appear when disabled.

Thank you for your help.

答:
Set visibiliy of control to false.

If you don't want to display text

you can hide button

button.Visible=false;

OR

you can set text to empty

button.Text="";

See also my question Change TextColor of disabled control


问:
C How to get number of players and their names
Hi am trying to learn how to program and i would like the user to input how many players there are as well as their first names. i thought i was correct with my following code after watching some youtube videos and looking elsewhere online but i cannot see where i have gone wrong. if someone could please help that would be awesome.</p>

```<code>int main() {
  int i, player_num;
  char names[8][25];

  printf("\n\n");

  //user inputs value of player_num, here, as you have now

  for(i = 0; i < player_num; i++) {
    printf("Enter the player's name: ");
    scanf("%s", names[i]);  //enters name and creates a newline <enter key>
    getchar();                   //removes the newline from the keyboard buffer
  }
  printf("\n\n");
  for(i = 0; i < player_num; i++)
    printf("\n%s", names[i]);

  printf("\n\n\t\t\t     press enter when ready");

  getchar();   //holds the console window open until you press enter
  return 0;
}
</code>```

答:
You want to enter the number of player. It seems that you have already written code for entering players name. So for entering number of Player you need to use one scanf()

```<code>int main()
{
   int i, player_num;
   char names[8][25];
   printf("\n\n");
//user inputs value of player_num, here, as you have now
   printf("Enter the number of player(from 1 to 8)\n");
   scanf_s("%d",&player_num,sizeof(int));
   for(i = 0; i < player_num; i++) {
     printf("Enter the player's name: ");
     scanf_s("%s", names[i],25);  //enters name and creates a newline <enter key>
     getchar();               //removes the newline from the keyboard buffer
   }
   printf("\n\n");
   for(i = 0; i < player_num; i++)
      printf("\n%s", names[i]);
   printf("\n\n\t\t\t     press enter when ready");
   getchar();   //holds the console window open until you press enter
   return 0;
}
</code>```

Hope this Helps :)

Body:
Hi am trying to learn how to program and i would like the user to input how many players there are as well as their first names. i thought i was correct with my following code after watching some youtube videos and looking elsewhere online but i cannot see where i have gone wrong. if someone could please help that would be awesome.

int main() {
  int i, player_num;
  char names[8][25];

  printf("\n\n");

  //user inputs value of player_num, here, as you have now

  for(i = 0; i < player_num; i++) {
    printf("Enter the player's name: ");
    scanf("%s", names[i]);  //enters name and creates a newline <enter key>
    getchar();                   //removes the newline from the keyboard buffer
  }
  printf("\n\n");
  for(i = 0; i < player_num; i++)
    printf("\n%s", names[i]);

  printf("\n\n\t\t\t     press enter when ready");

  getchar();   //holds the console window open until you press enter
  return 0;
}

Body:
You want to enter the number of player. It seems that you have already written code for entering players name. So for entering number of Player you need to use one scanf()

int main()
{
   int i, player_num;
   char names[8][25];
   printf("\n\n");
//user inputs value of player_num, here, as you have now
   printf("Enter the number of player(from 1 to 8)\n");
   scanf_s("%d",&player_num,sizeof(int));
   for(i = 0; i < player_num; i++) {
     printf("Enter the player's name: ");
     scanf_s("%s", names[i],25);  //enters name and creates a newline <enter key>
     getchar();               //removes the newline from the keyboard buffer
   }
   printf("\n\n");
   for(i = 0; i < player_num; i++)
      printf("\n%s", names[i]);
   printf("\n\n\t\t\t     press enter when ready");
   getchar();   //holds the console window open until you press enter
   return 0;
}

Hope this Helps :)


问:
How to fetch radio button value dynamically in angular 2?
Need to display radio button values dynamically from array, and fetch the value of it based on which I need to display a
. please find the code below

html

```<code><div *ngFor = "let fruit of fruits"
<input type = "radio"/>{{fruit}}>
</div>
</code>```

component.ts -> contains the following array

```<code>fruits : string[] = ["apple", "mango"];
</code>```

With this I am getting the radio buttons apple and mango.Need to get the value of the selected radio button (in assigning[(ngModel)], value) and Need to display another div based on individual selections.
Please guide me on this

答:
You can use [value]

```<code><div *ngFor="let fruit of fruits">
    <input type="radio" formControlName="options" [value]="fruit">
    {{fruit}}
</div>`
</code>```

Body:
Need to display radio button values dynamically from array, and fetch the value of it based on which I need to display a
. please find the code below

html

<div *ngFor = "let fruit of fruits"
<input type = "radio"/>{{fruit}}>

component.ts -> contains the following array

fruits : string[] = ["apple", "mango"];

With this I am getting the radio buttons apple and mango.Need to get the value of the selected radio button (in assigning[(ngModel)], value) and Need to display another div based on individual selections.
Please guide me on this

Body:
You can use [value]

<div *ngFor="let fruit of fruits">
    <input type="radio" formControlName="options" [value]="fruit">
    {{fruit}}
</div>`


问:
Azure Web Site App with multiple custom domains
I have a web app service set up in Azure. With the default auto generated name it is working fine.

I need to add several custom domain I've purchased. Let's say domain1.com, domain2.com, etc.

I went to my App Service > Custom domains > + Add host > Validated domain1.com succesfuly. I clicked on "Add host name" button, and domain1.com was successfuly added to my Azure Web App.

The thing is that, when I follow all the same steps to add domain2.com, Azure alerts states that domain2.com was successfuly added, but in fact it wasn't added at all.

I tried several times now. It always says it was added, but the second domain name does not appear listed along with the first one.

Any thoughts?

Thank you!!

答:
According to your description, I have mapped multiple custom domains to my web app. It works well, the result as below:

I suggest you could try another way(use code or powershell) to list your current web app's hostname.

If the hostname has been already set, but the portal doesn't show it, I suggest you firstly refresh your web browser. If this operation is useless, I suggest you could send the feedback to azure support team and delete the hostname by code or powershell. At last, you could try to bind the hostname again.

More details about how to list the hostname and delete the hostname by code(Using azure management fluent api which could be downloaded from Nuget), you could refer to below codes:

Using this way, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.

```<code>  string subscription = "subscriptionid";
            string client = "clientid";
            string key = "clientkey";
            string tenant = "tenantid";

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(client,key,tenant,AzureEnvironment.AzureGlobalCloud);

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            //List the hostname
            var resut = azure.WebApps.GetByResourceGroup("ResourceGroupName", "WebappName").EnabledHostNames; ;

            var app1 = azure.WebApps.GetByResourceGroup("ResourceGroupName", "WebappName");

            //Delete the hostname
            app1 = app1.Update().WithoutHostnameBinding("yourCustomDomain").Apply();
</code>```

Result:

Body:
According to your description, I have mapped multiple custom domains to my web app. It works well, the result as below:

I suggest you could try another way(use code or powershell) to list your current web app's hostname.

If the hostname has been already set, but the portal doesn't show it, I suggest you firstly refresh your web browser. If this operation is useless, I suggest you could send the feedback to azure support team and delete the hostname by code or powershell. At last, you could try to bind the hostname again.

More details about how to list the hostname and delete the hostname by code(Using azure management fluent api which could be downloaded from Nuget), you could refer to below codes:

Using this way, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.

  string subscription = "subscriptionid";
            string client = "clientid";
            string key = "clientkey";
            string tenant = "tenantid";

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(client,key,tenant,AzureEnvironment.AzureGlobalCloud);

            var azure = Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(credentials)
                .WithDefaultSubscription();

            //List the hostname
            var resut = azure.WebApps.GetByResourceGroup("ResourceGroupName", "WebappName").EnabledHostNames; ;

            var app1 = azure.WebApps.GetByResourceGroup("ResourceGroupName", "WebappName");

            //Delete the hostname
            app1 = app1.Update().WithoutHostnameBinding("yourCustomDomain").Apply();

Result:


问:
Play a youtube video when an image is clicked and go back to the image when video ends
I am developing an website where my client wants to be able to play an youtube video when he clicks an image and when the video finishes, the video disappears and the same image reappears again.

For example, view the website below and click the image on the home page.
https://www.oldbankruptcypapers.com/

答:
You can use the youtube Iframe API (https://developers.google.com/youtube/iframe_api_reference) to resolve this.

Here is the example script:

```<code>$('#yourImage').on('click', function () {
    var player = new YT.Player('yourDivToAppendVideo', {
        // height: '1080',
        // width: '1920',
        videoId: 'putVideoIdHere',
        playerVars: {
            'autoplay': 1,
            'controls': 0,
            'showinfo': 0,
            // and other options
        },
        events: {
            'onReady': function (event) {
                // Write your logic to HIDE the image here
                event.target.playVideo(); // play video
            },
            'onStateChange': function (event) {
                if (event.data == YT.PlayerState.ENDED) {
                    // Write your logic to UNHIDE the image here
                }
            }
        }
    });
}
</code>```

Body:
You can use the youtube Iframe API (https://developers.google.com/youtube/iframe_api_reference) to resolve this.

Here is the example script:

$('#yourImage').on('click', function () {
    var player = new YT.Player('yourDivToAppendVideo', {
        // height: '1080',
        // width: '1920',
        videoId: 'putVideoIdHere',
        playerVars: {
            'autoplay': 1,
            'controls': 0,
            'showinfo': 0,
            // and other options
        },
        events: {
            'onReady': function (event) {
                // Write your logic to HIDE the image here
                event.target.playVideo(); // play video
            },
            'onStateChange': function (event) {
                if (event.data == YT.PlayerState.ENDED) {
                    // Write your logic to UNHIDE the image here
                }
            }
        }
    });
}


问:
disable caps lock detection for soft keyboards (mobile browsers)
For password inputs I have some JavaScript which checks if caps lock is pressed so as to warn the user.  It uses the "standard" way of doing this -- looking at keyboardEvent.keyCode and keyboardEvent.shiftKey (and some other nonsense for ancient browsers).

The problem is this is annoying for mobile users (at least iOS, no reports from Android people) because "caps lock" is the normal way one gets a capital letter.

Currently I am using some grievous user agent sniffing to disable this, but I am feeling there has to be a less fragile way of knowing that this is a soft (mobile) keyboard and caps lock for uppercase is the normal way of things (so I quit bellyaching about it!)

答:
So, imperfect as it is, this is what I came up with:</p>

```<code>$(document).ready(function() {
        function hasTouch() {
                try {
                        document.createEvent("TouchEvent");
                } catch (e) {
                        return false;
                }
                return true;
        }
        capsLockQuiet = hasTouch();
        ...
});
</code>```

Body:
So, imperfect as it is, this is what I came up with:

$(document).ready(function() {
        function hasTouch() {
                try {
                        document.createEvent("TouchEvent");
                } catch (e) {
                        return false;
                }
                return true;
        }
        capsLockQuiet = hasTouch();
        ...
});


问:
How to echo values from two indexed arrays in an alternating fashion?
I have this code:

```<code><?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>
</code>```

And it brings: 123567abcdef. How can I get 123abc567def?

答:
Just try this:</p>

```<code>$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName = array_combine($arrayName2,$arrayName3);
foreach ($arrayName as $key => $value) {
  echo $key.$value;
}
</code>```

Body:
I have this code:

<?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>

And it brings: 123567abcdef. How can I get 123abc567def?

Body:
Just try this:

$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName = array_combine($arrayName2,$arrayName3);
foreach ($arrayName as $key => $value) {
  echo $key.$value;
}


问:
remove default nginx welcome page when access directly from ip address
At my ubuntu server, I install nginx and setup virtual host using this article.
https://www.digitalocean.com/community/articles/how-to-set-up-nginx-virtual-hosts-server-blocks-on-ubuntu-12-04-lts--3

The virtual host's domain name is like www.example.com. When I go to www.example.com, I can see my application's index page. However, when I go to the real ip address, I still see the nginx welcome page. What can I do to remove this welcome page or point to www.example.com if someone uses ip address to access my site?

I setup a A record to point ip xxx.xxx.xxx.xxx to www.example.com.

答:
You need to remove the file default, located in /etc/nginx/sites-enabled:

```<code>rm /etc/nginx/sites-enabled/default
</code>```

Then restart nginx:

```<code>service nginx reload
</code>```

Body:
You need to remove the file default, located in /etc/nginx/sites-enabled:

rm /etc/nginx/sites-enabled/default

Then restart nginx:

service nginx reload


答:
You can follow below approach to achieve that :

When you click on the image, hide it and make your player container div visible. Bind onStateChange event of your YT Player to check for video ending and then hide the player or remove it and make your image visible.

Below is the code snippet :

```<code><img src="http://d3gnp09177mxuh.cloudfront.net/tech-page-images/java.png" id="javaImg">
<div id="playerContainer">
  <div id="player" width="300" align="left" height="238" style="margin-right:30px;"></div>
</div>

$("#javaImg").click(function(){
if($("#player").is("div"))
{
  $(this).hide();
  player = new YT.Player('player', {
    height: '335',
    width: '596',
    playerVars: { 'controls': 1,'autohide':1},
    videoId: 'r59xYe3Vyks',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

}
  else {
    player.autohide=1;
    player.playVideo();
  }
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  function onPlayerStateChange(event) {
    if(event.data === 0) {
      $("#player").remove();
      $("#playerContainer").append('<div id ="player" width="300" align="left" height="238" style="margin-right:30px;"></div>');
      $("#javaImg").show();
    }
  }
});
</code>```

I have also created a fiddle, https://jsfiddle.net/qLzpg27g/

Title: Play a youtube video when an image is clicked and go back to the image when video ends

Body:
I am developing an website where my client wants to be able to play an youtube video when he clicks an image and when the video finishes, the video disappears and the same image reappears again.

For example, view the website below and click the image on the home page.
https://www.oldbankruptcypapers.com/

Body:
You can follow below approach to achieve that :

When you click on the image, hide it and make your player container div visible. Bind onStateChange event of your YT Player to check for video ending and then hide the player or remove it and make your image visible.

Below is the code snippet :

<img src="http://d3gnp09177mxuh.cloudfront.net/tech-page-images/java.png" id="javaImg">
<div id="playerContainer">
  <div id="player" width="300" align="left" height="238" style="margin-right:30px;"></div>
</div>

$("#javaImg").click(function(){
if($("#player").is("div"))
{
  $(this).hide();
  player = new YT.Player('player', {
    height: '335',
    width: '596',
    playerVars: { 'controls': 1,'autohide':1},
    videoId: 'r59xYe3Vyks',
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

}
  else {
    player.autohide=1;
    player.playVideo();
  }
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  function onPlayerStateChange(event) {
    if(event.data === 0) {
      $("#player").remove();
      $("#playerContainer").append('<div id ="player" width="300" align="left" height="238" style="margin-right:30px;"></div>');
      $("#javaImg").show();
    }
  }
});

I have also created a fiddle, https://jsfiddle.net/qLzpg27g/


问:
SQL Server: Check Upper Case or Lower Case after certain Character
I have data like 'John is my name; Ram is my name; Adam is my name'.

My rule is such that every first letter that comes after ; should be capital letter.

How do I select all values that satisfy the rule?

答:
You can grab a copy of NGrams8K and do this:

```<code>-- note that I made the 3rd item start with lower-case
DECLARE @YourString VARCHAR(100)='John is my name; Ram is my name; adam is my name';

WITH D(n) AS
(
  SELECT 0 UNION ALL SELECT position
  FROM dbo.NGrams8k(@yourstring,1) WHERE token = ';'
),
TOKEN(token) AS
(
  SELECT LTRIM(SUBSTRING(@YourString, N+1,
           ISNULL(NULLIF(CHARINDEX(';', @YourString, N+1),0), 101)-(N+1)))
  FROM D
)
SELECT token,
       FirstLetterIsCaptial = IIF(ASCII(SUBSTRING(token,1,1)) BETWEEN 65 AND 90, 1, 0)
FROM TOKEN;
</code>```

Results

```<code>token              FirstLetterIsCaptial
------------------ --------------------
John is my name    1
Ram is my name     1
adam is my name    0
</code>```

Body:
You can grab a copy of NGrams8K and do this:

-- note that I made the 3rd item start with lower-case
DECLARE @YourString VARCHAR(100)='John is my name; Ram is my name; adam is my name';

WITH D(n) AS
(
  SELECT 0 UNION ALL SELECT position
  FROM dbo.NGrams8k(@yourstring,1) WHERE token = ';'
),
TOKEN(token) AS
(
  SELECT LTRIM(SUBSTRING(@YourString, N+1,
           ISNULL(NULLIF(CHARINDEX(';', @YourString, N+1),0), 101)-(N+1)))
  FROM D
)
SELECT token,
       FirstLetterIsCaptial = IIF(ASCII(SUBSTRING(token,1,1)) BETWEEN 65 AND 90, 1, 0)
FROM TOKEN;

Results

token              FirstLetterIsCaptial
------------------ --------------------
John is my name    1
Ram is my name     1
adam is my name    0


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
Below is the query you can use:

```<code> select count(*) from sysobjects where xtype='P'
</code>```

If all your db access is mandated to be through SP's, then the sky is the limit.

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

Body:
Below is the query you can use:

 select count(*) from sysobjects where xtype='P'

If all your db access is mandated to be through SP's, then the sky is the limit.

ContentLicense: CC BY-SA 4.0


问:
Where does jQuery UI fit in MVC?
I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is.  I want to do the following:

```<code>$().ready(function() {
    $('#searchHolder').customSearch('MyApp.Models.User');
});
</code>```

As long as I have implemented a specific interface on Models.User, jQuery will be able to talk to a reflection service to generically construct the relevant UI.

Sounds fun, but it seems that I'm now calling the JavaScript from the View, which is in turn going to do some View-related activity to build the search UI, and then to do the search and interact with the user it's going to throw a bunch of Controller tasks in there.

So where does this really fit?  Is there a different way I can structure my jQuery plugin so that it conforms more to the idea of MVC?  Does MVC work when it scales down to its own form within another MVC structure?  Should I just ignore these issues for the sake of one plugin?

答: so I have actually been looking into this a lot lot, and have found that the new officially supported jquery plugin tmpl can work as a view engine. I have written a tutorial here, how you can create a full MVC/MVP paradigm in JavaScript</p>

Title: Where does jQuery UI fit in MVC?

Body:
I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is.  I want to do the following:

$().ready(function() {
    $('#searchHolder').customSearch('MyApp.Models.User');
});

As long as I have implemented a specific interface on Models.User, jQuery will be able to talk to a reflection service to generically construct the relevant UI.

Sounds fun, but it seems that I'm now calling the JavaScript from the View, which is in turn going to do some View-related activity to build the search UI, and then to do the search and interact with the user it's going to throw a bunch of Controller tasks in there.

So where does this really fit?  Is there a different way I can structure my jQuery plugin so that it conforms more to the idea of MVC?  Does MVC work when it scales down to its own form within another MVC structure?  Should I just ignore these issues for the sake of one plugin?


问:
HTML text doesn't print to screen when using canvas in conjunction
In this snippet of code, even though I align the text far outside of the canvas boundaries, the text shows up below the canvas height.  I'm new to HTML and I question why using a canvas seems to block the whole row it's on.  I also want to know if there is a way around this, so I can have my canvas and have the text to the right of it on the same row.</p>

```<code><!DOCTYPE html>
<html>
<canvas id= "myCanvas" width="600" height="600">
</canvas>
<head>
<title>test</title>
<meta name="generator" content="BBEdit 11.6" />
</head>
<body>
<p style="text-align:right">JavaScript can change the content of an HTML element:</p>
</body>
</html>
</code>```

答:
First your code is some wrong, you need to follow a structure.

```<code><!DOCTYPE html>
<html>
    <head>
        <!-- Code -->
    </head>
    <body>
        <!-- Code -->
    </body>
</html>
</code>```

Your canvas you need to write inside body tag.
You have many options but each options have differences, depend of what you want to do after, you can to choose :

float, inline, inline-block or inline-flex

Float:

This is the old form, that make an element float.

<canvas style="float:left; border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>

JavaScript can change the content of an HTML element:
```
</div>
</div>
</p>

<p><strong>Inline:</strong></p>

<p>Element in one line but doesn't respect the width and height property of the element.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="display:inline;">JavaScript can change the content of an HTML element:</p></code>```

Inline-block:

Element in one line respecting the width and height property of the element.

<canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>

JavaScript can change the content of an HTML element:
```
</div>
</div>
</p>

<p><strong>Inline-Flex:</strong></p>

<p>Introduced in css3, inline in version flex.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="display:inline-flex;">JavaScript can change the content of an HTML element:</p></code>```

The definitions are very quickly, refer more information:

Reference 1

Reference 2

Update:

Align in the top, using flex:

  <canvas style="border:1px solid red;" id= "myCanvas" width="100" height="100">
  </canvas>

JavaScript can change the content of an HTML element:

```

Body:
In this snippet of code, even though I align the text far outside of the canvas boundaries, the text shows up below the canvas height.  I'm new to HTML and I question why using a canvas seems to block the whole row it's on.  I also want to know if there is a way around this, so I can have my canvas and have the text to the right of it on the same row.

<!DOCTYPE html>

<canvas id= "myCanvas" width="600" height="600">
</canvas>

<title>test</title>
<meta name="generator" content="BBEdit 11.6" />

JavaScript can change the content of an HTML element:

Body:
First your code is some wrong, you need to follow a structure.

<!DOCTYPE html>
<html>
    <head>
        <!-- Code -->
    </head>
    <body>
        <!-- Code -->
    </body>
</html>

Your canvas you need to write inside body tag.
You have many options but each options have differences, depend of what you want to do after, you can to choose :

float, inline, inline-block or inline-flex

Float:

This is the old form, that make an element float.

<canvas style="float:left; border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="text-align:right">JavaScript can change the content of an HTML element:</p>

Inline:

Element in one line but doesn't respect the width and height property of the element.

<canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="display:inline;">JavaScript can change the content of an HTML element:</p>

Inline-block:

Element in one line respecting the width and height property of the element.

<canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="display:inline-block;">JavaScript can change the content of an HTML element:</p>

Inline-Flex:

Introduced in css3, inline in version flex.

<canvas style="border:1px solid red;" id= "myCanvas" width="30" height="30">
</canvas>
<p style="display:inline-flex;">JavaScript can change the content of an HTML element:</p>

The definitions are very quickly, refer more information:

Reference 1

Reference 2

Update:

Align in the top, using flex:

<div style="display:flex;align-self: flex-start">
  <canvas style="border:1px solid red;" id= "myCanvas" width="100" height="100">
  </canvas>
  <p style="margin-top:0">JavaScript can change the content of an HTML element:</p>
</div>


问:
MySQL procedure with insert and update
I need some help to create a procedure in MySQL.

I have two tables:

connection

connection_temporary

And I want to create a procedure that does:

If SELECT keyname FROM connection WHERE keyname NOT IN (SELECT keyname FROM connection_temporary) update connection.connection_status to offline

If SELECT keyname FROM connection_temporary WHERE keyname NOT IN (SELECT keyname FROM CONNECTION) insert in connection with connection_temporary's row content

If SELECT keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp FROM connection_temporary WHERE keyname IN (SELECT keyname FROM CONNECTION) update connection with connection_temporary's row content

How can I do this?

答:
You should post the schema of your two tables, though, you can do some try by yourself based on following:</p>

```<code>DELIMITER $$
CREATE PROCEDURE `proc`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
    UPDATE `connection`
    SET `connection`.connection_status = 'offline'
    WHERE NOT EXISTS(
        SELECT 1
        FROM connection_temporary
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    INSERT INTO `connection` (keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp)
    SELECT keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp
    FROM connection_temporary
    WHERE NOT EXISTS(
        SELECT 1
        FROM `connection`
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    UPDATE `connection`
    JOIN connection_temporary ON connection_temporary.keyname = `connection`.keyname
    SET `connection`.keyname = connection_temporary.keyname
    ,`connection`.real_ip = connection_temporary.real_ip
    ,`connection`.virtual_ip = connection_temporary.virtual_ip
    ,`connection`.received_bytes = connection_temporary.received_bytes
    ,`connection`.sent_bytes = connection_temporary.sent_bytes
    ,`connection`.connection_tstamp = connection_temporary.connection_tstamp;
END
$$ DELIMITER ;
</code>```

Title: MySQL procedure with insert and update

Body:
You should post the schema of your two tables, though, you can do some try by yourself based on following:

DELIMITER $$
CREATE PROCEDURE `proc`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
    UPDATE `connection`
    SET `connection`.connection_status = 'offline'
    WHERE NOT EXISTS(
        SELECT 1
        FROM connection_temporary
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    INSERT INTO `connection` (keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp)
    SELECT keyname, real_ip, virtual_ip, received_bytes, sent_bytes, connection_tstamp
    FROM connection_temporary
    WHERE NOT EXISTS(
        SELECT 1
        FROM `connection`
        WHERE connection_temporary.keyname = `connection`.keyname
    );

    UPDATE `connection`
    JOIN connection_temporary ON connection_temporary.keyname = `connection`.keyname
    SET `connection`.keyname = connection_temporary.keyname
    ,`connection`.real_ip = connection_temporary.real_ip
    ,`connection`.virtual_ip = connection_temporary.virtual_ip
    ,`connection`.received_bytes = connection_temporary.received_bytes
    ,`connection`.sent_bytes = connection_temporary.sent_bytes
    ,`connection`.connection_tstamp = connection_temporary.connection_tstamp;
END
$$ DELIMITER ;


问:
VB.Net Window Programming database coonection open close
I am working on a window project using VB.net. On every form of my project I opened Microsoft access database connection on form load and closed on form closing event. So I want to ask that this is good practice to open/close database connection on every form.</p>

答:
Consider the followings:

Would the db connection be used to update or only query?

How many users would open the form and connect to db at the same time?

If the users are many and they update db, I think it's not a good idea to keep connected while opening the form. Usually you may query some data upon opening and then close the connection immediately, and the same for updating.


问:
Submit form after successful ajax call using jQuery in asp.net mvc 5
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

```<code><div class="form-group">
  <div>
    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
  </div>
</div>
</code>```

My JavaScript code is defined as follows:

```<code>$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});
</code>```

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

答:
Try it out :

```<code>$('#btnApply').click(function (e) {
alert('submit');
e.preventDefault();
var form  = $('form'); // change selector your form
if (!form.attr('validated')) {
    if (form.valid()) {
        $.ajax({
            type: "POST",
            data: form.serialize(),
            url: "/ApplicationForm/ValidateForm",
            dataType: 'json',
            success: function (response) {
                console.log('response received.');
                if (response != null && response.success) {
                    console.log('No validation errors detected.');
                    form.attr('validated', true);
                    form.attr('action', '/ApplicationForm/Index')
                        .submit();
                } else if (response != null && !response.success) {
                    console.log('Validation errors detected.');
                    var errors = response['errors'];
                    displayValidationErrors(errors);
                    window.scrollTo(0, 0);
                }

            },
            error: function (response) {
                console.log(response);
                $('validationSummary').hide();
            }
        });
    }

}
</code>```

});

Body:
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:

Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.

Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.

The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.

I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.

When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!

The Submit button is defined as follows:

    <input type="button" id="btnApply" value="Apply" class="btn btn-primary" />

My JavaScript code is defined as follows:

$('#AppllicationForm').submit(function () {
    if (!$(this).attr('validated')) {
        if ($(this).valid()) {
            $.ajax({
                type: "POST",
                data: $(this).serialize(),
                url: "/ApplicationForm/ValidateForm",
                dataType: 'json',
                success: function (response) {
                    $('validationSummary').show();
                    if (response != null && response.success) {
                        console.log('No Validation errors detected');
                        $('#ApplicationForm').attr('validated', true);
                        $('#ApplicationForm').attr('action', '/ApplicationForm/Index')
                            .submit();
                        return true;
                    }
                    else if (response != null && !response.success) {
                        console.log('Validation errors detected');
                        var errors = response['errors'];
                        displayValidationErrors(errors);
                        window.scrollTo(0, 0);
                    }
                    return false;
                },
                error: function (response) {
                    $('validationSummary').hide();
                    console.log(response);
                    return false;
                }
            });
        }
    }
    return false;
});

The above is using a regular button but I've also tried to define its type as Submit but to no avail.

I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!

The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values

I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.

I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.

Any help would be greatly appreciated.

Body:
Try it out :

$('#btnApply').click(function (e) {
alert('submit');
e.preventDefault();
var form  = $('form'); // change selector your form
if (!form.attr('validated')) {
    if (form.valid()) {
        $.ajax({
            type: "POST",
            data: form.serialize(),
            url: "/ApplicationForm/ValidateForm",
            dataType: 'json',
            success: function (response) {
                console.log('response received.');
                if (response != null && response.success) {
                    console.log('No validation errors detected.');
                    form.attr('validated', true);
                    form.attr('action', '/ApplicationForm/Index')
                        .submit();
                } else if (response != null && !response.success) {
                    console.log('Validation errors detected.');
                    var errors = response['errors'];
                    displayValidationErrors(errors);
                    window.scrollTo(0, 0);
                }

            },
            error: function (response) {
                console.log(response);
                $('validationSummary').hide();
            }
        });
    }

}

});


问:
Delete an unpublished app from Google Play
I create a new app in my Google play account. I did not publish it yet. It is just ready to publish.

Is there any way to delete it permanently from my account since it is not published yet?

I can not find any remove or delete button. I read here and here, but I couldn't find any delete button.

What about if the app is published only to alpha, or perhaps beta - in those cases can you reuse the package name?

答:
You can delete an app anytime before it is published. Note this answer was given before the OP specified that his app had not yet been published.

After it has been published, it "owns" its unique packagename forever in the Google PlayStore app naming hierarchy like com.yourdomain.yourapp.

There is no "deleting" this packagename after publication. That would cause mayhem.

Google Analytics, for example needs this permanent unique id. Hostile developers could take over your packagename by forcing you to delete it with bad review attacks.

The package name itself is not really a public-facing asset. If all you want to do is "reboot" your app (ie start again with zero downloads and reviews) then just unpublish (retire) the old packagename and republish the apk under a new packagename.

The right way to publish your app is using the alpha and beta streams in the dev console which do not retain reviews.

The only problem with this is the rule about once an app (package) is priced as free, it remains forever free, meaning you have to republish under a new package name to price a free beta.

Paid betas are only possible if you already have successful apps.

PlayStore publication policies are in constant flux (there is now a manual review policy). You may wish to take your concerns to them directly - they do respond.

I am sure every developer wants to delete and republish an app after finding out that it won't run on device X, because device X manufacturer has tweaked Android, causing device X owners to give the app unfair reviews.

This is also a way to avoid giving people free upgrades to your apps forever, which is not realistic, esp. given piracy stats. Owners often reboot to start fresh after a major upgrade.

You may want to adopt a packagename with a major version codename baked in, like the big boys do it (mountainlion, xenial, marshmallow, etc) like com.yourdomain.yourapp.codename.

X is usually Samsung


问:
Proper way to escape/unescape newline characters
Suppose I have a simple text input box. When a value is entered, the jQuery script fires an AJAX request to the server. The value is passed as a string to the server. The problem I am running into is that when I call $(selector).val() on the input box, it will escape newline characters (example: if I enter "test\ntest", calling val() returns "test\\ntest"). I could unescape the value before sending to the server (and modify the server to allow unescaped values for that request), but obviously that wouldn't be a good idea. Does this mean that the server should be unescaping the \\n? Is there a proper/standard way to unescape the \\n values on the server side? I am using ASP.NET MVC. What about \r and others? Thanks.</p>

答:
In this case , i hope Regex.Escape and Regex.UnEscape method will be helpful for you:

Regex.Escape:

It converts user-specified strings into escaped strings to match in a regular expression

Regex.unEscape:

Regex.Unescape changes escape sequences. It eliminates the escape characters.

Source/Example:

https://www.dotnetperls.com/regex-escape

https://www.dotnetperls.com/unescape

Hope it was helpful

Thanks

Karthik


问:
How do you add a native library (.so) to android studio?
I am currently getting the following error:

```<code>java.lang.UnsatisfiedLinkError: nativeLibraryDirectories=[/data/app/com.example.ryane.jzy-1/lib/arm, /vendor/lib, /system/lib] couldn't find "libgluegen-rt.so"
</code>```

While performing the following line of code

```<code>System.loadLibrary("gluegen-rt");
</code>```

I've included the following in my build.gradle

```<code>sourceSets {
    main {
        jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
    }
}
</code>```

And have placed my libgluegen.so within src/main/jniLibs. According to the error it seems as if it isn't looking in the directory I specified. Are there steps that I'm missing?

答:
Hmm... Actually I want to see your .so path...

And for example, in my build.gradle
jniLibs.srcDirs = ['src/main/libs'] .

The path of .so is MyProj\app\src\main\libs\armeabi-v7a\libSmartAlgorithm.so .

libs/TARGET_ARCH_ABI

```<code>arm64-v8a
armeabi
armeabi-v7a
mips
mips64
x86
x86_64
</code>```

Body:
I am currently getting the following error:

java.lang.UnsatisfiedLinkError: nativeLibraryDirectories=[/data/app/com.example.ryane.jzy-1/lib/arm, /vendor/lib, /system/lib] couldn't find "libgluegen-rt.so"

While performing the following line of code

System.loadLibrary("gluegen-rt");

I've included the following in my build.gradle

sourceSets {
    main {
        jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
    }
}

And have placed my libgluegen.so within src/main/jniLibs. According to the error it seems as if it isn't looking in the directory I specified. Are there steps that I'm missing?

Body:
Hmm... Actually I want to see your .so path...

And for example, in my build.gradle
jniLibs.srcDirs = ['src/main/libs'] .

The path of .so is MyProj\app\src\main\libs\armeabi-v7a\libSmartAlgorithm.so .

libs/TARGET_ARCH_ABI

arm64-v8a
armeabi
armeabi-v7a
mips
mips64
x86
x86_64


问:
POSTMAN: "You do not have permission to view this directory or page" with Bearer Token
I've got a website hosted on HostGator, let's say it's domain is https://example.com.

I also have an application hosted on Azure, with Active Directory Authentication enabled on the entire site (including the API component), let's say it's domain is https://example.azurewebsites.net

THE GOAL - To have a PHP file be executed (as a CRON job) on https://example.com and have the file first Authenticate itself with Azure's Active Directory, and then to pull data from https://example.azurewebsites.net/api/getValues via an HTTP GET call.

THE PROBLEM - Obviously, just calling the API without a bearer token will cause a 401, but I'm still getting a 401 even though I'm passing in what appears to be a valid Bearer Token.

Here's what I did:

Using https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code -

I visited https://login.microsoftonline.com/{{tenant_id}}/oauth2/authorize?response_type=code&client_id={{client_id}} that was given to me through Azure AD Management Portal.

This returned:

https://example.com/?code={{really_long_string_of_code}}

I took this really_long_string_of_code and put it through postman as a body parameter called code, seen below:

As you can see, it returned the token seen above ^.

I then took this token and put it through another Postman call:

But the problem is, I still get that exact error message:

You do not have permission to view this directory or page.

I feel like I've tried everything. I've even went into the portal.azure and set the "allowed token audiences":

Anyone know any settings I can change to allow this sort of call to happen?

答:
The evilSnobu have already explained this issue which caused by incorrect audience.  I want to explain it more general to help understand this issue.

There are two concepts client and resource server in the OAuth 2.0 Authorization Framework(refer rfc6749). When the client calls the resource server, the resource server will verify the token passed in the request. For example, it will verify the signature, issuer, client id, audience etc.

client:
An application making protected resource requests on behalf of the
resource owner and with its authorization.  The term "client" does
not imply any particular implementation characteristics (e.g.,
whether the application executes on a server, a desktop, or other
devices).

resource server:
The server hosting the protected resources, capable of accepting
and responding to protected resource requests using access tokens.

In your scenario, you were acquire the access_token for the Azure AD Graph(https://graph.windows.net). However, the audience you config at the portal doesn't match the aud claim in the access_token. To fix the issue, we can use the app registered at Azure AD as both client and resource. If that, we need to acquire the access token using the Application ID instead of App ID URI. And config this value as the ALLOWED TOKEN AUDIENCES on the Azure portal.

Or we can just to register two apps in Azure AD to represent the client app and resource app separately. And using the client app to acquire the token for the resource app. If this, the value of resource should the App ID URI of resource app and we also need to config it as the ALLOWED TOKEN AUDIENCES on the Azure portal.