问:
Delete records from huge table which are not exists in large subset from another table
Below is ma method (Symfony, Doctrine) to removing etities where its ids are not present in other table which contains together list of ids from several different types. (exactly 6, but it is important only to understand the structure of system)

And everything works perfect unless the method is called with parameter of entity which contains about 300000 records and the helper table ('oId') has similar amount of records. (so the method should remove only several records I explain) When earlier all works (a records count of to tables below the 50000), here I encounter the problem from database:

SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction

This error never appear with the previous entities.
I don't know what is the problem because count of records is only ten times bigger so when those queries are executed through several seconds, why I can't see result after eg. 20 s.?
What is behind the scene, that such error is thrown?

I even rebuild my method to do the task in loop as it was said in some answers about how to delete huge amount of records from table. Also I decreased limit to 1000 records and everything run ok, except when it start doing it with the entity described earlier.

Here is the whole method.

Only one more little explanation. Don't be afraid of sql injection. The $typeId and $borderId cames from database not from the user.

```<code>/**
 * Deletes records from given entity which are not exists in imported csv file.
 *
 * @param string $entity
 * @param integer $typeId
 * @param int $borderId Additional condition. Eg. 5 means, none of entities below id of value 5 will be delted (id < 5)
 */
public function removeNonExistent($entity, $typeId, $borderId = null)
{
    $subQueryQb = $this->repository->createQueryBuilder('oId');
    $subQueryQb->select('oId.originalId')
        ->andWhere('oId.type = '.$typeId)
        //->andWhere('oId.originalId = e.originalId')
        //Uncomment to have subquery of EXIST rather the IN()
    ;

    $qb = $this->em->createQueryBuilder();
    $qb->select('min(e.id) as minId, max(e.id) as maxId, count(e.id) as countId');
    $qb->from($entity, 'e');
    $tableData = $qb->getQuery()->getArrayResult();

    $queries = 0;
    $limit = 1000;
    $id = $tableData[0]['minId'];
    while ($id < $tableData[0]['maxId']) {

        $deleteQb = $this->em->createQueryBuilder();
        $deleteQb->delete()
            ->from($entity, 'e')
            ->andWhere('e.id BETWEEN '.$id.' AND '.($id + $limit - 1))
            ->andWhere($deleteQb->expr()->notIn('e.originalId', $subQueryQb→getDQL())) //Comment to use subquery as EXIST rather than IN()
            //->andWhere($deleteQb->expr()->not($deleteQb->expr()->exists($subQueryQb->getDQL())))
         //Uncomment to use subquery as EXIST rather than IN()
        ;
        if ($borderId !== null) {
            $deleteQb->andWhere('e.id > '.$borderId);
        }

        $qResult = $deleteQb->getQuery()->getResult();
        $this->em->flush($entity);
        $queries++;
        echo $queries.'# delete query executed. Rows deleted: '.$qResult."\n";
        $id += $limit;

        if ($tableData[0]['countId'] < $limit) {
            break;
        }
    }

    echo $queries.' delete queries executed.'."\n";
}
</code>```

Anyone can help? I will be glad for any kind of any clue.

答:
The first thing which I discovered is the last line of this query

```<code>DELETE FROM table
WHERE id NOT IN (
        SELECT a.original_id
        FROM table_ids a
        WHERE a.type = 6
)
AND id > 3
</code>```

If the query has this form (without last line – we are still talking about MySQL5.6)

```<code>DELETE FROM table
WHERE id NOT IN (
        SELECT a.original_id
        FROM table_ids a
        WHERE a.type = 6
)
– (without last this line)
</code>```

The query with count of ids equal to about 300 thousands with this line excluded all executes very quickly (about several seconds) but if I add the line  AND id > 3 everything slow down to even stopping.
So this is the solution but I MUST have this condition!

Well now it comes solution number two:

```<code>   /**
    * Deletes records from given entity which are not exists in imported csv file.
    *
    * @param string $entity
    * @param integer $typeId
    * @param int $borderId Additional condition. Eg. 5 means, none of entities below id of value 5 will be delted (id < 5)
    */
    public function removeNonExistent($entity, $typeId, $borderId = null)
    {
        $metaData = $this->em->getClassMetadata($entity);
        $mainMetaData = $this->em->getClassMetadata($this->class);

        $connection = $this->em->getConnection();

        $connection->query('BEGIN;');

        $connection->query('CREATE TABLE '.$metaData->getTableName().'_copy LIKE '.$metaData->getTableName().';');

        $connection->query('INSERT INTO '.$metaData->getTableName().'_copy
            SELECT *
            FROM '.$metaData->getTableName().'
            WHERE '.$metaData->getTableName().'.'.$metaData->getColumnName('originalId').' IN (
                SELECT '.$mainMetaData->getColumnName('originalId').' FROM '.$mainMetaData->getTableName().' WHERE '.$mainMetaData->getColumnName('type').' = '.$typeId.'
            )
             ;');

        if ($borderId !== null) {
            $connection->query('INSERT INTO '.$metaData->getTableName().'_copy
                SELECT *
                FROM '.$metaData->getTableName().'
                WHERE '.$metaData->getTableName().'.'.$metaData->getColumnName('id').' <= '.$borderId.';');
        }

        $connection->query('RENAME TABLE '.$metaData->getTableName().' TO '.$metaData->getTableName().'_old, '.$metaData->getTableName().'_copy TO '.$metaData->getTableName().';');

        $connection->query('
            ALTER TABLE '.$metaData->getTableName().' DISABLE KEYS;
            SET FOREIGN_KEY_CHECKS = 0;
            SET UNIQUE_CHECKS = 0;
            SET AUTOCOMMIT = 0;
        ;');
        $connection->query('DROP TABLE '.$metaData->getTableName().'_old;');
        $connection->query('
            SET UNIQUE_CHECKS = 1;
            SET FOREIGN_KEY_CHECKS = 1;
            ALTER TABLE '.$metaData->getTableName().' ENABLE KEYS;
        ;');

        $connection->query('COMMIT;');
    }
</code>```

Simply and shortly:
We copy data to the new tmp table then we change names and all return the previous order.

And now it works.
Only one disadvantage is that I have to rebuild schema of database while the foreign keys are not added.

I only wonder why this simple line of one more condition
AND id > 3
makes the query unable to finish…

And in the end one clearification:
When I first executed the script from the question I did't want to wait so long when the query had been executed so I entered ^C. Every next time the error of timeout appeared. Only very first time there was no error as well as no effect and what is more end.

So that it is.

Body:
Below is ma method (Symfony, Doctrine) to removing etities where its ids are not present in other table which contains together list of ids from several different types. (exactly 6, but it is important only to understand the structure of system)

And everything works perfect unless the method is called with parameter of entity which contains about 300000 records and the helper table ('oId') has similar amount of records. (so the method should remove only several records I explain) When earlier all works (a records count of to tables below the 50000), here I encounter the problem from database:

SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction

This error never appear with the previous entities.
I don't know what is the problem because count of records is only ten times bigger so when those queries are executed through several seconds, why I can't see result after eg. 20 s.?
What is behind the scene, that such error is thrown?

I even rebuild my method to do the task in loop as it was said in some answers about how to delete huge amount of records from table. Also I decreased limit to 1000 records and everything run ok, except when it start doing it with the entity described earlier.

Here is the whole method.

Only one more little explanation. Don't be afraid of sql injection. The $typeId and $borderId cames from database not from the user.

/**
 * Deletes records from given entity which are not exists in imported csv file.
 *
 * @param string $entity
 * @param integer $typeId
 * @param int $borderId Additional condition. Eg. 5 means, none of entities below id of value 5 will be delted (id < 5)
 */
public function removeNonExistent($entity, $typeId, $borderId = null)
{
    $subQueryQb = $this->repository->createQueryBuilder('oId');
    $subQueryQb->select('oId.originalId')
        ->andWhere('oId.type = '.$typeId)
        //->andWhere('oId.originalId = e.originalId')
        //Uncomment to have subquery of EXIST rather the IN()
    ;

    $qb = $this->em->createQueryBuilder();
    $qb->select('min(e.id) as minId, max(e.id) as maxId, count(e.id) as countId');
    $qb->from($entity, 'e');
    $tableData = $qb->getQuery()->getArrayResult();

    $queries = 0;
    $limit = 1000;
    $id = $tableData[0]['minId'];
    while ($id < $tableData[0]['maxId']) {

        $deleteQb = $this->em->createQueryBuilder();
        $deleteQb->delete()
            ->from($entity, 'e')
            ->andWhere('e.id BETWEEN '.$id.' AND '.($id + $limit - 1))
            ->andWhere($deleteQb->expr()->notIn('e.originalId', $subQueryQb→getDQL())) //Comment to use subquery as EXIST rather than IN()
            //->andWhere($deleteQb->expr()->not($deleteQb->expr()->exists($subQueryQb->getDQL())))
         //Uncomment to use subquery as EXIST rather than IN()
        ;
        if ($borderId !== null) {
            $deleteQb->andWhere('e.id > '.$borderId);
        }

        $qResult = $deleteQb->getQuery()->getResult();
        $this->em->flush($entity);
        $queries++;
        echo $queries.'# delete query executed. Rows deleted: '.$qResult."\n";
        $id += $limit;

        if ($tableData[0]['countId'] < $limit) {
            break;
        }
    }

    echo $queries.' delete queries executed.'."\n";
}

Anyone can help? I will be glad for any kind of any clue.

Body:
The first thing which I discovered is the last line of this query

DELETE FROM table
WHERE id NOT IN (
        SELECT a.original_id
        FROM table_ids a
        WHERE a.type = 6
)
AND id > 3

If the query has this form (without last line – we are still talking about MySQL5.6)

DELETE FROM table
WHERE id NOT IN (
        SELECT a.original_id
        FROM table_ids a
        WHERE a.type = 6
)
– (without last this line)

The query with count of ids equal to about 300 thousands with this line excluded all executes very quickly (about several seconds) but if I add the line  AND id > 3 everything slow down to even stopping.
So this is the solution but I MUST have this condition!

Well now it comes solution number two:

   /**
    * Deletes records from given entity which are not exists in imported csv file.
    *
    * @param string $entity
    * @param integer $typeId
    * @param int $borderId Additional condition. Eg. 5 means, none of entities below id of value 5 will be delted (id < 5)
    */
    public function removeNonExistent($entity, $typeId, $borderId = null)
    {
        $metaData = $this->em->getClassMetadata($entity);
        $mainMetaData = $this->em->getClassMetadata($this->class);

        $connection = $this->em->getConnection();

        $connection->query('BEGIN;');

        $connection->query('CREATE TABLE '.$metaData->getTableName().'_copy LIKE '.$metaData->getTableName().';');

        $connection->query('INSERT INTO '.$metaData->getTableName().'_copy
            SELECT *
            FROM '.$metaData->getTableName().'
            WHERE '.$metaData->getTableName().'.'.$metaData->getColumnName('originalId').' IN (
                SELECT '.$mainMetaData->getColumnName('originalId').' FROM '.$mainMetaData->getTableName().' WHERE '.$mainMetaData->getColumnName('type').' = '.$typeId.'
            )
             ;');

        if ($borderId !== null) {
            $connection->query('INSERT INTO '.$metaData->getTableName().'_copy
                SELECT *
                FROM '.$metaData->getTableName().'
                WHERE '.$metaData->getTableName().'.'.$metaData->getColumnName('id').' <= '.$borderId.';');
        }

        $connection->query('RENAME TABLE '.$metaData->getTableName().' TO '.$metaData->getTableName().'_old, '.$metaData->getTableName().'_copy TO '.$metaData->getTableName().';');

        $connection->query('
            ALTER TABLE '.$metaData->getTableName().' DISABLE KEYS;
            SET FOREIGN_KEY_CHECKS = 0;
            SET UNIQUE_CHECKS = 0;
            SET AUTOCOMMIT = 0;
        ;');
        $connection->query('DROP TABLE '.$metaData->getTableName().'_old;');
        $connection->query('
            SET UNIQUE_CHECKS = 1;
            SET FOREIGN_KEY_CHECKS = 1;
            ALTER TABLE '.$metaData->getTableName().' ENABLE KEYS;
        ;');

        $connection->query('COMMIT;');
    }

Simply and shortly:
We copy data to the new tmp table then we change names and all return the previous order.

And now it works.
Only one disadvantage is that I have to rebuild schema of database while the foreign keys are not added.

I only wonder why this simple line of one more condition
AND id > 3
makes the query unable to finish…

And in the end one clearification:
When I first executed the script from the question I did't want to wait so long when the query had been executed so I entered ^C. Every next time the error of timeout appeared. Only very first time there was no error as well as no effect and what is more end.

So that it is.


来源: stackexchange

问:
Find the longest arithmetic progression from an array
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].</p>

```<code>#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}
</code>```

答:
There are a number of ways to approach this challenge. You can either check each diff against each value in the array or work the other way around. Given you are not sorting the values, you may benefit by nesting the check of values within your loop over all possible diffs. Something similar to the following works:

```<code>#include <stdio.h>

int main (void) {

    int a[] = {5, 1, 2, 4, 6, 8, 12},
        n = sizeof a / sizeof *a,
        startidx = 0,
        maxlen = 0;

    for (int d = 1; d < n; d++) {       /* loop over diffs */
        int idx = -1,
            len = 1;
        for (int i = 1; i < n; i++)     /* loop over values */
            if (a[i - 1] + d == a[i]) {
                if (idx < 0)            /* if index not set */
                    idx = i - 1;        /* set to 1st index */
                len++;                  /* increment length */
            }
        if (idx >= 0 && len > maxlen) { /* if progression found */
            maxlen = len;               /* save length */
            startidx = idx;             /* save start index */
        }
    }

    printf ("longest progression: '%d' elements.\n", maxlen);
    for (int i = 0; i < maxlen; i++)
        printf (i ? ", %d" : "%d", a[startidx + i]);
    putchar ('\n');

    return 0;
}
</code>```

Example Use/Output

```<code>$ ./bin/maxprogression
longest progression: '4' elements.
2, 4, 6, 8
</code>```

Investigate several ways to approach it, and finally settle on the one that makes the most sense to you. You can work on optimizing later.

As far as the code you posted goes, always validate all user input by, at minimum, checking that the number of expected conversions to type took place, e.g.

```<code>if (scanf("%d", &num) != 1) {
    fprintf (stderr, "error: input conversion failed for 'num'.\n");
    return 1;
}
</code>```

You would do the same in your values loop. Let me know if you have any questions. Good luck with your coding.

ContentLicense: CC BY-SA 3.0

Body:
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].

#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}

Body:
There are a number of ways to approach this challenge. You can either check each diff against each value in the array or work the other way around. Given you are not sorting the values, you may benefit by nesting the check of values within your loop over all possible diffs. Something similar to the following works:

#include <stdio.h>

int main (void) {

    int a[] = {5, 1, 2, 4, 6, 8, 12},
        n = sizeof a / sizeof *a,
        startidx = 0,
        maxlen = 0;

    for (int d = 1; d < n; d++) {       /* loop over diffs */
        int idx = -1,
            len = 1;
        for (int i = 1; i < n; i++)     /* loop over values */
            if (a[i - 1] + d == a[i]) {
                if (idx < 0)            /* if index not set */
                    idx = i - 1;        /* set to 1st index */
                len++;                  /* increment length */
            }
        if (idx >= 0 && len > maxlen) { /* if progression found */
            maxlen = len;               /* save length */
            startidx = idx;             /* save start index */
        }
    }

    printf ("longest progression: '%d' elements.\n", maxlen);
    for (int i = 0; i < maxlen; i++)
        printf (i ? ", %d" : "%d", a[startidx + i]);
    putchar ('\n');

    return 0;
}

Example Use/Output

$ ./bin/maxprogression
longest progression: '4' elements.
2, 4, 6, 8

Investigate several ways to approach it, and finally settle on the one that makes the most sense to you. You can work on optimizing later.

As far as the code you posted goes, always validate all user input by, at minimum, checking that the number of expected conversions to type took place, e.g.

if (scanf("%d", &num) != 1) {
    fprintf (stderr, "error: input conversion failed for 'num'.\n");
    return 1;
}

You would do the same in your values loop. Let me know if you have any questions. Good luck with your coding.


问:
Regex for a random set of chars and digits
I am looking for a regex that matches only when it sees a string that is randomly filled by digits and chars.

For example, adfak332arg3 is allowed but 332352 and fagaaah are not allowed. .*[^\\s] looks fine for strings with only chars but how to fix it to accepts the desired strings and refuses the other two types?

Body:
Try this Regex.

[A-z][0-9]|[0-9][A-z]


问:
How to integrate multiple Android Applications using the same Laravel Application using multiple FCM sender keys
I am using brozot/laravel package for sending notification to users.

But I have multiple mobile apps (for each app I manage different server key and sender id) and I am using same laravel backend to send notifications to all different mobile apps.

How can I send notification to different app using different sender id (not using single sender id) with laravel brozot package?

答:
Going through the brozot/Laravel-FCM package documentation, specifying multiple Sender IDs doesn't seem to be a current feature. You can see that only a single Sender ID is set in the .env file when Setting the Package Config, which I presume is the Sender ID automatically used for when the message is built.

The only way I can see this moving forward is for you to file for a Feature Request.


问:
SonarQube Server shows zero issues for C-Sharp Code
Our Sonar Build Environment details as follows:

```<code>- SonarQube Server Version - 5.6.6 (64-Bit).
- Sonar Client Build Operating System – Ubuntu - 14.04.5 LTS (64-Bit).
- Sonar-scanner- Version - 3.0.3.778.
- sonar-csharp-plugin Version -5.11.0.1761.
</code>```

When I tried to run the sonar-scanner though Jenkins, scanning finished successfully, However post that it shows zero issues over sonar server dashboard. Could you help me to resolve the same.

答: Per SonarC# documentation, analysis of C# projects must be done with the SonarQube Scanner for MSBuild on a Windows environment (where you would anyhow develop your .Net applications). Analysing .Net projects on Linux is bound to fail, and in fact there might soon be a fail-fast mechanism preventing that.

ContentLicense: CC BY-SA 4.0

Body:
Our Sonar Build Environment details as follows:

- SonarQube Server Version - 5.6.6 (64-Bit).
- Sonar Client Build Operating System – Ubuntu - 14.04.5 LTS (64-Bit).
- Sonar-scanner- Version - 3.0.3.778.
- sonar-csharp-plugin Version -5.11.0.1761.

When I tried to run the sonar-scanner though Jenkins, scanning finished successfully, However post that it shows zero issues over sonar server dashboard. Could you help me to resolve the same.


问:
Angular 2 value is not updating in html
I am working on an application where facebook login is required. Here is my ts file

```<code> ngOnInit() {
    setTimeout(() => {
      this.initialize();
    })
  }

  initialize() {
    (function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
      window.fbAsyncInit =  () =>{
        FB.init({
          appId: 'your-app-id', //I gave my app id here
          cookie: true,  // enable cookies to allow the server to access
          // the session
          xfbml: true,  // parse social plugins on this page
          version: 'v2.8' // use graph api version 2.8
        });
        this.checkFBLoginStatus();
      }
    })

  }

  checkFBLoginStatus() {
    FB.getLoginStatus((response) =>{
      this.verifyResponse(response);
    });
  }

 verifyResponse(response){
    this.response = response;

   console.log(this.response) // I am getting the console output
 }
</code>```

Here is my HTML

```<code><!--For Testing purpose-->
Response is->
<p *ngIf="response">{{response.status}}</p>
<!--For Testing purpose-->

<button *ngIf="response && response.status && response.status == 'unknown'" class="btn blue fb-login-button" (click)="loginUsingFacebook()"><span class="fa fa-facebook white-text"></span>Login Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'not_authorized'" class="btn blue fb-login-button" (click)="continueUsingFacebook()"><span class="fa fa-facebook white-text"></span>Continue Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'connected'" class="btn blue fb-login-button" (click)="logoutFacebook()"><span class="fa fa-facebook white-text"></span>Logout Facebook</button>
</code>```

The response.status is showing in console. But its not getting binded to html. And so i am not able to see the respective buttons.

I am trying to detect whether the user is logged in or if not, what is the best way i can capture the onlogin function of javascript (facebook attr) in typescript.

Thanks

答:
Here you will have to manually refresh model data. And for that you can use NgZone

In below way

```<code>import {Component, NgZone} from '@angular/core';

constructor() {
   this.zone = new NgZone({enableLongStackTrace: false});
}

 verifyResponse(response){
    this.zone.run(() => {
      this.response = response;
    });

   console.log(this.response) // I am getting the console output
 }
</code>```

Title: Angular 2 value is not updating in html

Body:
I am working on an application where facebook login is required. Here is my ts file

 ngOnInit() {
    setTimeout(() => {
      this.initialize();
    })
  }

  initialize() {
    (function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    setTimeout(() => {
      window.fbAsyncInit =  () =>{
        FB.init({
          appId: 'your-app-id', //I gave my app id here
          cookie: true,  // enable cookies to allow the server to access
          // the session
          xfbml: true,  // parse social plugins on this page
          version: 'v2.8' // use graph api version 2.8
        });
        this.checkFBLoginStatus();
      }
    })

  }

  checkFBLoginStatus() {
    FB.getLoginStatus((response) =>{
      this.verifyResponse(response);
    });
  }

 verifyResponse(response){
    this.response = response;

   console.log(this.response) // I am getting the console output
 }

Here is my HTML

Response is->

{{response.status}}

<button *ngIf="response && response.status && response.status == 'unknown'" class="btn blue fb-login-button" (click)="loginUsingFacebook()">Login Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'not_authorized'" class="btn blue fb-login-button" (click)="continueUsingFacebook()">Continue Using Facebook</button>

<button *ngIf="response && response.status && response.status == 'connected'" class="btn blue fb-login-button" (click)="logoutFacebook()">Logout Facebook</button>

The response.status is showing in console. But its not getting binded to html. And so i am not able to see the respective buttons.

I am trying to detect whether the user is logged in or if not, what is the best way i can capture the onlogin function of javascript (facebook attr) in typescript.

Thanks

Body:
Here you will have to manually refresh model data. And for that you can use NgZone

In below way

import {Component, NgZone} from '@angular/core';

constructor() {
   this.zone = new NgZone({enableLongStackTrace: false});
}

 verifyResponse(response){
    this.zone.run(() => {
      this.response = response;
    });

   console.log(this.response) // I am getting the console output
 }


问:
Jabber multiple JID in one account
maybe anyone know solution.

I have multiple JID.

```<code>user@domain.com
user@domain2.com
user@domain3.com
</code>```

15 JID, on public servers, and also have own jabber(prosody server)
can i split all that JID to one ?

Now i use PSI with multiple accounts, but I would like to use one and the other to forward messages to it.
And that the answer was from the account in which they wrote.

答:
You may use xmpp-2-xmpp transport. It connects the other XMPP account(s) in your name and forwards (proxies) all messages etc.

There are two implementations that I am aware of:

J2J: http://wiki.jrudevels.org/Eng:J2J

Spectrum: http://spectrum.im (with Libpurple Jabber backend)

Unfortunately if you need to connect multiple accounts, you will need to set up multiple transport instances, as one transport instance allows only one registration per user.

Title: Jabber multiple JID in one account

Body:
maybe anyone know solution.

I have multiple JID.

user@domain.com
user@domain2.com
user@domain3.com

15 JID, on public servers, and also have own jabber(prosody server)
can i split all that JID to one ?

Now i use PSI with multiple accounts, but I would like to use one and the other to forward messages to it.
And that the answer was from the account in which they wrote.


问:
Write Decimal numbers in SQL 2008
In need to write the number 7.2 in a table field.

What type the field needs to be.

And what type needs the variable to be?

答:
SQL Server 2008 has a DECIMAL type which works quite well.

You can define a precision (total number of digits) and a scale (number of digits after the decimal separator).

DECIMAL(2,1) would be: two digits, one of which after the separator (one before)

DECIMAL(5,2) would be: five figits total, two of which after the separator (three before)

See DECIMAL and NUMERIC in SQL Server Books Online for more details

In .NET, this would be a type decimal as well.

ContentLicense: CC BY-SA 2.5

Title: Write Decimal numbers in SQL 2008


问:
Drop default constraint on a column in TSQL
I have a table with a column like this that is currently live:

name NVARCHAR(128) NOT NULL DEFAULT ''
```

<p>I am altering the column like this to make it nullable:</p>

<pre class="lang-sql prettyprint-override"><code>ALTER TABLE  mytable ALTER COLUMN name NVARCHAR(128) NULL
</code>```

However, the default constraint, named 'DF__mytable__datab__7DE4B36' in one instance of the table, still remains. I know this could have been avoided if the original author named the constraint. I have several of instances of these tables but I don't want to manually delete every constraint in every table I have. What is the easiest and most elegant way of dropping this default constraint on a column in Sql Server that I can uniformily apply to every instance of this table?

EDIT

This is the script that I ended up using:

DECLARE @table_id AS INT
DECLARE @name_column_id AS INT
DECLARE @sql nvarchar(255)

-- Find table id
SET @table_id = OBJECT_ID('mytable')

-- Find name column id
SELECT @name_column_id = column_id
FROM sys.columns
WHERE object_id = @table_id
AND name = 'name'

-- Remove default constraint from name column
SELECT @sql = 'ALTER TABLE mytable DROP CONSTRAINT ' + D.name
FROM sys.default_constraints AS D
WHERE D.parent_object_id = @table_id
AND D.parent_column_id = @name_column_id
EXECUTE sp_executesql @sql
```

Another script that can be used to accomplish this can be found here:
How to drop SQL default constraint without knowing its name?

Thanks!

答:
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

```<code>DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command
</code>```

It will drop your default constraint. However if you want to create it again you can simply try this

```<code>ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
</code>```

Finally, just simply run a DROP command to drop the column.

Body:
I have a table with a column like this that is currently live:

name NVARCHAR(128) NOT NULL DEFAULT ''

I am altering the column like this to make it nullable:

ALTER TABLE  mytable ALTER COLUMN name NVARCHAR(128) NULL

However, the default constraint, named 'DF__mytable__datab__7DE4B36' in one instance of the table, still remains. I know this could have been avoided if the original author named the constraint. I have several of instances of these tables but I don't want to manually delete every constraint in every table I have. What is the easiest and most elegant way of dropping this default constraint on a column in Sql Server that I can uniformily apply to every instance of this table?

EDIT

This is the script that I ended up using:

DECLARE @table_id AS INT
DECLARE @name_column_id AS INT
DECLARE @sql nvarchar(255)

-- Find table id
SET @table_id = OBJECT_ID('mytable')

-- Find name column id
SELECT @name_column_id = column_id
FROM sys.columns
WHERE object_id = @table_id
AND name = 'name'

-- Remove default constraint from name column
SELECT @sql = 'ALTER TABLE mytable DROP CONSTRAINT ' + D.name
FROM sys.default_constraints AS D
WHERE D.parent_object_id = @table_id
AND D.parent_column_id = @name_column_id
EXECUTE sp_executesql @sql

Another script that can be used to accomplish this can be found here:
How to drop SQL default constraint without knowing its name?

Thanks!

Body:
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.


问:
PHP sum two different minutes
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

```<code>$default_time = "00:30";
 $extra_time   = "00:25";
</code>```

my expected output : 00:55

but now display 01:00

this is my code

```<code>$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
</code>```

答:
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.</p>

```<code>$base = strtotime("00:00");

$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds

$break_time =  $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds

$total_break = $default_duration + $break_duration; // 55 min in seconds

// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
</code>```

Title: PHP sum two different minutes

Body:
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

$default_time = "00:30";
 $extra_time   = "00:25";

my expected output : 00:55

but now display 01:00

this is my code

$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));

Body:
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.

$base = strtotime("00:00");

$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds

$break_time =  $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds

$total_break = $default_duration + $break_duration; // 55 min in seconds

// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);


问:
findIndex() javascript array object
```<code> var array = [{"one":1, "two":2},{"one":3, "two":4}];

            var result = array.findIndex(function (value) {
                if (value === 2) {
                    return false;
                }
                return true;
            });

            console.log(result);
</code>```

i keep getting '0' in the console.
how should i change (value ===2) ?
i have tried change to (value === {"two":2})
but still return '0'.

is there any other array method that suitable ?

答:
You need to check one of the properties of the objects of the array. Then return the result of the check.

var array = [{ one: 1, two: 2 }, { one: 3, two: 4 }],
    result = array.findIndex(function(object) {
        return object.two === 2;
    });

console.log(result);```

Title: findIndex() javascript array object

Body:
 var array = [{"one":1, "two":2},{"one":3, "two":4}];

            var result = array.findIndex(function (value) {
                if (value === 2) {
                    return false;
                }
                return true;
            });

            console.log(result);

i keep getting '0' in the console.
how should i change (value ===2) ?
i have tried change to (value === {"two":2})
but still return '0'.

is there any other array method that suitable ?


答:
Its first argument of the array .change with value.two .its object property not a array

var array = [{"one":1, "two":2},{"one":3, "two":4}];
            var result = array.findIndex(function (value) {
                               return value.two == 2;
            });
            console.log(result); ```

Title: findIndex() javascript array object


问:
Webhook response with "suggestion chips"
I would like to guide users based on webhook response with suggestions chips. From webhook sample, I see below structure:

```<code>"fulfillment": {
  "speech": "Today in Boston: Fair, the temperature is 37 F",
  "source": "apiai-weather-webhook-sample",
  "displayText": "Today in Boston: Fair, the temperature is 37 F"
}
</code>```

But, if I want to suggest users what next you can request to continue the conversation, then how do I pass suggestions chips in webhook response?

答:
The response you displayed is the basic API.AI response format. However, Actions on Google expands on this and mainly uses the data.google field as presented below:

```<code>{
  "speech":"This is a simple response with suggestion chips",
  "data": {
    "google":
    {
      "expectUserResponse":true,
      "richResponse":
      {
        "items":
        [
          {
            "simpleResponse":
            {
              "textToSpeech":"This is a simple response for with suggestion chips"
            }
          }
        ],
        "suggestions":
        [
          {
            "title":"Option 1"
          },
          {
            "title":"Option 2"
          }
        ]
      }
    }
  }
}
</code>```

It is important to note, that this only displays suggestions for an actions-on-google application, it won't do anything for stuff like Facebook etc.

Body:
I would like to guide users based on webhook response with suggestions chips. From webhook sample, I see below structure:

"fulfillment": {
  "speech": "Today in Boston: Fair, the temperature is 37 F",
  "source": "apiai-weather-webhook-sample",
  "displayText": "Today in Boston: Fair, the temperature is 37 F"
}

But, if I want to suggest users what next you can request to continue the conversation, then how do I pass suggestions chips in webhook response?

Body:
The response you displayed is the basic API.AI response format. However, Actions on Google expands on this and mainly uses the data.google field as presented below:

{
  "speech":"This is a simple response with suggestion chips",
  "data": {
    "google":
    {
      "expectUserResponse":true,
      "richResponse":
      {
        "items":
        [
          {
            "simpleResponse":
            {
              "textToSpeech":"This is a simple response for with suggestion chips"
            }
          }
        ],
        "suggestions":
        [
          {
            "title":"Option 1"
          },
          {
            "title":"Option 2"
          }
        ]
      }
    }
  }
}

It is important to note, that this only displays suggestions for an actions-on-google application, it won't do anything for stuff like Facebook etc.


问:
App crashes because of "context" issue
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

```<code>public static Context context;
</code>```

and in onResume I do:

```<code>@Override
public void onResume() {
    super.onResume();

    this.context = this;
}
</code>```

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks

答: Use ActivityName.this replace of context.Your problem will be solved.</p>

Title: App crashes because of "context" issue

Body:
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

public static Context context;

and in onResume I do:

@Override
public void onResume() {
    super.onResume();

    this.context = this;
}

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks


问:
XSFR-TOKEN and a laravel_session cookies not generating on server laravel 5
I'm doing a laravel 5.2 app but when I try to create an account it gives a csrf error..

When I check what cookies the website have, I find that I have no cookies, there should be a XSFR-TOKEN and a laravel_session cookies, but laravel is not generating any of those cookies, so it gives me a token not found when i try to create an account.. anyone know why it does that? any idea how to fix that?

Also just installed a new clean laravel and find out if I put the "app" view inside of a folder it also happends and doesnt generate the cookies, I have tried to change the folder permissions but the problem persists.

答:
Make sure your route has the web middleware applied to it.

```<code>Route::group(['middleware' => 'web'], function () {
    //
});

<input type="hidden" name="_Token" value="{{ csrf_token() }}">
</code>```

Also, you need to pass hidden filed with csrf token value in your form something like display above

Body:
Make sure your route has the web middleware applied to it.

Route::group(['middleware' => 'web'], function () {
    //
});

<input type="hidden" name="_Token" value="{{ csrf_token() }}">

Also, you need to pass hidden filed with csrf token value in your form something like display above


问:
Is it possible to create a LifeTimeScope per eventhandler with Autofac and MediatR using a decorator class
Is it possible to create a LifeTimeScope per eventhandler with Autofac and MediatR using a decorator class?

So we have two Eventhandlers listening to the same event.
A decorator is supposed to create a LifteTimeScope, resolve the decorated eventhandler and invoke the Handle method of the decorated eventhandler.
I found lot of examples of doing this with CommandHandlers.
I have played around with code similar to what is shown below.
But I cant make it work. Some posts also suggest making a autofac registrationsource.
Ihave placed a fiddle here https://dotnetfiddle.net/fw4IBw

```<code>class EventHandlerA : IAsyncNotificationHandler<AnEvent>
{
     public void Handle(AnEvent theEvent)
     {
     }
}

class EventHandlerB : IAsyncNotificationHandler<AnEvent>
{
     public void Handle(AnEvent theEvent)
     {
     }
}

/// <summary>
///  Wraps inner Notification Handler in Autofac Lifetime scope named
     PerEventHandlerScope"
/// </summary>
/// <typeparam name="TNotification"></typeparam>
public class LifetimeScopeEventHandlerDecorator<TNotification> :
    IAsyncNotificationHandler<TNotification> where TNotification : class,
              IAsyncNotification
{
    private readonly ILifetimeScope _scope;
    private readonly Type _decoratedType;

    /// <summary>
    /// Const Name of Scope that dependencies can Match using
     PerMatchingLifeTimeScope(LifetimeScopeEventHandlerDecorator.ScopeName)
    /// </summary>
    public const string ScopeName = LifeTimeScopeKeys.PerHandlerKey;

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="scope"></param>
    public LifetimeScopeEventHandlerDecorator( ILifetimeScope scope, Type
          decoratedType )
    {
        _decoratedType = decoratedType;
        _scope = scope;
    }

    /// <summary>
    /// Wraps inner Notification Handler in Autofac Lifetime scope
    /// </summary>
    /// <param name="notification"></param>
    /// <returns></returns>
    public async Task Handle( TNotification notification )
    {
        using ( var perHandlerScope = _scope.BeginLifetimeScope(
         LifeTimeScopeKeys.PerHandlerKey ) )
        {
            var decoratedHandler =
   perHandlerScope.ResolveKeyed<IAsyncNotificationHandler<TNotification>>(
              "IAsyncNotificationHandlerKey" );
            await decoratedHandler.Handle( notification );
        }
    }
}
</code>```

答:
Yes its possible.

Finally I figured out a solution. The code can bee seen here  https://dotnetfiddle.net/fw4IBw

It involves the following steps for registration

iterate all your assemblies and get all eventHandler types

iterate all eventhandler types and register them as
        Named("EventHandler", eventHandlerType) and with
        .InstancePerMatchingLifetimeScope( "PerHandlerKey" );

in same loop get notification type

in same loop register a
eventhandlerFactory per eventhandler AsSelf and as
implementedInterfaces

in same loop register only one
eventHandlerDecorator per notification type .Named(
"EventHandlerDecorator", interfaceType
).AsSelf().InstancePerLifetimeScope();

For MultiInstanceFactory resolve only one decorator for the
notification  c.ResolveKeyed( "EventHandlerDecorator"...

In EventHandlerDecorator do..

Resolve all Factories for NotificationType

for each factory create per handler lifetimescope

create handler

invoke handler

Body:
Is it possible to create a LifeTimeScope per eventhandler with Autofac and MediatR using a decorator class?

So we have two Eventhandlers listening to the same event.
A decorator is supposed to create a LifteTimeScope, resolve the decorated eventhandler and invoke the Handle method of the decorated eventhandler.
I found lot of examples of doing this with CommandHandlers.
I have played around with code similar to what is shown below.
But I cant make it work. Some posts also suggest making a autofac registrationsource.
Ihave placed a fiddle here https://dotnetfiddle.net/fw4IBw

class EventHandlerA : IAsyncNotificationHandler<AnEvent>
{
     public void Handle(AnEvent theEvent)
     {
     }
}

class EventHandlerB : IAsyncNotificationHandler<AnEvent>
{
     public void Handle(AnEvent theEvent)
     {
     }
}

///
///  Wraps inner Notification Handler in Autofac Lifetime scope named
     PerEventHandlerScope"
///
/// <typeparam name="TNotification"></typeparam>
public class LifetimeScopeEventHandlerDecorator<TNotification> :
    IAsyncNotificationHandler<TNotification> where TNotification : class,
              IAsyncNotification
{
    private readonly ILifetimeScope _scope;
    private readonly Type _decoratedType;

    ///
    /// Const Name of Scope that dependencies can Match using
     PerMatchingLifeTimeScope(LifetimeScopeEventHandlerDecorator.ScopeName)
    ///
    public const string ScopeName = LifeTimeScopeKeys.PerHandlerKey;

    ///
    /// constructor
    ///
    /// <param name="scope"></param>
    public LifetimeScopeEventHandlerDecorator( ILifetimeScope scope, Type
          decoratedType )
    {
        _decoratedType = decoratedType;
        _scope = scope;
    }

    ///
    /// Wraps inner Notification Handler in Autofac Lifetime scope
    ///
    /// <param name="notification"></param>
    /// <returns></returns>
    public async Task Handle( TNotification notification )
    {
        using ( var perHandlerScope = _scope.BeginLifetimeScope(
         LifeTimeScopeKeys.PerHandlerKey ) )
        {
            var decoratedHandler =
   perHandlerScope.ResolveKeyed<IAsyncNotificationHandler<TNotification>>(
              "IAsyncNotificationHandlerKey" );
            await decoratedHandler.Handle( notification );
        }
    }
}


答:
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):

```<code>$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'

$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
</code>```

Title: PHP sum two different minutes

Body:
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):

$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'

$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');


问:
Is declaring an header file essential?
Is declaring an header file essential? This code:

```<code>main()
{
  int i=100;

  printf("%d\n",i);
}
</code>```

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

答:
This is possible because when C compiler sees an undeclared function call (printf() in your case) it assumes that it has

```
<code>
int printf(...)
```

signature and tries to call it casting all the arguments to int type. Since "int" and "void *" types often have same size it works most of the time. But it is not wise to rely on such behavior.

Title: Is declaring an header file essential?

Body:
Is declaring an header file essential? This code:

main()
{
  int i=100;

  printf("%d\n",i);
}

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

Body:
This is possible because when C compiler sees an undeclared function call (printf() in your case) it assumes that it has

int printf(...)

signature and tries to call it casting all the arguments to int type. Since "int" and "void *" types often have same size it works most of the time. But it is not wise to rely on such behavior.


问:
Jquery: Datepicker on an appended row in a table is not working
i have created a table that inside of it, contains a column in a row that lets the user picks the date. The datepicker works on the static text field, but on the one generated by the click of a button, it is not working.(The row is appended, but the datepicker will not appear on the newly generated row.)

This is the code for the table:

```<code><div class="table-responsive">
<table class = "table" id="dynamic_admin_add_event_time">
<thead>
<th>Event Date</th>
<th>Event Start</th>
<th>Event Ends</th>
<th></th>
</thead>

<tbody>
<tr>
<td><input type="text" id="dateEvent" name="admin_add_event_date[]"  class="form-control" required></td>
<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>
<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>
<td><button type="button" name=button_add_event_time id="add_event_time" class="btn btn-success">Add More Event</button></td>
</tr>
</tbody>
</table>
</div>
</code>```

This is the code for the datepicker:

```<code>  $("#dateEvent").datetimepicker({
  useCurrent: true,
  format: "dddd, MMM D YYYY"
  });
</code>```

And this is the one for the jquery for generating the rows:

```<code>$('#add_event_time').click(function(){

        i++;

        $('#dynamic_admin_add_event_time').append(
            '<tr id="row'+i+'">' +
            '<td><input type="text" id="dateEvent"name="admin_add_event_date[]" class="form-control" required></td>' +
            '<td><input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required></td>' +
            '<td><input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required></td>' +
            '<td><button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button></td>' +
            '</tr>');
 });
</code>```

Can you guys help me by with this problem? Thank you.

答:
Try this - </p>

```<code>$("#dynamic_admin_add_event_time").on("click", "#dateEvent", function(){
    $(this).datetimepicker({
        useCurrent: true,
        format: "dddd, MMM D YYYY"
    });
});
</code>```

Body:
i have created a table that inside of it, contains a column in a row that lets the user picks the date. The datepicker works on the static text field, but on the one generated by the click of a button, it is not working.(The row is appended, but the datepicker will not appear on the newly generated row.)

This is the code for the table:

Event Date
Event Start
Event Ends

<input type="text" id="dateEvent" name="admin_add_event_date[]"  class="form-control" required>
<input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required>
<input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required>
<button type="button" name=button_add_event_time id="add_event_time" class="btn btn-success">Add More Event</button>

This is the code for the datepicker:

  $("#dateEvent").datetimepicker({
  useCurrent: true,
  format: "dddd, MMM D YYYY"
  });

And this is the one for the jquery for generating the rows:

$('#add_event_time').click(function(){

        i++;

        $('#dynamic_admin_add_event_time').append(
            '
' +
            '<input type="text" id="dateEvent"name="admin_add_event_date[]" class="form-control" required>	' +
            '<input type="text" id="startTime" name="admin_add_start_event[]" class="form-control" required>	' +
            '<input type="text" id="endTime" name="admin_add_end_event[]" class="form-control" required>	' +
            '<button type="button" name="button_remove_event_time" id="'+i+'" class="btn btn-danger btn_remove">Remove Event</button>	' +
            '
');
 });

Can you guys help me by with this problem? Thank you.

Body:
Try this -

$("#dynamic_admin_add_event_time").on("click", "#dateEvent", function(){
    $(this).datetimepicker({
        useCurrent: true,
        format: "dddd, MMM D YYYY"
    });
});


问:
JPA EntityManager: Why use persist() over merge()?
EntityManager.merge() can insert new objects and update existing ones.

Why would one want to use persist() (which can only create new objects)?

答:
JPA is indisputably a great simplification in the domain of enterprise
  applications built on the Java platform. As a developer who had to
  cope up with the intricacies of the old entity beans in J2EE I see the
  inclusion of JPA among the Java EE specifications as a big leap
  forward. However, while delving deeper into the JPA details I find
  things that are not so easy. In this article I deal with comparison of
  the EntityManager’s merge and persist methods whose overlapping
  behavior may cause confusion not only to a newbie. Furthermore I
  propose a generalization that sees both methods as special cases of a
  more general method combine.

Persisting entities

In contrast to the merge method the persist method is pretty straightforward and intuitive. The most common scenario of the persist method's usage can be summed up as follows:

"A newly created instance of the entity class is passed to the persist method. After this method returns, the entity is managed and planned for insertion into the database. It may happen at or before the transaction commits or when the flush method is called. If the entity references another entity through a relationship marked with the PERSIST cascade strategy this procedure is applied to it also."

The specification goes more into details, however, remembering them is not crucial as these details cover more or less exotic situations only.

Merging entities

In comparison to persist, the description of the merge's behavior is not so simple. There is no main scenario, as it is in the case of persist, and a programmer must remember all scenarios in order to write a correct code. It seems to me that the JPA designers wanted to have some method whose primary concern would be handling detached entities (as the opposite to the persist method that deals with newly created entities primarily.) The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context. This task, however, divides further into several scenarios which worsen the intelligibility of the overall method's behavior.

Instead of repeating paragraphs from the JPA specification I have prepared a flow diagram that schematically depicts the behaviour of the merge method:

So, when should I use persist and when merge?

persist

You want the method always creates a new entity and never updates an entity. Otherwise, the method throws an exception as a consequence of primary key uniqueness violation.

Batch processes, handling entities in a stateful manner (see Gateway pattern).

Performance optimization

merge

You want the method either inserts or updates an entity in the database.

You want to handle entities in a stateless manner (data transfer objects in services)

You want to insert a new entity that may have a reference to another entity that may but may not be created yet (relationship must be marked MERGE). For example, inserting a new photo with a reference to either a new or a preexisting album.


问:
Can't run application on iOS 8
When I'm trying to run my application on iOS 8 device or simulator it crashes with messages in console:

```<code>cwd:/dir=/Users/alexedunov/Library/Developer/CoreSimulator/Devices/B0F6F815-1209-48D8-8485-    5B5EB35686B9/data/Containers/Data/Application/65B6100A-22C8-43B3-A6E2-506571B92E66/Documents
cwd:/Users/alexedunov/Library/Developer/CoreSimulator/Devices/B0F6F815-1209-48D8-8485-    5B5EB35686B9/data/Containers/Data/Application/65B6100A-22C8-43B3-A6E2-506571B92E66/Documents
2014-09-18 22:57:39.581 BankApp[3943:45325] Wrong directory.
Run application from /var/mobile/Applications/<App id>/<App name>.app
</code>```

I didn't find any solution to fix it.

My OS X version is Mac OS Yosemite beta 10.10.
XCode 6.0 (6A313)

答:
I catched the same error when running "Np Cades Browser". I figure out that it's because of iOS version. On iOS 10 error persists.

You need iOS 7 to make this work. Don't know about above versions. I assume paths different on different OS.

Title: Can't run application on iOS 8

Body:
When I'm trying to run my application on iOS 8 device or simulator it crashes with messages in console:

cwd:/dir=/Users/alexedunov/Library/Developer/CoreSimulator/Devices/B0F6F815-1209-48D8-8485-    5B5EB35686B9/data/Containers/Data/Application/65B6100A-22C8-43B3-A6E2-506571B92E66/Documents
cwd:/Users/alexedunov/Library/Developer/CoreSimulator/Devices/B0F6F815-1209-48D8-8485-    5B5EB35686B9/data/Containers/Data/Application/65B6100A-22C8-43B3-A6E2-506571B92E66/Documents
2014-09-18 22:57:39.581 BankApp[3943:45325] Wrong directory.
Run application from /var/mobile/Applications/<App id>/<App name>.app

I didn't find any solution to fix it.

My OS X version is Mac OS Yosemite beta 10.10.
XCode 6.0 (6A313)


问:
What is your workflow for skinning Flex apps?
Also, where do you start if you want to create a complete Flex 4 skin? Is there a list of all the "pieces" (component parts) you need to create graphics for somewhere, or some complete, example skins out there to use as a template? And do your skins render correctly in Flash Builder Design View? (including embedded fonts)

答:
Basically, you have many options when skinning Flex 4 apps :

Using "general" styles (chromeColor, selectionColor, focusColor, ...). This is usually called "Styling" instead of Skinning because you only change the overall look of the application. It's by far the easiest way to change the appareance of your application quickly without knowing anything about FXG, MXMLG, ... The drawback is it will still look like a Flex app, but with different colors/fonts

Using Adobe tools to produce FXG files. These tools can be Illustrator, Photoshop, Flash CS5. You design each of the spark component with these tools and export the result in .fxg format. FXG is great because it's optimized, but you can't use things such as Data Binding in it

Write your skin in MXMLG , by hand (starting from scratch or copying the default spark skin) or with the help of Flash Catalyst. Catalyst can take your Illustrator or Photoshop design and convert it to MXMLG. Experience shows it's still painfull, even with the last version. And you often end up doing things like this.

In our team, there is no such thing like designer/developer workflow with Flash Catalyst. The next version looks better but it's still far from what Microsoft is doing with Visual Studio/Blend.
That being said, the new Spark architecture is awesome. Skinning is much easier, flexible and readable. With this architecture, a developer codes the component and the designer skins it only by knowing the contract (skinparts, skinstates, data)
This also true for views if you use the Presentation Model pattern.

There is no "template" skins as the one available in Flex 3 because skinning doesn't use symbol anymore. What could be done though is a Flex 4 style explorer.

A final word, it has already been said here, but don't forget that with the current version (4.1), there is no spark equivalent for all of the components, so you  will still use Flex 3 skinning techniques for components such as DataGrid, Tree, ...


问:
Always run service as NetworkService, even in interactive mode
I have a service application that supports both start as service and interactive mode. The service I register is executed as the NetworkService user; the interactive mode is running as a computer administrator (normal users have no access to the program).

Now, some resources (e.g. files) are only available to the user NetworkService. Can I somehow tell the program to run the code as NetworkService, even if started by an administrator?

答:
Now, some resources (e.g. files) are only available to the user NetworkService. Can I somehow tell the program to run the code as NetworkService, even if started by an administrator?

NetworkService is a low privilege account. Administrator is a high privilege one. Having a situation where files are available to NS but not do admin is somewhat unusual. While is true that an admin has the right to impersonate most accounts (WindowsIdentity.Impersonate(), see Hans link for NS impersonate issues), I would revisit the situation and make sure this is actually necessary. It is much more likely that the files in question can, and should, be ACL-ed differently so that both NS and Local Administrators have access to the file.

Also consider splitting the application into a service component, always running as service, and a UI component that the administrator can invoke. Have the UI communicate with the service over some protocol, eg. via LRPC or shared memory of even HTTP.


问:
Storing data through app updates in App Store/Google Play with React-Native AsyncStorage
Considering that I have an application in the App Store/Google Play, which will locally save some data in AsyncStorage (React-Native) depending on the user interaction, what will happen with that data if I make an updated version of the app and push it to the App Store/Google Play?

It will still be saved in AsyncStorage?

答: if you are saving data in your document directory then after updation it will still remain as same. you can overwrite or use save same data. you can also make new directory for new version data also.</p>


问:
How to find the indexpath of tableview when Collectionview is clicked which is in tabelview Cell
I have tableview cell which is having collection view in it.

CollectionView contains images coming from server.

I want particular image on which user has tapped.
i.e.
Let Tableview have 4 rows. In the four row I have collection in every tableview row. When I click on 3rd row collectionview cell, I have to get that image from that row.

code is here

```<code>    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = (ISclassifiedCell*)[_isclassifed_tblview dequeueReusableCellWithIdentifier:@"ISclassifiedCell" forIndexPath:indexPath];
[cell.layer setCornerRadius:4.0f];
[cell.layer setMasksToBounds:YES];
     cell.profile_img.layer.cornerRadius=4.0f;
    cell.profile_img.layer.masksToBounds = YES;
    cell.iseventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"title"];
cell.eventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"category"];
cell.description_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"description"];

    UIFont *font=[UIFont fontWithName:@"Montserrat" size:14.0];

    CGFloat size = [self getLabelHeightForString:cell.description_lbl.text font:font];
    cell.description_lbl.frame=CGRectMake(cell.description_lbl.frame.origin.x, cell.description_lbl.frame.origin.y, cell.description_lbl.frame.size.width, size);
NSString *clubberid=[NSString stringWithFormat:@"%@",[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberId"]];
    cell.clubbername_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberName"];

if ([clubberid isEqualToString:[NSString stringWithFormat:@"%@",mainclubberId]]) {

    [cell.editbutnoutlet setImage:[UIImage imageNamed:@"note-interface-symbol"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=YES;
    cell.editbutnoutlet.hidden=NO;
    cell.editbutnoutlet.tag = indexPath.section;
    [cell.editbutnoutlet addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_providertbl reloadData];
}else{

 [cell.pokebtnoutlet setImage:[UIImage imageNamed:@"hold"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=NO;
    cell.editbutnoutlet.hidden=YES;
    cell.pokebtnoutlet.tag = indexPath.section;
    [cell.pokebtnoutlet addTarget:self action:@selector(pokeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

}
NSString *imgUrl = [NSString stringWithFormat:@"%s/presignin/clubber/getImage?clubberId=%@",urlPath,clubberid];

 NSURL *imageURL=[NSURL URLWithString:imgUrl];
imgarray=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"media"];
cell.profile_img.imageURL=imageURL;
    cell.imgcollection_view.tag=indexPath.section;
if (imgarray.count==0) {
    cell.imgcollection_view.hidden=YES;

}else{

   cell.imgcollection_view.hidden=NO;
}
cell.imgcollection_view.delegate=self;
cell.imgcollection_view.dataSource=self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //cell.imgcollection_view.allowsSelection=NO;
return cell;
}
 }
</code>```

collectionviewcode

```<code>    - (NSInteger)collectionView:(UICollectionView *)view
 numberOfItemsInSection:(NSInteger)section {

return imgarray.count;
 }
   // 2
   - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView
                                            *)collectionView {
return 1;
  }

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//isclasifiedimageCell *cell1 = nil;

    cell1=[cv
          dequeueReusableCellWithReuseIdentifier:@"isclasifiedimageCell"
          forIndexPath:indexPath];

NSLog(@"%ld",(long)indexPath.row);

NSString *clubberid=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];

NSString *clubberidtype=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"type"]];
}
else{
     NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/classifieds/showMedia?idclassifieds_media=%@",urlPath,clubberid];
    NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];

     cell1.img_view.imageURL=imageURL;
 }

    return cell1;
}
 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  {
NSLog(@"%ld",(long)cell.imgcollection_view.tag);
mediaimgarray=[[isclassifiedarray objectAtIndex:cell.imgcollection_view.tag]valueForKey:@"media"];
NSString *cluderimgid=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
// NSString *mediatypeurlstr=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                     bundle:nil];
isclasifiedImgpreviewVC * isclasifiedImgpreview =
[storyboard instantiateViewControllerWithIdentifier:@"isclasifiedImgpreview"];
// isclasifiedImgpreview.mediaatype=cluderimgid;
isclasifiedImgpreview.mediaatypeurlid=cluderimgid;
[self presentViewController:isclasifiedImgpreview
                   animated:YES
                 completion:nil];
</code>```

}

答:
Sample TableView Code:

```<code>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellTableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellCol"];
// Give Tag to CollectionView
    cell.collectionView.tag = indexPath.row;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)indexPath.row);

}
</code>```

Sample ColleCtionView Code:

```<code>-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *celll = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    celll.contentView.backgroundColor = [UIColor greenColor];
    return celll;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)collectionView.tag);
}
</code>```

Body:
I have tableview cell which is having collection view in it.

CollectionView contains images coming from server.

I want particular image on which user has tapped.
i.e.
Let Tableview have 4 rows. In the four row I have collection in every tableview row. When I click on 3rd row collectionview cell, I have to get that image from that row.

code is here

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    cell = (ISclassifiedCell*)[_isclassifed_tblview dequeueReusableCellWithIdentifier:@"ISclassifiedCell" forIndexPath:indexPath];
[cell.layer setCornerRadius:4.0f];
[cell.layer setMasksToBounds:YES];
     cell.profile_img.layer.cornerRadius=4.0f;
    cell.profile_img.layer.masksToBounds = YES;
    cell.iseventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"title"];
cell.eventtype_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"category"];
cell.description_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"description"];

    UIFont *font=[UIFont fontWithName:@"Montserrat" size:14.0];

    CGFloat size = [self getLabelHeightForString:cell.description_lbl.text font:font];
    cell.description_lbl.frame=CGRectMake(cell.description_lbl.frame.origin.x, cell.description_lbl.frame.origin.y, cell.description_lbl.frame.size.width, size);
NSString *clubberid=[NSString stringWithFormat:@"%@",[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberId"]];
    cell.clubbername_lbl.text=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"clubberName"];

if ([clubberid isEqualToString:[NSString stringWithFormat:@"%@",mainclubberId]]) {

    [cell.editbutnoutlet setImage:[UIImage imageNamed:@"note-interface-symbol"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=YES;
    cell.editbutnoutlet.hidden=NO;
    cell.editbutnoutlet.tag = indexPath.section;
    [cell.editbutnoutlet addTarget:self action:@selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_providertbl reloadData];
}else{

 [cell.pokebtnoutlet setImage:[UIImage imageNamed:@"hold"] forState:UIControlStateNormal];
    cell.pokebtnoutlet.hidden=NO;
    cell.editbutnoutlet.hidden=YES;
    cell.pokebtnoutlet.tag = indexPath.section;
    [cell.pokebtnoutlet addTarget:self action:@selector(pokeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

}
NSString *imgUrl = [NSString stringWithFormat:@"%s/presignin/clubber/getImage?clubberId=%@",urlPath,clubberid];

 NSURL *imageURL=[NSURL URLWithString:imgUrl];
imgarray=[[isclassifiedarray objectAtIndex:indexPath.section]valueForKey:@"media"];
cell.profile_img.imageURL=imageURL;
    cell.imgcollection_view.tag=indexPath.section;
if (imgarray.count==0) {
    cell.imgcollection_view.hidden=YES;

}else{

   cell.imgcollection_view.hidden=NO;
}
cell.imgcollection_view.delegate=self;
cell.imgcollection_view.dataSource=self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //cell.imgcollection_view.allowsSelection=NO;
return cell;
}
 }

collectionviewcode

    - (NSInteger)collectionView:(UICollectionView *)view
 numberOfItemsInSection:(NSInteger)section {

return imgarray.count;
 }
   // 2
   - (NSInteger)numberOfSectionsInCollectionView: (UICollectionView
                                            *)collectionView {
return 1;
  }

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//isclasifiedimageCell *cell1 = nil;

    cell1=[cv
          dequeueReusableCellWithReuseIdentifier:@"isclasifiedimageCell"
          forIndexPath:indexPath];

NSLog(@"%ld",(long)indexPath.row);

NSString *clubberid=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];

NSString *clubberidtype=[NSString stringWithFormat:@"%@",[[imgarray objectAtIndex:indexPath.row]valueForKey:@"type"]];
}
else{
     NSString *typeimgUrl1 = [NSString stringWithFormat:@"%s/presignin/classifieds/showMedia?idclassifieds_media=%@",urlPath,clubberid];
    NSURL *imageURL=[NSURL URLWithString:typeimgUrl1];

     cell1.img_view.imageURL=imageURL;
 }

    return cell1;
}
 -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
  {
NSLog(@"%ld",(long)cell.imgcollection_view.tag);
mediaimgarray=[[isclassifiedarray objectAtIndex:cell.imgcollection_view.tag]valueForKey:@"media"];
NSString *cluderimgid=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
// NSString *mediatypeurlstr=[NSString stringWithFormat:@"%@",[[mediaimgarray objectAtIndex:indexPath.row]valueForKey:@"idclassifieds_media"]];
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main"
                                                     bundle:nil];
isclasifiedImgpreviewVC * isclasifiedImgpreview =
[storyboard instantiateViewControllerWithIdentifier:@"isclasifiedImgpreview"];
// isclasifiedImgpreview.mediaatype=cluderimgid;
isclasifiedImgpreview.mediaatypeurlid=cluderimgid;
[self presentViewController:isclasifiedImgpreview
                   animated:YES
                 completion:nil];

}

Body:
Sample TableView Code:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellTableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellCol"];
// Give Tag to CollectionView
    cell.collectionView.tag = indexPath.row;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)indexPath.row);

}

Sample ColleCtionView Code:

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 3;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *celll = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    celll.contentView.backgroundColor = [UIColor greenColor];
    return celll;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",(long)collectionView.tag);
}


问:
Use Windows 7 login for SonarQube login
I am on a Windows 7 standalone machine - no internet connection, no networking. I installed SonarQube 5.6.6 and scanner 3.0.3 to analyze some of my projects - it works great. There are 3 of us who have separate windows logins to this standalone machine and I would like to use that windows login as the login to SonarQube for each of our profiles. How do I do this?
Thanks!</p>

答: Centralized authentication/authorization would typically be done with the LDAP Plugin. However if the machine is purely standalone (no networking as you said), then I presume user accounts are completely local, in which case the SonarQube accounts can only be managed locally by SonarQube too (i.e. SonarQube admin sets username/password).</p>

Title: Use Windows 7 login for SonarQube login


问:
How to make a anonymous class with void return type method and no parameters into a lambda expression?
I have the following piece of code where I need to change it into a lambda expression (Sonarlint presents this as an issue)

```<code>      Runnable runnableObj = new Runnable() {
        @Override
        public void run() {
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }
        }
      }
</code>```

I tried to change this into

```<code>       Runnable runnableObj = ()->{
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }

      }
</code>```

I am not sure if this the correct way to do it.
Please help as I have not implemented lambda expressions previously.

答: This is the correct implementation. The lambda expressions takes no arguments as the run() method doesn't, and it contains the same implementation.

Body:
I have the following piece of code where I need to change it into a lambda expression (Sonarlint presents this as an issue)

      Runnable runnableObj = new Runnable() {
        @Override
        public void run() {
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }
        }
      }

I tried to change this into

       Runnable runnableObj = ()->{
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }

      }

I am not sure if this the correct way to do it.
Please help as I have not implemented lambda expressions previously.


问:
How I can connect delphi 2010 to Telegram
I'm a Delphi program and I want to connect Delphi 2010 to Telegram.
I found this API https://github.com/ms301/TelegAPI that wont work on D2010

any one have any idea?

答: The API you want to use is for Delphi XE8 and up. You can not use it with Delphi 2010. Basically, you need to use a Delphi version supported by the TelegAPI.</p>


问:
rails: displaying a user friendly message for a routing error in rails
i am working in rails 2.3 on mac osx leopard.
every time i type a url that does not exist in a rails application i get the following error

```<code>Routing Error

No route matches "/whatever_i_typed" with {:method=>:get}
</code>```

this is find for development, but i was wondering how i can make sure users see a friendlier 'oops! not found' page. i was thinking about doing a begin...rescue block but i didn't know where to put it, not did i know the error code (i.e ActiveRecord::RecordNotFound)

thanks!
yuval

答:
I found the below url helpful for Rails 3.0.. users.

http://techoctave.com/c7/posts/36-rails-3-0-rescue-from-routing-error-solution

Body:
i am working in rails 2.3 on mac osx leopard.
every time i type a url that does not exist in a rails application i get the following error

Routing Error

No route matches "/whatever_i_typed" with {:method=>:get}

this is find for development, but i was wondering how i can make sure users see a friendlier 'oops! not found' page. i was thinking about doing a begin...rescue block but i didn't know where to put it, not did i know the error code (i.e ActiveRecord::RecordNotFound)

thanks!
yuval


问:
For Windows: Where to create connection profile for Fabric Composer / REST Server?
The information about creating a new connection profile references $HOME/.composer-connection-profiles as the directory to store connection profiles. Where is that located on Windows 7?

(Background: have both Fabric and Composer Playground running via docker-compose, using Docker Toolbox for Windows - now want to replace the playground by using the locally installed composer-cli, and locally installed composer-rest-server.)

答:
Mine are available on following location in Window 7 OS:

C:\Users\YourUserName\ .composer-connection-profiles

C:\Users\YourUserName\ .composer-credentials


问:
How to use getOrCreate() method in SparkContext class and what exactly is the functionality we achieve from this method
What is the use of getOrCreate() method in SparkContext Class and how I can use it? I did not found any suitable example(coding wise) for this.

What I understand is that using above method I can share spark context between applications. What do we mean by applications here?
Is application a different job submitted to a spark cluster?
If so then we should be able to use global variables(broadcast) and temp tables registered in one application into another application ?

Please if anyone can elaborate and give suitable example on this.

答:
As given in the Javadoc for SparkContext, getOrCreate() is useful when applications may wish to share a SparkContext. So yes, you can use it to share a SparkContext object across Applications. And yes, you can re-use broadcast variables and temp tables across.

As for understanding Spark Applications, please refer this link. In short, an application is the highest-level unit of computation in Spark. And what you submit to a spark cluster is not a job, but an application. Invoking an action inside a Spark application triggers the launch of a job to fulfill it.


问:
Find the longest arithmetic progression from an array
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].</p>

```<code>#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}
</code>```

答:
like this</p>

```<code>#include <stdio.h>

int main(void){
#if DEBUG
    int array[] = {5,1,2,4,6,8,12};
    int num = sizeof(array)/sizeof(*array);
    int i, diff;
#else
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }
#endif
    int j, len, longest_len = 2, longest_i = 0;

    for (i = 0; i < num - longest_len; i += len-1) {
        diff = array[i+1]-array[i];
        for(j = i+2; j < num && array[j-1]+diff == array[j]; ++j);
        len = j - i;
        if(longest_len < len){
            longest_len = len;
            longest_i = i;
        }
    }
    printf("\n Numbers in a.p: ");
    diff = array[longest_i+1] - array[longest_i];
    printf("[ ");
    for(i = 0; i < longest_len; ++i){
        printf("%d", array[longest_i + i]);
        if(i == longest_len-1)
            printf(" ]\n");
        else
            printf(", ");
    }
    printf("\n Common difference:%d", diff);
}
</code>```

Body:
I have an array of numbers ex.[5,1,2,4,6,8,12], and I want to find the length of longest arithmetic progression within the sequence and to print it. Longest arithmetic progression means an increasing sequence with common difference, in this case [2,4,6,8].

#include <stdio.h>

void main()
{
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }

    printf("\n Numbers in a.p: ");

    for (i = 0; i < num; i++) {
        diff = array[i+1]-array[i];
        if (array[i]-diff == array[i+1]-diff);
        {
            printf("%d, ", array[i]);
        }
    }
    printf("\n Common difference:%d", diff);
}

Body:
like this

#include <stdio.h>

int main(void){
#if DEBUG
    int array[] = {5,1,2,4,6,8,12};
    int num = sizeof(array)/sizeof(*array);
    int i, diff;
#else
    int array[100], i, num,diff;
    printf("Enter the size of an array \n");

    scanf("%d", &num);

    printf("Enter the elements of the array \n");

    for (i = 0; i < num; i++) {
        scanf("%d", &array[i]);
    }
#endif
    int j, len, longest_len = 2, longest_i = 0;

    for (i = 0; i < num - longest_len; i += len-1) {
        diff = array[i+1]-array[i];
        for(j = i+2; j < num && array[j-1]+diff == array[j]; ++j);
        len = j - i;
        if(longest_len < len){
            longest_len = len;
            longest_i = i;
        }
    }
    printf("\n Numbers in a.p: ");
    diff = array[longest_i+1] - array[longest_i];
    printf("[ ");
    for(i = 0; i < longest_len; ++i){
        printf("%d", array[longest_i + i]);
        if(i == longest_len-1)
            printf(" ]\n");
        else
            printf(", ");
    }
    printf("\n Common difference:%d", diff);
}


问:
Spring data Query-By-Example
I am trying to filter away results returned by my AppService by the current login of the user who is not part of the allowedusers set of App entity.

The current approach I am taking is Query-By-Example. The filtering of platform field works perfectly but the filter by allowedusers doesn't seems to be in effect?

App Entity

```<code>@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "app_alloweduser",
           joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
           inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
private Set<User> allowedusers = new HashSet<>();

public void setAllowedusers(Set<User> users) {
        this.allowedusers = users;
    }
</code>```

AppService

```<code>@Override
@Transactional(readOnly = true)
public Page<AppDTO> findAll(RequestParams requestParams, Pageable pageable) {
    App newApp = new App();
    Example<App> appExample;

    // set to current logged in user
    User user = new User();
    user.setLogin(SecurityUtils.getCurrentUserLogin());
    Set<User> users = new HashSet<User>();
    users.add(user);
    newApp.setAllowedusers(users);

    // set platform selected
    if (requestParams.platform != null) {
        newApp.setPlatform(requestParams.platform);
    }

    appExample = Example.of(newApp);

    // find by example
    Page<App> results = appRepository.findAll(appExample, pageable);
    return results.map(app -> appMapper.toDto(app));
}
</code>```

答:
TL;DR

Collection-valued properties are not supported for Query By Example in Spring Data JPA

Long version

The documentation describes the following limitations of Query By Example emphasis mine:

Only supports starts/contains/ends/regex matching for strings and exact matching for other property types

So expecting IN logic to apply is certainly out of scope of the current implementation.

Further down in the same document it then says:

Only SingularAttribute properties can currently be used for property matching.

Which is a somewhat confusing way to state: Does work only with simple properties

Title: Spring data Query-By-Example

Body:
I am trying to filter away results returned by my AppService by the current login of the user who is not part of the allowedusers set of App entity.

The current approach I am taking is Query-By-Example. The filtering of platform field works perfectly but the filter by allowedusers doesn't seems to be in effect?

App Entity

@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "app_alloweduser",
           joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
           inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
private Set<User> allowedusers = new HashSet<>();

public void setAllowedusers(Set<User> users) {
        this.allowedusers = users;
    }

AppService

@Override
@Transactional(readOnly = true)
public Page<AppDTO> findAll(RequestParams requestParams, Pageable pageable) {
    App newApp = new App();
    Example<App> appExample;

    // set to current logged in user
    User user = new User();
    user.setLogin(SecurityUtils.getCurrentUserLogin());
    Set<User> users = new HashSet<User>();
    users.add(user);
    newApp.setAllowedusers(users);

    // set platform selected
    if (requestParams.platform != null) {
        newApp.setPlatform(requestParams.platform);
    }

    appExample = Example.of(newApp);

    // find by example
    Page<App> results = appRepository.findAll(appExample, pageable);
    return results.map(app -> appMapper.toDto(app));
}


问:
iTunes Connect: "Release This Version" button is disabled
my app is in Pending Developer Release state, but the Release This Version button is disabled, why ?
the app has been set to be manually released to the store.

p.s. I am signed in with an Admin role.

screenshot:

答:
This is iTunes website bug - > use iTunes Mobile App instead

I've experienced this issue once on deployment night and spent long time trying different browsers and desktop machines however without success.

I end up downloading iTunes Mobile App on my phone and releasing App using it – that worked. Since then I use Mobile App as a second option in case iTunes website is bugging up again.


问:
how to check a varible in react native is null?
im trying out an example. Here is my code

export default class newApp extends Component {

```<code>  render() {
    var data = this.getWeatherFromApiAsync()

    return (
      if(data != null )
      {
        <View>
      <Text>got data</Text>
      </View>
      }else
      {
        <View>
      <Text>no data</Text>
      </View>
      }

    );
  }

   getWeatherFromApiAsync() {
      return fetch('http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=14&APPID=18dcba27e5bca83fe4ec6b8fbeed7827')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({isLoading: false, jsonData: responseJson});
          console.log(responseJson);
          return responseJson;
        })
        .catch((error) => {
          console.error(error);
        });
    }
}
</code>```

this gives following errors

```<code>E:/REACT_NATIVE_PROJECTS/newApp/index.android.js: Unexpected token (25:6)
  at E:\REACT_NATIVE_PROJECTS\newApp\index.android.js:25:6
processBundleResult
    DevServerHelper.java:381
access$400
    DevServerHelper.java:65
execute
    DevServerHelper.java:333
emitChunk
    MultipartStreamReader.java:69
readAllParts
    MultipartStreamReader.java:116
onResponse
    DevServerHelper.java:321
execute
    RealCall.java:126
run
    NamedRunnable.java:32
runWorker
    ThreadPoolExecutor.java:1113
run
    ThreadPoolExecutor.java:588
run
    Thread.java:818
</code>```

what do i do wrong. is it comparing part?

答:
This is how we use conditional rendering in react native :

{1 + 2 == 3 && I show up only when the left hand is true}

correct your syntax.

https://atticuswhite.com/blog/render-if-conditionally-render-react-components/

Body:
im trying out an example. Here is my code

export default class newApp extends Component {

  render() {
    var data = this.getWeatherFromApiAsync()

    return (
      if(data != null )
      {
        <View>
      <Text>got data</Text>
      </View>
      }else
      {
        <View>
      <Text>no data</Text>
      </View>
      }

    );
  }

   getWeatherFromApiAsync() {
      return fetch('http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=14&APPID=18dcba27e5bca83fe4ec6b8fbeed7827')
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({isLoading: false, jsonData: responseJson});
          console.log(responseJson);
          return responseJson;
        })
        .catch((error) => {
          console.error(error);
        });
    }
}

this gives following errors

E:/REACT_NATIVE_PROJECTS/newApp/index.android.js: Unexpected token (25:6)
  at E:\REACT_NATIVE_PROJECTS\newApp\index.android.js:25:6
processBundleResult
    DevServerHelper.java:381
access$400
    DevServerHelper.java:65
execute
    DevServerHelper.java:333
emitChunk
    MultipartStreamReader.java:69
readAllParts
    MultipartStreamReader.java:116
onResponse
    DevServerHelper.java:321
execute
    RealCall.java:126
run
    NamedRunnable.java:32
runWorker
    ThreadPoolExecutor.java:1113
run
    ThreadPoolExecutor.java:588
run
    Thread.java:818

what do i do wrong. is it comparing part?


问:
How to pick image from particular folder, say sdcard/mypics?
How to pick image from particular folder, say sdcard/mypics?</p>

答:
i can recommend the gridview tutorial.

you will have to modify the code a bit to get the resource into an array before showing the gridview. but therefore you can use the BitmapFactory  class.


问:
p_threads: Condition Variable Locking
Let's say I had 4 threads, a producer and three consumers, a single mutex and a single condition variable, every consumer runs the same function that does the below:

```<code>mutexlock(mutex)
signal[i] = 1;
while(signal[i] == 1) {
condwait(cond, mutex)
}
mutexunlock(mutex)
</code>```

And the producer does the below

```<code>if(signal == 1)
{
set 0 - atomically using CAS
mutexlock(mutex)
condbroadcast(cond)
mutexunlock(mutex)
}
</code>```

Let's say if more than one consumer were in that lock, wouldn't they fight for the cond variable? Should I create one for each thread or can p_thread condition variables be shared accross multiple threads without any race conditions?

答: When you create a muti-thread program,they share the resource signal[i] and all the three thread will compete for the resources.When signal[i] == 0,the threads which didn't get the resource will be put into the queue of the condition variable.And when you send a broadcast,all the waiting threads in the condition variable will weak up and compete for the resouce.Here is a tourial for muti-thread beginner in C.</p>

Title: p_threads: Condition Variable Locking

Body:
Let's say I had 4 threads, a producer and three consumers, a single mutex and a single condition variable, every consumer runs the same function that does the below:

mutexlock(mutex)
signal[i] = 1;
while(signal[i] == 1) {
condwait(cond, mutex)
}
mutexunlock(mutex)

And the producer does the below

if(signal == 1)
{
set 0 - atomically using CAS
mutexlock(mutex)
condbroadcast(cond)
mutexunlock(mutex)
}

Let's say if more than one consumer were in that lock, wouldn't they fight for the cond variable? Should I create one for each thread or can p_thread condition variables be shared accross multiple threads without any race conditions?