问:
using php xmlreader to get data from xml to mysql
I am using php and xmlreader to retreive data from an xml file and insert into a mysql table.  I chose xmlreader because the files supplied me are 500mb.  I am new to all of this and am at a sticking point getting the data to insert properly into the mysql table.

Sample xml from file...

```<code><us:ItemMaster>
  <us:ItemMasterHeader>
    <oa:ItemID agencyRole="Prefix_Number" >
      <oa:ID>CTY</oa:ID>
    </oa:ItemID>
    <oa:ItemID agencyRole="Stock_Number_Butted" >
      <oa:ID>TN2100</oa:ID>
    </oa:ItemID>
    <oa:Specification>
      <oa:Property sequence="3" >
        <oa:NameValue name="Color(s)" >Black</oa:NameValue>
      </oa:Property>
      <oa:Property sequence="22" >
        <oa:NameValue name="Coverage Percent " >5.00 %</oa:NameValue>
      </oa:Property>
    </oa:Specification>
  </us:ItemMasterHeader>
</us:ItemMaster>
</code>```

I am reading the xml file using xmlreader and utilizing expand() to SimpleXML for flexibility in getting the particulars.  I could not figure out how to do what I wanted using strictly xmlreader.

I want each record of the mysql table to reflect prefix, stockNumber, attributePriority, AttributeName and AttributeValue.

Here's my code so far...

```<code><?php
$reader = XMLReader::open($file);

while ($reader->read())  {
  if ($reader->nodeType == XMLREADER::ELEMENT &&
     $reader->localName == 'ItemMasterHeader' )  {
    $node = $reader->expand();
    $dom = new DomDocument();
    $n = $dom->importNode($node,true);
    $dom->appendChild($n);
    $sxe = simplexml_import_dom($n);

    foreach ($sxe->xpath("//oa:Property[@sequence]") as $Property) {
      $AttributePriority = $Property[@sequence];
      echo "(" . $AttributePriority . ") ";

      $Prefix = $sxe->xpath("//oa:ItemID[@agencyRole = 'Prefix_Number']/oa:ID");
      foreach ($Prefix as $Prefix)  {
        echo $Prefix;
      }

      $StockNumber = $sxe->xpath("//oa:ItemID[@agencyRole        ='Stock_Number_Butted']/oa:ID");
          foreach ($StockNumber as $StockNumber)  {
        echo $StockNumber;
      }
   }
   foreach ($sxe->xpath("//oa:NameValue[@name]") as $NameValue)  {
     $AttributeName = $NameValue[@name];
     echo $AttributeName . " ";
   }
   foreach ($sxe->xpath("//oa:NameValue[@name]") as $NameValue)  {
     $AttributeValue = $NameValue;
     echo $AttributeValue . "<br/>";
   }

// mysql insert
mysql_query("INSERT INTO $table  (Prefix,StockNumber,AttributePriority,AttributeName,AttributeValue)
VALUES('$Prefix','$StockNumber','$AttributePriority','$AttributeName','$AttributeValue')");
}
  if($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'ItemMaster')  {
    // visual seperator between products
    echo "<hr style = 'color:red;'>";
   }
}
?>
</code>```

答:
I am no expert in XML manipulation in PHP but I doubt your code using DOM and simpleXML both with xmlReader. So, I thought to check what I can suggest to you. I got this code and this looks straight to me. I suggest you concentrate on this for betterment. The is using DOM after XMLReader and after that it is using DOM's XPath as you are also doing.

```<code><?php

// Parsing a large document with XMLReader with Expand - DOM/DOMXpath
$reader = new XMLReader();

$reader->open("tooBig.xml");

while ($reader->read()) {
    switch ($reader->nodeType) {
        case (XMLREADER::ELEMENT):
        if ($reader->localName == "entry") {
            if ($reader->getAttribute("ID") == 5225) {
                $node = $reader->expand();
                $dom = new DomDocument();
                $n = $dom->importNode($node,true);
                $dom->appendChild($n);
                $xp = new DomXpath($dom);
                $res = $xp->query("/entry/title");
                echo $res->item(0)->nodeValue;
            }
        }
    }
}

?>
</code>```

For more.

Body:
I am using php and xmlreader to retreive data from an xml file and insert into a mysql table.  I chose xmlreader because the files supplied me are 500mb.  I am new to all of this and am at a sticking point getting the data to insert properly into the mysql table.

Sample xml from file...

<us:ItemMaster>
  <us:ItemMasterHeader>
    <oa:ItemID agencyRole="Prefix_Number" >
      <oa:ID>CTY</oa:ID>
    </oa:ItemID>
    <oa:ItemID agencyRole="Stock_Number_Butted" >
      <oa:ID>TN2100</oa:ID>
    </oa:ItemID>
    <oa:Specification>
      <oa:Property sequence="3" >
        <oa:NameValue name="Color(s)" >Black</oa:NameValue>
      </oa:Property>
      <oa:Property sequence="22" >
        <oa:NameValue name="Coverage Percent " >5.00 %</oa:NameValue>
      </oa:Property>
    </oa:Specification>
  </us:ItemMasterHeader>
</us:ItemMaster>

I am reading the xml file using xmlreader and utilizing expand() to SimpleXML for flexibility in getting the particulars.  I could not figure out how to do what I wanted using strictly xmlreader.

I want each record of the mysql table to reflect prefix, stockNumber, attributePriority, AttributeName and AttributeValue.

Here's my code so far...

<?php
$reader = XMLReader::open($file);

while ($reader->read())  {
  if ($reader->nodeType == XMLREADER::ELEMENT &&
     $reader->localName == 'ItemMasterHeader' )  {
    $node = $reader->expand();
    $dom = new DomDocument();
    $n = $dom->importNode($node,true);
    $dom->appendChild($n);
    $sxe = simplexml_import_dom($n);

    foreach ($sxe->xpath("//oa:Property[@sequence]") as $Property) {
      $AttributePriority = $Property[@sequence];
      echo "(" . $AttributePriority . ") ";

      $Prefix = $sxe->xpath("//oa:ItemID[@agencyRole = 'Prefix_Number']/oa:ID");
      foreach ($Prefix as $Prefix)  {
        echo $Prefix;
      }

      $StockNumber = $sxe->xpath("//oa:ItemID[@agencyRole        ='Stock_Number_Butted']/oa:ID");
          foreach ($StockNumber as $StockNumber)  {
        echo $StockNumber;
      }
   }
   foreach ($sxe->xpath("//oa:NameValue[@name]") as $NameValue)  {
     $AttributeName = $NameValue[@name];
     echo $AttributeName . " ";
   }
   foreach ($sxe->xpath("//oa:NameValue[@name]") as $NameValue)  {
     $AttributeValue = $NameValue;
     echo $AttributeValue . "
";
   }

// mysql insert
mysql_query("INSERT INTO $table  (Prefix,StockNumber,AttributePriority,AttributeName,AttributeValue)
VALUES('$Prefix','$StockNumber','$AttributePriority','$AttributeName','$AttributeValue')");
}
  if($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'ItemMaster')  {
    // visual seperator between products
    echo "
";
   }
}
?>

Body:
I am no expert in XML manipulation in PHP but I doubt your code using DOM and simpleXML both with xmlReader. So, I thought to check what I can suggest to you. I got this code and this looks straight to me. I suggest you concentrate on this for betterment. The is using DOM after XMLReader and after that it is using DOM's XPath as you are also doing.

<?php

// Parsing a large document with XMLReader with Expand - DOM/DOMXpath
$reader = new XMLReader();

$reader->open("tooBig.xml");

while ($reader->read()) {
    switch ($reader->nodeType) {
        case (XMLREADER::ELEMENT):
        if ($reader->localName == "entry") {
            if ($reader->getAttribute("ID") == 5225) {
                $node = $reader->expand();
                $dom = new DomDocument();
                $n = $dom->importNode($node,true);
                $dom->appendChild($n);
                $xp = new DomXpath($dom);
                $res = $xp->query("/entry/title");
                echo $res->item(0)->nodeValue;
            }
        }
    }
}

?>

For more.


来源: stackexchange

问:
Is it best-practice to commit the `vendor` directory?
I am using dep to handle my Go dependencies. Is it best practice to also commit the vendor directory into version control? Or is best practice to always execute dep ensure after checking out a repository?

答:
The dep tool's FAQ answers this:

Should I commit my vendor directory?

It's up to you:

Pros

It's the only way to get truly reproducible builds, as it guards
against upstream renames, deletes and commit history overwrites.

You don't need an extra dep ensure step to sync vendor/ with
Gopkg.lock after most operations, such as go get, cloning, getting
latest, merging, etc.

Cons

Your repo will be bigger, potentially a lot bigger, though prune can help minimize this problem.

PR diffs will include changes for files under vendor/ when Gopkg.lock is modified, however files in vendor/ are hidden by default on GitHub.

ContentLicense: CC BY-SA 4.0


问:
How to access a class property with rtti?
Is it possible to get a class property with a rtti? What's wrong with the code below?

```<code>...
type
  TTest = class
  private
    class function GetCP: string; static;
  public
    class property CP: string read GetCP;
  end;

class function TTest.GetCP: string;
begin
  Result := 'ABC';
end;
...
procedure TForm1.Button5Click(Sender: TObject);
var
  oTest: TTest;
  oType: TRttiType;
begin
  oTest := TTest.Create;
  try
    oType := TRttiContext.Create.GetType(oTest.ClassType);
    ShowMessage(Length(oType.GetProperties).ToString);  // oType.GetProperties = nil !!!
  finally
    oTest.Free;
  end;
end;
</code>```

TIA and best regards,
Branko

答: Class properties cannot be accessed via RTTI.</p>

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to get a class property with a rtti? What's wrong with the code below?

...
type
  TTest = class
  private
    class function GetCP: string; static;
  public
    class property CP: string read GetCP;
  end;

class function TTest.GetCP: string;
begin
  Result := 'ABC';
end;
...
procedure TForm1.Button5Click(Sender: TObject);
var
  oTest: TTest;
  oType: TRttiType;
begin
  oTest := TTest.Create;
  try
    oType := TRttiContext.Create.GetType(oTest.ClassType);
    ShowMessage(Length(oType.GetProperties).ToString);  // oType.GetProperties = nil !!!
  finally
    oTest.Free;
  end;
end;

TIA and best regards,
Branko


问:
is it possible for `ConcurrentHashMap` to hang?
First I'll summarize what I've found so far.

This answer suggests that changing the concurrencyLevel parameter of ConcurrentHashMap's constructor might help. I've tried that and my code still hanged.

Answers here suggest that it could be a runtime bug.

What I'm trying to do:

I have 10 worker threads running along with a main thread. The worker threads will have to process many arrays to find the index of the max element in the array (if there are multiple max values, the first occurrence will be used). Among these "many arrays," some of them can be duplicate, so I'm trying to avoid those full array scans to speed up the program.

The controller class contains a ConcurrentHashMap that maps the hash values of arrays to the corresponding max-element indices.

The worker threads will ask the controller class for the mapped index first before trying to calculate the index by doing full array scans. In the latter case, the newly calculated index will be put into the map.

The main thread does not access the hash map.

What happened:

My code will hang after 70,000 ~ 130,000 calls to getMaxIndex(). This count is obtained by putting a log string into getMaxIndex() so it might not be exactly accurate.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

If the code does not use map it works just fine (see getMaxIndex() version 2 below).

I've tried to add synchronized to getMaxIndex()'s signature and use the regular HashMap instead, that also did not work.

I've tried to use different initialCapacity values too (e.g. 50,000 & 100,000). Did not work.

Here's my code:

```<code>// in the controller class
int getMaxIndex(@NotNull double[] arr) {
    int hash = Arrays.hashCode(arr);

    if(maxIndices.containsKey(hash)) {
        return maxIndices.get(hash);
    } else {
        int maxIndex =
            IntStream.range(0, arr.length)
                .reduce((a, b) -> arr[a] < arr[b] ? b : a)
                .orElse(-1); // -1 to let program crash

        maxIndices.put(hash, maxIndex);
        return maxIndex;
    }
}
</code>```

The worker thread will call getMaxIndex() like this: return remaining[controller.getMaxIndex(arr)];, remaining is just another int array.

getMaxIndex() v2:

```<code>int getMaxIndex(@NotNull double[] arr) {
    return IntStream.range(0, arr.length)
        .reduce((a, b) -> arr[a] < arr[b] ? b : a)
        .orElse(-1); // -1 to let program crash
}
</code>```

JVM info in case it matters:

```<code>java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
</code>```

EDIT: stack dump; I used Phaser to synchronize the worker threads, so some of them appear to be waiting on the phaser, but pool-1-thread-2, pool-1-thread-10, pool-1-thread-11, and pool-1-thread-12 do not appear to be waiting on the phaser.

```<code>Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode):

"Attach Listener" #23 daemon prio=9 os_prio=0 tid=0x00007f0c54001000 nid=0x4da2 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"pool-1-thread-13" #22 prio=5 os_prio=0 tid=0x00007f0c8c2cb800 nid=0x4d5e waiting on condition [0x00007f0c4eddd000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e792f40> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-12" #21 prio=5 os_prio=0 tid=0x00007f0c8c2ca000 nid=0x4d5d waiting on condition [0x00007f0c4eede000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-11" #20 prio=5 os_prio=0 tid=0x00007f0c8c2c8000 nid=0x4d5c waiting on condition [0x00007f0c4efdf000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-10" #19 prio=5 os_prio=0 tid=0x00007f0c8c2c6000 nid=0x4d5b waiting on condition [0x00007f0c4f0e0000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-9" #18 prio=5 os_prio=0 tid=0x00007f0c8c2c4800 nid=0x4d5a waiting on condition [0x00007f0c4f1e1000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e7c74f8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-8" #17 prio=5 os_prio=0 tid=0x00007f0c8c2c2800 nid=0x4d59 waiting on condition [0x00007f0c4f2e2000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e64fb78> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-7" #16 prio=5 os_prio=0 tid=0x00007f0c8c2c1000 nid=0x4d58 waiting on condition [0x00007f0c4f3e3000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e8b44c8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-6" #15 prio=5 os_prio=0 tid=0x00007f0c8c2bf800 nid=0x4d57 waiting on condition [0x00007f0c4f4e4000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e5b4500> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-5" #14 prio=5 os_prio=0 tid=0x00007f0c8c2bd800 nid=0x4d56 waiting on condition [0x00007f0c4f5e5000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e836958> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-4" #13 prio=5 os_prio=0 tid=0x00007f0c8c2bc000 nid=0x4d55 waiting on condition [0x00007f0c4f6e6000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e4f4cf0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-3" #12 prio=5 os_prio=0 tid=0x00007f0c8c2ba000 nid=0x4d54 waiting on condition [0x00007f0c4f7e7000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e40abb8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-2" #11 prio=5 os_prio=0 tid=0x00007f0c8c2b8800 nid=0x4d53 waiting on condition [0x00007f0c4f8e8000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-1" #10 prio=5 os_prio=0 tid=0x00007f0c8c2b5800 nid=0x4d52 waiting on condition [0x00007f0c4f9e9000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e486ab0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f0c8c200800 nid=0x4d50 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread2" #8 daemon prio=9 os_prio=0 tid=0x00007f0c8c1fd800 nid=0x4d4f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #7 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f8800 nid=0x4d4e waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #6 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f7800 nid=0x4d4d waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #5 daemon prio=5 os_prio=0 tid=0x00007f0c8c1fb000 nid=0x4d4c runnable [0x00007f0c781b4000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f0c8c181000 nid=0x4d49 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f0c8c14d800 nid=0x4d42 in Object.wait() [0x00007f0c78564000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f0c8c149000 nid=0x4d41 in Object.wait() [0x00007f0c78665000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00007f0c8c00c800 nid=0x4d35 waiting on condition [0x00007f0c91f77000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076dd5e268> (a java.util.concurrent.FutureTask)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
    at java.util.concurrent.FutureTask.get(FutureTask.java:191)
    at java.util.concurrent.AbstractExecutorService.invokeAll(AbstractExecutorService.java:244)
    at ConcurrentACS.loop(ConcurrentACS.java:138)
    at ConcurrentACS.compute(ConcurrentACS.java:165)
    at ConcurrentACS.main(ConcurrentACS.java:192)

"VM Thread" os_prio=0 tid=0x00007f0c8c141800 nid=0x4d3f runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f0c8c022000 nid=0x4d37 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f0c8c024000 nid=0x4d38 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f0c8c025800 nid=0x4d39 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f0c8c027800 nid=0x4d3a runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00007f0c8c205800 nid=0x4d51 waiting on condition

JNI global references: 272
</code>```

答:
The first version isn't thread safe cause your check-than-act sequence isn't atomic. Try to use this implementation:</p>

```<code>  private final Map<Integer, Integer> maxIndices = new ConcurrentHashMap<>();

  int getMaxIndex(final double[] arr) {
    // make sure the content of the arr can't be modified concurrently
    // otherwise create a copy of the array in this method
    int hash = Arrays.hashCode(arr);
    return maxIndices.computeIfAbsent(hash,
        key -> IntStream.range(0, arr.length).reduce((a, b) -> arr[a] < arr[b] ? b : a).orElse(-1));
  }
</code>```

Body:
First I'll summarize what I've found so far.

This answer suggests that changing the concurrencyLevel parameter of ConcurrentHashMap's constructor might help. I've tried that and my code still hanged.

Answers here suggest that it could be a runtime bug.

What I'm trying to do:

I have 10 worker threads running along with a main thread. The worker threads will have to process many arrays to find the index of the max element in the array (if there are multiple max values, the first occurrence will be used). Among these "many arrays," some of them can be duplicate, so I'm trying to avoid those full array scans to speed up the program.

The controller class contains a ConcurrentHashMap that maps the hash values of arrays to the corresponding max-element indices.

The worker threads will ask the controller class for the mapped index first before trying to calculate the index by doing full array scans. In the latter case, the newly calculated index will be put into the map.

The main thread does not access the hash map.

What happened:

My code will hang after 70,000 ~ 130,000 calls to getMaxIndex(). This count is obtained by putting a log string into getMaxIndex() so it might not be exactly accurate.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

If the code does not use map it works just fine (see getMaxIndex() version 2 below).

I've tried to add synchronized to getMaxIndex()'s signature and use the regular HashMap instead, that also did not work.

I've tried to use different initialCapacity values too (e.g. 50,000 & 100,000). Did not work.

Here's my code:

// in the controller class
int getMaxIndex(@NotNull double[] arr) {
    int hash = Arrays.hashCode(arr);

    if(maxIndices.containsKey(hash)) {
        return maxIndices.get(hash);
    } else {
        int maxIndex =
            IntStream.range(0, arr.length)
                .reduce((a, b) -> arr[a] < arr[b] ? b : a)
                .orElse(-1); // -1 to let program crash

        maxIndices.put(hash, maxIndex);
        return maxIndex;
    }
}

The worker thread will call getMaxIndex() like this: return remaining[controller.getMaxIndex(arr)];, remaining is just another int array.

getMaxIndex() v2:

int getMaxIndex(@NotNull double[] arr) {
    return IntStream.range(0, arr.length)
        .reduce((a, b) -> arr[a] < arr[b] ? b : a)
        .orElse(-1); // -1 to let program crash
}

JVM info in case it matters:

java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

EDIT: stack dump; I used Phaser to synchronize the worker threads, so some of them appear to be waiting on the phaser, but pool-1-thread-2, pool-1-thread-10, pool-1-thread-11, and pool-1-thread-12 do not appear to be waiting on the phaser.

Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode):

"Attach Listener" #23 daemon prio=9 os_prio=0 tid=0x00007f0c54001000 nid=0x4da2 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"pool-1-thread-13" #22 prio=5 os_prio=0 tid=0x00007f0c8c2cb800 nid=0x4d5e waiting on condition [0x00007f0c4eddd000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e792f40> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-12" #21 prio=5 os_prio=0 tid=0x00007f0c8c2ca000 nid=0x4d5d waiting on condition [0x00007f0c4eede000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-11" #20 prio=5 os_prio=0 tid=0x00007f0c8c2c8000 nid=0x4d5c waiting on condition [0x00007f0c4efdf000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-10" #19 prio=5 os_prio=0 tid=0x00007f0c8c2c6000 nid=0x4d5b waiting on condition [0x00007f0c4f0e0000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-9" #18 prio=5 os_prio=0 tid=0x00007f0c8c2c4800 nid=0x4d5a waiting on condition [0x00007f0c4f1e1000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e7c74f8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-8" #17 prio=5 os_prio=0 tid=0x00007f0c8c2c2800 nid=0x4d59 waiting on condition [0x00007f0c4f2e2000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e64fb78> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-7" #16 prio=5 os_prio=0 tid=0x00007f0c8c2c1000 nid=0x4d58 waiting on condition [0x00007f0c4f3e3000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e8b44c8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-6" #15 prio=5 os_prio=0 tid=0x00007f0c8c2bf800 nid=0x4d57 waiting on condition [0x00007f0c4f4e4000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e5b4500> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-5" #14 prio=5 os_prio=0 tid=0x00007f0c8c2bd800 nid=0x4d56 waiting on condition [0x00007f0c4f5e5000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e836958> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-4" #13 prio=5 os_prio=0 tid=0x00007f0c8c2bc000 nid=0x4d55 waiting on condition [0x00007f0c4f6e6000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e4f4cf0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-3" #12 prio=5 os_prio=0 tid=0x00007f0c8c2ba000 nid=0x4d54 waiting on condition [0x00007f0c4f7e7000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e40abb8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-2" #11 prio=5 os_prio=0 tid=0x00007f0c8c2b8800 nid=0x4d53 waiting on condition [0x00007f0c4f8e8000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-1" #10 prio=5 os_prio=0 tid=0x00007f0c8c2b5800 nid=0x4d52 waiting on condition [0x00007f0c4f9e9000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e486ab0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f0c8c200800 nid=0x4d50 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread2" #8 daemon prio=9 os_prio=0 tid=0x00007f0c8c1fd800 nid=0x4d4f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #7 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f8800 nid=0x4d4e waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #6 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f7800 nid=0x4d4d waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #5 daemon prio=5 os_prio=0 tid=0x00007f0c8c1fb000 nid=0x4d4c runnable [0x00007f0c781b4000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f0c8c181000 nid=0x4d49 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f0c8c14d800 nid=0x4d42 in Object.wait() [0x00007f0c78564000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f0c8c149000 nid=0x4d41 in Object.wait() [0x00007f0c78665000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00007f0c8c00c800 nid=0x4d35 waiting on condition [0x00007f0c91f77000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076dd5e268> (a java.util.concurrent.FutureTask)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
    at java.util.concurrent.FutureTask.get(FutureTask.java:191)
    at java.util.concurrent.AbstractExecutorService.invokeAll(AbstractExecutorService.java:244)
    at ConcurrentACS.loop(ConcurrentACS.java:138)
    at ConcurrentACS.compute(ConcurrentACS.java:165)
    at ConcurrentACS.main(ConcurrentACS.java:192)

"VM Thread" os_prio=0 tid=0x00007f0c8c141800 nid=0x4d3f runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f0c8c022000 nid=0x4d37 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f0c8c024000 nid=0x4d38 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f0c8c025800 nid=0x4d39 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f0c8c027800 nid=0x4d3a runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00007f0c8c205800 nid=0x4d51 waiting on condition

JNI global references: 272

Body:
The first version isn't thread safe cause your check-than-act sequence isn't atomic. Try to use this implementation:

  private final Map<Integer, Integer> maxIndices = new ConcurrentHashMap<>();

  int getMaxIndex(final double[] arr) {
    // make sure the content of the arr can't be modified concurrently
    // otherwise create a copy of the array in this method
    int hash = Arrays.hashCode(arr);
    return maxIndices.computeIfAbsent(hash,
        key -> IntStream.range(0, arr.length).reduce((a, b) -> arr[a] < arr[b] ? b : a).orElse(-1));
  }


问:
OData query against DTO, execute against EF
On a project I am working on, we want to use OData to query our data from the frontend.
The trouble is that the frontend ODataControllers are exposing the DTOs of the project, and it constructs the queries against the DTOs and not the entities from the EntityFramework.

The data is mapped between DTO and Entity by AutoMapper.

Is there any way to make the OData controllers map the queries so they query against EF entities and not DTOs?

答:
The AutoMapper IQueryable extension is designed to achieve this result : mapping OData queries on DTOs/POCOs to EF Queries on entities.

For example :

In some scenarios, such as OData, a generic DTO is returned through an
  IQueryable controller action. Without explicit instructions,
  AutoMapper will expand all members in the result. To control which
  members are expanded during projection, set ExplicitExpansion in the
  configuration and then pass in the members you want to explicitly
  expand

You may give it a try.


问:
How to use @Parcelize in Kotlin 1.1.60?
Kotlin 1.1.60 is recently out with the Parcelable support.

With this new feature, I created my data as:

```<code>@Parcelize
data class Question {
   val id: String,
   val title: String,
   val detail: String
} : Parcelable
</code>```

But this raise an error of This class implements Parcelable but does not provide a CREATOR field.

It seems like I still have to write tedious code to implement Parcel data, if so, what's the benefit of using @Parcelize ?

答:
I would say this feature is still experimental. What you describe is a known bug: https://youtrack.jetbrains.com/issue/KT-19300

But it should not be preventing the code from being compiled as expected (try disregarding the warning and see if your code works as expected).

Title: How to use @Parcelize in Kotlin 1.1.60?

Body:
Kotlin 1.1.60 is recently out with the Parcelable support.

With this new feature, I created my data as:

@Parcelize
data class Question {
   val id: String,
   val title: String,
   val detail: String
} : Parcelable

But this raise an error of This class implements Parcelable but does not provide a CREATOR field.

It seems like I still have to write tedious code to implement Parcel data, if so, what's the benefit of using @Parcelize ?


问:
XMPP library for iOS (iPhone/iPad)
I'm making a GTalk client for iOS and would need a XMPP library to do the heavy lifting.
Anyone know of such?</p>

答: There's a single Objective-C library (xmppframework) listed on the XMPP Standards Foundation site, although if this doesn't prove to be suitable you should be able to get the C/C++ libraries up and running with some wrangling.</p>

Title: XMPP library for iOS (iPhone/iPad)


问:
Do a count and group by weeks or months
I have an object array like this:

```<code>[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]
</code>```

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

```<code>[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]
</code>```

Month Grouping: (1st of month is start of month)

```<code>[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]
</code>```

Thank You.

答:
You could use a function for grouping with a callback for individual grouping (here for month) and take a hash table for keeping same groups.

function groupBy(array, groupFn) {
    var hash = Object.create(null),
        result = [];

    array.forEach(function (o) {
        var key = groupFn(o);
        if (!hash[key]) {
            hash[key] = { date: key, count: 0 };
            result.push(hash[key]);
        }
        hash[key].count += o.count;
    });
    return result;
}

var data = [{ date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 }],
    month = function (o) { return o.date.slice(0, 7) + '-01'; },
    week = function (o) {
        var d = new Date(o.date),
            day = 1000 * 60 * 60 * 24,
            offset = 4 * day;

        d.setTime(Math.floor((d.valueOf() - offset) / 7 / day) * 7 * day + offset);
        return d.toISOString().slice(0, 10);
    };

console.log(groupBy(data, month));
console.log(groupBy(data, week));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Do a count and group by weeks or months

Body:
I have an object array like this:

[ { date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 } ]

Using the momentJS library and pure javascript only (no lodash _groupBy etc), how can I group the results and add together the 'count' to be like this:

Week Grouping: (Monday is start of week)

[ { date: '2017-11-13', count: 104 }, { date: '2017-11-06', count: 22 }, { date: '2017-10-02', count: 66 } ]

Month Grouping: (1st of month is start of month)

[ { date: '2017-11-01', count: 26 }, { date: '2017-10-01', count: 66 } ]

Thank You.

Body:
You could use a function for grouping with a callback for individual grouping (here for month) and take a hash table for keeping same groups.

function groupBy(array, groupFn) {
    var hash = Object.create(null),
        result = [];

    array.forEach(function (o) {
        var key = groupFn(o);
        if (!hash[key]) {
            hash[key] = { date: key, count: 0 };
            result.push(hash[key]);
        }
        hash[key].count += o.count;
    });
    return result;
}

var data = [{ date: '2017-11-17', count: 2 }, { date: '2017-11-16', count: 24 }, { date: '2017-11-15', count: 42 }, { date: '2017-11-14', count: 23 }, { date: '2017-11-13', count: 33 }, { date: '2017-11-12', count: 22 }, { date: '2017-11-11', count: 11 }, { date: '2017-10-04', count: 66 }],
    month = function (o) { return o.date.slice(0, 7) + '-01'; },
    week = function (o) {
        var d = new Date(o.date),
            day = 1000 * 60 * 60 * 24,
            offset = 4 * day;

        d.setTime(Math.floor((d.valueOf() - offset) / 7 / day) * 7 * day + offset);
        return d.toISOString().slice(0, 10);
    };

console.log(groupBy(data, month));
console.log(groupBy(data, week));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
ESRI maps giving Main Thread Checker: UI API called on a background thread in iOS 11
I'm using ESRI maps in my application. When i run the application in iOS 10 there was no issue in loading the ESRI maps, zoom in and out works fine too. But when i run the same application with iOS 11 it gives me

```<code>Main Thread Checker: UI API called on a background thread: -[UIApplication
applicationState]
PID: 485, TID: 72091, Thread name: Runtime Network Callback Thread, Queue
name: com.apple.root.default-qos.overcommit, QoS: 21
Backtrace:
4   Altus Mobile                        0x00000001006f4844 -
    [AGSRequestOperation kickoffConnection] + 1108 .
5   Foundation                          0x0000000185987a50 <redacted> + 340
6   CoreFoundation                      0x0000000184f40358 <redacted> + 24
7   CoreFoundation                      0x0000000184f402d8 <redacted> + 88
8   CoreFoundation                      0x0000000184f3fb60 <redacted> + 204
9   CoreFoundation                      0x0000000184f3d738 <redacted> + 1048
10  CoreFoundation                      0x0000000184e5e2d8
    CFRunLoopRunSpecific + 436
11  Foundation                          0x00000001858866e4 <redacted> + 304
12  Altus Mobile                        0x00000001007dbf28 -
    [AGSThreadTargetImpl mainRoutine] + 292
13  Foundation                          0x0000000185987860 <redacted> + 996
14  libsystem_pthread.dylib             0x0000000184bc432c <redacted> + 308
15  libsystem_pthread.dylib             0x0000000184bc41f8 <redacted> + 0
16  libsystem_pthread.dylib             0x0000000184bc2c38 thread_start + 4
    2017-10-26 13:11:41.375952+0530 Altus Mobile[485:72091] [reports] Main
Thread Checker: UI API called on a background thread: -[UIApplication .
applicationState]
</code>```

I know Apple has enable the Main Thead Checker in Latest Xcode version which tells if we use any UI Main Thread in background. Just to make sure the issue is with ESRI Maps have commented the loading part of ESRI maps, main thread checker issue didn't popped up, but when i uncommented it back, issue back again. Also when i zoom in and zoom out the ESRI map i'm getting

```<code> 2017-10-26 13:11:41.659743+0530 Altus Mobile[485:72060] Task <504051EF-9770-
 4852-AFB8-C47DF112DA52>.<30> finished with error - code: -999
</code>```

Did anyone faced similar issue with ESRI maps? Any help is appreciated. Thank you.

答: Yes I was facing the same issue with ArcGIS SDK version 100.0.0 in iOS 11. Upgrading the ArcGIS SDK to 100.1.1 solved this issue for me.

Body:
I'm using ESRI maps in my application. When i run the application in iOS 10 there was no issue in loading the ESRI maps, zoom in and out works fine too. But when i run the same application with iOS 11 it gives me

Main Thread Checker: UI API called on a background thread: -[UIApplication
applicationState]
PID: 485, TID: 72091, Thread name: Runtime Network Callback Thread, Queue
name: com.apple.root.default-qos.overcommit, QoS: 21
Backtrace:
4   Altus Mobile                        0x00000001006f4844 -
    [AGSRequestOperation kickoffConnection] + 1108 .
5   Foundation                          0x0000000185987a50 <redacted> + 340
6   CoreFoundation                      0x0000000184f40358 <redacted> + 24
7   CoreFoundation                      0x0000000184f402d8 <redacted> + 88
8   CoreFoundation                      0x0000000184f3fb60 <redacted> + 204
9   CoreFoundation                      0x0000000184f3d738 <redacted> + 1048
10  CoreFoundation                      0x0000000184e5e2d8
    CFRunLoopRunSpecific + 436
11  Foundation                          0x00000001858866e4 <redacted> + 304
12  Altus Mobile                        0x00000001007dbf28 -
    [AGSThreadTargetImpl mainRoutine] + 292
13  Foundation                          0x0000000185987860 <redacted> + 996
14  libsystem_pthread.dylib             0x0000000184bc432c <redacted> + 308
15  libsystem_pthread.dylib             0x0000000184bc41f8 <redacted> + 0
16  libsystem_pthread.dylib             0x0000000184bc2c38 thread_start + 4
    2017-10-26 13:11:41.375952+0530 Altus Mobile[485:72091] [reports] Main
Thread Checker: UI API called on a background thread: -[UIApplication .
applicationState]

I know Apple has enable the Main Thead Checker in Latest Xcode version which tells if we use any UI Main Thread in background. Just to make sure the issue is with ESRI Maps have commented the loading part of ESRI maps, main thread checker issue didn't popped up, but when i uncommented it back, issue back again. Also when i zoom in and zoom out the ESRI map i'm getting

 2017-10-26 13:11:41.659743+0530 Altus Mobile[485:72060] Task <504051EF-9770-
 4852-AFB8-C47DF112DA52>.<30> finished with error - code: -999

Did anyone faced similar issue with ESRI maps? Any help is appreciated. Thank you.


问:
StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First
What is the difference in behavior of [MaxLength] and [StringLength] attributes?

As far as I can tell (with the exception that [MaxLength] can validate the maximum length of an array) these are identical and somewhat redundant?

答: When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.  </p>


问:
Cannot open a SQL server database
I am using SQL Server to connect to the database. But, I receive this error when I attempt to connect.

Code for connecting database

```<code>ConnectionConfig connectionConfig = new ConnectionConfig();
Connection con = connectionConfig.CONN();
</code>```

The error produces by Log

```<code>Cannot open database "FBMain" requested by the login. The login failed.
</code>```

Here is the code

```<code>public class ConnectionConfig {
    private String ip = "192.168.56.1";
    private String classs = "net.sourceforge.jtds.jdbc.Driver";
    private String db = "FBMain";
    private String un = "sa";
    private String password = "Password123";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL;
        try {
            Class.forName(classs);
            ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
                + "databaseName=" + db + ";user=" + un + ";password="
                + password + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage());
        }
        return conn;
    }
}
</code>```

I have checked the user mappings for user sa. The database role membership for FBMain is set to db_owner and public. But, I can't connect at all.

答:
There are TWO instances od SQL Server on 192.168.56.1, default and named(SQL).

The app tried to connect to the default instance where there is no FBMain database.
This database exists on the named istance.

To connect to the named instance the connection string should specify the port (that can be found in SQL Server error log or in the Configuration Manager), or it can specify instance name like this: 192.168.56.1\SQL or ANIME-PC\SQL and SQL Server Browser shuold run in the second case.

Title: Cannot open a SQL server database

Body:
I am using SQL Server to connect to the database. But, I receive this error when I attempt to connect.

Code for connecting database

ConnectionConfig connectionConfig = new ConnectionConfig();
Connection con = connectionConfig.CONN();

The error produces by Log

Cannot open database "FBMain" requested by the login. The login failed.

Here is the code

public class ConnectionConfig {
    private String ip = "192.168.56.1";
    private String classs = "net.sourceforge.jtds.jdbc.Driver";
    private String db = "FBMain";
    private String un = "sa";
    private String password = "Password123";

    @SuppressLint("NewApi")
    public Connection CONN() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL;
        try {
            Class.forName(classs);
            ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
                + "databaseName=" + db + ";user=" + un + ";password="
                + password + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage());
        }
        return conn;
    }
}

I have checked the user mappings for user sa. The database role membership for FBMain is set to db_owner and public. But, I can't connect at all.


问:
Inline assembler question
Using inline assembler I could specify an add operation with
two inputs and one result as follows:

```<code>int a = 5;
int b = 5;
int res;

asm volatile (
" add %1, %2, %0          \n\t"
: "=r" (res)
: "r" (a), "r" (b)
: "%g0"
);
</code>```

On a 32-bit architecture, this produces me an instruction word that could look like
this: 0x91050101

Now I am wondering, rather then explicitly specifying the assembler code for the addition,
I would like to specify the instruction word right away and put it into the executable. That should look something like this here

```<code>asm volatile (%x91, %x05, %x01, %x01);
</code>```

Anyone an idea where I can find more information how this could be done and how the syntax has to look like to do that (the above is only a wild guess).

Many thanks!

答:
```<code>asm volatile (
" .byte 0x91, 0x5, 0x1, 0x1          \n"
);
</code>```

should do it.

You find the documentation at http://sourceware.org/binutils/docs/as/

ContentLicense: CC BY-SA 2.5

Title: Inline assembler question

Body:
Using inline assembler I could specify an add operation with
two inputs and one result as follows:

int a = 5;
int b = 5;
int res;

asm volatile (
" add %1, %2, %0          \n\t"
: "=r" (res)
: "r" (a), "r" (b)
: "%g0"
);

On a 32-bit architecture, this produces me an instruction word that could look like
this: 0x91050101

Now I am wondering, rather then explicitly specifying the assembler code for the addition,
I would like to specify the instruction word right away and put it into the executable. That should look something like this here

asm volatile (%x91, %x05, %x01, %x01);

Anyone an idea where I can find more information how this could be done and how the syntax has to look like to do that (the above is only a wild guess).

Many thanks!

Body:
asm volatile (
" .byte 0x91, 0x5, 0x1, 0x1          \n"
);

should do it.

You find the documentation at http://sourceware.org/binutils/docs/as/


问:
Google Maps API InfoWindow not Displaying content
My Code looks like this:

```<code>var map = /*some google map - defined earlier in the code*/;
var geocoder = new google.maps.Geocoder();
var address = 'Some Address, Some Street, Some Place';
geocoder.geocode({'address':address},function(results,status){
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var infobox = new google.maps.InfoWindow({
            content: 'Hello world'
        });
        for(i in results){
            var marker = new google.maps.Marker({
                map: map,
                position: results[i].geometry.location
            });
            google.maps.event.addListener(marker, 'click', function() {
                infobox.setContent('blablabla');
                infobox.open(map,marker);
                alert(infobox.content); //displays 'blablabla'
            });
        }
    }
});
</code>```

Basically it's creating some markers on a single map based on a given address-string. It adds an infoWindow to the markers that opens on click.

Problem is: the infoWindow displays empty.

Screenshot here:

PS: Using Maps API V3

答:
I have resolved issue by adding below code.

setTimeout(function () {    GeocodeMarker.info.open(GoogleMap,
  GeocodeMarker);  }, 300);

Thanks

Body:
My Code looks like this:

var map = /*some google map - defined earlier in the code*/;
var geocoder = new google.maps.Geocoder();
var address = 'Some Address, Some Street, Some Place';
geocoder.geocode({'address':address},function(results,status){
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var infobox = new google.maps.InfoWindow({
            content: 'Hello world'
        });
        for(i in results){
            var marker = new google.maps.Marker({
                map: map,
                position: results[i].geometry.location
            });
            google.maps.event.addListener(marker, 'click', function() {
                infobox.setContent('blablabla');
                infobox.open(map,marker);
                alert(infobox.content); //displays 'blablabla'
            });
        }
    }
});

Basically it's creating some markers on a single map based on a given address-string. It adds an infoWindow to the markers that opens on click.

Problem is: the infoWindow displays empty.

Screenshot here:

PS: Using Maps API V3


问:
Remove babel from production build to reduce payload size
Can anyone help with this question?

Does removing babel in production build reduce payload size?

NB: I only want to support modern browsers.

答:
babel is just a library that adds some code to yours so that the browser can understand some of the syntax that is not natively understood by the browser.

Yes, this adds to the bundle size. But if you didn't want to use babel, you couldn't do most of the cool stuff here

If you were to remove babel-loader in the webpack config but still continued to use es6 syntax, then the final distribution asset may not be understood by the browser (you'll get SyntaxErrors in the browser at runtime)


问:
Granting read access to the Authenticated Users group for a file
How do I grant read access to the Authenticated Users group for a file? I'm using s3cmd and want to do it while uploading but I'm just focusing directly on changing the acl. What should I put in for http://acs.amazonaws.com/groups/global/AuthenticatedUsers? I have tried every combination of AuthenticatedUsers possible.

./s3cmd setacl
--acl-grant=read:http://acs.amazonaws.com/groups/global/AuthenticatedUsers
s3://BUCKET/FILE

./s3cmd setacl
--acl-grant=read:AuthenticatedUsers
s3://BUCKET/FILE

答:
Here is an example command that will set the ACL on an S3 object to  authenticated-read.

```<code>aws s3api put-object-acl --acl authenticated-read --bucket mybucket --key myfile.txt
</code>```

.

Body:
Here is an example command that will set the ACL on an S3 object to  authenticated-read.

aws s3api put-object-acl --acl authenticated-read --bucket mybucket --key myfile.txt

.


问:
php errors when logged out because of session user_id
I'm making a product details page, and on the product details page I'm having if functions to see if the $_SESSION user_id is the same as the $product user_id to echo something or not for example. When no user is logged in, I get alot of errors that it can't find the $session user_id. How can I solve this problem so when there is no user logged in it does the same as if the session user_id is wrong to the product user_id?

for example:

```<code><?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>
</code>```

So if the session user_id is wrong to the product user_id i want the same thing to happen when there is no $_SESSION user_id found which is echoing this: <?php echo $userarray['email'];?>

This is my whole details page:

```<code><?php include_once ('templates/header.php'); ?>

<div class="all-content">
       <div class="row">
        <div class="col-lg-12 bg-warning" style="font-size:25px">

            <!-- Maak variables voor gele balkje ingelogt of niet -->
            <?php $overditcadeau = '<center>Over dit cadeau</center>'; ?>
            <?php $mijncadeau = '<center>Mijn cadeau</center>'; ?>

         <?php   if ($_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

        </div>
        </div>
<div class="container">
    <br><br>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <!-- Als het cadeau niet van de ingelogde gebruiker is laat email van de eigenaar van het cadeau zien -->
    <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>

<div class="container">
 <div class="row">

     <div class="overditcadeau" >
    <div class="overditcadeau_foto">
    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">
</div>

<div class="overditcadeau_tekst1">
  <h1> <div class="product_naam"> <?php echo $product['product_naam']; ?>  </div> </h1>
   <h3>Over dit cadeau</h3>
     <div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
   </div>
   <div class="overditcadeau_tekst2">

       <!--Als het cadeau niet van de ingelogde gebruiker is laat een button zien dat heet cadeau aanvragen -->
       <div class="cadeau_aanvragen">
  <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button></a>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>
<script>
function myFunction() {
    alert("Uw cadeau aanvraag is geaccepteerd, Klik hier om een bericht naar de eigenaar van het cadeau te sturen.");
}
</script>

<?php endif; ?>
</div>

<!--Als het cadeau van de ingelogde gebruiker is laat een button zien dat heet cadeau bewerken-->
<div class="cadeau_bewerken">
        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken </a>
<?php endif; ?>
    </div>
    <br>
    <div class="cadeau_verwijderen">
        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen </a>
<?php endif; ?>
    </div>

    <!--Als het cadeau van de ingelogde gebruiker is laat aantal geïnteresseerden zien-->
    <div class="aantal_geinteresseerden">
         <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <h4>Aantal geïnteresseerden:</h4>
<?php endif; ?>
    </div>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <div class="aangeboden_door">   Aangeboden door:
<tr>
    <td>
        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>
        </a>
    </td>
    </tr>
</div>

<?php endif; ?>
</div>

     </div>
     </div>
</div>

<div class="container">

<footer>
 <p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
</code>```

答:
Use isset() to check variable is set or not.

Like below:-

```<code>if (isset($_SESSION['user_id']) && isset($product["user_id"]) && $_SESSION['user_id'] != $product["user_id"]) {
</code>```

Note:- Do same for other variables too used on the page.

So the whole code need to be like below:-

```<code><?php include_once ('templates/header.php'); ?>

<div class="all-content">
       <div class="row">
        <div class="col-lg-12 bg-warning" style="font-size:25px">

            <!-- Maak variables voor gele balkje ingelogt of niet -->
            <?php $overditcadeau = '<center>Over dit cadeau</center>'; ?>
            <?php $mijncadeau = '<center>Mijn cadeau</center>'; ?>

         <?php   if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) && $_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

        </div>
        </div>
<div class="container">
    <br><br>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <!-- Als het cadeau niet van de ingelogde gebruiker is laat email van de eigenaar van het cadeau zien -->
    <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>

<div class="container">
 <div class="row">

     <div class="overditcadeau" >
    <div class="overditcadeau_foto">
    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">
</div>

<div class="overditcadeau_tekst1">
  <h1> <div class="product_naam"> <?php echo $product['product_naam']; ?>  </div> </h1>
   <h3>Over dit cadeau</h3>
     <div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
   </div>
   <div class="overditcadeau_tekst2">

       <!--Als het cadeau niet van de ingelogde gebruiker is laat een button zien dat heet cadeau aanvragen -->
       <div class="cadeau_aanvragen">
  <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button></a>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>
<script>
function myFunction() {
    alert("Uw cadeau aanvraag is geaccepteerd, Klik hier om een bericht naar de eigenaar van het cadeau te sturen.");
}
</script>

<?php endif; ?>
</div>

<!--Als het cadeau van de ingelogde gebruiker is laat een button zien dat heet cadeau bewerken-->
<div class="cadeau_bewerken">
        <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken </a>
<?php endif; ?>
    </div>
    <br>
    <div class="cadeau_verwijderen">
        <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen </a>
<?php endif; ?>
    </div>

    <!--Als het cadeau van de ingelogde gebruiker is laat aantal geïnteresseerden zien-->
    <div class="aantal_geinteresseerden">
         <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <h4>Aantal geïnteresseerden:</h4>
<?php endif; ?>
    </div>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <div class="aangeboden_door">   Aangeboden door:
<tr>
    <td>
        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>
        </a>
    </td>
    </tr>
</div>

<?php endif; ?>
</div>

     </div>
     </div>
</div>

<div class="container">

<footer>
 <p>© kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>
</code>```

Body:
I'm making a product details page, and on the product details page I'm having if functions to see if the $_SESSION user_id is the same as the $product user_id to echo something or not for example. When no user is logged in, I get alot of errors that it can't find the $session user_id. How can I solve this problem so when there is no user logged in it does the same as if the session user_id is wrong to the product user_id?

for example:

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

Email van de eigenaar:

<?php echo $userarray['email'];?>
       <?php endif; ?>

So if the session user_id is wrong to the product user_id i want the same thing to happen when there is no $_SESSION user_id found which is echoing this: <?php echo $userarray['email'];?>

This is my whole details page:

<?php include_once ('templates/header.php'); ?>

            <?php $overditcadeau = 'Over dit cadeau'; ?>
            <?php $mijncadeau = 'Mijn cadeau'; ?>

         <?php   if ($_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

Email van de eigenaar:

<?php echo $userarray['email'];?>
       <?php endif; ?>

    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">

 <?php echo $product['product_naam']; ?>

Over dit cadeau

<?php echo $product['product_beschrijving']; ?>

  <?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>

<?php endif; ?>

        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken
<?php endif; ?>

        <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen
<?php endif; ?>

         <?php if ( $_SESSION['user_id'] ==  $product["user_id"]): ?>

Aantal geïnteresseerden:

<?php endif; ?>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>

   Aangeboden door:

        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>

<?php endif; ?>

© kadokado 2017, Inc.

<?php include_once ('templates/footer.php'); ?>

Body:
Use isset() to check variable is set or not.

Like below:-

if (isset($_SESSION['user_id']) && isset($product["user_id"]) && $_SESSION['user_id'] != $product["user_id"]) {

Note:- Do same for other variables too used on the page.

So the whole code need to be like below:-

<?php include_once ('templates/header.php'); ?>

<div class="all-content">
       <div class="row">
        <div class="col-lg-12 bg-warning" style="font-size:25px">

            <!-- Maak variables voor gele balkje ingelogt of niet -->
            <?php $overditcadeau = '<center>Over dit cadeau</center>'; ?>
            <?php $mijncadeau = '<center>Mijn cadeau</center>'; ?>

         <?php   if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) && $_SESSION['user_id'] != $product["user_id"]) {
    echo $overditcadeau;
 } else {
    echo $mijncadeau;
  } ?>

        </div>
        </div>
<div class="container">
    <br><br>

<?php    $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();  ?>

    <!-- Als het cadeau niet van de ingelogde gebruiker is laat email van de eigenaar van het cadeau zien -->
    <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] != $product["user_id"]): ?>
 <h3>Email van de eigenaar:</h4>
<?php echo $userarray['email'];?>
       <?php endif; ?>
 </div>

<div class="container">
 <div class="row">

     <div class="overditcadeau" >
    <div class="overditcadeau_foto">
    <img src="<?php echo base_url(); ?>upload/<?php echo $product['product_foto']; ?>" id="cadeaufoto_overditcadeau">
</div>

<div class="overditcadeau_tekst1">
  <h1> <div class="product_naam"> <?php echo $product['product_naam']; ?>  </div> </h1>
   <h3>Over dit cadeau</h3>
     <div class="product_beschrijving"><?php echo $product['product_beschrijving']; ?> </div>
   </div>
   <div class="overditcadeau_tekst2">

       <!--Als het cadeau niet van de ingelogde gebruiker is laat een button zien dat heet cadeau aanvragen -->
       <div class="cadeau_aanvragen">
  <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] != $product["user_id"]): ?>
     <a href="<?php echo base_url() ?>/Cadeau_ontvang"> <button type="button" class="btn btn-default">Ik wil dit cadeau!</button></a>

     <button onclick="myFunction()">Ik wil dit cadeau!</button>
<script>
function myFunction() {
    alert("Uw cadeau aanvraag is geaccepteerd, Klik hier om een bericht naar de eigenaar van het cadeau te sturen.");
}
</script>

<?php endif; ?>
</div>

<!--Als het cadeau van de ingelogde gebruiker is laat een button zien dat heet cadeau bewerken-->
<div class="cadeau_bewerken">
        <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product['product_id']; ?>"> Cadeau bewerken </a>
<?php endif; ?>
    </div>
    <br>
    <div class="cadeau_verwijderen">
        <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <a class="btn btn-primary" href="<?php echo base_url() ?>/Delete_ctrl/delete_product_id/<?php echo $product['product_id']; ?>"> Cadeau verwijderen </a>
<?php endif; ?>
    </div>

    <!--Als het cadeau van de ingelogde gebruiker is laat aantal geïnteresseerden zien-->
    <div class="aantal_geinteresseerden">
         <?php if (isset($_SESSION['user_id']) &&  isset($product["user_id"]) &&  $_SESSION['user_id'] ==  $product["user_id"]): ?>
    <h4>Aantal geïnteresseerden:</h4>
<?php endif; ?>
    </div>

<?php if ( $_SESSION['user_id'] != $product["user_id"]): ?>
     <div class="aangeboden_door">   Aangeboden door:
<tr>
    <td>
        <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id']?>">
          <?php echo $userarray['voornaam'];?>
        </a>
    </td>
    </tr>
</div>

<?php endif; ?>
</div>

     </div>
     </div>
</div>

<div class="container">

<footer>
 <p>&copy; kadokado 2017, Inc.</p>
</footer>
<hr>
</div>
</div>
<div class="clearfix"></div>
<?php include_once ('templates/footer.php'); ?>


问:
Loop invariant of linear search
As seen on Introduction to Algorithms (http://mitpress.mit.edu/algorithms), the exercise states the following:

Input: Array A[1..n] and a value v

Output: Index i, where A[i] = v or NIL if v does not found in A

Write pseudocode for LINEAR-SEARCH,
  which scans through the sequence,
  looking for v. Using a loop invariant,
  prove that your algorithm is correct.
  (Make sure that your loop invariant
  fulﬁlls the three necessary properties
  – initialization, maintenance,
  termination.)

I have no problem creating the algorithm, but what I don't get is how can I decide what's my loop invariant. I think I understood the concept of loop invariant, that is, a condition that is always true before the beginning of the loop, at the end/beginning of each iteration and still true when the loop ends. This is usually the goal, so for example, at insertion sort, iterating over j, starting at j = 2, the A[1..j-1] elements are always sorted. This makes sense to me. But for a linear search? I can't think of anything, it just sounds too simple to think of a loop invariant. Did I understand something wrong? I can only think of something obvious like (it's either NIL or between 0 and n). Thanks a lot in advance!

答:
Assume that you have an array of length i, indexed from [0...i-1], and the algorithm is checking if v is present in this array.
I'm not totally sure, but I think, the loop invariant is as follows:
If j is the index of v, then [0..j-1] will be an array that does not have v.

Initialization : Before iterating from 0..i-1, the current array checked (none), does not consist of v.

Maintenance : On finding v at j, array from [0..j-1] will be an array without v.

Termination : As the loop terminates on finding v at j, [0..j-1] will be an array without j.

If the array itself does not have v, then j = i-1, and the above conditions will still hold true.

Title: Loop invariant of linear search


问:
JHipster changes in HTML are not effective
my question is about a little problem with changes in Jhipster. I've created a project and imported it to intellij idea. After that I tried to make some changes in the "home.components.html" file. That is the file, which is shown wenn you open the app as a localhost. I tried to run the app after the changes,  but the changes aren't shown. For example i changed the h1 tag in this file, from "Welcome Java Hipster" to "ABC".

What can i do?

Thank you very much!

答: If you're using i18n, you need to make your changes in those files, not in the HTML.</p>


问:
How to get clipboard data in non main thread?
I'm trying to get data from Clipboard with the below code.

```<code>private void TestBtn_Click(object sender, EventArgs e)
{
 Thread sampleThread = new Thread(SampleMethod);
 sampleThread.IsBackground = true;
 sampleThread.Start();
 Thread.Sleep(2000);
 var textFromMain = Clipboard.GetText(TextDataFormat.Text);
}

private void SampleMethod()
{
 var textFromThread = Clipboard.GetText(TextDataFormat.Text);
 Thread.Sleep(1000);
}
</code>```

I'm getting whatever text copied to clipboard with this line -

var textFromMain = Clipboard.GetText(TextDataFormat.Text);

But below line returns empty string or blank string.

var textFromThread = Clipboard.GetText(TextDataFormat.Text);

I'm not getting what's the issue. Can somebody help me to understand. If it's multi-threading, please point me to right direction.

答:
Clipboard.GetText(TextDataFormat.Text) use COM and throws exception if called in thread which not marked with STAThreadAttribute.

One way to solve is use delegate to return call of Clipboard.GetText to main thread with Invoke. But in this case thread will freeze it execution on Invoke till the SampleMethod() ends it execution on main form thread and main thread will be free.

Other way is to use own call to COM to get clipboard text instead of System.Windows.Forms.Clipboard.GetText(), see ClipboardCom.GetText(), this method not need waiting main form thread.

```<code>    private string _textFromMain, _textFromThreadByInvoke, _textFromThreadByCom;

    private delegate string GetClipboardInvoke(TextDataFormat textformat);
    private void SampleInvokeMethod()
    {
        GetClipboardInvoke invokerClipboard = new GetClipboardInvoke(Clipboard.GetText);
        _textFromThreadByInvoke = (string)this.Invoke(invokerClipboard, TextDataFormat.Text); // where this is a Form
        Thread.Sleep(1000);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread sampleInvokeThread = new Thread(SampleInvokeMethod) { IsBackground = true };
        sampleInvokeThread.Start();

        Thread sampleComThread = new Thread(SampleComMethod) { IsBackground = true };
        sampleComThread.Start();

        Thread.Sleep(10000);
        _textFromMain = Clipboard.GetText(TextDataFormat.Text);
    }

    private void SampleComMethod()
    {
        _textFromThreadByCom = ClipboardCom.GetText();
        Thread.Sleep(1000);
    }

    public static class ClipboardCom
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetClipboardData(uint uFormat);
        [DllImport("user32.dll")]
        static extern bool IsClipboardFormatAvailable(uint format);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool CloseClipboard();
        [DllImport("kernel32.dll")]
        static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        static extern bool GlobalUnlock(IntPtr hMem);

        const uint CF_UNICODETEXT = 13;

        public static string GetText()
        {
            if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
                return null;
            if (!OpenClipboard(IntPtr.Zero))
                return null;

            string data = null;
            var hGlobal = GetClipboardData(CF_UNICODETEXT);
            if (hGlobal != IntPtr.Zero)
            {
                var lpwcstr = GlobalLock(hGlobal);
                if (lpwcstr != IntPtr.Zero)
                {
                    data = Marshal.PtrToStringUni(lpwcstr);
                    GlobalUnlock(lpwcstr);
                }
            }
            CloseClipboard();

            return data;
        }
    }
</code>```

Body:
I'm trying to get data from Clipboard with the below code.

private void TestBtn_Click(object sender, EventArgs e)
{
 Thread sampleThread = new Thread(SampleMethod);
 sampleThread.IsBackground = true;
 sampleThread.Start();
 Thread.Sleep(2000);
 var textFromMain = Clipboard.GetText(TextDataFormat.Text);
}

private void SampleMethod()
{
 var textFromThread = Clipboard.GetText(TextDataFormat.Text);
 Thread.Sleep(1000);
}

I'm getting whatever text copied to clipboard with this line -

var textFromMain = Clipboard.GetText(TextDataFormat.Text);

But below line returns empty string or blank string.

var textFromThread = Clipboard.GetText(TextDataFormat.Text);

I'm not getting what's the issue. Can somebody help me to understand. If it's multi-threading, please point me to right direction.

Body:
Clipboard.GetText(TextDataFormat.Text) use COM and throws exception if called in thread which not marked with STAThreadAttribute.

One way to solve is use delegate to return call of Clipboard.GetText to main thread with Invoke. But in this case thread will freeze it execution on Invoke till the SampleMethod() ends it execution on main form thread and main thread will be free.

Other way is to use own call to COM to get clipboard text instead of System.Windows.Forms.Clipboard.GetText(), see ClipboardCom.GetText(), this method not need waiting main form thread.

    private string _textFromMain, _textFromThreadByInvoke, _textFromThreadByCom;

    private delegate string GetClipboardInvoke(TextDataFormat textformat);
    private void SampleInvokeMethod()
    {
        GetClipboardInvoke invokerClipboard = new GetClipboardInvoke(Clipboard.GetText);
        _textFromThreadByInvoke = (string)this.Invoke(invokerClipboard, TextDataFormat.Text); // where this is a Form
        Thread.Sleep(1000);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread sampleInvokeThread = new Thread(SampleInvokeMethod) { IsBackground = true };
        sampleInvokeThread.Start();

        Thread sampleComThread = new Thread(SampleComMethod) { IsBackground = true };
        sampleComThread.Start();

        Thread.Sleep(10000);
        _textFromMain = Clipboard.GetText(TextDataFormat.Text);
    }

    private void SampleComMethod()
    {
        _textFromThreadByCom = ClipboardCom.GetText();
        Thread.Sleep(1000);
    }

    public static class ClipboardCom
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetClipboardData(uint uFormat);
        [DllImport("user32.dll")]
        static extern bool IsClipboardFormatAvailable(uint format);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool CloseClipboard();
        [DllImport("kernel32.dll")]
        static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        static extern bool GlobalUnlock(IntPtr hMem);

        const uint CF_UNICODETEXT = 13;

        public static string GetText()
        {
            if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
                return null;
            if (!OpenClipboard(IntPtr.Zero))
                return null;

            string data = null;
            var hGlobal = GetClipboardData(CF_UNICODETEXT);
            if (hGlobal != IntPtr.Zero)
            {
                var lpwcstr = GlobalLock(hGlobal);
                if (lpwcstr != IntPtr.Zero)
                {
                    data = Marshal.PtrToStringUni(lpwcstr);
                    GlobalUnlock(lpwcstr);
                }
            }
            CloseClipboard();

            return data;
        }
    }