问:
Collection View inside Table View Cell
I want to create collection view inside the table view cell for horizontal scrolling of elements. But I have the problem how to fill right my collection views. I need a way to connect collection views with my data.

How can I get and loop through Table View Cells to find needed collection view and return the cells with data?

答:
below is a general example of how you can pass data to collection views inside your table view cell. Also this link is a youtube tutorial on this subject.

Models:

```<code>class ListOfParents: NSObject {
var parents:[Parent]?
}

class Parent: NSObject {
var children: [Child]?

static func fetchParents(_ completionHandler: @escaping (ListOfParents) -> ()) {
    //fetch parents data
 }

}

class Child: NSObject {

}
</code>```

TableView cell:

```<code>class CustomTableViewController: UITableViewController {

var listOfParents: ListOfParents?

override func viewDidLoad() {
    super.viewDidLoad()
    Parent.fetchparents { (listOfParents) in
        self.listOfParents = listOfParents
    }
    tableView.register(CustomParentCell.self, forCellReuseIdentifier: "tableCell")

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let parentsCount = listOfParents?.parents?.count else {return 0}
    return parentsCount
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomParentCell

    cell.parent = listOfParents?.parents?[indexPath.item]
    return cell
 }
}
</code>```

Parent cell:

```<code>class CustomParentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

var parent: Parent? {
    didSet {
        // set child value here
    }
}

lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return collectionView
}()

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.register(CustomChildCell.self, forCellWithReuseIdentifier: "childCellID")
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    guard let childrenCount = parent?.children?.count else {return 0}
    return childrenCount
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "childCellID", for: indexPath) as! CustomChildCell

    cell.child = parent?.children?[indexPath.item]
    return cell
 }
}
</code>```

Child cell:

```<code>class CustomChildCell: UICollectionViewCell {
var child: Child?
}
</code>```

Title: Collection View inside Table View Cell

Body:
below is a general example of how you can pass data to collection views inside your table view cell. Also this link is a youtube tutorial on this subject.

Models:

class ListOfParents: NSObject {
var parents:[Parent]?
}

class Parent: NSObject {
var children: [Child]?

static func fetchParents(_ completionHandler: @escaping (ListOfParents) -> ()) {
    //fetch parents data
 }

}

class Child: NSObject {

}

TableView cell:

class CustomTableViewController: UITableViewController {

var listOfParents: ListOfParents?

override func viewDidLoad() {
    super.viewDidLoad()
    Parent.fetchparents { (listOfParents) in
        self.listOfParents = listOfParents
    }
    tableView.register(CustomParentCell.self, forCellReuseIdentifier: "tableCell")

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let parentsCount = listOfParents?.parents?.count else {return 0}
    return parentsCount
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomParentCell

    cell.parent = listOfParents?.parents?[indexPath.item]
    return cell
 }
}

Parent cell:

class CustomParentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

var parent: Parent? {
    didSet {
        // set child value here
    }
}

lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return collectionView
}()

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.register(CustomChildCell.self, forCellWithReuseIdentifier: "childCellID")
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    guard let childrenCount = parent?.children?.count else {return 0}
    return childrenCount
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "childCellID", for: indexPath) as! CustomChildCell

    cell.child = parent?.children?[indexPath.item]
    return cell
 }
}

Child cell:

class CustomChildCell: UICollectionViewCell {
var child: Child?
}


来源: stackexchange

问:
how to remove duplicate and filter array object like below mentioned
let array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"},]

let array2 = [{id: 575, name: "Saloon Grand"} , {id: 562, name: "Eva Bridal"}]

Final Output :

```<code>let newarray = [{id: 582, name: "Finger Touch"},{id: 575, name: "Saloon Grand"} ]
</code>```

答:
I assume that a duplicate can appear more than once (ie 3 items with the same id). If this is the case, you can use a Set to hold existing ids. Concat the two arrays, and use reduce to create a Map. If an item's id exists in the Set, remove it from Map, if not add the item to the Map, and it's id to the Set. When the reduce process ends, get the Map values, and spread to an array:

const array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"}]

const array2 = [{id: 575, name: "Saloon Grand"}, {id: 562, name: "Eva Bridal"}]

const existing = new Set();
const result = [...array1.concat(array2).reduce((r, o) => {
  if(existing.has(o.id)) {
    r.delete(o.id);
  } else {
    existing.add(o.id);
    r.set(o.id, o);
  }

  return r;
}, new Map).values()];

console.log(result);```
</div>
</div>
</p>

<p>If you are sure that there will only be pairs of duplicated items (ie - no more than 2 items with the same <code>id</code>), use just the Map, and remove an item if it already exists in the Map:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"}]

const array2 = [{id: 575, name: "Saloon Grand"}, {id: 562, name: "Eva Bridal"}]

const result = [...array1.concat(array2).reduce((r, o) => {
  if(r.has(o.id)) {
    r.delete(o.id);
  } else {
    r.set(o.id, o);
  }

  return r;
}, new Map).values()];

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

ContentLicense: CC BY-SA 3.0

Body:
let array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"},]

let array2 = [{id: 575, name: "Saloon Grand"} , {id: 562, name: "Eva Bridal"}]

Final Output :

let newarray = [{id: 582, name: "Finger Touch"},{id: 575, name: "Saloon Grand"} ]

Body:
I assume that a duplicate can appear more than once (ie 3 items with the same id). If this is the case, you can use a Set to hold existing ids. Concat the two arrays, and use reduce to create a Map. If an item's id exists in the Set, remove it from Map, if not add the item to the Map, and it's id to the Set. When the reduce process ends, get the Map values, and spread to an array:

const array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"}]

const array2 = [{id: 575, name: "Saloon Grand"}, {id: 562, name: "Eva Bridal"}]

const existing = new Set();
const result = [...array1.concat(array2).reduce((r, o) => {
  if(existing.has(o.id)) {
    r.delete(o.id);
  } else {
    existing.add(o.id);
    r.set(o.id, o);
  }

  return r;
}, new Map).values()];

console.log(result);

If you are sure that there will only be pairs of duplicated items (ie - no more than 2 items with the same id), use just the Map, and remove an item if it already exists in the Map:

const array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"}]

const array2 = [{id: 575, name: "Saloon Grand"}, {id: 562, name: "Eva Bridal"}]

const result = [...array1.concat(array2).reduce((r, o) => {
  if(r.has(o.id)) {
    r.delete(o.id);
  } else {
    r.set(o.id, o);
  }

  return r;
}, new Map).values()];

console.log(result);


问:
why do Realm generate proxy classes for all the model class?
I am trying to understand how does Realm for Android works under the hood. when I used the custom methods in our model class, couldn't see them in the generated proxy class.</p>

答:
The proxy classes extend your model class, which is why they cannot be final and need to be marked open in Kotlin, but that means that the proxy class automatically inherit all the methods from your model class.

You can read https://academy.realm.io/posts/is-realm-magic-makoto-yamazaki/ if you are interested in more detail.


问:
Automatically transfer money from one bank account to another
Is there available any API which allow us to automatically transfer money to other bank account? I only found that I can't have it done with paypal API.

I have user money on one bank account and after some action in application I need to transfer this money to other user bank account.

So to summary it all, step by step:

User1 send money to application bank account.

After few hours User1 confirm some action on aplication by clicking button.

After User1 clicked button I want to transfer money to User2 bank account from application bank account automatically.

I already have in DB every information needed to do bank transfer.

I am looking for API which would allow me to do third step which is automatically transfering money from my (app) bank account to user bank account no matter which bank he is using.

答:
You can also use this api

Money Transfer API


问:
WPF Changing Button Properties after clicked
My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amount of time and I want to reflect the restarting status inside of the control. This is roughly what I have for the restart button click handler

```<code>private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    Controller.Stop();
    Controller.WaitForStatus(ServiceControllerStatus.Stopped);
    Controller.Start();
    Controller.WaitForStatus(ServiceControllerStatus.Running);

    startStopButton.Visibility = Visibility.Visible;
    restartButton.Visibility   = Visibility.Visible;

    statusTextBlock.Text = Controller.Status.ToString();
}
</code>```

Even when I step through the debugger I don't see these changes reflected in the application. Must be something that I'm missing. Also, I've tried disabling the buttons instead of hiding them and that does not work either.

答: That's because execution is happening in the UI thread.  Your button won't update because between { and } the UI thread is busy doing your work and it cannot update the button.

ContentLicense: CC BY-SA 2.5

Body:
My app has a UserControl that wraps a ServiceController to expose start/stop/restart win service functionality to the user. My concern at the moment is restarting. It takes a small amount of time and I want to reflect the restarting status inside of the control. This is roughly what I have for the restart button click handler

private void RestartButton_Click(object sender, RoutedEventArgs e)
{
    startStopButton.Visibility = Visibility.Hidden;
    restartButton.Visibility   = Visibility.Hidden;
    statusTextBlock.Text = "Restarting...";

    Controller.Stop();
    Controller.WaitForStatus(ServiceControllerStatus.Stopped);
    Controller.Start();
    Controller.WaitForStatus(ServiceControllerStatus.Running);

    startStopButton.Visibility = Visibility.Visible;
    restartButton.Visibility   = Visibility.Visible;

    statusTextBlock.Text = Controller.Status.ToString();
}

Even when I step through the debugger I don't see these changes reflected in the application. Must be something that I'm missing. Also, I've tried disabling the buttons instead of hiding them and that does not work either.


问:
browser adding comma and domain name on links with partial url
On my python 3, flask based website recently upgraded from ubuntu 14.04 to 16.04. i have noticed strange thing when i run my site using gunicorn behind nginx (1.12.2) and click on links such as blog which are defined in href tag just as "/blog" once i click on them i am redirected to domain.com,domain.com/blog? If i hover over link i see it proper link as domain.com/blog. If i start site locally without gunicorn and nginx it works properly. There is no change in code just modules upgraded along with os version and nginx. Btw i am running this using circus proc manager.

Just need pointers as what could be causing this?

答:
This could be a problem with your Nginx settings rather than gunicorn as I encountered the same problem yesterday. I'm just a beginner on this but I guess gunicorn somehow react to "X-Forwarded-For" in header in an unexpected way.

My solution was: remove the first line in your conf file under sites-enabled(-available), and delete the second as well if it doesn't work.

```<code>   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header Host $host;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This could be a problem with your Nginx settings rather than gunicorn as I encountered the same problem yesterday. I'm just a beginner on this but I guess gunicorn somehow react to "X-Forwarded-For" in header in an unexpected way.

My solution was: remove the first line in your conf file under sites-enabled(-available), and delete the second as well if it doesn't work.

   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_set_header Host $host;


问:
Running command on freeSSHD server with WinSCP fails with "Your shell is probably incompatible with the application (BASH is recommended)"
I am using below script to Verify checksum of a remote file against a local file. The server I installed on my machine is freeSSHd.

When I tried to execute the below script using PowerShell ISE I get an error message saying:

Your shell is probably incompatible with the application (BASH is recommended)

I've granted shell access in the FreeSSHd Server User properties:

Script:

```<code>param (
    # Use Generate URL function to obtain a value for -sessionUrl parameter.
    $sessionUrl = "sftp://user:mypassword;fingerprint=ssh-rsa-xx-xx-xx@example.com/",
    [Parameter(Mandatory = $True)]
    $localPath,
    [Parameter(Mandatory = $True)]
    $remotePath,
    [Switch]
    $pause = $False
)

try
{
    Write-Host $localPath -foregroundcolor Gray

# Calculate local file checksum
$localChecksum = ((CertUtil -hashfile $localPath SHA1)[1] -replace " ","")

# Write-Host "Local Checksum:"
Write-Host $localChecksum

# Load WinSCP .NET assembly
#Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
[Reflection.Assembly]::LoadFrom("\\c:\Program Files (x86)\WinSCP\WinSCPnet.dll") | Out-Null

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl($sessionUrl)

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    Write-Host $remotePath -foregroundcolor Gray

    # Calculate remote file checksum
    $sha1Command = "bash sha1sum -b $remotePath | awk '{print `$1}'"

    $result = $session.ExecuteCommand($sha1Command)
    $result.Check()
    $remoteChecksum = $result.Output;
    #$remoteChecksum =
        [System.BitConverter]::ToString($session.CalculateFileChecksum("sha-1", $remotePath))

    # Write-Host "Remote Checksum:"
    Write-Host $remoteChecksum
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

# Compare cheksums
if ($localChecksum -eq $remoteChecksum)
{
    Write-Host
    Write-Host "Match" -foregroundcolor "green"
    $result = 0
}
else
{
    Write-Host
    Write-Host "Does NOT match" -foregroundcolor "red"
    $result = 1
}
}
catch [Exception]
{
Write-Host $_.Exception.Message
$result = 1
}

# Pause if -pause switch was used
if ($pause)
{
    Write-Host "Press any key to exit..."
    [System.Console]::ReadKey() | Out-Null
}

exit $result
</code>```

答:
FreeSSHd server does not support any "bash". Its "shell" is Windows cmd.exe.

Your code cannot work. Windows cmd.exe is not compatible with WinSCP.

Moreover FreeSSHd is pretty buggy, do not use it.

You should use another Windows SSH server.

You can use Windows build of OpenSSH. It would allow you to execute a PowerShell script on the server to calculate the checksum.

If you install Windows Subsystem for Linux, you may even get the sha1sum (but I'm not sure).

You can use Cygwin, if you need to simulate *nix environment on Windows.

You can use Bitvise SSH Server for personal use for free. Its SFTP server supports checksum calculation on its own, so you would be able to use WinSCP Session.CalculateFileChecksum method directly.

There are lot of other options.

Body:
I am using below script to Verify checksum of a remote file against a local file. The server I installed on my machine is freeSSHd.

When I tried to execute the below script using PowerShell ISE I get an error message saying:

Your shell is probably incompatible with the application (BASH is recommended)

I've granted shell access in the FreeSSHd Server User properties:

Script:

param (
    # Use Generate URL function to obtain a value for -sessionUrl parameter.
    $sessionUrl = "sftp://user:mypassword;fingerprint=ssh-rsa-xx-xx-xx@example.com/",
    [Parameter(Mandatory = $True)]
    $localPath,
    [Parameter(Mandatory = $True)]
    $remotePath,
    [Switch]
    $pause = $False
)

try
{
    Write-Host $localPath -foregroundcolor Gray

# Calculate local file checksum
$localChecksum = ((CertUtil -hashfile $localPath SHA1)[1] -replace " ","")

# Write-Host "Local Checksum:"
Write-Host $localChecksum

# Load WinSCP .NET assembly
#Add-Type -Path (Join-Path $PSScriptRoot "WinSCPnet.dll")
[Reflection.Assembly]::LoadFrom("\\c:\Program Files (x86)\WinSCP\WinSCPnet.dll") | Out-Null

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl($sessionUrl)

$session = New-Object WinSCP.Session

try
{
    # Connect
    $session.Open($sessionOptions)

    Write-Host $remotePath -foregroundcolor Gray

    # Calculate remote file checksum
    $sha1Command = "bash sha1sum -b $remotePath | awk '{print `$1}'"

    $result = $session.ExecuteCommand($sha1Command)
    $result.Check()
    $remoteChecksum = $result.Output;
    #$remoteChecksum =
        [System.BitConverter]::ToString($session.CalculateFileChecksum("sha-1", $remotePath))

    # Write-Host "Remote Checksum:"
    Write-Host $remoteChecksum
}
finally
{
    # Disconnect, clean up
    $session.Dispose()
}

# Compare cheksums
if ($localChecksum -eq $remoteChecksum)
{
    Write-Host
    Write-Host "Match" -foregroundcolor "green"
    $result = 0
}
else
{
    Write-Host
    Write-Host "Does NOT match" -foregroundcolor "red"
    $result = 1
}
}
catch [Exception]
{
Write-Host $_.Exception.Message
$result = 1
}

# Pause if -pause switch was used
if ($pause)
{
    Write-Host "Press any key to exit..."
    [System.Console]::ReadKey() | Out-Null
}

exit $result


问:
When declaring variable is not completed, why compiler know its size?
After pointer pa declaring, right now,to use it in the function malloc(),

why compiler can know its size? And compiler how to parse under code:

```<code>int *pa = malloc(10 * sizeof *pa); // allocate an array of 10 int
</code>```

and

```<code>struct Node {
    int value;
    struct Node *prev;
    struct Node *next;
}
</code>```

prev and next is struct Node *, but now struct Node is undefined.

Why compiler is able to allocate enough size for *prev, *next?

答: Because they are pointers. Compiler knows how much memory to allocate for pointers.</p>

Body:
After pointer pa declaring, right now,to use it in the function malloc(),

why compiler can know its size? And compiler how to parse under code:

int *pa = malloc(10 * sizeof *pa); // allocate an array of 10 int

and

struct Node {
    int value;
    struct Node *prev;
    struct Node *next;
}

prev and next is struct Node *, but now struct Node is undefined.

Why compiler is able to allocate enough size for *prev, *next?


问:
Firebase user data storage issue
I am working with Firebase Authentication and while coding I realised that I can use User user = FirebaseAuth.getInstance().getCurrentUser; to fetch user data in any activity through out the application if user successfully logged in but I am confused that whether I can store user data in sharedPreferences after user login or I can use User user = FirebaseAuth.getInstance().getCurrentUser; way to get user data in whichever activity I want to. So which method is preferable to use firebase user data. And if there any other method you have to suggest then you are always welcome. Thanks in advance.

答:
The user data is limit to login info like user id or email address by using FirebaseAuth.getInstance().getCurrentUser().
If it's enough to use it for you, that's ok.

In order to get the data which saved to sharedpreferences, you can define PreferencesUtils class.
The class is singleton or has static members.
If so, I think you can call this members anywhere.

I hope it helps.. If you any questions, let me know.

Title: Firebase user data storage issue


问:
Comparing Two Sets of Date Ranges in SQL
I have two sets of data with different date ranges.

```<code>Tbl 1:
ID, Date_Start, Date_End
1, 2010-01-01, 2010-01-09
1, 2010-01-10, 2010-01-19
1, 2010-01-30, 2010-01-31

Tbl 2:
ID, Date_Start, Date_End
1, 2010-01-01, 2010-01-04
1, 2010-01-08, 2010-01-17
1, 2010-01-30, 2010-01-31
</code>```

I'd like to find cases date ranges do not entirely overlap date ranges in Tbl 2.  So for instance, in this example, I'd like output that looks something like this --

```<code>Output:
ID, Gap_Start, Gap_End
1, 2010-01-05, 2010-01-07
1, 2010-01-18, 2010-01-19
</code>```

Date ranges will never overlap within a table.  To do this, I'm using either DB2 SQL or SAS.  Unfortunately, the datasets are big enough (millions of records) that I can't just brute force it.

Thank you!

答:
For what it's worth, this is the method I ended up using.  I think you could do it in pure SQL, but it got horrifically ugly and difficult to debug.

Step 1 -- I consolidated the date ranges in both datasets.  This means that something like

```<code>ID, Start_Date, End_Date
1,  2010-01-01, 2010-01-31
1,  2010-02-01, 2010-02-28
</code>```

got transformed into this --

```<code>ID, Start_Date, End_Date
1,  2010-01-01, 2010-02-28.
</code>```

The query I used to produce this was --

```<code>WITH Cte_recomb (Id, Start_date, End_date, Hopcount) AS
        (SELECT Id,
                Start_date,
                End_date,
                1 AS Hopcount
         FROM Table1
         UNION ALL
         SELECT Cte_recomb.Id,
                Cte_recomb.Start_date,
                Table1.End_date,
                (Recomb.Hopcount + 1) AS Hopcount
         FROM Cte_recomb, Table1
         WHERE (Cte_recomb.Id = Table1.Id) AND
               (Cte_recomb.End_date + 1 day = Table1.Start_date)),
     Cte_maxenddate AS
        (SELECT Id,
                Start_date,
                Max (End_date) AS End_date
         FROM Cte_recomb
         GROUP BY Id, Start_date
         ORDER BY Id, Start_date)
SELECT Maxend.*
FROM    Cte_maxenddate AS Maxend
     LEFT JOIN
        Cte_recomb AS Nextrec
     ON (Nextrec.Id = Maxend.Id) AND
        (Nextrec.Start_date < Maxend.Start_date) AND
        (Nextrec.End_date >= Maxend.End_date)
WHERE Nextrec.Id IS NULL;
</code>```

Step 2 --

I produced another dataset that created a record for every overlap between the two datasets.  You'll need an additional step to find cases where a given record in Table1 doesn't have a corresponding record in Table2 at all.

```<code>SELECT Table1.Id,
       Table1.Start_date AS Table1_start_date,
       Table1.End_date AS Table1_end_date,
       Table2.Start_date AS Table2_start_date,
       Table2.End_date AS Table2_end_date
FROM    Table1
     INNER JOIN
        Table2
     ON (Table1.Plcy_id_sk = Id) AND
        ( (Table1.Start_date BETWEEN Table2.Start_date AND Table2.End_date) OR
         (Table2.Start_date  BETWEEN Table1.Start_date AND Table1.End_date)) AND
        ( (Table1.Start_date <> Table2.Start_date) OR
         (Table1.End_date    <> Table2.End_date))
ORDER BY Table1.Id, Table1.Start_date, Table2.Start_date;
</code>```

Step 3 --

I take the above dataset, and run the following SAS job.  I tried to do this in pure SQL with recursive queries, but it got uglier and uglier every time I looked at it.

```<code>Data Table1_Gaps;
  Set Table1_Compare;
  By ID Table1_Start_Date Table2_Start_Date;
  format Gap_Start_Date yymmdd10.;
  format Gap_End_Date   yymmdd10.;
  format Old_Start_Date yymmdd10.;
  format Old_End_Date   yymmdd10.;
  Retain Old_Start_Date Old_End_Date;
  IF (Table2_End_Date = .) then do;
      Gap_Start_Date = Table1_Start_Date;
      Gap_End_Date   = Table1_End_Date;
      output;
  end;
  else do;
    If (Table2_Start_Date > Table1_Start_Date) then do;
      if first.Table1_Start_Date then do;
        Gap_Start_Date = Table1_Start_Date;
        Gap_End_Date   = Table2_Start_Date - 1;
        output;
      end;
      else do;
        Gap_Start_Date = Old_End_Date + 1;
        Gap_End_Date   = Table2_Start_Date - 1;
        output;
      end;
    end;
    If (Table2_End_Date < Table1_End_Date) then do;
      if Last.Table1_Start_Date then do;
        Gap_Start_Date = Table2_End_Date + 1;
        Gap_End_Date   = Table1_End_Date;
        output;
      end;
    end;
  end;
  Old_Start_Date = Table2_Start_Date;
  Old_End_Date   = Table2_End_Date;
  drop Old_Start_Date Old_End_Date;
run;
</code>```

I haven't verified it entirely yet, but this approach does seem to have given me the results I wanted.  Any thoughts?

Body:
I have two sets of data with different date ranges.

Tbl 1:
ID, Date_Start, Date_End
1, 2010-01-01, 2010-01-09
1, 2010-01-10, 2010-01-19
1, 2010-01-30, 2010-01-31

Tbl 2:
ID, Date_Start, Date_End
1, 2010-01-01, 2010-01-04
1, 2010-01-08, 2010-01-17
1, 2010-01-30, 2010-01-31

I'd like to find cases date ranges do not entirely overlap date ranges in Tbl 2.  So for instance, in this example, I'd like output that looks something like this --

Output:
ID, Gap_Start, Gap_End
1, 2010-01-05, 2010-01-07
1, 2010-01-18, 2010-01-19

Date ranges will never overlap within a table.  To do this, I'm using either DB2 SQL or SAS.  Unfortunately, the datasets are big enough (millions of records) that I can't just brute force it.

Thank you!

Body:
For what it's worth, this is the method I ended up using.  I think you could do it in pure SQL, but it got horrifically ugly and difficult to debug.

Step 1 -- I consolidated the date ranges in both datasets.  This means that something like

ID, Start_Date, End_Date
1,  2010-01-01, 2010-01-31
1,  2010-02-01, 2010-02-28

got transformed into this --

ID, Start_Date, End_Date
1,  2010-01-01, 2010-02-28.

The query I used to produce this was --

WITH Cte_recomb (Id, Start_date, End_date, Hopcount) AS
        (SELECT Id,
                Start_date,
                End_date,
                1 AS Hopcount
         FROM Table1
         UNION ALL
         SELECT Cte_recomb.Id,
                Cte_recomb.Start_date,
                Table1.End_date,
                (Recomb.Hopcount + 1) AS Hopcount
         FROM Cte_recomb, Table1
         WHERE (Cte_recomb.Id = Table1.Id) AND
               (Cte_recomb.End_date + 1 day = Table1.Start_date)),
     Cte_maxenddate AS
        (SELECT Id,
                Start_date,
                Max (End_date) AS End_date
         FROM Cte_recomb
         GROUP BY Id, Start_date
         ORDER BY Id, Start_date)
SELECT Maxend.*
FROM    Cte_maxenddate AS Maxend
     LEFT JOIN
        Cte_recomb AS Nextrec
     ON (Nextrec.Id = Maxend.Id) AND
        (Nextrec.Start_date < Maxend.Start_date) AND
        (Nextrec.End_date >= Maxend.End_date)
WHERE Nextrec.Id IS NULL;

Step 2 --

I produced another dataset that created a record for every overlap between the two datasets.  You'll need an additional step to find cases where a given record in Table1 doesn't have a corresponding record in Table2 at all.

SELECT Table1.Id,
       Table1.Start_date AS Table1_start_date,
       Table1.End_date AS Table1_end_date,
       Table2.Start_date AS Table2_start_date,
       Table2.End_date AS Table2_end_date
FROM    Table1
     INNER JOIN
        Table2
     ON (Table1.Plcy_id_sk = Id) AND
        ( (Table1.Start_date BETWEEN Table2.Start_date AND Table2.End_date) OR
         (Table2.Start_date  BETWEEN Table1.Start_date AND Table1.End_date)) AND
        ( (Table1.Start_date <> Table2.Start_date) OR
         (Table1.End_date    <> Table2.End_date))
ORDER BY Table1.Id, Table1.Start_date, Table2.Start_date;

Step 3 --

I take the above dataset, and run the following SAS job.  I tried to do this in pure SQL with recursive queries, but it got uglier and uglier every time I looked at it.

Data Table1_Gaps;
  Set Table1_Compare;
  By ID Table1_Start_Date Table2_Start_Date;
  format Gap_Start_Date yymmdd10.;
  format Gap_End_Date   yymmdd10.;
  format Old_Start_Date yymmdd10.;
  format Old_End_Date   yymmdd10.;
  Retain Old_Start_Date Old_End_Date;
  IF (Table2_End_Date = .) then do;
      Gap_Start_Date = Table1_Start_Date;
      Gap_End_Date   = Table1_End_Date;
      output;
  end;
  else do;
    If (Table2_Start_Date > Table1_Start_Date) then do;
      if first.Table1_Start_Date then do;
        Gap_Start_Date = Table1_Start_Date;
        Gap_End_Date   = Table2_Start_Date - 1;
        output;
      end;
      else do;
        Gap_Start_Date = Old_End_Date + 1;
        Gap_End_Date   = Table2_Start_Date - 1;
        output;
      end;
    end;
    If (Table2_End_Date < Table1_End_Date) then do;
      if Last.Table1_Start_Date then do;
        Gap_Start_Date = Table2_End_Date + 1;
        Gap_End_Date   = Table1_End_Date;
        output;
      end;
    end;
  end;
  Old_Start_Date = Table2_Start_Date;
  Old_End_Date   = Table2_End_Date;
  drop Old_Start_Date Old_End_Date;
run;

I haven't verified it entirely yet, but this approach does seem to have given me the results I wanted.  Any thoughts?


问:
Facebook login error with https
I got this error message when login with facebook.

100 Message: Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request

Redirect url with http working fine but with https I'm getting above error message.

Please help.

Thanks

答:
I believed you have used different redirect_uri in your facebook app settings and Oauth API code. thats why you got this error.

For facebook login you must set same redirect_uri into both place.

Title: Facebook login error with https


问:
Custom PageControl image - Swift
I am trying to set an image for UIPageControl dots.

I need to change the default dots, instead of that I need an image.
I used the below code

```<code>self.pageCtrl.currentPageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Selected")!)
self.pageCtrl.pageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Normal")!)
</code>```

I could set the image in Pagecontrol but, it is overlapping with default dots.

答:
This approach works for me. I create a custom pageControl class and change the images for dots to be any custom image.

In the code below I changed the image for the first dot in pageControl with any custom image.

You can change updateDots() method as per your needs.

Hope it helps!!!

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let pageControl = CustomPageControl(frame: CGRect(x: 100, y: 100, width: 104, height: 40))
    pageControl.numberOfPages = 5
    pageControl.currentPage = 0
    self.view.addSubview(pageControl)
}

class CustomPageControl: UIPageControl {

var imageToBeReplacedByDot: UIImage {
    return // Image you want to replace with dots
}
var circleImage: UIImage {

    return //Default Image
}

override var numberOfPages: Int {
    didSet {
        updateDots()
    }
}

override var currentPage: Int {
    didSet {
        updateDots()
    }
}

override func awakeFromNib() {
    super.awakeFromNib()
    self.pageIndicatorTintColor = UIColor.clear
    self.currentPageIndicatorTintColor = UIColor.clear
    self.clipsToBounds = false
}

func updateDots() {
    var i = 0
    for view in self.subviews {
        var imageView = self.imageView(forSubview: view)
        if imageView == nil {
            if i == 0 {
                imageView = UIImageView(image: imageToBeReplacedByDot)
            } else {
                imageView = UIImageView(image: circleImage)
            }
            imageView!.center = view.center
            view.addSubview(imageView!)
            view.clipsToBounds = false
        }
        if i == self.currentPage {
            imageView!.alpha = 1.0
        } else {
            imageView!.alpha = 0.5
        }
        i += 1
    }
}

fileprivate func imageView(forSubview view: UIView) -> UIImageView? {
    var dot: UIImageView?
    if let dotImageView = view as? UIImageView {
        dot = dotImageView
    } else {
        for foundView in view.subviews {
            if let imageView = foundView as? UIImageView {
                dot = imageView
                break
            }
        }
    }
    return dot
}
}
</code>```

Title: Custom PageControl image - Swift

Body:
I am trying to set an image for UIPageControl dots.

I need to change the default dots, instead of that I need an image.
I used the below code

self.pageCtrl.currentPageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Selected")!)
self.pageCtrl.pageIndicatorTintColor = UIColor.init(patternImage: UIImage(named: "Page Indicator_Normal")!)

I could set the image in Pagecontrol but, it is overlapping with default dots.

Body:
This approach works for me. I create a custom pageControl class and change the images for dots to be any custom image.

In the code below I changed the image for the first dot in pageControl with any custom image.

You can change updateDots() method as per your needs.

Hope it helps!!!

override func viewDidLoad() {
    super.viewDidLoad()

    let pageControl = CustomPageControl(frame: CGRect(x: 100, y: 100, width: 104, height: 40))
    pageControl.numberOfPages = 5
    pageControl.currentPage = 0
    self.view.addSubview(pageControl)
}

class CustomPageControl: UIPageControl {

var imageToBeReplacedByDot: UIImage {
    return // Image you want to replace with dots
}
var circleImage: UIImage {

    return //Default Image
}

override var numberOfPages: Int {
    didSet {
        updateDots()
    }
}

override var currentPage: Int {
    didSet {
        updateDots()
    }
}

override func awakeFromNib() {
    super.awakeFromNib()
    self.pageIndicatorTintColor = UIColor.clear
    self.currentPageIndicatorTintColor = UIColor.clear
    self.clipsToBounds = false
}

func updateDots() {
    var i = 0
    for view in self.subviews {
        var imageView = self.imageView(forSubview: view)
        if imageView == nil {
            if i == 0 {
                imageView = UIImageView(image: imageToBeReplacedByDot)
            } else {
                imageView = UIImageView(image: circleImage)
            }
            imageView!.center = view.center
            view.addSubview(imageView!)
            view.clipsToBounds = false
        }
        if i == self.currentPage {
            imageView!.alpha = 1.0
        } else {
            imageView!.alpha = 0.5
        }
        i += 1
    }
}

fileprivate func imageView(forSubview view: UIView) -> UIImageView? {
    var dot: UIImageView?
    if let dotImageView = view as? UIImageView {
        dot = dotImageView
    } else {
        for foundView in view.subviews {
            if let imageView = foundView as? UIImageView {
                dot = imageView
                break
            }
        }
    }
    return dot
}
}


问:
python print matched string, another string at nth line again starting the loop for finding string
i have just started to learn python programming.
below is output file.

```<code>SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2
</code>```

I am reading line by line. firstly it will search for "Server*" and print

Then within SERVER another loop will start to search for another string text3 and print and Loop breaks.

then again 1st loop will search for another word matched SERVER*and so on.

i require the output as :

```<code>SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3
</code>```

below is the code which i have prepared

```<code>import re
f = open('dsp.txt', 'r')
for i, line in enumerate(f.readlines()):
    line=line.rstrip('\n')
    line=line.strip()
    print(i, line)
    if line.startswith("SERVER"):
        while i > 0:
            i=i+1
            print i
            if "text3" in line: # here i am not able to increment line.
                x= line[i]
                print ("%d" % line + /n + x)
                break
</code>```

答:
You don't need two for loops for this. You just need to change the search term when one is found. Something like this:

```<code>look = 'SERVER'
tooglelook = lambda x: 'SERVER' if x == 'text3' else 'text3'
for i, line in enumerate(f.readlines()):
    if look in line:
        print line
        look = tooglelook(look)
</code>```

for your given sample input:

```<code>SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2
</code>```

produces this output

```<code>SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3
</code>```

Body:
i have just started to learn python programming.
below is output file.

SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2

I am reading line by line. firstly it will search for "Server*" and print

Then within SERVER another loop will start to search for another string text3 and print and Loop breaks.

then again 1st loop will search for another word matched SERVER*and so on.

i require the output as :

SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3

below is the code which i have prepared

import re
f = open('dsp.txt', 'r')
for i, line in enumerate(f.readlines()):
    line=line.rstrip('\n')
    line=line.strip()
    print(i, line)
    if line.startswith("SERVER"):
        while i > 0:
            i=i+1
            print i
            if "text3" in line: # here i am not able to increment line.
                x= line[i]
                print ("%d" % line + /n + x)
                break

Body:
You don't need two for loops for this. You just need to change the search term when one is found. Something like this:

look = 'SERVER'
tooglelook = lambda x: 'SERVER' if x == 'text3' else 'text3'
for i, line in enumerate(f.readlines()):
    if look in line:
        print line
        look = tooglelook(look)

for your given sample input:

SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2

produces this output

SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3


问:
Upload file to google drive using REST API in Node.js
I am trying to upload a file to google drive using rest API(insert) in node.js, I have access_token and refresh_token. how can I upload without any sdk.</p>

答: Check this out Node.js QuickStart for Google Drive</p>


答:
In case of the structure declaration shown here, the member variables you are interested in are pointer-to-some-type.

For any given environment, a pointer (to type) holds a defined size. While allocating memory for a variable of the type, compiler need not know the actual size for the type, it just needs to know the size required for a pointer to that type and it knows that.

Title: When declaring variable is not completed, why compiler know its size?


答: Compiler does not allocate enough space for a Node structure, inside a Node structure. Though it does know how much a pointer needs, and allocates enough space for two pointers and in integer.


问:
unexpected token:where when using spring data jpa with hibernate
I am trying to use spring data jpa and hibernate in my project. I added the annotation @Query in repository, trying to write a hql with a Pageable argument passed in like this:

@Query("select name,code,id from Region where fatherId is NULL or fatherId=''")
Page<Region> findAllRoots(Pageable pageable);

but when I tried to compile and run it, I got unexpected token: where printed on console. Full info is:

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: where near line 1, column 14 [select count(where) from com.nitccs.demo.entity.Region where fatherId is NULL or fatherId='']

How could it ran like this? I am totally confused. Why it is not select count(id) or something? I am sure I got no variable named where in my pojo.

答:
You need an alias in your query in order for the count query necessary for Pageable results getting created correctly. So this should work.

```<code>select r from Region r where r.fatherId is NULL or r.fatherId=''
</code>```

Body:
You need an alias in your query in order for the count query necessary for Pageable results getting created correctly. So this should work.

select r from Region r where r.fatherId is NULL or r.fatherId=''


问:
Trying to remove a RecycleView item(Loaded from webservices) by swiping left or right
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

```<code>    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}
</code>```

and my Adapter class is

MyRecyclerAdapter.java

```<code>    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}
</code>```

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

```<code>        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());
</code>```

答:
Please change below code in onSwiped method.</p>

```<code>@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
     adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
     list.remove(position);
     adapter.notifyDataSetChanged();
}
</code>```

Body:
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}

and my Adapter class is

MyRecyclerAdapter.java

    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());

Body:
Please change below code in onSwiped method.

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
     adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
     list.remove(position);
     adapter.notifyDataSetChanged();
}


问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
The datetime module has most of what you need:

datetime is a class that represents a moment in time, like 1970-01-01 17:03:22 UTC.

datetime.strptime() can be used to create a datetime from a string.

The overloaded - operator on datetime objects gives you a timedelta, which has a total_seconds() method to convert it to seconds.

Note that the time class is closer to what you actually want to represent (a time of day, without the date part), but you cannot subtract two time objects.

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?


问:
Live streaming from Android app to Facebook
Is it possible to stream video from Android app to Face book live?

I would like to publish a live video from my application to face book using my device camera.Is that possible? If it is possible, where should I start with?

答: Yes it is possible, I haven't tried this before but there is a Facebook Live Api available you can check with that for more detail.</p>


问:
How to iterate over a file with huge no of lines to find a string?
Python:

I have a particular word which Iam looking in a text file of large size which is in millions of records.

So actually i wanted to search if a particular string is availabe in the file.

One way i did is :

```<code>with open('ip.log', 'r') as f:
     for line in f:
         if semething in line:
            break
     else:
         print 'Not found'
</code>```

But for small files this process will be fine,but when file size increases or records grow to tens of millions.Loading that big file into memory may not be a feasible solution.

Is there any better way to deal with this problem?

Observations:

If file is so huge of 1GB or something, it will slow up the system

Looking for one text we need to iterate over millions of records each time.

答:
Use the any function. It will stop on the first match, and won't load the whole file into memory. It is pretty efficient.

```<code>with open('ip.log', 'r') as f:
    if any(line for line in f if something in line):
        break
    else:
        print 'Not found'
</code>```

Body:
Python:

I have a particular word which Iam looking in a text file of large size which is in millions of records.

So actually i wanted to search if a particular string is availabe in the file.

One way i did is :

with open('ip.log', 'r') as f:
     for line in f:
         if semething in line:
            break
     else:
         print 'Not found'

But for small files this process will be fine,but when file size increases or records grow to tens of millions.Loading that big file into memory may not be a feasible solution.

Is there any better way to deal with this problem?

Observations:

If file is so huge of 1GB or something, it will slow up the system

Looking for one text we need to iterate over millions of records each time.

Body:
Use the any function. It will stop on the first match, and won't load the whole file into memory. It is pretty efficient.

with open('ip.log', 'r') as f:
    if any(line for line in f if something in line):
        break
    else:
        print 'Not found'


问:
Laravel store session to redis
I want to store the session to redis in Laravel.

I was do :
- Change the session driver into 'redis'
- Set my redis server
- and then use this code to store $req->session()->put($email, json_encode($user));

The code was run successfully. And it was store to redis.
But, I just simply add the code to 1 function.

Why the other function like example testing()/check(), also setex to redis? I don't even put the code into that function.

答:
You can just set the session driver to redis (in your .env file) and use

```<code>session(['key', $val]);
</code>```

to store session values

and

```<code>session('key');
</code>```

to retrieve them

Title: Laravel store session to redis

Body:
You can just set the session driver to redis (in your .env file) and use

session(['key', $val]);

to store session values

and

session('key');

to retrieve them


问:
Split the overlapping time in SQL
I have a requirement to equally split the duration for records which has overlapping in the datetime.

Example:

As per the example, if I calculate total runtime of the machine for Order 1, it is 3 hours. But I want it to be 2 hours because in the same machine another order ran between that duration (From 9 AM to 11 AM).

I tried searching the form, and all are pointed to exclude the overlapping duration or doing some other functionality. But I want to split the overlapping duration for all the records.

Sample Table Structure:

```<code>declare @st datetime, @et datetime;

DECLARE @table TABLE (Machine varchar(4),OrderId varchar(6),StartTime DateTime2, EndTime DateTime2)

INSERT INTO @table SELECT 'M2','ORD1','2017-11-01 10:30:00.000', '2017-11-01 12:00:00.000'
INSERT INTO @table SELECT 'M2','ORD2','2017-11-01 11:00:00.000', '2017-11-01 12:30:00.000'
INSERT INTO @table SELECT 'M2','ORD3','2017-11-01 11:30:00.000', '2017-11-01 13:00:00.000'
</code>```

Expected Result:
Expected Result

Based on the above picture,

Duration for ORD1 = 30 MIN + 15 MIN (30 MIN overlap between ORD1 and ORD2) + 10 MIN (30 MIN overlap between ORD1, ORD2 and  ORD3)

Duration for ORD2 = 15 MIN + 10 MIN + 15 MIN

Duration for ORD3 = 10 MIN + 15 MIN + 30 MIN

Total Machine Run time will be 55 + 40 + 55 = 150 MIN (2 Hours and 30 MIN)

Thanks,
Aravinth

答:
You should be able to use "window functions" to determine the overall span then divide by number of orders processed, along these lines:

```<code>select
  machine, order, datetime_start, datetime_end
, min(datetime_start) over(partition by machine, order, date(datetime_start)) min_dt
, max(datetime_start) over(partition by machine, order, date(datetime_start)) max_dt
, count(*) over(partition by machine, order, date(datetime_start)) num

, datediff(ss,min(datetime_start) over(partition by machine, order, date(datetime_start))
             ,max(datetime_start) over(partition by machine, order, date(datetime_start)))
  / count(*) over(partition by machine, order) as equal_duration
from (
    select * from your_query here
     )
</code>```

For more; we would need much more detail from you.

Title: Split the overlapping time in SQL

Body:
I have a requirement to equally split the duration for records which has overlapping in the datetime.

Example:

As per the example, if I calculate total runtime of the machine for Order 1, it is 3 hours. But I want it to be 2 hours because in the same machine another order ran between that duration (From 9 AM to 11 AM).

I tried searching the form, and all are pointed to exclude the overlapping duration or doing some other functionality. But I want to split the overlapping duration for all the records.

Sample Table Structure:

declare @st datetime, @et datetime;

DECLARE @table TABLE (Machine varchar(4),OrderId varchar(6),StartTime DateTime2, EndTime DateTime2)

INSERT INTO @table SELECT 'M2','ORD1','2017-11-01 10:30:00.000', '2017-11-01 12:00:00.000'
INSERT INTO @table SELECT 'M2','ORD2','2017-11-01 11:00:00.000', '2017-11-01 12:30:00.000'
INSERT INTO @table SELECT 'M2','ORD3','2017-11-01 11:30:00.000', '2017-11-01 13:00:00.000'

Expected Result:
Expected Result

Based on the above picture,

Duration for ORD1 = 30 MIN + 15 MIN (30 MIN overlap between ORD1 and ORD2) + 10 MIN (30 MIN overlap between ORD1, ORD2 and  ORD3)

Duration for ORD2 = 15 MIN + 10 MIN + 15 MIN

Duration for ORD3 = 10 MIN + 15 MIN + 30 MIN

Total Machine Run time will be 55 + 40 + 55 = 150 MIN (2 Hours and 30 MIN)

Thanks,
Aravinth

Body:
You should be able to use "window functions" to determine the overall span then divide by number of orders processed, along these lines:

select
  machine, order, datetime_start, datetime_end
, min(datetime_start) over(partition by machine, order, date(datetime_start)) min_dt
, max(datetime_start) over(partition by machine, order, date(datetime_start)) max_dt
, count(*) over(partition by machine, order, date(datetime_start)) num

, datediff(ss,min(datetime_start) over(partition by machine, order, date(datetime_start))
             ,max(datetime_start) over(partition by machine, order, date(datetime_start)))
  / count(*) over(partition by machine, order) as equal_duration
from (
    select * from your_query here
     )

For more; we would need much more detail from you.


问:
html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."
My webapp have javascript errors in ios safari private browsing:

JavaScript:error

undefined

QUOTA_EXCEEDED_ERR:DOM Exception 22:An attempt was made to add something to storage...

my code:

```<code>localStorage.setItem('test',1)
</code>```

答:
I just created this repo to provide sessionStorage and localStorage features for unsupported or disabled browsers.

Supported browsers

IE5+

Chrome all versions

Mozilla all versions

Yandex all versions

How it works

It detects the feature with the storage type.

```<code>function(type) {
    var testKey = '__isSupported',
        storage = window[type];
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
};
</code>```

Sets StorageService.localStorage to window.localStorage if it is supported or creates a cookie storage.
Sets StorageService.sessionStorage to window.sessionStorage if it is supported or creates a in memory storage for SPA, cookie storage with sesion features for non SPA.

Body:
My webapp have javascript errors in ios safari private browsing:

JavaScript:error

undefined

QUOTA_EXCEEDED_ERR:DOM Exception 22:An attempt was made to add something to storage...

my code:

localStorage.setItem('test',1)

Body:
I just created this repo to provide sessionStorage and localStorage features for unsupported or disabled browsers.

Supported browsers

IE5+

Chrome all versions

Mozilla all versions

Yandex all versions

How it works

It detects the feature with the storage type.

function(type) {
    var testKey = '__isSupported',
        storage = window[type];
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
};

Sets StorageService.localStorage to window.localStorage if it is supported or creates a cookie storage.
Sets StorageService.sessionStorage to window.sessionStorage if it is supported or creates a in memory storage for SPA, cookie storage with sesion features for non SPA.


问:
How to select rows from db where the given date range falls?
The table structure:

```<code>ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0
</code>```

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

```<code>SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)
</code>```

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

答:
Solution for oracle:

```<code>SELECT * FROM SHIFTS
WHERE FFROMDATE<=20170614 AND (FTODATE>=20170528 OR NVL(FTODATE,0)=0)
</code>```

For SQL server:

Instead of NVL you can use ISNULL or CASE. I didn't try on sql server because I don't have it.

Body:
The table structure:

ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

Body:
Solution for oracle:

SELECT * FROM SHIFTS
WHERE FFROMDATE<=20170614 AND (FTODATE>=20170528 OR NVL(FTODATE,0)=0)

For SQL server:

Instead of NVL you can use ISNULL or CASE. I didn't try on sql server because I don't have it.


问:
Gradle build of Android app in VSTS failing after running out of memory
I have a gradle build in VSTS that is building an Android app and it's failing with the below error. Does the build machine really have to little memory or should I change some settings in gradle.properties, e.g. the org.gradle.jvmargs settings?

```<code>:app:transformDexArchiveWithExternalLibsDexMergerForDebug
Expiring Daemon because JVM Tenured space is exhausted
Problem in daemon expiration check
org.gradle.internal.event.ListenerNotificationException: Failed to notify daemon expiration listener.
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:341)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast.dispatch(DefaultListenerManager.java:152)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast.dispatch(DefaultListenerManager.java:126)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy3.onExpirationEvent(Unknown Source)
    at org.gradle.launcher.daemon.server.Daemon$DaemonExpirationPeriodicCheck.run(Daemon.java:271)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.lang.ClassLoader.findLoadedClass0(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:1038)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:406)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.gradle.launcher.daemon.server.DaemonRegistryUpdater.onExpire(DaemonRegistryUpdater.java:86)
    at org.gradle.launcher.daemon.server.Daemon$DefaultDaemonExpirationListener.onExpirationEvent(Daemon.java:303)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:371)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:353)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    ... 16 more
Expiring Daemon because JVM Tenured space is exhausted
Daemon will be stopped at the end of the build after running out of JVM memory
:app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> GC overhead limit exceeded
</code>```

答: After specifying parameter org.gradle.jvmargs=-Xmx2048M -XX\:MaxHeapSize\=32g in file gradle.properties the build started working.

Body:
I have a gradle build in VSTS that is building an Android app and it's failing with the below error. Does the build machine really have to little memory or should I change some settings in gradle.properties, e.g. the org.gradle.jvmargs settings?

:app:transformDexArchiveWithExternalLibsDexMergerForDebug
Expiring Daemon because JVM Tenured space is exhausted
Problem in daemon expiration check
org.gradle.internal.event.ListenerNotificationException: Failed to notify daemon expiration listener.
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:341)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast.dispatch(DefaultListenerManager.java:152)
    at org.gradle.internal.event.DefaultListenerManager$EventBroadcast.dispatch(DefaultListenerManager.java:126)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy3.onExpirationEvent(Unknown Source)
    at org.gradle.launcher.daemon.server.Daemon$DaemonExpirationPeriodicCheck.run(Daemon.java:271)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.lang.ClassLoader.findLoadedClass0(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:1038)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:406)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:411)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.gradle.launcher.daemon.server.DaemonRegistryUpdater.onExpire(DaemonRegistryUpdater.java:86)
    at org.gradle.launcher.daemon.server.Daemon$DefaultDaemonExpirationListener.onExpirationEvent(Daemon.java:303)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:371)
    at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:353)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
    ... 16 more
Expiring Daemon because JVM Tenured space is exhausted
Daemon will be stopped at the end of the build after running out of JVM memory
:app:transformDexArchiveWithExternalLibsDexMergerForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> GC overhead limit exceeded


问:
textarea keyup event for submit
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

```<code><textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

<script type="text/javascript">
function enter_comment(postid,userpostedid) {
       if (event.which == 13) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else
       {
           return;
       }
}
</script>
</code>```

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

答:
You can check if the shift key was pressed or not through event.shiftKey property. So your event handler could be modified to:

```<code>function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else if (event.which == 13 && event.shiftKey)
       {
            // Create the new line.
       }
       else
       {
           return;
       }
}
</code>```

Title: textarea keyup event for submit

Body:
Here in my code I am having a textarea, where after user typed anything and press enter then some code need to be executed, but if the user press shift+enter then a new line should come in the textarea only. Below is my code so far --

<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>

Now, when I am pressing enter, it's working fine, but if I press shift+enter, then also it is doing the same. I want to prevent this, kindly help.

Body:
You can check if the shift key was pressed or not through event.shiftKey property. So your event handler could be modified to:

function enter_comment(postid,userpostedid) {
       if (event.which == 13 && !event.shiftKey) {
           document.getElementById('commentarea'+postid).value='';
           //insert_comment(id); // Call any function here: Just pass your actual Parameters to enter_comment().
       }
       else if (event.which == 13 && event.shiftKey)
       {
            // Create the new line.
       }
       else
       {
           return;
       }
}


问:
Is there a way to identify unused or stale FxCop message suppressions?
We use FxCop's global suppressions to suppress rule violations found in old code.  By old code I mean code that was written sometimes years before we turned on code analysis.  We fix violations in new code.  We cannot fix the violations in the old code all at once so we use suppressions.

Over time our global suppression files have become bloated.  Often when a signature has changed on an old method the prior suppression becomes invalid because it no longer matches up with the code.  We created new suppressions to ignore the old violation but often the old SuppressMessage attributes were left behind.

Does anybody know how to identify these SupressMessage declarations that do not match up with code?  For that matter does anybody know how to identify SuppressMessage attributes that are invalid because there is no violation to supress?

I am thinking there may be a compiler or FxCopCmd warning or log message that might identify unused suppressions.  If not that does anybody know of a script or VS extension that does it?

Thanks.

答:
You can use the stand-alone FxCop UI application for this.  Add the "Seen Last Run" column to the "Excluded In Source" results tab.  After analysis, this column will show a false value for any in-source suppressions for which a corresponding violation was not found during the analysis run.  In order to maximize the reliability of the results, you should ensure that you are using the same set of rule assemblies for the analysis that you use when running the analysis from Visual Studio.

BTW, if you would like to be able to break your build when "stale" suppressions are found, you might want to consider voting at https://connect.microsoft.com/visualstudio/feedback/details/277253/add-mechanism-for-detecting-unnecessary-suppressmessageattribute-instances.


问:
Scanner and validating answers like a dictionary in Java
I just wanted to practice my java so I made sort of a dictionary.

But I can't get my code to work on the console. Like it doesn't give me any error, it's just that my console in eclipse won't pop up and when I remove the scanner parts it will pop up. Any help is appreciated! Code:

```<code>public static void main(String[] args) {
    HeleLijst lijst = new HeleLijst();

    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    System.out.println("Geef een afkorting op: ");
    lijst.all();

    if (lijst.betekenislist.containsKey(input)) {
        System.out.println("De betekenis van " + input + " is: " + lijst.betekenislist.get(input));
    } else {
        System.out.println("Geen correcte afkorting!");
    }

    sc.close();

}
</code>```

答: The console is waiting for your input... You probably should have printed some kind of message signifying what the input is for</p>

Body:
I just wanted to practice my java so I made sort of a dictionary.

But I can't get my code to work on the console. Like it doesn't give me any error, it's just that my console in eclipse won't pop up and when I remove the scanner parts it will pop up. Any help is appreciated! Code:

public static void main(String[] args) {
    HeleLijst lijst = new HeleLijst();

    Scanner sc = new Scanner(System.in);
    String input = sc.nextLine();

    System.out.println("Geef een afkorting op: ");
    lijst.all();

    if (lijst.betekenislist.containsKey(input)) {
        System.out.println("De betekenis van " + input + " is: " + lijst.betekenislist.get(input));
    } else {
        System.out.println("Geen correcte afkorting!");
    }

    sc.close();

}


问:
Publishing an internal NuGet Package with Automatic Versioning best practice
So we are experimenting with automating our build processes and NuGet publishing for some of our internal dlls and trying to figure out what would be best practice for the VSTS Automatic versioning.

I've been reading this article (Versioning Nuget Packages CD) which talks about the SemVar for automatic versioning which is fine but I'm wondering if there is a way we can automate the versioning down to just a Major.Minor.Patch schema. My gut tells me this isn't reasonable, I mean how could the process know whether you are publishing a Major, Minor, or Patch but maybe there isn't something I am thinking of.

Either way, any tips on best practice for versioning would be great. I'm thinking there has to be a way at the very least for us to just edit the Assembly Info before we commit to master and trigger the Build process to then package it all up and acquire that new version. Thanks in advance.

答:
Publishing nuget package version authomcatically and increase major/minor/patch correspondingly, two suggested way is using GitFlow branching module with GitVersion and calculating the updated version manually.

Option 1: using GitFlow branching module with Gitversion

If you manage manging your source code in git repo, you can use GitFlow as the branching module. Then you can use GitVersion task in your build/release definition, it will provider the increment version.

More details, you can refer Versioning NuGet packages in a continuous delivery world: part 3.

Option 2: calculate the updated version manually

You can define how to update major, minor and patch as the way you need to update. You can achieve it by adding a PowerShell task:

Add a variable (such as version) in Variables Tab -> Get current version -> set the variable version with the value of the current version -> define the way how to update the version (such as changed file A for the build commit/changeset, then update minor) -> update variable version's value with the updated version.

In the Nuget pack step, specify the package version for the variable version's value. Then publish the package.

More details, you can refer Better selection of version numbers in the article Versioning NuGet packages in a continuous delivery world: part 2.


问:
Prevent TFS from deleting Node Modules on a build/release
I've an on-premise TFS server where I am trying to speed up the CI/CD of an Angular application.  The longest part of the release process is the npm install, and the entire drop folder gets removed on each trigger (or environment release).  Ideally, I'd like the node_modules folder not be removed so the npm install just has to retrieve new packages.

I'm not able to take screenshots of the settings, so I'll do my best to describe them.

Build:

Copy Files (Contents: ***, .angular-cli.json)

Publish Artifact (path to publish $(build.artifactstagingdirectory))

Release:

npm install (working folder $(System.DefaultWorkingDirectory/app-name/drop/projectartifiacts)

ng build (not important)

Upload (not important)

I've tried to set Clean = false, Clean Options = sources on the Build.  However, this does not seem to help.  And each time an environment is built, it still destroys the previous drop.

Any ideas on how to have the drop folder preserver the node_modules folder?

Thanks for your time.

答:
There isn't a way to keep part of the sources when cleaning the repo.

And to speed up the CI/CD, you should not enable the Clean option.

In general, for faster performance by your private agents, don't clean
  the repo. In this case to get the most performance advantage, make
  sure you are also building incrementally.

Source link : Clean the local repo on the agent

However, you can check in the node_modules folder to source control if that's an option.Thus, it will be retrieved in the Get source step. Also disable the clean option for both Repositoy and Build setp.

Reference this article: checking in node_modules