问:
CSS: resize div width according to parents width
Ok, I am basically building a fluid layout.
My HTML is like this:

```<code><div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="center">This text is long and can get longer</div>
    <div class="box" id="right">Right</div>
    <div class="clear"></div>
</div>
</code>```

Here is the css:

```<code>#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}
</code>```

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.

答:
Try these corrections (just simple floating elements, no need to set absolute elems or paddings)

just added a new fiddle

```<code><!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>fluid layout</title>
<style>
    /*class to set the width of the columns */
    .floatbox{
        width:100px;
    }

    #container{
        width: 100%;
        float:left;
    }
    #left{
        float:left;
    }
    #right{
        float:right;
    }
    #center{
        overflow: hidden;
    }
    .clear{
        clear:both;
    }
</style>
</head>
<body>
    <div id="container">
        <!-- floating column to the right, it must be placed BEFORE the left one -->
        <div class="floatbox" id="right">Right</div>
        <div class="floatbox" id="left">Left</div>

        <!-- central column, it takes automatically the remaining width, no need to declare further css rules -->
        <div id="center">This text is long and can get longer</div>

        <!-- footer, beneath everything, css is ok -->
        <div class="clear"></div>
    </div>
</body>
</html>
</code>```

Body:
Ok, I am basically building a fluid layout.
My HTML is like this:

Left

This text is long and can get longer

Right

Here is the css:

#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.

Body:
Try these corrections (just simple floating elements, no need to set absolute elems or paddings)

just added a new fiddle

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>fluid layout</title>
<style>
    /*class to set the width of the columns */
    .floatbox{
        width:100px;
    }

    #container{
        width: 100%;
        float:left;
    }
    #left{
        float:left;
    }
    #right{
        float:right;
    }
    #center{
        overflow: hidden;
    }
    .clear{
        clear:both;
    }
</style>
</head>
<body>
    <div id="container">
        <!-- floating column to the right, it must be placed BEFORE the left one -->
        <div class="floatbox" id="right">Right</div>
        <div class="floatbox" id="left">Left</div>

        <!-- central column, it takes automatically the remaining width, no need to declare further css rules -->
        <div id="center">This text is long and can get longer</div>

        <!-- footer, beneath everything, css is ok -->
        <div class="clear"></div>
    </div>
</body>
</html>


来源: stackexchange

问:
CSS for long (scrolling) dropdown menu
I'm trying to create a nested dropdown menu that may potentially be very long and overflow off the page.

What I'd like to do is, when the menu is too long it will display a scroll bar.  I'm doing this with overflow: auto.  However, when I do this, it traps any submenus within the same 'scroll space' as defined by the first scroll bar.

I've also tried various iterations of overflow: none with the :not(:hover) selector, but nothing I've tried seems to work.

What I'd like it to do is show the scrollbar on each level, only if necessary (i.e. that submenu would scroll off the page).  Each submenu should 'pop' out of the previous scroll bar, if any, as if it was not there.

I'd like to do this in all CSS, but I'm open to a JS solution as well.

I have a code pen showing the issue here:
https://codepen.io/mcmurphy510/pen/ZyGLKd

答:
Mouse over on item "Link 3" will shows its sub-menu on the right side of it and then mouse over on "Link 31" for further sub menu.

.menu {
  position: relative;
}

ul {
  width: 200px;
  margin: 0;
  color: black;
  list-style:none;
  padding:0;
  max-height:100px;
  overflow-x: hidden;
  overflow-y: auto;
}

li {
  padding:0.5em;
}
li:hover{
  background-color:blue;
  color:white;
}
li .menu {
  position: absolute;
  z-index: 10;
  background-color:lightgrey;
  opacity: 0;
  transition: opacity 0.5s;
}
li:hover > .menu,
.menu:hover {
  opacity: 1;
}

li.parent {
  cursor: pointer;
}

.level2 {
  top: 0px;
  left: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <ul>
    <li>Link1</li>
    <li class="parent">Link3...
      <div class="menu level2">
        <ul>
          <li class="parent">Link31...
            <div class="menu level2">
              <ul>
                <li>Link 311</li>
                <li>Link 312</li>
                <li>Link 313</li>
                <li>Link 314</li>
              </ul>
            </div>
          </li>
          <li>Link 32</li>
          <li>Link 33</li>
          <li>Link 34</li>
        </ul>
      </div>
    </li>
    <li>Link2</li>

    <li>Link1</li>
    <li>Link2</li>

  </ul>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: CSS for long (scrolling) dropdown menu

Body:
Mouse over on item "Link 3" will shows its sub-menu on the right side of it and then mouse over on "Link 31" for further sub menu.

.menu {
  position: relative;
}

ul {
  width: 200px;
  margin: 0;
  color: black;
  list-style:none;
  padding:0;
  max-height:100px;
  overflow-x: hidden;
  overflow-y: auto;
}

li {
  padding:0.5em;
}
li:hover{
  background-color:blue;
  color:white;
}
li .menu {
  position: absolute;
  z-index: 10;
  background-color:lightgrey;
  opacity: 0;
  transition: opacity 0.5s;
}
li:hover > .menu,
.menu:hover {
  opacity: 1;
}

li.parent {
  cursor: pointer;
}

.level2 {
  top: 0px;
  left: 200px;
}

<div class="menu">
  <ul>
    <li>Link1</li>
    <li class="parent">Link3...
      <div class="menu level2">
        <ul>
          <li class="parent">Link31...
            <div class="menu level2">
              <ul>
                <li>Link 311</li>
                <li>Link 312</li>
                <li>Link 313</li>
                <li>Link 314</li>
              </ul>
            </div>
          </li>
          <li>Link 32</li>
          <li>Link 33</li>
          <li>Link 34</li>
        </ul>
      </div>
    </li>
    <li>Link2</li>

    <li>Link1</li>
    <li>Link2</li>

  </ul>
</div>


问:
How can I save as word.docx in open xml
I need to open a template, add some text, and then save it with a new name.
How can I save it with a new name?</p>

```<code>        String Dir = @"F:\template.docx";
     WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(Dir, true);

        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

        Paragraph paragraph1 = body.AppendChild(new Paragraph());

        Run run1 = new Run();
        RunProperties runProperties1 = new RunProperties();
        Bold bold2 = new Bold();
        FontSize fontSize2 = new FontSize() { Val = "28" };
        runProperties1.Append(bold2);
        runProperties1.Append(fontSize2);

        Text text1 = new Text();
        text1.Text = "text";
        run1.Append(runProperties1);
        run1.Append(text1);
        paragraph1.Append(Hearder1);
        paragraph1.Append(run1);

        wordprocessingDocument.Close();
</code>```

答:
```<code>byte[] byteArray = File.ReadAllBytes("D:\Document.docx");
using (var stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);
        using (var document = WordprocessingDocument.Open(stream, true))
        {
           //Here fill document
        }
        // And save file
        File.WriteAllBytes("D:\NewDocument.docx", stream.ToArray());
    }
</code>```

Title: How can I save as word.docx in open xml

Body:
I need to open a template, add some text, and then save it with a new name.
How can I save it with a new name?

        String Dir = @"F:\template.docx";
     WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(Dir, true);

        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

        Paragraph paragraph1 = body.AppendChild(new Paragraph());

        Run run1 = new Run();
        RunProperties runProperties1 = new RunProperties();
        Bold bold2 = new Bold();
        FontSize fontSize2 = new FontSize() { Val = "28" };
        runProperties1.Append(bold2);
        runProperties1.Append(fontSize2);

        Text text1 = new Text();
        text1.Text = "text";
        run1.Append(runProperties1);
        run1.Append(text1);
        paragraph1.Append(Hearder1);
        paragraph1.Append(run1);

        wordprocessingDocument.Close();


问:
Suppress warning message Akka.net
I'm a newbie on Akka.NET so excuse me if this question is silly.

I've tried to suppress the following Akka.NET warning

"NewtonSoftJsonSerializer has been detected as a default serializer.
It will be obsoleted in Akka.NET starting from version 1.5 in the favor of Hyperion
for more info visit: http://getakka.net/docs/Serialization#how-to-setup-hyperion-as-default-serializer
If you want to suppress this message set HOCON 'akka.suppress-json-serializer-warning' config flag to on."

But I'm not entirely sure where can I set that flag.

So far I've tried

```<code>var config = ConfigurationFactory.ParseString(@"
akka {
    actor {
       akka.suppress-json-serializer-warning = true
          }
     }");
TlogSystem = ActorSystem.Create("TlogSystem",config);
</code>```

But it doesn't work, it keep printing the warning. Could someone point me at the right direction?

答:
Try moving suppress-json-serializer-warning outside the actor block:

```<code>akka {
    suppress-json-serializer-warning = on
}
</code>```

Title: Suppress warning message Akka.net

Body:
I'm a newbie on Akka.NET so excuse me if this question is silly.

I've tried to suppress the following Akka.NET warning

"NewtonSoftJsonSerializer has been detected as a default serializer.
It will be obsoleted in Akka.NET starting from version 1.5 in the favor of Hyperion
for more info visit: http://getakka.net/docs/Serialization#how-to-setup-hyperion-as-default-serializer
If you want to suppress this message set HOCON 'akka.suppress-json-serializer-warning' config flag to on."

But I'm not entirely sure where can I set that flag.

So far I've tried

var config = ConfigurationFactory.ParseString(@"
akka {
    actor {
       akka.suppress-json-serializer-warning = true
          }
     }");
TlogSystem = ActorSystem.Create("TlogSystem",config);

But it doesn't work, it keep printing the warning. Could someone point me at the right direction?

Body:
Try moving suppress-json-serializer-warning outside the actor block:

akka {
    suppress-json-serializer-warning = on
}


问:
Collections.max function for iterable<Integer> in java
The Java Collections.max takes only a collection of a sortable object. However since the collection is not necessarily sorted, I don't see any reason not to implement the same max function for iterable types.

Is there a max method for Iterable<T extends Comparable<? super T>> in java's standard library?

答: Hmm… no, there isn’t. If you want to use Collections.max() you have to convert your Iterable into a Collection first, probably by adding all of the elements into a List (or Set, depending on the data).</p>

OwnerDisplayName: Elazar Leibovich

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mmyers

OwnerDisplayName: Bombe


问:
mySQL query for top N entries of a grouped records
I'm new to MySql and to databases in general. I have a query, which I built together via snippets from online resources and trail and error. It is really slow (27sec) and I assume it can be optimized. Maybe someone could help me out with that.

This is the datastructure for my mySQL - Database. Version 5.1.51-0

```<code>|- purchaseID -|- customerID -|- emotionID -|- customerCountryCode -|- customerContinentCode-|
|     1        |     2345     |     0       |        US             |            NA          |
|     2        |     2345     |     3       |        US             |            NA          |
|     3        |     4456     |     0       |        UK             |            EU          |
|     3        |     4456     |     5       |        UK             |            EU          |
|     4        |     4456     |     2       |        UK             |            EU          |
|     5        |     4456     |     2       |        UK             |            EU          |
|     6        |     1234     |     0       |        US             |            NA          |
|     7        |     6678     |     0       |        US             |            NA          |
|     8        |     9900     |     0       |        US             |            NA          |
|     9        |     3334     |     0       |        US             |            NA          |
|     10       |     3334     |     4       |        US             |            NA          |
</code>```

The database is used to save all the purchases, which are made. For every purchase the customerID, the country and the continent he comes from are saved. The customer also has the possibility to rate his purchase from a set of 6 emotions. (happy, disappointed,...) The emotion he choses is saved as emotionID.

So now I need a query to get me the top 6 costumers for a certain emotionID with a percentage info. Assume I looked for emotionID = 0 this is, what I would like to get:

```<code>|- customerID -|- emotionPercent -|
|     1234     |        100       |
|     6678     |        100       |
|     9900     |        100       |
|     2345     |        50        |
|     3334     |        50        |
|     4456     |        25        |
</code>```

I'm using this query:

```<code>SELECT customers.customerID, Count( customers.emotionID ) / C.totalPeople * 100.0 AS emotionPercent
FROM `customers`
INNER JOIN

    (SELECT customers.customerID, Count( customers.emotionID ) AS totalPeople
    FROM `customers`
    GROUP BY customerID) C

ON customers.customerID = C.customerID
WHERE customers.emotionID = 0
GROUP BY customers.customerID
ORDER BY emotionPercent DESC
LIMIT 0,6
</code>```

I have searched for answers, but the additional percentage calculation is throwing me off. I have found some solutions, which would require to populate some sort of temporary table, but I couldn't get it to work.

Problem is:
Right now, there are 140,000 entries in the database and this query takes about 27 seconds. Can this be right? Would using a SQL - Server increase the speed significantly?

What I don't get is this: Asking for the happiest country in the world is lightning fast (0.4 seconds), but structurally similar to the first query (27 sec):

```<code>SELECT customers.customerCountryCode, Count( customers.emotionID ) / C.totalPeople * 100.0 AS emotionPercent
FROM `customers`
INNER JOIN

    (SELECT customers.customerCountryCode, Count( customers.emotionID ) AS totalPeople
    FROM `customers`
    GROUP BY customerCountryCode) C

ON customers.customerCountryCode = C.customerCountryCode
WHERE customers.emotionID = 0
GROUP BY customers.customerCountryCode
ORDER BY emotionPercent DESC
LIMIT 0,6
</code>```

When I change the GROUP BY of the INNER Query in this example to customerID, the query also takes forever. So it's the grouping by customerID that's causing the problem. But why?

The customerCountryCode is defined as varchar(2). The customerID is an int(11). Is this causing the huge difference in the query performance? Is there some more appropiate varible type? The customerID can have up to 8 numbers.

A lot of questions! Thanks for reading and any help!

答:
Thanks for your help!

The guys from the mySQL forum suggested to add some indices:

```<code>ALTER TABLE customers
  ADD KEY idx_country_emid (customerCountryCode, emotionID),
  ADD KEY idx_emid_custid (emotionID, customerID);
</code>```

The query time dropped from 27 seconds to 0,1 seconds. ;)

Also, for the inner query, you can write

```<code>(SELECT customers.customerCountryCode, Count( * ) AS totalPeople
    FROM `customers`
    GROUP BY customerCountryCode) C
</code>```

Body:
I'm new to MySql and to databases in general. I have a query, which I built together via snippets from online resources and trail and error. It is really slow (27sec) and I assume it can be optimized. Maybe someone could help me out with that.

This is the datastructure for my mySQL - Database. Version 5.1.51-0

|- purchaseID -|- customerID -|- emotionID -|- customerCountryCode -|- customerContinentCode-|
|     1        |     2345     |     0       |        US             |            NA          |
|     2        |     2345     |     3       |        US             |            NA          |
|     3        |     4456     |     0       |        UK             |            EU          |
|     3        |     4456     |     5       |        UK             |            EU          |
|     4        |     4456     |     2       |        UK             |            EU          |
|     5        |     4456     |     2       |        UK             |            EU          |
|     6        |     1234     |     0       |        US             |            NA          |
|     7        |     6678     |     0       |        US             |            NA          |
|     8        |     9900     |     0       |        US             |            NA          |
|     9        |     3334     |     0       |        US             |            NA          |
|     10       |     3334     |     4       |        US             |            NA          |

The database is used to save all the purchases, which are made. For every purchase the customerID, the country and the continent he comes from are saved. The customer also has the possibility to rate his purchase from a set of 6 emotions. (happy, disappointed,...) The emotion he choses is saved as emotionID.

So now I need a query to get me the top 6 costumers for a certain emotionID with a percentage info. Assume I looked for emotionID = 0 this is, what I would like to get:

|- customerID -|- emotionPercent -|
|     1234     |        100       |
|     6678     |        100       |
|     9900     |        100       |
|     2345     |        50        |
|     3334     |        50        |
|     4456     |        25        |

I'm using this query:

SELECT customers.customerID, Count( customers.emotionID ) / C.totalPeople * 100.0 AS emotionPercent
FROM `customers`
INNER JOIN

    (SELECT customers.customerID, Count( customers.emotionID ) AS totalPeople
    FROM `customers`
    GROUP BY customerID) C

ON customers.customerID = C.customerID
WHERE customers.emotionID = 0
GROUP BY customers.customerID
ORDER BY emotionPercent DESC
LIMIT 0,6

I have searched for answers, but the additional percentage calculation is throwing me off. I have found some solutions, which would require to populate some sort of temporary table, but I couldn't get it to work.

Problem is:
Right now, there are 140,000 entries in the database and this query takes about 27 seconds. Can this be right? Would using a SQL - Server increase the speed significantly?

What I don't get is this: Asking for the happiest country in the world is lightning fast (0.4 seconds), but structurally similar to the first query (27 sec):

SELECT customers.customerCountryCode, Count( customers.emotionID ) / C.totalPeople * 100.0 AS emotionPercent
FROM `customers`
INNER JOIN

    (SELECT customers.customerCountryCode, Count( customers.emotionID ) AS totalPeople
    FROM `customers`
    GROUP BY customerCountryCode) C

ON customers.customerCountryCode = C.customerCountryCode
WHERE customers.emotionID = 0
GROUP BY customers.customerCountryCode
ORDER BY emotionPercent DESC
LIMIT 0,6

When I change the GROUP BY of the INNER Query in this example to customerID, the query also takes forever. So it's the grouping by customerID that's causing the problem. But why?

The customerCountryCode is defined as varchar(2). The customerID is an int(11). Is this causing the huge difference in the query performance? Is there some more appropiate varible type? The customerID can have up to 8 numbers.

A lot of questions! Thanks for reading and any help!

Body:
Thanks for your help!

The guys from the mySQL forum suggested to add some indices:

ALTER TABLE customers
  ADD KEY idx_country_emid (customerCountryCode, emotionID),
  ADD KEY idx_emid_custid (emotionID, customerID);

The query time dropped from 27 seconds to 0,1 seconds. ;)

Also, for the inner query, you can write

(SELECT customers.customerCountryCode, Count( * ) AS totalPeople
    FROM `customers`
    GROUP BY customerCountryCode) C


问:
Beginner / How to configure my .htaccess file so that it runs the PHP inside my HTML files?
So I'm trying to configure my .htaccess file so that it can runs the PHP code inside the HTML files.

When I go to mysite.com/thefile.php, it runs it correctly without any problem. Same if I go to mysite.com/thefile.html. But if I add <?php echo "Hello"; ?> inside the HTML file, it doesnt display anything. In fact, when I right click "View source code", it displays the php lines.

Here's what I tried with my .htaccess file:

RemoveHandler .html .htm

AddType application/x-httpd-php .php .html .htm

I also a tried with just

AddType application/x-httpd-php .php .html .htm

But it displays a "500 Internal Server Error" that says:

```<code>The server encountered an internal error or misconfiguration and was unable to complete your request.

The most common causes of this problem are errors in the app's .htaccess file or incorrect file or directory permissions preventing the web server from reading the .htaccess file.

More information about this error is available in the app's Apache error log at:

/srv/users/SYSUSER/log/APPNAME/APPNAME_apache.error.log
</code>```

I'm quite new to web development in general, and I want to mention that, except from these 2/1 lines in the .htaccess file, I have nothing else. Maybe I'm missing some lines in it? Just a guess

Thanks guys (and gals if they exist!)

答:
With Ubuntu/Apache 2.4.x, in your /etc/apache2/mods-enabled/php7.1.conf or equivalent, you could add:

<FilesMatch ".+\.html$">
    SetHandler application/x-httpd-php
</FilesMatch>

(But you shouldn't do this at all! Use .php files for PHP code.)

Body:
So I'm trying to configure my .htaccess file so that it can runs the PHP code inside the HTML files.

When I go to mysite.com/thefile.php, it runs it correctly without any problem. Same if I go to mysite.com/thefile.html. But if I add <?php echo "Hello"; ?> inside the HTML file, it doesnt display anything. In fact, when I right click "View source code", it displays the php lines.

Here's what I tried with my .htaccess file:

RemoveHandler .html .htm

AddType application/x-httpd-php .php .html .htm

I also a tried with just

AddType application/x-httpd-php .php .html .htm

But it displays a "500 Internal Server Error" that says:

The server encountered an internal error or misconfiguration and was unable to complete your request.

The most common causes of this problem are errors in the app's .htaccess file or incorrect file or directory permissions preventing the web server from reading the .htaccess file.

More information about this error is available in the app's Apache error log at:

/srv/users/SYSUSER/log/APPNAME/APPNAME_apache.error.log

I'm quite new to web development in general, and I want to mention that, except from these 2/1 lines in the .htaccess file, I have nothing else. Maybe I'm missing some lines in it? Just a guess

Thanks guys (and gals if they exist!)


问:
How to access Kibana from Amazon elasticsearch service?
I created Amazon elasticsearch service and populated data into it using logstash, which has been installed on an EC2 instance. On the Amazon elasticservice console page, there will be a link to access Kibana.

```<code>search-cluster_name-XXXXXXXXXXXXXXXXXXX.region_name.es.amazonaws.com/_plugin/kibana/
</code>```

when I click the link, browser is throwing the following error.

```<code>{"Message":"User: anonymous is not authorized to perform: es:ESHttpGet on resource: arn:aws:es:region_name:account_id:domain/cluster_name/_plugin/kibana/"}
</code>```

I'm sure that this has something related with access policy of ES domain.How should I modify my access policy so that I can access Kibana from a click on the link specified ?

答:
I used for that purpose proxy tool called aws-es-kibana.
It signs all your requests sent to aws kibana.

IAM configuration:

I created new IAM user "elasticsearch_user" with programmatic access (and I got accessKeyId and secretAccessKey associated with that account).

Elasticsearch configuration:

I created elasticsearch policy that enables access for the new created IAM user:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::{YOUR_AWS_ACCOUNT_ID}:user/elasticsearch_user"
        ]
      },
      "Action": "es:*",
      "Resource": "arn:aws:es:eu-central-1:{YOUR_AWS_ACCOUNT_ID}:domain/{YOUR_ELASTICSEARCH_DOMAIN}/*"
    }
  ]
}
</code>```

Connect to kibana from your local station:

To connect from my local station (windows) to kibana I just need to type in console:

```<code>SET AWS_ACCESS_KEY_ID=myAccessKeyId
SET AWS_SECRET_ACCESS_KEY=mySecretAccessKey

aws-es-kibana search-{PROTECTED_PART_OF_YOUR_ELASTICSEARCH_ENDPOINT}.eu-central-1.es.amazonaws.com
</code>```

After that you should have proxied access to your kibana under: http://127.0.0.1:9200/_plugin/kibana

Body:
I created Amazon elasticsearch service and populated data into it using logstash, which has been installed on an EC2 instance. On the Amazon elasticservice console page, there will be a link to access Kibana.

search-cluster_name-XXXXXXXXXXXXXXXXXXX.region_name.es.amazonaws.com/_plugin/kibana/

when I click the link, browser is throwing the following error.

{"Message":"User: anonymous is not authorized to perform: es:ESHttpGet on resource: arn:aws:es:region_name:account_id:domain/cluster_name/_plugin/kibana/"}

I'm sure that this has something related with access policy of ES domain.How should I modify my access policy so that I can access Kibana from a click on the link specified ?

Body:
I used for that purpose proxy tool called aws-es-kibana.
It signs all your requests sent to aws kibana.

IAM configuration:

I created new IAM user "elasticsearch_user" with programmatic access (and I got accessKeyId and secretAccessKey associated with that account).

Elasticsearch configuration:

I created elasticsearch policy that enables access for the new created IAM user:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::{YOUR_AWS_ACCOUNT_ID}:user/elasticsearch_user"
        ]
      },
      "Action": "es:*",
      "Resource": "arn:aws:es:eu-central-1:{YOUR_AWS_ACCOUNT_ID}:domain/{YOUR_ELASTICSEARCH_DOMAIN}/*"
    }
  ]
}

Connect to kibana from your local station:

To connect from my local station (windows) to kibana I just need to type in console:

SET AWS_ACCESS_KEY_ID=myAccessKeyId
SET AWS_SECRET_ACCESS_KEY=mySecretAccessKey

aws-es-kibana search-{PROTECTED_PART_OF_YOUR_ELASTICSEARCH_ENDPOINT}.eu-central-1.es.amazonaws.com

After that you should have proxied access to your kibana under: http://127.0.0.1:9200/_plugin/kibana


问:
Java collections vs manual loops - Coding challenges/interview best practices
For coding challenges/interview as well as optimization, is it good to use collections at all? For example, check the palindrome running time for below program

```<code>    import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Palindrome {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        if(isPalindrome(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

        if(isPalindromeUsingSet(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }

    public static boolean isPalindrome(String str) {
        final long startTime = System.nanoTime();
        final long duration;
        for (int i=0;i<str.length()/2;i++) {
            if(str.charAt(i) != str.charAt(str.length() -1 -i)) {
                duration = System.nanoTime() - startTime;
                System.out.println("isPalindrome - " + duration);
                return false;
            }
        }
        duration = System.nanoTime() - startTime;
        System.out.println("isPalindrome - " + duration);

        return true;
    }

    public static boolean isPalindromeUsingSet(String str) {
    final long startTime = System.nanoTime();
    final long duration;
    Set<Character> charSet = new HashSet<>();
    for (int i=0;i<str.length()/2;i++) {
        if(charSet.add(str.charAt(i)) == false) {
            duration = System.nanoTime() - startTime;
            System.out.println("isPalindromeUsingSet - " + duration);
            return false;
        } else {
            charSet.remove(str.charAt(i));
        }
    }
    duration = System.nanoTime() - startTime;
    System.out.println("isPalindromeUsingSet - " + duration);
    return true;
}

}
</code>```

Running Time as calculated is shown below.

```<code>AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES
</code>```

My couple of questions are:

So java collections are mostly safe and versatile in various CRUD
operations, why not use them?

For coding better optimized solutions, should I look for one loop
execution, use a lot of O(1) data structures?

My approach in learning optmization code:

For each coding problem, solve my crude way of java and data
structures.

Go and study the best solution later, calculate time and complexity and adapt in my solutions gradually.

Background:
I've been coding java for couple of years.  Now learning coding for puzzles, algorithms and time complexity for acing bigger interviews!

Any good direction is appreciated.

Thanks

答:
Let's take a look at the HashSet.add implementation:

```<code>public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}
</code>```

Internally, HashSet uses a HashMap.

Now, let's take a look at the HashMap.put method implementation:

```<code>public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}
</code>```

We can notice that puting a registry into the map it's a "hard task", computationally speaking. There is a:

hash algorithm

for loop

add entry method execution

and so on...

So, if execution time it's a concern in your scenario, manual loops it's a better choice than Java Collections.

Now, in terms of readability and maintainability, Collections is the best choice.

Body:
For coding challenges/interview as well as optimization, is it good to use collections at all? For example, check the palindrome running time for below program

    import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Palindrome {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        if(isPalindrome(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

        if(isPalindromeUsingSet(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }

    public static boolean isPalindrome(String str) {
        final long startTime = System.nanoTime();
        final long duration;
        for (int i=0;i<str.length()/2;i++) {
            if(str.charAt(i) != str.charAt(str.length() -1 -i)) {
                duration = System.nanoTime() - startTime;
                System.out.println("isPalindrome - " + duration);
                return false;
            }
        }
        duration = System.nanoTime() - startTime;
        System.out.println("isPalindrome - " + duration);

        return true;
    }

    public static boolean isPalindromeUsingSet(String str) {
    final long startTime = System.nanoTime();
    final long duration;
    Set<Character> charSet = new HashSet<>();
    for (int i=0;i<str.length()/2;i++) {
        if(charSet.add(str.charAt(i)) == false) {
            duration = System.nanoTime() - startTime;
            System.out.println("isPalindromeUsingSet - " + duration);
            return false;
        } else {
            charSet.remove(str.charAt(i));
        }
    }
    duration = System.nanoTime() - startTime;
    System.out.println("isPalindromeUsingSet - " + duration);
    return true;
}

}

Running Time as calculated is shown below.

AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES

My couple of questions are:

So java collections are mostly safe and versatile in various CRUD
operations, why not use them?

For coding better optimized solutions, should I look for one loop
execution, use a lot of O(1) data structures?

My approach in learning optmization code:

For each coding problem, solve my crude way of java and data
structures.

Go and study the best solution later, calculate time and complexity and adapt in my solutions gradually.

Background:
I've been coding java for couple of years.  Now learning coding for puzzles, algorithms and time complexity for acing bigger interviews!

Any good direction is appreciated.

Thanks

Body:
Let's take a look at the HashSet.add implementation:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

Internally, HashSet uses a HashMap.

Now, let's take a look at the HashMap.put method implementation:

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

We can notice that puting a registry into the map it's a "hard task", computationally speaking. There is a:

hash algorithm

for loop

add entry method execution

and so on...

So, if execution time it's a concern in your scenario, manual loops it's a better choice than Java Collections.

Now, in terms of readability and maintainability, Collections is the best choice.


问:
Registration page with PHP & MySQL
I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?</p>

```<code><?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
    registerUser();
}
function registerUser() {
    $query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
    VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
    $run = mysqli_query($query);
    if ($run) {
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['user'] = $_POST['email'];
        header('Location: http://localhost/homepage.php');
    } else {
        echo 'Error';
    }
}
?>
</code>```

答:
mysqli_query need run on connection object or pass connection to it:

```<code>$run = mysqli->query($connection, $query);
</code>```

or

```<code>$run = $connection->query($query);
</code>```

Title: Registration page with PHP & MySQL

Body:
I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?

<?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
    registerUser();
}
function registerUser() {
    $query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
    VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
    $run = mysqli_query($query);
    if ($run) {
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['user'] = $_POST['email'];
        header('Location: http://localhost/homepage.php');
    } else {
        echo 'Error';
    }
}
?>

Body:
mysqli_query need run on connection object or pass connection to it:

$run = mysqli->query($connection, $query);

or

$run = $connection->query($query);


问:
Python rename KML file name wit '(' and ')'
I am trying to rename a few KML files with
1) spaces to _
2) - to _

I am running the script in Arcmap. for the first two it works fine.

But for the ( and ) it's going wrong ?

```<code># Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("(", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(")", "_")))
</code>```

The goals is that I need to import KML files, import them in a Gdb, and then Append them to a excisting layer.

The whole script already works. But I still need to rename the files manually while the gdb will not take in files wit a - minus blancs and ( or ) sign whom are by default in a lot of kml files I have.

Below the whole script that works fine, if i manually rename the - or ( or ) or blanks

```<code># Name: BatchKML_to_GDB.py
# Description: Converts a directory of KMLs and copies the output into a single fGDB.
#              A 2 step process: first convert the KML files, and then copy the featureclases

# Import system models
import arcpy, os

# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

# Set workspace (where all the KMLs are)
arcpy.env.workspace= (r"C:\DATA")

# Set local variables and location for the consolidated file geodatabase
outLocation = "C:\\WorkingData\\fGDBs"
MasterGDB = 'AllKMLLayers.gdb'
MasterGDBLocation = os.path.join(outLocation, MasterGDB)

# Create the master FileGeodatabase
arcpy.CreateFileGDB_management(outLocation, MasterGDB)

# Convert all KMZ and KML files found in the current workspace
for kml in arcpy.ListFiles('*.kml'):
  print "CONVERTING: " + os.path.join(arcpy.env.workspace,kml)
  arcpy.KMLToLayer_conversion(kml, outLocation)

# Change the workspace to fGDB location
arcpy.env.workspace = outLocation

# Loop through all the FileGeodatabases within the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the Master GDB
wks.remove(MasterGDBLocation)

for fgdb in wks:

  # Change the workspace to the current FileGeodatabase
  arcpy.env.workspace = fgdb

  # For every Featureclass inside, copy it to the Master and use the name from the original fGDB
  featureClasses = arcpy.ListFeatureClasses('*', '', 'Placemarks')
  for fc in featureClasses:
    print "COPYING: " + fc + " FROM: " + fgdb
    fcCopy = fgdb + os.sep + 'Placemarks' + os.sep + fc
    arcpy.FeatureClassToFeatureClass_conversion(fcCopy, MasterGDBLocation, fgdb[fgdb.rfind(os.sep)+1:-4])

# Clean up
del kml, wks, fc, featureClasses, fgdb
</code>```

答:
It should be obvious why this doesn't work - once one of your loops has actually renamed a file, the subsequent loops won't be able to find it, because they're still looking for the original name!

You need a SINGLE loop, with all of the .replace() operations chained together so that the file gets renamed directly to its final name.

Body:
I am trying to rename a few KML files with
1) spaces to _
2) - to _

I am running the script in Arcmap. for the first two it works fine.

But for the ( and ) it's going wrong ?

# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("(", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(")", "_")))

The goals is that I need to import KML files, import them in a Gdb, and then Append them to a excisting layer.

The whole script already works. But I still need to rename the files manually while the gdb will not take in files wit a - minus blancs and ( or ) sign whom are by default in a lot of kml files I have.

Below the whole script that works fine, if i manually rename the - or ( or ) or blanks

# Name: BatchKML_to_GDB.py
# Description: Converts a directory of KMLs and copies the output into a single fGDB.
#              A 2 step process: first convert the KML files, and then copy the featureclases

# Import system models
import arcpy, os

# Rename file
path = "C:\\DATA\\"
files = os.listdir(path)

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace(" ", "_")))

for file in files:
  os.rename(os.path.join(path, file), os.path.join(path, file.replace("-", "_")))

# Set workspace (where all the KMLs are)
arcpy.env.workspace= (r"C:\DATA")

# Set local variables and location for the consolidated file geodatabase
outLocation = "C:\\WorkingData\\fGDBs"
MasterGDB = 'AllKMLLayers.gdb'
MasterGDBLocation = os.path.join(outLocation, MasterGDB)

# Create the master FileGeodatabase
arcpy.CreateFileGDB_management(outLocation, MasterGDB)

# Convert all KMZ and KML files found in the current workspace
for kml in arcpy.ListFiles('*.kml'):
  print "CONVERTING: " + os.path.join(arcpy.env.workspace,kml)
  arcpy.KMLToLayer_conversion(kml, outLocation)

# Change the workspace to fGDB location
arcpy.env.workspace = outLocation

# Loop through all the FileGeodatabases within the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the Master GDB
wks.remove(MasterGDBLocation)

for fgdb in wks:

  # Change the workspace to the current FileGeodatabase
  arcpy.env.workspace = fgdb

  # For every Featureclass inside, copy it to the Master and use the name from the original fGDB
  featureClasses = arcpy.ListFeatureClasses('*', '', 'Placemarks')
  for fc in featureClasses:
    print "COPYING: " + fc + " FROM: " + fgdb
    fcCopy = fgdb + os.sep + 'Placemarks' + os.sep + fc
    arcpy.FeatureClassToFeatureClass_conversion(fcCopy, MasterGDBLocation, fgdb[fgdb.rfind(os.sep)+1:-4])

# Clean up
del kml, wks, fc, featureClasses, fgdb


问:
java.lang.ClassCastException: class com.airbnb.kafka.kafka08.StatsdMetricsReporter
Working on setting up a monitoring system for a Kafka cluster using statsd. I'm using the statsd library here. Currently my broker server won't start up.

I am positive my issue lies in this configuration line inside my server.properties file: metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter.

When I comment that line out, the server starts up. Hell, I even get the statsd confirmation like this:

```<code>[2017-06-06 15:19:35,669] INFO Reporter is enabled and starting... (com.airbnb.metrics.StatsDReporter)
[2017-06-06 15:19:35,679] INFO Started Reporter with host=localhost, port=8125, polling_period_secs=10, prefix= (com.airbnb.metrics.StatsDReporter)
</code>```

However, stats aren't reported (I believe) because this is also true: metric.reporters = []. Therefore, that line that's causing the issue must exist in the properties file, right?

When I try to start the server, it fails with this message:

```<code>[2017-06-06 15:21:34,712] FATAL [Kafka Server 0], Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
java.lang.ClassCastException: class com.airbnb.kafka.kafka08.StatsdMetricsReporter
    at java.lang.Class.asSubclass(Class.java:3404)
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:356)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:243)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:198)
    at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:39)
    at kafka.Kafka$.main(Kafka.scala:67)
    at kafka.Kafka.main(Kafka.scala)
[2017-06-06 15:21:34,713] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)
[2017-06-06 15:21:34,714] INFO Terminate ZkClient event thread. (org.I0Itec.zkclient.ZkEventThread)
[2017-06-06 15:21:34,718] INFO Session: 0x15c7ed717e30004 closed (org.apache.zookeeper.ZooKeeper)
[2017-06-06 15:21:34,720] INFO EventThread shut down for session: 0x15c7ed717e30004 (org.apache.zookeeper.ClientCnxn)
[2017-06-06 15:21:34,720] INFO [Kafka Server 0], shut down completed (kafka.server.KafkaServer)
[2017-06-06 15:21:34,720] FATAL Fatal error during KafkaServerStartable startup. Prepare to shutdown (kafka.server.KafkaServerStartable)
java.lang.ClassCastException: class com.airbnb.kafka.kafka08.StatsdMetricsReporter
    at java.lang.Class.asSubclass(Class.java:3404)
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:356)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:243)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:198)
    at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:39)
    at kafka.Kafka$.main(Kafka.scala:67)
    at kafka.Kafka.main(Kafka.scala)
[2017-06-06 15:21:34,721] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)
</code>```

For the record, here is my config:

```<code>kafka:type=com.airbnb.kafka.kafka08.StatsdMetricsReporter
metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter
kafka.metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter
external.kafka.statsd.reporter.enabled=true
external.kafka.statsd.host=localhost
external.kafka.statsd.port=8125
external.kafka.statsd.metrics.prefix=
external.kafka.statsd.tag.enabled=true
</code>```

答: I found the answer. I had to use kafka09 instead of kafka08.

Body:
Working on setting up a monitoring system for a Kafka cluster using statsd. I'm using the statsd library here. Currently my broker server won't start up.

I am positive my issue lies in this configuration line inside my server.properties file: metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter.

When I comment that line out, the server starts up. Hell, I even get the statsd confirmation like this:

[2017-06-06 15:19:35,669] INFO Reporter is enabled and starting... (com.airbnb.metrics.StatsDReporter)
[2017-06-06 15:19:35,679] INFO Started Reporter with host=localhost, port=8125, polling_period_secs=10, prefix= (com.airbnb.metrics.StatsDReporter)

However, stats aren't reported (I believe) because this is also true: metric.reporters = []. Therefore, that line that's causing the issue must exist in the properties file, right?

When I try to start the server, it fails with this message:

[2017-06-06 15:21:34,712] FATAL [Kafka Server 0], Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
java.lang.ClassCastException: class com.airbnb.kafka.kafka08.StatsdMetricsReporter
    at java.lang.Class.asSubclass(Class.java:3404)
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:356)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:243)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:198)
    at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:39)
    at kafka.Kafka$.main(Kafka.scala:67)
    at kafka.Kafka.main(Kafka.scala)
[2017-06-06 15:21:34,713] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)
[2017-06-06 15:21:34,714] INFO Terminate ZkClient event thread. (org.I0Itec.zkclient.ZkEventThread)
[2017-06-06 15:21:34,718] INFO Session: 0x15c7ed717e30004 closed (org.apache.zookeeper.ZooKeeper)
[2017-06-06 15:21:34,720] INFO EventThread shut down for session: 0x15c7ed717e30004 (org.apache.zookeeper.ClientCnxn)
[2017-06-06 15:21:34,720] INFO [Kafka Server 0], shut down completed (kafka.server.KafkaServer)
[2017-06-06 15:21:34,720] FATAL Fatal error during KafkaServerStartable startup. Prepare to shutdown (kafka.server.KafkaServerStartable)
java.lang.ClassCastException: class com.airbnb.kafka.kafka08.StatsdMetricsReporter
    at java.lang.Class.asSubclass(Class.java:3404)
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:356)
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstances(AbstractConfig.java:243)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:198)
    at kafka.server.KafkaServerStartable.startup(KafkaServerStartable.scala:39)
    at kafka.Kafka$.main(Kafka.scala:67)
    at kafka.Kafka.main(Kafka.scala)
[2017-06-06 15:21:34,721] INFO [Kafka Server 0], shutting down (kafka.server.KafkaServer)

For the record, here is my config:

kafka:type=com.airbnb.kafka.kafka08.StatsdMetricsReporter
metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter
kafka.metric.reporters=com.airbnb.kafka.kafka08.StatsdMetricsReporter
external.kafka.statsd.reporter.enabled=true
external.kafka.statsd.host=localhost
external.kafka.statsd.port=8125
external.kafka.statsd.metrics.prefix=
external.kafka.statsd.tag.enabled=true


问:
joomla scheduled task run every second
how can I set a scheduled task that run every second on Joomla website?

I saw different extensions but they make only every minute, like minimum threshold.
Any idea?

答:
Using a Joomla extension is not reliable at all, since someone must visit the actual website for the (fake) cron to run. So, this whole cron thing when it's a Joomla extension really depends on the traffic of your website, which makes it very unreliable especially if you are developing a mission critical functionality.

Your best option is to use a Linux cron, which cannot run every second, as the minimum for a cron to run is every minute. Any solution requiring the use of sleep or a for loop is not reliable - especially when you take into consideration that you want to run something every second. All the solutions on the Internet for running a cron every second (or less than a minute) are half baked and completely unreliable. In short, you cannot run a cron every second reliably.

An imaginary solution is to have 60 servers, each server is behind the other by 1 second, and then you run the cron from each of these servers every minute. It is important that all these servers are on the same network to prevent any lag.

Title: joomla scheduled task run every second


问:
How can I export Eclipse GUI settings?
I've created a new workspace in Eclipse, and it starts at the standard GUI settings (e.g. white, standard font, welcome screen shows up every time Eclipse is opened, etc.). I have another workspace that has all the settings that I like, and I would like to export them and use them in my new workspace. How can I do so?</p>

答:
I dont think Eclipse provides export functionality for UI settings.
Here is what I am doing with my Eclipse workspaces.

1) Create empty workspace and customze it to your liking. Lets call it 'template' workspace.

2) Copy the whole 'template' workspace to another directory, rename it and use it for your project. Next time you need another project with same customization just copy that 'template' workspace and rename according to the other project.

Title: How can I export Eclipse GUI settings?


问:
Excel: Converting a duration (hours, minutes, seconds) to increments of 6 minutes
I have a spreadsheet column with durations of hours, minutes, and seconds.  For example, 0:01:00 is 1 minute.  1:06:28 is 1 hour, 6 minutes, and 28 seconds.

I'm trying to convert this data into increments of 10% of an hour (6 minutes).  So, 0:00:01 (a second) would be converted to 0.1.  0:06:00 (6 minutes) would also be 0.1.  1:12:01 (1 hour, 12 minutes and 1 second) would be 1.3.

Any ideas on how to handle this in Excel (or Google Sheets)?  Thanks very much.

答:
=ROUNDUP(A1*24, 1) won't work in OpenOffice Calc nor in some configurations of Google Sheets and Excel, but

```<code>=ROUNDUP(A1*24;1)
</code>```

will (in OpenOffice Calc and some configurations of Google Sheets and Excel).

Body:
=ROUNDUP(A1*24, 1) won't work in OpenOffice Calc nor in some configurations of Google Sheets and Excel, but

=ROUNDUP(A1*24;1)

will (in OpenOffice Calc and some configurations of Google Sheets and Excel).


问:
PHP MYSQL. How to retrieve the same data from a table based on 2 different ID's in another table
I'm building a website for Airplane Tickets, i have 2 tables, AIRPORTS and AIRPLANES, the AIRPLANES table has 2 columns containing its airport destination id(ID_DESTINATION) and its airport origin id(ID_ORIGIN), what i want to do is to loop all of the AIRPLANES using while with the AIRPORT_NAME as its origin and destination from the AIRPORTS table, how can i do that?

this is the query i'm using :

```<code>SELECT a.ID_PLANE, a.PLANE_NAME,
       a.ID_ORIGIN, a.ID_DESTINATION,
       a.TAKEOFF, a.LANDING, a.PRICE,
       b.ID_AIRPORT, b.AIRPORT_NAME
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS b
ON a.ID_ORIGIN = b.ID_AIRPORT
</code>```

Thanks in advance.

答:
Why dont you just use a sql-join?

http://www.sql-join.com/

Body:
I'm building a website for Airplane Tickets, i have 2 tables, AIRPORTS and AIRPLANES, the AIRPLANES table has 2 columns containing its airport destination id(ID_DESTINATION) and its airport origin id(ID_ORIGIN), what i want to do is to loop all of the AIRPLANES using while with the AIRPORT_NAME as its origin and destination from the AIRPORTS table, how can i do that?

this is the query i'm using :

SELECT a.ID_PLANE, a.PLANE_NAME,
       a.ID_ORIGIN, a.ID_DESTINATION,
       a.TAKEOFF, a.LANDING, a.PRICE,
       b.ID_AIRPORT, b.AIRPORT_NAME
FROM AIRPLANES AS a
LEFT JOIN AIRPORTS AS b
ON a.ID_ORIGIN = b.ID_AIRPORT

Thanks in advance.


问:
SQL query to resolve overlaps based on priority
I am looking at writing a query to resolve overlapping date periods based on a column which stores the priority of that row. That helps me to decide if I need to keep that row or replace it with the other overlapping row. For e.g:

```
<b>FromDate   ToDate    Priority</b>
-----------------------------
1/1/2014   6/30/2014     1    --row1
2/1/2014   7/30/2014     2    --row2```

My results should look like the below

```
<b>FromDate   ToDate     Priority</b>
------------------------------
1/1/2014   6/30/2014     1    --row 1
7/1/2014   7/30/2012     2    --row 2
```

答:
```<code>with temp1 (FromDate,todate, dt, priority) as
(
  SELECT FromDate,todate,fromdate as dt  ,Priority
  FROM mytable
    UNION ALL

  SELECT FromDate,todate ,
dt + 1 day as dt  ,Priority
  FROM temp1
  WHERE dt < todate
)
SELECT min(dt) as fromdate, max(dt) as todate, priority
FROM temp1 a
where priority = (select min(priority) from temp1 where dt =a.dt)
group by priority
</code>```

Body:
I am looking at writing a query to resolve overlapping date periods based on a column which stores the priority of that row. That helps me to decide if I need to keep that row or replace it with the other overlapping row. For e.g:

FromDate   ToDate    Priority
-----------------------------
1/1/2014   6/30/2014     1    --row1
2/1/2014   7/30/2014     2    --row2

My results should look like the below

FromDate   ToDate     Priority
------------------------------
1/1/2014   6/30/2014     1    --row 1
7/1/2014   7/30/2012     2    --row 2


问:
Swift Progress View animation makes the bar go further than 100%
When using animations for the ProgressView, it works completely fine if I let the animation run out but if I try to run this code again while the animation is still going, it will add 100% to the current bar and make it go through the bar. Images should explain the situation in a more logical sense.

Progress starts at 1.0 (100%):

Progress is half-way through:

The code was ran again, resulting in the progress going above 100%, although it uses the correct amount of time to finish.

Here's the code used:

```<code>self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  UIView.animate(withDuration: 10, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { [unowned self] in
    self.progressView.setProgress(0, animated: true)
  })
}
</code>```

Thanks in advance!

答:
The setProgress(_:animated:) method already handles the animation for you. When the animated parameter is set to true, the progress change will be animated.

Try without the animation block :

```<code>self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    self.progressView.setProgress(0.0, animated: true)
}
</code>```

Also make sure this is not an autolayout issue. Check your constraints on the progress view and make sure its width is properly constrained.

ContentLicense: CC BY-SA 4.0

Body:
When using animations for the ProgressView, it works completely fine if I let the animation run out but if I try to run this code again while the animation is still going, it will add 100% to the current bar and make it go through the bar. Images should explain the situation in a more logical sense.

Progress starts at 1.0 (100%):

Progress is half-way through:

The code was ran again, resulting in the progress going above 100%, although it uses the correct amount of time to finish.

Here's the code used:

self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  UIView.animate(withDuration: 10, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { [unowned self] in
    self.progressView.setProgress(0, animated: true)
  })
}

Thanks in advance!

Body:
The setProgress(_:animated:) method already handles the animation for you. When the animated parameter is set to true, the progress change will be animated.

Try without the animation block :

self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    self.progressView.setProgress(0.0, animated: true)
}

Also make sure this is not an autolayout issue. Check your constraints on the progress view and make sure its width is properly constrained.


问:
Scrolling on VBox with lots of Textfields
I am having lots of Textfields in VBox in a Scrollpane. When scrolling and touching a textfields it just grabs the focus. So smooth scrolling is not possible. How can I get it nice scrolling without the unwanted focus on any textfield.  Do I need to consume the events on the textfield while scrolling?</p>

答:
Here is a class which I use for the purpose you describe:

```<code>public class MouseClickedFilter{

    private final Node                       observableNode;

    private BooleanProperty                  scrolling          = new ReadOnlyBooleanWrapper(false);

    private EventHandler<? super MouseEvent> dragDetectedFilter = e -> scrolling.set(true);
    private EventHandler<? super MouseEvent> mouseExitedHandler = e -> scrolling.set(false);

    private EventHandler<? super MouseEvent> mouseClickedFilter = evt ->
                                                                    {
                                                                        if (scrolling.get()) {
                                                                            evt.consume();
                                                                            scrolling.set(false);
                                                                        }
                                                                    };

    private boolean                          listenersEnabled;

    public MouseClickedFilter(Node observableNode) {
        this.observableNode = observableNode;
    }

    public void activate() {
        if (!listenersEnabled) {
            observableNode.addEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
            observableNode.addEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
            observableNode.addEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
        }
    }

    public void deactivate() {
        if (listenersEnabled) {
            observableNode.removeEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
            observableNode.removeEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
            observableNode.removeEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
        }
    }

    public final ReadOnlyBooleanProperty scrollingProperty() {
        return scrolling;
    }

    public final boolean isScrolling() {
        return scrolling.get();
    }

}
</code>```

ObservableNode is your ScrollPane containing the textFields

Body:
Here is a class which I use for the purpose you describe:

public class MouseClickedFilter{

    private final Node                       observableNode;

    private BooleanProperty                  scrolling          = new ReadOnlyBooleanWrapper(false);

    private EventHandler<? super MouseEvent> dragDetectedFilter = e -> scrolling.set(true);
    private EventHandler<? super MouseEvent> mouseExitedHandler = e -> scrolling.set(false);

    private EventHandler<? super MouseEvent> mouseClickedFilter = evt ->
                                                                    {
                                                                        if (scrolling.get()) {
                                                                            evt.consume();
                                                                            scrolling.set(false);
                                                                        }
                                                                    };

    private boolean                          listenersEnabled;

    public MouseClickedFilter(Node observableNode) {
        this.observableNode = observableNode;
    }

    public void activate() {
        if (!listenersEnabled) {
            observableNode.addEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
            observableNode.addEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
            observableNode.addEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
        }
    }

    public void deactivate() {
        if (listenersEnabled) {
            observableNode.removeEventFilter(MouseEvent.DRAG_DETECTED, dragDetectedFilter);
            observableNode.removeEventHandler(MouseEvent.MOUSE_EXITED, mouseExitedHandler);
            observableNode.removeEventFilter(MouseEvent.MOUSE_CLICKED, mouseClickedFilter);
        }
    }

    public final ReadOnlyBooleanProperty scrollingProperty() {
        return scrolling;
    }

    public final boolean isScrolling() {
        return scrolling.get();
    }

}

ObservableNode is your ScrollPane containing the textFields


问:
Read XML file while it is being written (in Python)
I have to monitor an XML file being written by a tool running all the day. But the XML file is properly completed and closed only at the end of the day.

Same constraints as XML stream processing:

Parse an incomplete XML file on-the-fly and trigger actions

Keep track of the last position within the file to avoid processing it again from the beginning

On answer of Need to read XML files as a stream using BeautifulSoup in Python, slezica suggests xml.sax, xml.etree.ElementTree and cElementTree. But no success with my attempts to use xml.etree.ElementTree and cElementTree. There are also xml.dom, xml.parsers.expat and lxml but I do not see support for "on-the-fly parsing".

I need more obvious examples...

I am currently using Python 2.7 on Linux, but I will migrate to Python 3.x => please also provide tips on new Python 3.x features. I also use watchdog to detect XML file modifications => Optionally, reuse the watchdog mechanism. Optionally support also Windows.

Please provide easy to understand/maintain solutions. If it is too complex, I may just use tell()/seek() to move within the file, use stupid text search in the raw XML and finally extract the values using basic regex.

XML sample:

```<code><dfxml xmloutputversion='1.0'>
   <creator version='1.0'>
     <program>TCPFLOW</program>
     <version>1.4.6</version>
   </creator>
   <configuration>
     <fileobject>
       <filename>file1</filename>
       <filesize>288</filesize>
       <tcpflow packets='12' srcport='1111' dstport='2222' family='2' />
     </fileobject>
     <fileobject>
       <filename>file2</filename>
       <filesize>352</filesize>
       <tcpflow packets='12' srcport='3333' dstport='4444' family='2' />
     </fileobject>
     <fileobject>
       <filename>file3</filename>
       <filesize>456</filesize>
       ...
       ...
</code>```

First test using SAX failed:

```<code>import xml.sax

class StreamHandler(xml.sax.handler.ContentHandler):
    def startElement(self, name, attrs):
        print 'start: name=', name
    def endElement(self, name):
        print 'end:   name=', name
        if name == 'root':
            raise StopIteration

if __name__ == '__main__':
    parser = xml.sax.make_parser()
    parser.setContentHandler(StreamHandler())
    with open('f.xml') as f:
        parser.parse(f)
</code>```

Shell:

```<code>$ while read line; do echo $line; sleep 1; done <i.xml >f.xml &
...
$ ./test-using-sax.py
start: name= dfxml
start: name= creator
start: name= program
end:   name= program
start: name= version
end:   name= version
Traceback (most recent call last):
  File "./test-using-sax.py", line 17, in <module>
    parser.parse(f)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib64/python2.7/xml/sax/xmlreader.py", line 125, in parse
    self.close()
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 220, in close
    self.feed("", isFinal = 1)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 214, in feed
    self._err_handler.fatalError(exc)
  File "/usr/lib64/python2.7/xml/sax/handler.py", line 38, in fatalError
    raise exception
xml.sax._exceptions.SAXParseException: report.xml:15:0: no element found
</code>```

答:
Three hours after posting my question, no answer received. But I have finally implemented the simple example I was looking for.

My inspiration is from saaj's answer and is based on xml.sax and watchdog.

```<code>from __future__ import print_function, division
import time
import watchdog.events
import watchdog.observers
import xml.sax

class XmlStreamHandler(xml.sax.handler.ContentHandler):
  def startElement(self, tag, attributes):
    print(tag, 'attributes=', attributes.items())
    self.tag = tag
  def characters(self, content):
    print(self.tag, 'content=', content)

class XmlFileEventHandler(watchdog.events.PatternMatchingEventHandler):
  def __init__(self):
    watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.xml'])
    self.file = None
    self.parser = xml.sax.make_parser()
    self.parser.setContentHandler(XmlStreamHandler())
  def on_modified(self, event):
    if not self.file:
      self.file = open(event.src_path)
    self.parser.feed(self.file.read())

if __name__ == '__main__':
  observer = watchdog.observers.Observer()
  event_handler = XmlFileEventHandler()
  observer.schedule(event_handler, path='.')
  try:
    observer.start()
    while True:
      time.sleep(10)
  finally:
    observer.stop()
    observer.join()
</code>```

While the script is running, do not forget to touch one XML file, or simulate the on-the-fly writing using the following command:

```<code>while read line; do echo $line; sleep 1; done <in.xml >out.xml &
</code>```

Body:
I have to monitor an XML file being written by a tool running all the day. But the XML file is properly completed and closed only at the end of the day.

Same constraints as XML stream processing:

Parse an incomplete XML file on-the-fly and trigger actions

Keep track of the last position within the file to avoid processing it again from the beginning

On answer of Need to read XML files as a stream using BeautifulSoup in Python, slezica suggests xml.sax, xml.etree.ElementTree and cElementTree. But no success with my attempts to use xml.etree.ElementTree and cElementTree. There are also xml.dom, xml.parsers.expat and lxml but I do not see support for "on-the-fly parsing".

I need more obvious examples...

I am currently using Python 2.7 on Linux, but I will migrate to Python 3.x => please also provide tips on new Python 3.x features. I also use watchdog to detect XML file modifications => Optionally, reuse the watchdog mechanism. Optionally support also Windows.

Please provide easy to understand/maintain solutions. If it is too complex, I may just use tell()/seek() to move within the file, use stupid text search in the raw XML and finally extract the values using basic regex.

XML sample:

<dfxml xmloutputversion='1.0'>
   <creator version='1.0'>
     <program>TCPFLOW</program>
     <version>1.4.6</version>
   </creator>
   <configuration>
     <fileobject>
       <filename>file1</filename>
       <filesize>288</filesize>
       <tcpflow packets='12' srcport='1111' dstport='2222' family='2' />
     </fileobject>
     <fileobject>
       <filename>file2</filename>
       <filesize>352</filesize>
       <tcpflow packets='12' srcport='3333' dstport='4444' family='2' />
     </fileobject>
     <fileobject>
       <filename>file3</filename>
       <filesize>456</filesize>
       ...
       ...

First test using SAX failed:

import xml.sax

class StreamHandler(xml.sax.handler.ContentHandler):
    def startElement(self, name, attrs):
        print 'start: name=', name
    def endElement(self, name):
        print 'end:   name=', name
        if name == 'root':
            raise StopIteration

if __name__ == '__main__':
    parser = xml.sax.make_parser()
    parser.setContentHandler(StreamHandler())
    with open('f.xml') as f:
        parser.parse(f)

Shell:

$ while read line; do echo $line; sleep 1; done f.xml &
...
$ ./test-using-sax.py
start: name= dfxml
start: name= creator
start: name= program
end:   name= program
start: name= version
end:   name= version
Traceback (most recent call last):
  File "./test-using-sax.py", line 17, in <module>
    parser.parse(f)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib64/python2.7/xml/sax/xmlreader.py", line 125, in parse
    self.close()
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 220, in close
    self.feed("", isFinal = 1)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 214, in feed
    self._err_handler.fatalError(exc)
  File "/usr/lib64/python2.7/xml/sax/handler.py", line 38, in fatalError
    raise exception
xml.sax._exceptions.SAXParseException: report.xml:15:0: no element found

Body:
Three hours after posting my question, no answer received. But I have finally implemented the simple example I was looking for.

My inspiration is from saaj's answer and is based on xml.sax and watchdog.

from __future__ import print_function, division
import time
import watchdog.events
import watchdog.observers
import xml.sax

class XmlStreamHandler(xml.sax.handler.ContentHandler):
  def startElement(self, tag, attributes):
    print(tag, 'attributes=', attributes.items())
    self.tag = tag
  def characters(self, content):
    print(self.tag, 'content=', content)

class XmlFileEventHandler(watchdog.events.PatternMatchingEventHandler):
  def __init__(self):
    watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.xml'])
    self.file = None
    self.parser = xml.sax.make_parser()
    self.parser.setContentHandler(XmlStreamHandler())
  def on_modified(self, event):
    if not self.file:
      self.file = open(event.src_path)
    self.parser.feed(self.file.read())

if __name__ == '__main__':
  observer = watchdog.observers.Observer()
  event_handler = XmlFileEventHandler()
  observer.schedule(event_handler, path='.')
  try:
    observer.start()
    while True:
      time.sleep(10)
  finally:
    observer.stop()
    observer.join()

While the script is running, do not forget to touch one XML file, or simulate the on-the-fly writing using the following command:

while read line; do echo $line; sleep 1; done <in.xml >out.xml &


答: Open the workspace from which you want to copy settings. File -> Switch Workspace -> Other and expand Copy Settings check Workbench Layout. See whether this copies the settings that you want by choosing your workspace.

Title: How can I export Eclipse GUI settings?

Body: I've created a new workspace in Eclipse, and it starts at the standard GUI settings (e.g. white, standard font, welcome screen shows up every time Eclipse is opened, etc.). I have another workspace that has all the settings that I like, and I would like to export them and use them in my new workspace. How can I do so?


问:
C++ delete vector, objects, free memory
I am totally confused with regards to deleting things in C++. If I declare an array of objects and if I use the clear() member function. Can I be sure that the memory was released?

For example :

```<code>tempObject obj1;
tempObject obj2;
vector<tempObject> tempVector;

tempVector.pushback(obj1);
tempVector.pushback(obj2);
</code>```

Can I safely call clear to free up all the memory? Or do I need to iterate through to delete one by one?

```<code>tempVector.clear();
</code>```

If this scenario is changed to a pointer of objects, will the answer be the same as above?

```<code>vector<tempObject> *tempVector;
//push objects....
tempVector->clear();
</code>```

答:
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

```<code>my_arr.resize()
</code>```

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time.
Hope this helped.
Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.

Title: C++ delete vector, objects, free memory

Body:
I am totally confused with regards to deleting things in C++. If I declare an array of objects and if I use the clear() member function. Can I be sure that the memory was released?

For example :

tempObject obj1;
tempObject obj2;
vector<tempObject> tempVector;

tempVector.pushback(obj1);
tempVector.pushback(obj2);

Can I safely call clear to free up all the memory? Or do I need to iterate through to delete one by one?

tempVector.clear();

If this scenario is changed to a pointer of objects, will the answer be the same as above?

vector<tempObject> *tempVector;
//push objects....
tempVector->clear();

Body:
If you need to use the vector over and over again and your current code declares it repeatedly within your loop or on every function call, it is likely that you will run out of memory. I suggest that you declare it outside, pass them as pointers in your functions and use:

my_arr.resize()

This way, you keep using the same memory sequence for your vectors instead of requesting for new sequences every time.
Hope this helped.
Note: resizing it to different sizes may add random values. Pass an integer such as 0 to initialise them, if required.


问:
How to set selected row in ASP.NET GridView based on DataKey?
I want something similar to the following pseudocode:

```<code>myGridView.SelectedIndex = myGridView.DataKeys.IndexOf("mySpecificKey");
</code>```

I've done some Intellisense exploring, but I haven't found an obvious way to do this.  I would want to set SelectedIndex to -1 if DataKey was not found.

答:
Put something like this in your GridView_RowDataBound() event:

```<code>Dim p As Catalog.Product = CType(e.Row.DataItem, Catalog.Product)
If p IsNot Nothing Then

    If p.Bvin = MySpecificID Then
        e.Row.RowState = DataControlRowState.Selected
    End If

End If
</code>```

In this example, we are binding the GridView to a collection of custom objects of type Catalog.Product and the DataKey is named Bvin - you will need to adjust the datatype and key name depending on what you are binding to.

Note this event runs once per row already, so there is no need to loop. However, care should be taken to prevent things like data access from occurring more than once.

OwnerDisplayName: DLarsen

Body:
I want something similar to the following pseudocode:

myGridView.SelectedIndex = myGridView.DataKeys.IndexOf("mySpecificKey");

I've done some Intellisense exploring, but I haven't found an obvious way to do this.  I would want to set SelectedIndex to -1 if DataKey was not found.

Body:
Put something like this in your GridView_RowDataBound() event:

Dim p As Catalog.Product = CType(e.Row.DataItem, Catalog.Product)
If p IsNot Nothing Then

    If p.Bvin = MySpecificID Then
        e.Row.RowState = DataControlRowState.Selected
    End If

End If

In this example, we are binding the GridView to a collection of custom objects of type Catalog.Product and the DataKey is named Bvin - you will need to adjust the datatype and key name depending on what you are binding to.

Note this event runs once per row already, so there is no need to loop. However, care should be taken to prevent things like data access from occurring more than once.


问:
How to set FireMonkey form icon runtime in Delphi 10.2
I'm creating an application for Windows and OS X using Firemonkey Framework with Delphi 10.2 Tokyo and can't set application or form icon dynamically.

In VCL project I've used following code:

```<code>Form1.Icon.LoadFromFile()
</code>```

or

```<code>Application.Icon.LoadFromFile()
</code>```

But there are no such properties or methods in FMX. Is there any way to set project icon otherwise than in Project -> Options menu?

答:
Add to your uses list {$IFDEF WIN32}WinApi.Windows,FMX.Platform.Win,{$ENDIF}

```<code>procedure setFormIcon(Form: TForm; FileName: String);
  var Icon : NativeUInt;
begin
  {$IFDEF WIN32}
  ICON := LoadImage(0,PWideChar(Filename),IMAGE_ICON,0,0,LR_LOADFROMFILE OR LR_DEFAULTSIZE OR LR_SHARED);
  SetClassLong(FmxHandleToHWND(Form.Handle), GCL_HICON, icon);
  {$ENDIF}
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  setFormIcon(Form1,'my icon path.ico');
end;
</code>```

Body:
I'm creating an application for Windows and OS X using Firemonkey Framework with Delphi 10.2 Tokyo and can't set application or form icon dynamically.

In VCL project I've used following code:

Form1.Icon.LoadFromFile()

or

Application.Icon.LoadFromFile()

But there are no such properties or methods in FMX. Is there any way to set project icon otherwise than in Project -> Options menu?

Body:
Add to your uses list {$IFDEF WIN32}WinApi.Windows,FMX.Platform.Win,{$ENDIF}

procedure setFormIcon(Form: TForm; FileName: String);
  var Icon : NativeUInt;
begin
  {$IFDEF WIN32}
  ICON := LoadImage(0,PWideChar(Filename),IMAGE_ICON,0,0,LR_LOADFROMFILE OR LR_DEFAULTSIZE OR LR_SHARED);
  SetClassLong(FmxHandleToHWND(Form.Handle), GCL_HICON, icon);
  {$ENDIF}
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  setFormIcon(Form1,'my icon path.ico');
end;


问:
How to visualize steps of a scalding job
My scalding job is translated into 9 map reduce jobs (m/r jobs). It's not easy for me to understand which part of code each m/r job represents. Is there anything that could help me understand my job better?

//this has been copy&pasted from our internal wiki at Tapad. Feel free to share your experience!

答:
Scalding can generate a job graph in .dot format. It's triggered by this code. Here are the steps:

```<code>sbt
project mapreduce

run-main com.twitter.scalding.Tool com.company.YourJobClass \
  --tool.graph \
  --hdfs
  --arg1 value_1
  --arg2 value_2
</code>```

You should have 2 files generated ending with .dot. They are text files. One is very detailed graph of all Cascading functions used by your job. The other file that ends with _steps.dot is a graph of m/r jobs. Open them in your favorite editor and try to find nodes and their connections.

It's possible to generate pdf or png files from .dot using graphviz. Here are the steps:

```<code>#if you don't have graphviz installed you can get it from brew on mac
brew install graphviz

#generate a pdf file
dot myjob_steps.dot -Tpdf myjob_steps.pdf

#generate a png file (could be huge!)
dot myjob_steps.dot -Tpng myjob_steps.png
</code>```

Bonus tip: it could be still hard to figure out where each m/r job is in your code. Adding descriptions to your code will add them to the myjob_steps.dot file. Experiment with this function and regenerate the .dot file. This is where generating a .pdf file is not necessary. You can just open myjob_steps.dot in your favorite editor and use search to find descriptions you put to markup the code. You can find examples in the scalding repo.

Body:
Scalding can generate a job graph in .dot format. It's triggered by this code. Here are the steps:

sbt
project mapreduce

run-main com.twitter.scalding.Tool com.company.YourJobClass \
  --tool.graph \
  --hdfs
  --arg1 value_1
  --arg2 value_2

You should have 2 files generated ending with .dot. They are text files. One is very detailed graph of all Cascading functions used by your job. The other file that ends with _steps.dot is a graph of m/r jobs. Open them in your favorite editor and try to find nodes and their connections.

It's possible to generate pdf or png files from .dot using graphviz. Here are the steps:

#if you don't have graphviz installed you can get it from brew on mac
brew install graphviz

#generate a pdf file
dot myjob_steps.dot -Tpdf myjob_steps.pdf

#generate a png file (could be huge!)
dot myjob_steps.dot -Tpng myjob_steps.png

Bonus tip: it could be still hard to figure out where each m/r job is in your code. Adding descriptions to your code will add them to the myjob_steps.dot file. Experiment with this function and regenerate the .dot file. This is where generating a .pdf file is not necessary. You can just open myjob_steps.dot in your favorite editor and use search to find descriptions you put to markup the code. You can find examples in the scalding repo.


答:
Doesn't general preferences hold GUI Settings?

If so,

File > Export, General > Preferences, export all and then select where to save.

Then import as usual

Title: How can I export Eclipse GUI settings?


问:
simple way to identify the user is having the account in Gmail?
Do any one say which is the simple way to identify the user is having the account in Gmail ?</p>

答: Why don't you ask the user to sign in with their email address and see for yourself if it's a gmail account?</p>


问:
Wordpress get plugin directory
Is there any function that would return the full path of my plugin in WordPress?

Example is

```<code>path/wp-contents/plugins/myplugin
</code>```

I have tried plugin_dir_path(__FILE__) but returns the current dir.

答:
Here is a solution, when you are not inside the plugin root:

As of now with 4.7.5, WordPress does not have a get_plugins_root() function like there is a get_theme_root() function. This is probably because you really shouldn't ever need to modify plugins from your theme, and the plugins root directory never changes.

However, it can be useful if you need to programmatically affect plug-ins while developing themes.

Simply, as WP does for the theme root:

```<code>$plugin_root = WP_CONTENT_DIR . '/plugins';
</code>```

Or, if you need a function, why not just do it the same way WordPress does it for the theme root?

Just make a copy of the function get_theme_root() from wp-includes/theme.php and paste it into your theme's functions.php file, rename the function to get_plugins_root(), simplify it, and change 'theme' to 'plugins' in the function...

```<code>get_plugins_root() {

    $plugins_root = WP_CONTENT_DIR . '/plugins';

    /**
     * Filters the absolute path to the plugins directory.
     *
     * @since now
     *
     * @param string $plugins_root Absolute path to plugins directory.
     */
    return apply_filters( 'plugins_root', $plugins_root );
}
</code>```

With the path, you can now add the plug-ins folder name that you wish to affect.

```<code>$the_plugin_root = get_plugins_root()."/the-plugin-name/";
</code>```

Title: Wordpress get plugin directory

Body:
Is there any function that would return the full path of my plugin in WordPress?

Example is

path/wp-contents/plugins/myplugin

I have tried plugin_dir_path(__FILE__) but returns the current dir.

Body:
Here is a solution, when you are not inside the plugin root:

As of now with 4.7.5, WordPress does not have a get_plugins_root() function like there is a get_theme_root() function. This is probably because you really shouldn't ever need to modify plugins from your theme, and the plugins root directory never changes.

However, it can be useful if you need to programmatically affect plug-ins while developing themes.

Simply, as WP does for the theme root:

$plugin_root = WP_CONTENT_DIR . '/plugins';

Or, if you need a function, why not just do it the same way WordPress does it for the theme root?

Just make a copy of the function get_theme_root() from wp-includes/theme.php and paste it into your theme's functions.php file, rename the function to get_plugins_root(), simplify it, and change 'theme' to 'plugins' in the function...

get_plugins_root() {

    $plugins_root = WP_CONTENT_DIR . '/plugins';

    /**
     * Filters the absolute path to the plugins directory.
     *
     * @since now
     *
     * @param string $plugins_root Absolute path to plugins directory.
     */
    return apply_filters( 'plugins_root', $plugins_root );
}

With the path, you can now add the plug-ins folder name that you wish to affect.

$the_plugin_root = get_plugins_root()."/the-plugin-name/";