问:
symfony Oops! An Error Occurred The server returned a "404 Not Found" on production
Be patience I'm brand new at symfony framework
if I run:

php app/console server:run

it works fine

if I go to:

http://myproject.com/app_dev.php

it works fine

if I go to:

http://myproject.com

I got that error

my project.conf

```<code><VirtualHost *:80>
    ServerName myproject.com
    ServerAlias www.myproject.com

    DocumentRoot /home/whisher/public_html/myproject/web
    <Directory /home/whisher/public_html/myproject/web>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>
</code>```

Can you help me, please ?

.htaccess

```<code># Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>
</code>```

答:
In my case it was a file ownership and permissions problem with the "cache" "logs" and "sessions" directories when installing symfony in a user public_html directory. I solved it with the following commands

```<code>$ chmod g+w myproject/var
$ rm –rf myproject/var/cache
$ rm –rf myproject/var/logs
$ rm –rf myproject/var/sessions
$ ls -ld myproject/var
drwxrwx--- 5 whisher www-data 4096 Feb 16 16:35 var/
</code>```

Now symfony was able to create the directories with the correct permissions and ownership.

Body:
Be patience I'm brand new at symfony framework
if I run:

php app/console server:run

it works fine

if I go to:

http://myproject.com/app_dev.php

it works fine

if I go to:

http://myproject.com

I got that error

my project.conf

<VirtualHost *:80>
    ServerName myproject.com
    ServerAlias www.myproject.com

    DocumentRoot /home/whisher/public_html/myproject/web
    <Directory /home/whisher/public_html/myproject/web>
        # enable the .htaccess rewrites
        AllowOverride All
        Order allow,deny
        Allow from All
    </Directory>

    ErrorLog /var/log/apache2/project_error.log
    CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>

Can you help me, please ?

.htaccess

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the app.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/app.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/app.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 302 ^/$ /app.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

Body:
In my case it was a file ownership and permissions problem with the "cache" "logs" and "sessions" directories when installing symfony in a user public_html directory. I solved it with the following commands

$ chmod g+w myproject/var
$ rm –rf myproject/var/cache
$ rm –rf myproject/var/logs
$ rm –rf myproject/var/sessions
$ ls -ld myproject/var
drwxrwx--- 5 whisher www-data 4096 Feb 16 16:35 var/

Now symfony was able to create the directories with the correct permissions and ownership.


来源: stackexchange

问:
POST Request (array ) in Oracle APEX
I have an array in json, I want to write it in the oracle method post.But I have somewhere the error I can not find it.
I try to write it all in a loop, the code compiles but does not write. The first thing I do is look for the first object using a loop. And then I use another loop in the middle of the object to record the data inside it!

```<code>    v_clob := iot_general.blob_to_clob(p_blob);
    apex_json.parse(tv, v_clob);
    sCount := APEX_JSON.get_count(p_path => 'GroupSensor' , p_values => tv);
    IF sCount > 0 THEN
      FOR i in 1 .. sCount LOOP
      v_id := apex_json.get_varchar2(p_path => 'GroupSensor.SerialNumber['|| i ||']', p_values => tv);
                  cCount := APEX_JSON.get_count(p_path => 'GroupSensor.GroupBob['|| i ||']' , p_values => tv);
                  IF cCount > 0 THEN
                              FOR q in 1 .. cCount LOOP
                              q_temp   := apex_json.get_varchar2(p_path => 'GroupSensor.GroupBob['|| i ||']['|| q ||']', p_values => tv);
                                INSERT INTO SILO_SENSOR( NAME,  DEVICES_ID)
                                VALUES (q_temp,v_id  );
                                commit;
                                END LOOP;
                 END IF;
      END LOOP;
    END IF;
</code>```

Here is my json

```<code> {
  "GroupSensor": [
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0001",
        "SENSOR0002",
        "SENSOR0003",
        "SENSOR0004",
        "SENSOR0005",
        "SENSOR0006",
        "SENSOR0007",
        "SENSOR0008",
        "SENSOR0009",
        "SENSOR0010"
      ],
      "SerialNumber": "1701"
    },
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0011",
        "SENSOR0012",
        "SENSOR0013",
        "SENSOR0014",
        "SENSOR0015",
        "SENSOR0016",
        "SENSOR0017",
        "SENSOR0018",
        "SENSOR0019"
      ],
      "SerialNumber": "1702"
    },
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0020",
        "SENSOR0021",
        "SENSOR0022",
        "SENSOR0023",
        "SENSOR0024",
        "SENSOR0025",
        "SENSOR0026",
        "SENSOR0027",
        "SENSOR0028"
      ],
      "SerialNumber": "1703"
    }
]
</code>```

}

I want to write the data to the SILO_SENSOR table, that's it

```<code>NAME            DEVICES_ID
SENSOR0001      1701
SENSOR0002      1701
SENSOR0003      1701
SENSOR0004      1701
SENSOR0005      1701
SENSOR0006      1701
SENSOR0007      1701
SENSOR0008      1701
SENSOR0009      1701
SENSOR0010      1701
</code>```

答:
Given this table:

```<code>create table silo_sensor (
  name      varchar2(255),
  devices_id varchar2(255)
);
</code>```

The following should work:

```<code>declare

  tv     apex_json.t_values;
  v_clob clob;
  scount number;
  ccount number;
  q_temp varchar2(255);
  v_id   varchar2(255);

begin

  v_clob := q'-
    {
      "GroupSensor": [
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0001",
            "SENSOR0002",
            "SENSOR0003",
            "SENSOR0004",
            "SENSOR0005",
            "SENSOR0006",
            "SENSOR0007",
            "SENSOR0008",
            "SENSOR0009",
            "SENSOR0010"
          ],
          "SerialNumber": "1701"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0011",
            "SENSOR0012",
            "SENSOR0013",
            "SENSOR0014",
            "SENSOR0015",
            "SENSOR0016",
            "SENSOR0017",
            "SENSOR0018",
            "SENSOR0019"
          ],
          "SerialNumber": "1702"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0020",
            "SENSOR0021",
            "SENSOR0022",
            "SENSOR0023",
            "SENSOR0024",
            "SENSOR0025",
            "SENSOR0026",
            "SENSOR0027",
            "SENSOR0028"
          ],
          "SerialNumber": "1703"
        }
      ]
    }
  -';

  apex_json.parse(tv, v_clob);

  sCount := APEX_JSON.get_count(p_path => 'GroupSensor' , p_values => tv);

  for i in 1 .. sCount loop
    v_id := apex_json.get_varchar2(p_path => 'GroupSensor[%d].SerialNumber', p_values => tv, p0 => i);

    cCount := APEX_JSON.get_count(p_path => 'GroupSensor[%d].GroupBob' , p_values => tv, p0 => i);

    for q in 1 .. cCount loop
      q_temp := apex_json.get_varchar2(p_path => 'GroupSensor[%d].GroupBob[%d]', p_values => tv, p0 => i, p1 => q);
      insert into silo_sensor(name, devices_id)
      values (q_temp, v_id);
    end loop;
  end loop;

  commit;

end;
</code>```

A couple of things to note:

You don't need the IF sCount > 0 THEN or IF cCount > 0 THEN checks. Just go into the loop, if the count is 0 then you will not go into it. The only reason you might need the if check is if it's possible the property will not exist. In that case, your check should be if sCount is not null because get_varchar2 will return null if the property doesn't exist.

Don't commit inside of a loop. If you get an error while looping, you'll have committed part of the transaction and it will be more difficult to fix. Either commit at the end or not at all (let the caller commit when they want).

Because you're running on 18c, you could use the built in PL/SQL types for JSON. These should perform better than APEX_JSON.

```<code>declare

  top_obj json_object_t;
  gs_arr  json_array_t;
  gs_obj  json_object_t;
  gb_arr  json_array_t;
  v_clob  clob;
  q_temp  varchar2(255);
  v_id    varchar2(255);

begin

  v_clob := q'-
    {
      "GroupSensor": [
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0001",
            "SENSOR0002",
            "SENSOR0003",
            "SENSOR0004",
            "SENSOR0005",
            "SENSOR0006",
            "SENSOR0007",
            "SENSOR0008",
            "SENSOR0009",
            "SENSOR0010"
          ],
          "SerialNumber": "1701"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0011",
            "SENSOR0012",
            "SENSOR0013",
            "SENSOR0014",
            "SENSOR0015",
            "SENSOR0016",
            "SENSOR0017",
            "SENSOR0018",
            "SENSOR0019"
          ],
          "SerialNumber": "1702"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0020",
            "SENSOR0021",
            "SENSOR0022",
            "SENSOR0023",
            "SENSOR0024",
            "SENSOR0025",
            "SENSOR0026",
            "SENSOR0027",
            "SENSOR0028"
          ],
          "SerialNumber": "1703"
        }
      ]
    }
  -';

  top_obj := json_object_t.parse(v_clob);
  gs_arr := top_obj.get_array('GroupSensor');

  for i in 0 .. gs_arr.get_size - 1 loop
    gs_obj := json_object_t(gs_arr.get(i));
    v_id := gs_obj.get_string('SerialNumber');
    gb_arr := gs_obj.get_array('GroupBob');

    for q in 0 .. gb_arr.get_size - 1 loop
      q_temp := gb_arr.get_string(i);
      insert into silo_sensor(name, devices_id)
      values (q_temp, v_id);
    end loop;
  end loop;

  commit;

end;
</code>```

ContentLicense: CC BY-SA 4.0

Title: POST Request (array ) in Oracle APEX

Body:
I have an array in json, I want to write it in the oracle method post.But I have somewhere the error I can not find it.
I try to write it all in a loop, the code compiles but does not write. The first thing I do is look for the first object using a loop. And then I use another loop in the middle of the object to record the data inside it!

    v_clob := iot_general.blob_to_clob(p_blob);
    apex_json.parse(tv, v_clob);
    sCount := APEX_JSON.get_count(p_path => 'GroupSensor' , p_values => tv);
    IF sCount > 0 THEN
      FOR i in 1 .. sCount LOOP
      v_id := apex_json.get_varchar2(p_path => 'GroupSensor.SerialNumber['|| i ||']', p_values => tv);
                  cCount := APEX_JSON.get_count(p_path => 'GroupSensor.GroupBob['|| i ||']' , p_values => tv);
                  IF cCount > 0 THEN
                              FOR q in 1 .. cCount LOOP
                              q_temp   := apex_json.get_varchar2(p_path => 'GroupSensor.GroupBob['|| i ||']['|| q ||']', p_values => tv);
                                INSERT INTO SILO_SENSOR( NAME,  DEVICES_ID)
                                VALUES (q_temp,v_id  );
                                commit;
                                END LOOP;
                 END IF;
      END LOOP;
    END IF;

Here is my json

 {
  "GroupSensor": [
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0001",
        "SENSOR0002",
        "SENSOR0003",
        "SENSOR0004",
        "SENSOR0005",
        "SENSOR0006",
        "SENSOR0007",
        "SENSOR0008",
        "SENSOR0009",
        "SENSOR0010"
      ],
      "SerialNumber": "1701"
    },
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0011",
        "SENSOR0012",
        "SENSOR0013",
        "SENSOR0014",
        "SENSOR0015",
        "SENSOR0016",
        "SENSOR0017",
        "SENSOR0018",
        "SENSOR0019"
      ],
      "SerialNumber": "1702"
    },
    {
      "silos": 1,
      "GroupBob": [
        "SENSOR0020",
        "SENSOR0021",
        "SENSOR0022",
        "SENSOR0023",
        "SENSOR0024",
        "SENSOR0025",
        "SENSOR0026",
        "SENSOR0027",
        "SENSOR0028"
      ],
      "SerialNumber": "1703"
    }
]

}

I want to write the data to the SILO_SENSOR table, that's it

NAME            DEVICES_ID
SENSOR0001      1701
SENSOR0002      1701
SENSOR0003      1701
SENSOR0004      1701
SENSOR0005      1701
SENSOR0006      1701
SENSOR0007      1701
SENSOR0008      1701
SENSOR0009      1701
SENSOR0010      1701

Body:
Given this table:

create table silo_sensor (
  name      varchar2(255),
  devices_id varchar2(255)
);

The following should work:

declare

  tv     apex_json.t_values;
  v_clob clob;
  scount number;
  ccount number;
  q_temp varchar2(255);
  v_id   varchar2(255);

begin

  v_clob := q'-
    {
      "GroupSensor": [
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0001",
            "SENSOR0002",
            "SENSOR0003",
            "SENSOR0004",
            "SENSOR0005",
            "SENSOR0006",
            "SENSOR0007",
            "SENSOR0008",
            "SENSOR0009",
            "SENSOR0010"
          ],
          "SerialNumber": "1701"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0011",
            "SENSOR0012",
            "SENSOR0013",
            "SENSOR0014",
            "SENSOR0015",
            "SENSOR0016",
            "SENSOR0017",
            "SENSOR0018",
            "SENSOR0019"
          ],
          "SerialNumber": "1702"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0020",
            "SENSOR0021",
            "SENSOR0022",
            "SENSOR0023",
            "SENSOR0024",
            "SENSOR0025",
            "SENSOR0026",
            "SENSOR0027",
            "SENSOR0028"
          ],
          "SerialNumber": "1703"
        }
      ]
    }
  -';

  apex_json.parse(tv, v_clob);

  sCount := APEX_JSON.get_count(p_path => 'GroupSensor' , p_values => tv);

  for i in 1 .. sCount loop
    v_id := apex_json.get_varchar2(p_path => 'GroupSensor[%d].SerialNumber', p_values => tv, p0 => i);

    cCount := APEX_JSON.get_count(p_path => 'GroupSensor[%d].GroupBob' , p_values => tv, p0 => i);

    for q in 1 .. cCount loop
      q_temp := apex_json.get_varchar2(p_path => 'GroupSensor[%d].GroupBob[%d]', p_values => tv, p0 => i, p1 => q);
      insert into silo_sensor(name, devices_id)
      values (q_temp, v_id);
    end loop;
  end loop;

  commit;

end;

A couple of things to note:

You don't need the IF sCount > 0 THEN or IF cCount > 0 THEN checks. Just go into the loop, if the count is 0 then you will not go into it. The only reason you might need the if check is if it's possible the property will not exist. In that case, your check should be if sCount is not null because get_varchar2 will return null if the property doesn't exist.

Don't commit inside of a loop. If you get an error while looping, you'll have committed part of the transaction and it will be more difficult to fix. Either commit at the end or not at all (let the caller commit when they want).

Because you're running on 18c, you could use the built in PL/SQL types for JSON. These should perform better than APEX_JSON.

declare

  top_obj json_object_t;
  gs_arr  json_array_t;
  gs_obj  json_object_t;
  gb_arr  json_array_t;
  v_clob  clob;
  q_temp  varchar2(255);
  v_id    varchar2(255);

begin

  v_clob := q'-
    {
      "GroupSensor": [
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0001",
            "SENSOR0002",
            "SENSOR0003",
            "SENSOR0004",
            "SENSOR0005",
            "SENSOR0006",
            "SENSOR0007",
            "SENSOR0008",
            "SENSOR0009",
            "SENSOR0010"
          ],
          "SerialNumber": "1701"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0011",
            "SENSOR0012",
            "SENSOR0013",
            "SENSOR0014",
            "SENSOR0015",
            "SENSOR0016",
            "SENSOR0017",
            "SENSOR0018",
            "SENSOR0019"
          ],
          "SerialNumber": "1702"
        },
        {
          "silos": 1,
          "GroupBob": [
            "SENSOR0020",
            "SENSOR0021",
            "SENSOR0022",
            "SENSOR0023",
            "SENSOR0024",
            "SENSOR0025",
            "SENSOR0026",
            "SENSOR0027",
            "SENSOR0028"
          ],
          "SerialNumber": "1703"
        }
      ]
    }
  -';

  top_obj := json_object_t.parse(v_clob);
  gs_arr := top_obj.get_array('GroupSensor');

  for i in 0 .. gs_arr.get_size - 1 loop
    gs_obj := json_object_t(gs_arr.get(i));
    v_id := gs_obj.get_string('SerialNumber');
    gb_arr := gs_obj.get_array('GroupBob');

    for q in 0 .. gb_arr.get_size - 1 loop
      q_temp := gb_arr.get_string(i);
      insert into silo_sensor(name, devices_id)
      values (q_temp, v_id);
    end loop;
  end loop;

  commit;

end;


问:
Adding input to a string with a max of 10 words C#
I am creating for my studies a program a simple one. In this program I need to make a sentence of 10 words. After the last input however I want to make it stop. So what I tried is this:
Create an empty string called textt, use a while loop since I make it always true it will proceed, create a string with the assignement that shows up in the program to the user aSentence its called, take an int named count and give it the value of 0, then I start my for loop I use the for loop cause I can add a condition and iterator so it stops and of course the initializer.

In the for loop I: print out the aSentence ( the user will read this ), I put a string called input and let the user put in a word ( I'm a beginner I do not know if how to make an error if the user put two words but thats not the assignment now ), I put the string textt since they are immutable but not in here and I add " " for create empty space and of course the input. Then I print out the textt what the user wrote down and I increment ( if I say this correctly ) with i++.

Then I start an if statement which says that if i ( see my for loop ) is equal == to 9 cause I increment this in my for loop it should print out End of the sentence, show the whole textt and then break.

However for some reason the loop is infinite everytime you input something. And the line End of the sentence will show up now and then and now when the loop should be finished at 9.
My question how do I fix this to make sure the sentencenends when 10 words have been inputted by the user and the End of the sentence pops up at exactly 10 input words.

```<code>using System;

namespace Opgave_10_woorden_invoegen_in_1_string_plakken
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a program that stops after input of 10 words
            string textt = "";
            while (true)
            {
                string aSentence = new string("We are making a sentence of 10 words.");
                int count = 0;
                for (int i = 0; i < 9; i++)
                {
                    Console.WriteLine(aSentence);
                    string input = Console.ReadLine();
                    textt = textt + " " + input;
                    Console.WriteLine(textt, i++);
                    if (i == 9)
                    {
                        Console.WriteLine("End of the sentence", textt);
                        break;
                    }
                }
            }
        }
    }
}
</code>```

答:
You while (true) statement means that your loop runs forever.

You are trying to break out of this by using break.  But as this is executed inside an inner for loop, then it will only break out of that inner loop and not your outer while loop, which is what you intend and expect.

You have no need for the outer while loop, so simply removing it will solve the problem.

If you want 10 inputs then you also need to change your for loop to run for 10 iterations, not 9 as your currently have.

Also, you should use StringBuilder class when concatenating strings together so many times, as it is more efficient.
See:  https://www.dotnetperls.com/stringbuilder  for more details

Body:
I am creating for my studies a program a simple one. In this program I need to make a sentence of 10 words. After the last input however I want to make it stop. So what I tried is this:
Create an empty string called textt, use a while loop since I make it always true it will proceed, create a string with the assignement that shows up in the program to the user aSentence its called, take an int named count and give it the value of 0, then I start my for loop I use the for loop cause I can add a condition and iterator so it stops and of course the initializer.

In the for loop I: print out the aSentence ( the user will read this ), I put a string called input and let the user put in a word ( I'm a beginner I do not know if how to make an error if the user put two words but thats not the assignment now ), I put the string textt since they are immutable but not in here and I add " " for create empty space and of course the input. Then I print out the textt what the user wrote down and I increment ( if I say this correctly ) with i++.

Then I start an if statement which says that if i ( see my for loop ) is equal == to 9 cause I increment this in my for loop it should print out End of the sentence, show the whole textt and then break.

However for some reason the loop is infinite everytime you input something. And the line End of the sentence will show up now and then and now when the loop should be finished at 9.
My question how do I fix this to make sure the sentencenends when 10 words have been inputted by the user and the End of the sentence pops up at exactly 10 input words.

using System;

namespace Opgave_10_woorden_invoegen_in_1_string_plakken
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a program that stops after input of 10 words
            string textt = "";
            while (true)
            {
                string aSentence = new string("We are making a sentence of 10 words.");
                int count = 0;
                for (int i = 0; i < 9; i++)
                {
                    Console.WriteLine(aSentence);
                    string input = Console.ReadLine();
                    textt = textt + " " + input;
                    Console.WriteLine(textt, i++);
                    if (i == 9)
                    {
                        Console.WriteLine("End of the sentence", textt);
                        break;
                    }
                }
            }
        }
    }
}


问:
Find Grand Total In Array
I want to find the Grand Total by finding from the unit*price, but it gets 0.00, although it should be 12,640.00 so does anybody know how I can do this?

Here is the code

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

int main()
{
    FILE *in;

    char id[20][15];  // 20 persons
    char des[20][15];
    int unit[30];
    float price[30];
    float sum = 0.0, total = 0.0;
    int i=0, j;

    in = fopen("price.txt", "r") ;
    if ( in == NULL )
    {
        printf( "Could not open file test.c" ) ;
        return 1;
    }

    while(!feof(in))
    {
        fscanf(in, "%s %s %d %f", &id[i], &des[i], &unit[i], &price[i]);
        i++;
    }

    printf("No. ID Descripton Price/Unit Unit Total Amount\n");
    for(j=0; j < i ;j++)
       printf("%d. %s %s %d %0.2f %0.2f \n",j, id[j], des[j], unit[j], price[j], unit[j]*price[j]);
    sum = unit[j]*price[j];
    total += sum;
    printf("Grand Total %0.2f",total);
    return 0;
}
</code>```

答:
I see that you are a beginner. Well, the error here is that your for loop never actually calculates the sum
By default, the for loop only reads the line below it, unless there is any code enclosed curly braces{} spanning multiple lines.

```<code>for(j=0; j < i ;j++)
{
    printf("%d. %s %s %d %0.2f %0.2f \n",j, id[j], des[j], unit[j],
    price[j],
    unit[j]*price[j]);
    sum = unit[j]*price[j];
    total += sum;
}
</code>```

Also, just an advice, please try to indent your code better. It will help you in the future :)

Best.

Title: Find Grand Total In Array

Body:
I want to find the Grand Total by finding from the unit*price, but it gets 0.00, although it should be 12,640.00 so does anybody know how I can do this?

Here is the code

#include <stdio.h>

int main()
{
    FILE *in;

    char id[20][15];  // 20 persons
    char des[20][15];
    int unit[30];
    float price[30];
    float sum = 0.0, total = 0.0;
    int i=0, j;

    in = fopen("price.txt", "r") ;
    if ( in == NULL )
    {
        printf( "Could not open file test.c" ) ;
        return 1;
    }

    while(!feof(in))
    {
        fscanf(in, "%s %s %d %f", &id[i], &des[i], &unit[i], &price[i]);
        i++;
    }

    printf("No. ID Descripton Price/Unit Unit Total Amount\n");
    for(j=0; j < i ;j++)
       printf("%d. %s %s %d %0.2f %0.2f \n",j, id[j], des[j], unit[j], price[j], unit[j]*price[j]);
    sum = unit[j]*price[j];
    total += sum;
    printf("Grand Total %0.2f",total);
    return 0;
}

Body:
I see that you are a beginner. Well, the error here is that your for loop never actually calculates the sum
By default, the for loop only reads the line below it, unless there is any code enclosed curly braces{} spanning multiple lines.

for(j=0; j < i ;j++)
{
    printf("%d. %s %s %d %0.2f %0.2f \n",j, id[j], des[j], unit[j],
    price[j],
    unit[j]*price[j]);
    sum = unit[j]*price[j];
    total += sum;
}

Also, just an advice, please try to indent your code better. It will help you in the future :)

Best.


问:
Invalid Host header when running Create React App on localhost subdomain
After updating to  the react-scripts 1.0.0 I get this error when I try to open my app in the browser on a localhost subdomain: 'Invalid Host header'

My app was set up to serve different data for different subdomains:
group1.localhost:3000
group2.localhost:3000
...

I found that adding the code below to my webpack config should fix the problem.

```<code>devServer: {
  disableHostCheck: true
}
</code>```

But how can i fix it in CRA without ejecting?

答:
An easy solution for development environment would be to set the following environment variable: DANGEROUSLY_DISABLE_HOST_CHECK=true

That can be done by e.g. adding that line to .env file in the root of the project. Note that this is not a secure solution and should not be used in production.

ContentLicense: CC BY-SA 3.0

Body:
After updating to  the react-scripts 1.0.0 I get this error when I try to open my app in the browser on a localhost subdomain: 'Invalid Host header'

My app was set up to serve different data for different subdomains:
group1.localhost:3000
group2.localhost:3000
...

I found that adding the code below to my webpack config should fix the problem.

devServer: {
  disableHostCheck: true
}

But how can i fix it in CRA without ejecting?


问:
Jquery Slider Effect
I am using jQuery for a slider effect on button click. My code is:

```<code>$(document).ready(function() {

  $("#mybutton").click(function () {
      $("#slidemarginleft").hide("slide", { direction: "down" }, 1000);
});
});
</code>```

When I click on the button, a JavaScript error occurs:

```<code>f.easing[e.animatedProperties[this.prop]] is not a function
</code>```

答:
The code snippet he provided is straight out of the jQuery UI documentation:

```<code>$("div").click(function () {
  $(this).hide("slide", { direction: "down" }, 1000);
});
</code>```

I just got this error and the issue was that the jQuery UI script wasn't loaded (D'oh!). jQuery UI is required for the easing animations.

Try adding this to see if it resolves the problem:

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
</code>```

Title: Jquery Slider Effect

Body:
I am using jQuery for a slider effect on button click. My code is:

$(document).ready(function() {

  $("#mybutton").click(function () {
      $("#slidemarginleft").hide("slide", { direction: "down" }, 1000);
});
});

When I click on the button, a JavaScript error occurs:

f.easing[e.animatedProperties[this.prop]] is not a function

Body:
The code snippet he provided is straight out of the jQuery UI documentation:

$("div").click(function () {
  $(this).hide("slide", { direction: "down" }, 1000);
});

I just got this error and the issue was that the jQuery UI script wasn't loaded (D'oh!). jQuery UI is required for the easing animations.

Try adding this to see if it resolves the problem:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>


问:
mPDF library issue: Image size changed after creating pdf
The pdf view in website is okay. But after creating the PDF, background size is changed.

Website view

After creating the pdf using MPDF

答: It seems to me that the width of the html element you gave it can be changed by increasing or decreasing it.


问:
How to make drop shadow for shape in Android?
I'm trying to design a shape so that it has a drop shadow like on the picture below(that login shape).

答:
you can use "gradient",the "gradientRadius="30" is you view high, color "10" is alpha value.</p>

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#10ff0000"
    android:endColor="#10ffffff"
    android:centerX="0.5"
    android:centerY="0.5"
    android:gradientRadius="30"
    android:type="radial"
    />
</code>```

Body:
you can use "gradient",the "gradientRadius="30" is you view high, color "10" is alpha value.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#10ff0000"
    android:endColor="#10ffffff"
    android:centerX="0.5"
    android:centerY="0.5"
    android:gradientRadius="30"
    android:type="radial"
    />


问:
Cannot fix The provided execution role does not have permissions to call CreateNetworkInterface on EC2
I am trying to deploy with VPC and this is my serverless.yaml

```<code>
vpcSettings: &vpcSettings
  vpc: ${self:custom.allVpcSettings.${self:provider.stage}.vpc}

provider:
  name: aws
  runtime: nodejs10.x
  stage: ${opt:stage, 'local'}
  region: us-west-1
  memorySize: 256
  timeout: 30
  deploymentPrefix: fs-sls-${self:provider.stage}-deploy
  deploymentBucket: fs-serverless-deployment
  variables: ${file(.env.${opt:stage, self:provider.stage}.json)}
  environment:
    NODE_ENV: ${self:provider.variables.NODE_ENV}

functions:
  ping:
    handler: src/handler.ping
    description: Let us know if the service is up and running
    events:
      - http:
          path: ping
          method: get
          cors: true
  graphql:
    handler: src/handler.graphqlHandler
    <<: *vpcSettings
    description: One function where all GQL request comes
    memorySize: 1024
    events:
      - http:
          path: graphql
          method: post
          cors: true
      - http:
          path: graphql
          method: get
          cors: true

plugins:
  - serverless-offline

custom:
  serverless-offline:
    port: 6000
  allVpcSettings:
    local:
      vpc: 'This is a dummy value that should be ignored'
    dev:
      vpc:
        securityGroupIds:
          - sg-xxxxxxxxxxxxxxx
        subnetIds:
          - subnet-xxxxxxxxxxxxxxx
          - subnet-xxxxxxxxxxxxxxx
    prod:
      vpc:
        securityGroupIds:
          - sg-xxxxxxxxxxxxxxx
        subnetIds:
          - subnet-xxxxxxxxxxxxxxx
          - subnet-xxxxxxxxxxxxxxx
</code>```

It fails with the following error

```<code>
  Serverless Error ---------------------------------------

  The provided execution role does not have permissions to call CreateNetworkInterface on EC2

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information ---------------------------
     Operating System:          darwin
     Node Version:              10.16.0
     Framework Version:         1.52.0
     Plugin Version:            2.0.0
     SDK Version:               2.1.1
</code>```

The user that I created for this purpose has AdministratorAccess as well as AWSLambdaVPCAccessExecutionRole in it's permissions. What else is expected here?

答:
Although the user that you've created to deploy this lambda function has Administrator access, the lambda function itself needs networking permissions if you're deploying it into a VPC.

Try adding these permissions in the provider block of your serverless.yml template:

```<code>    - Effect: Allow
      Action:
        - ec2:DescribeNetworkInterfaces
        - ec2:CreateNetworkInterface
        - ec2:DeleteNetworkInterface
        - ec2:DescribeInstances
        - ec2:AttachNetworkInterface
      Resource:
        - *
</code>```

If that works, you'll want to deploy a more limited permission structure for your production environment.

Body:
I am trying to deploy with VPC and this is my serverless.yaml

vpcSettings: &vpcSettings
  vpc: ${self:custom.allVpcSettings.${self:provider.stage}.vpc}

provider:
  name: aws
  runtime: nodejs10.x
  stage: ${opt:stage, 'local'}
  region: us-west-1
  memorySize: 256
  timeout: 30
  deploymentPrefix: fs-sls-${self:provider.stage}-deploy
  deploymentBucket: fs-serverless-deployment
  variables: ${file(.env.${opt:stage, self:provider.stage}.json)}
  environment:
    NODE_ENV: ${self:provider.variables.NODE_ENV}

functions:
  ping:
    handler: src/handler.ping
    description: Let us know if the service is up and running
    events:
      - http:
          path: ping
          method: get
          cors: true
  graphql:
    handler: src/handler.graphqlHandler
    <<: *vpcSettings
    description: One function where all GQL request comes
    memorySize: 1024
    events:
      - http:
          path: graphql
          method: post
          cors: true
      - http:
          path: graphql
          method: get
          cors: true

plugins:
  - serverless-offline

custom:
  serverless-offline:
    port: 6000
  allVpcSettings:
    local:
      vpc: 'This is a dummy value that should be ignored'
    dev:
      vpc:
        securityGroupIds:
          - sg-xxxxxxxxxxxxxxx
        subnetIds:
          - subnet-xxxxxxxxxxxxxxx
          - subnet-xxxxxxxxxxxxxxx
    prod:
      vpc:
        securityGroupIds:
          - sg-xxxxxxxxxxxxxxx
        subnetIds:
          - subnet-xxxxxxxxxxxxxxx
          - subnet-xxxxxxxxxxxxxxx

It fails with the following error

  Serverless Error ---------------------------------------

  The provided execution role does not have permissions to call CreateNetworkInterface on EC2

  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com

  Your Environment Information ---------------------------
     Operating System:          darwin
     Node Version:              10.16.0
     Framework Version:         1.52.0
     Plugin Version:            2.0.0
     SDK Version:               2.1.1

The user that I created for this purpose has AdministratorAccess as well as AWSLambdaVPCAccessExecutionRole in it's permissions. What else is expected here?

Body:
Although the user that you've created to deploy this lambda function has Administrator access, the lambda function itself needs networking permissions if you're deploying it into a VPC.

Try adding these permissions in the provider block of your serverless.yml template:

    - Effect: Allow
      Action:
        - ec2:DescribeNetworkInterfaces
        - ec2:CreateNetworkInterface
        - ec2:DeleteNetworkInterface
        - ec2:DescribeInstances
        - ec2:AttachNetworkInterface
      Resource:
        - *

If that works, you'll want to deploy a more limited permission structure for your production environment.


问:
Trouble adding element with text to DOM tree
I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.

```<code>var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);
</code>```

The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.

答:
This line

```<code>    var newEl = newEl.appendChild(newText);
</code>```

Change to

```<code>    newEl.appendChild(newText);
</code>```

When you reassign it its not the li anymore (this is not JQ)

Body:
I created an unordered list of elements and I'm trying to add a new element using DOM manipulation.

var newEl = document.create Element('li');
var newText = document.createTextNode('Hawaii');
var newEl = newEl.appendChild(newText);
document.getElementsByTagName('ul')[0].appendChild(newEl);

The element was added to the ul element but it was not added as an li element, so my new text doesn't have any bulleting.

Body:
This line

    var newEl = newEl.appendChild(newText);

Change to

    newEl.appendChild(newText);

When you reassign it its not the li anymore (this is not JQ)


问:
Retrospectively populate an access form field
I have an access database that I have been asked to add a field to (KeyStage). This field will auto populate from the NCY field that is already known and populated.  The code for this is;

```<code>Dim KeyStage As String
Dim NCY As Integer

NCY = Me.NationalCurriculumYear.Value

If NCY < 1 Then
Me.KeyStage = "Early Years"
ElseIf NCY > 0 And NCY < 3 Then
Me.KeyStage = "KS1"
ElseIf NCY > 2 And NCY < 7 Then
Me.KeyStage = "KS2"
ElseIf NCY > 6 And NCY < 10 Then
Me.KeyStage = "KS3"
ElseIf NCY > 9 And NCY < 12 Then
Me.KeyStage = "KS4"
Else: Me.KeyStage = "Left School"
End If
</code>```

If I put this into a GotFocus sub, it works fine.  The problem is I already have 2000 records and unless I tab through each record, I can't get the KeyStage field to auto populate.  I tried putting it in an onLoad sub for the form but that didn't work either.  Can anyone suggest how I would approach this?

Thank you in advance for your help.

答:
You would need to execute an UPDATE statement against records in the table that hadn't yet been updated. Something like this might work:</p>

```<code>UPDATE MyTable AS T

SET T.KeyStage =
    Iif(T.NationalCurriculumYear = 0, "Early Years",
    Iif(T.NationalCurriculumYear >=  1 And T.NationalCurriculumYear <  3, "KS1",
    Iif(T.NationalCurriculumYear >=  3 And T.NationalCurriculumYear <  7, "KS2",
    Iif(T.NationalCurriculumYear >=  7 And T.NationalCurriculumYear < 10, "KS3",
    Iif(T.NationalCurriculumYear >= 10 And T.NationalCurriculumYear < 12, "KS4", "Left School")))))

WHERE T.KeyStage Is Null
</code>```

Body:
I have an access database that I have been asked to add a field to (KeyStage). This field will auto populate from the NCY field that is already known and populated.  The code for this is;

Dim KeyStage As String
Dim NCY As Integer

NCY = Me.NationalCurriculumYear.Value

If NCY < 1 Then
Me.KeyStage = "Early Years"
ElseIf NCY > 0 And NCY < 3 Then
Me.KeyStage = "KS1"
ElseIf NCY > 2 And NCY < 7 Then
Me.KeyStage = "KS2"
ElseIf NCY > 6 And NCY < 10 Then
Me.KeyStage = "KS3"
ElseIf NCY > 9 And NCY < 12 Then
Me.KeyStage = "KS4"
Else: Me.KeyStage = "Left School"
End If

If I put this into a GotFocus sub, it works fine.  The problem is I already have 2000 records and unless I tab through each record, I can't get the KeyStage field to auto populate.  I tried putting it in an onLoad sub for the form but that didn't work either.  Can anyone suggest how I would approach this?

Thank you in advance for your help.

Body:
You would need to execute an UPDATE statement against records in the table that hadn't yet been updated. Something like this might work:

UPDATE MyTable AS T

SET T.KeyStage =
    Iif(T.NationalCurriculumYear = 0, "Early Years",
    Iif(T.NationalCurriculumYear >=  1 And T.NationalCurriculumYear <  3, "KS1",
    Iif(T.NationalCurriculumYear >=  3 And T.NationalCurriculumYear <  7, "KS2",
    Iif(T.NationalCurriculumYear >=  7 And T.NationalCurriculumYear < 10, "KS3",
    Iif(T.NationalCurriculumYear >= 10 And T.NationalCurriculumYear < 12, "KS4", "Left School")))))

WHERE T.KeyStage Is Null


问:
react-scripts Invalid Host header
I created an app with react-create-app, I just dev it using npm start, that seems to do react-scripts start according to my package.json

Whenever I add a proxy to my package.json, I get this error message :

```<code>Invalid Host header
</code>```

I get the idea, it's a security issue. What I don't get is how to fix it. I read several issues on github and QA here on the subject, the fix is easy enough, but I still don't get where to put it

in the end, I will add a whitelist of hosts. I think I saw it's possible.

but where do I put this config to start :

```<code>devServer: {
  disableHostCheck: true
}
</code>```

答:
Another way to disable the host check would be to set the following environment variable: DANGEROUSLY_DISABLE_HOST_CHECK=true

That can be done by e.g. adding that line to .env file in the root of the project. Note that this is not a secure solution and should not be used in production.

Title: react-scripts Invalid Host header

Body:
I created an app with react-create-app, I just dev it using npm start, that seems to do react-scripts start according to my package.json

Whenever I add a proxy to my package.json, I get this error message :

Invalid Host header

I get the idea, it's a security issue. What I don't get is how to fix it. I read several issues on github and QA here on the subject, the fix is easy enough, but I still don't get where to put it

in the end, I will add a whitelist of hosts. I think I saw it's possible.

but where do I put this config to start :

devServer: {
  disableHostCheck: true
}


问:
select sub dataset with specific conditions without using apply & subset functions
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

```<code> #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA
</code>```

I would like to do this work without apply and subset functions.

The final dataset that I would like to have is

```<code>#    name  age income
# 1 alicia 40  100
# 2 jessie 28  60
</code>```

By the way, someone can explain me why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

答:
This is probably what you want. We need to evaluate it column by column.

```<code>df[df$age > 0 & df$age <= 100 &  df$income > 0 & df$income <= 100, ]
#     name age income
# 1 alicia  40    100
# 4 jessie  28     60
</code>```

Or you can do this if this is easier. We used rowSums here because if each row satisfied your conditions, the sum would be two.

```<code>df[rowSums(df[,c(2:3)] >= 0 & df[,(2:3)] <= 100) == 2L, ]
#     name age income
# 1 alicia  40    100
# 4 jessie  28     60
</code>```

Body:
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

 #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA

I would like to do this work without apply and subset functions.

The final dataset that I would like to have is

#    name  age income
# 1 alicia 40  100
# 2 jessie 28  60

By the way, someone can explain me why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

Body:
This is probably what you want. We need to evaluate it column by column.

df[df$age > 0 & df$age <= 100 &  df$income > 0 & df$income <= 100, ]
#     name age income
# 1 alicia  40    100
# 4 jessie  28     60

Or you can do this if this is easier. We used rowSums here because if each row satisfied your conditions, the sum would be two.

df[rowSums(df[,c(2:3)] >= 0 & df[,(2:3)] <= 100) == 2L, ]
#     name age income
# 1 alicia  40    100
# 4 jessie  28     60


问:
Headroom.js with Typescript can't find the module
Anyone got this working in Typescript land? Googling around and it appears not.

Tying to incorporate this library into my Browserify project without any luck.

I have this typings file for v0.9.3 of headroom.js

https://github.com/retyped/headroom-tsd-ambient/blob/master/headroom.d.ts

node module installed as node_modules/headroom.js/ (yes it's a folder; I have never seen a node module named this way before.)

headroom.js's main entry as per package.json is node_modules/headroom.js/dist/headroom.js

When I try to import the module into my app, it can't be found.

```<code>{ [TypeScript error: resources/assets/typescript/app.ts(12,24): Error TS2307: Cannot find module 'headroom.js'.]
  message: 'resources/assets/typescript/app.ts(12,24): Error TS2307: Cannot find module \'headroom.js\'.',
  fileName: 'resources/assets/typescript/app.ts',
  line: 12,
  column: 24,
  name: 'TypeScript error' }
</code>```

Have tried all these permutations:

```<code>import {Headroom} from "headroom.js";    //nope
import {Headroom} from "headroom\.js";   //nope
import {Headroom} from "Headroom\.js";   //nope
import {Headroom} from "headroomjs";     //nope
import {Headroom} from "headroomjs";     //nope
import {Headroom} from "headroom";       //nope
import {Headroom} from "Headroom";       //nope
import * as headroom from "headroom.js"; // nope
</code>```

The typings file is definitely being imported as used correctly.

IDE is saying that it can find the directory:

What am I doing wrong?

Edit 13-08-2015

1.
app.ts pulls in the typings from the typings dir like this:

```<code>/// <reference path="../../../typings/index.d.ts" />
</code>```

index.d.ts contains these typings

  /// <reference path="bootstrap/bootstrap.d.ts" />
  /// <reference path="custom.d.ts" />
  /// ..etc...
  /// <reference path="Headroom/headroom.d.ts" />

It's definitely there.

答:
I made something similar to @Sebastian answer to get it working. In the src/ folder, created a new file called headroom.js.d.ts containing just:

declare module 'headroom.js';
```

<p>And that fixed it. In my functional component, I was able to do this:</p>

<pre class="lang-js prettyprint-override"><code>import Headroom from "headroom.js";

export const Navigation: React.FC = () => {
    React.useEffect(() => {
        let headroom = new Headroom(document.getElementById("navbar-main"));
        headroom.init();
    }, [classes]);

    return (...);
}
</code>```

Body:
Anyone got this working in Typescript land? Googling around and it appears not.

Tying to incorporate this library into my Browserify project without any luck.

I have this typings file for v0.9.3 of headroom.js

https://github.com/retyped/headroom-tsd-ambient/blob/master/headroom.d.ts

node module installed as node_modules/headroom.js/ (yes it's a folder; I have never seen a node module named this way before.)

headroom.js's main entry as per package.json is node_modules/headroom.js/dist/headroom.js

When I try to import the module into my app, it can't be found.

{ [TypeScript error: resources/assets/typescript/app.ts(12,24): Error TS2307: Cannot find module 'headroom.js'.]
  message: 'resources/assets/typescript/app.ts(12,24): Error TS2307: Cannot find module \'headroom.js\'.',
  fileName: 'resources/assets/typescript/app.ts',
  line: 12,
  column: 24,
  name: 'TypeScript error' }

Have tried all these permutations:

import {Headroom} from "headroom.js";    //nope
import {Headroom} from "headroom\.js";   //nope
import {Headroom} from "Headroom\.js";   //nope
import {Headroom} from "headroomjs";     //nope
import {Headroom} from "headroomjs";     //nope
import {Headroom} from "headroom";       //nope
import {Headroom} from "Headroom";       //nope
import * as headroom from "headroom.js"; // nope

The typings file is definitely being imported as used correctly.

IDE is saying that it can find the directory:

What am I doing wrong?

Edit 13-08-2015

1.
app.ts pulls in the typings from the typings dir like this:

/// <reference path="../../../typings/index.d.ts" />

index.d.ts contains these typings

  /// <reference path="bootstrap/bootstrap.d.ts" />
  /// <reference path="custom.d.ts" />
  /// ..etc...
  /// <reference path="Headroom/headroom.d.ts" />

It's definitely there.

Body:
I made something similar to @Sebastian answer to get it working. In the src/ folder, created a new file called headroom.js.d.ts containing just:

declare module 'headroom.js';

And that fixed it. In my functional component, I was able to do this:

import Headroom from "headroom.js";

export const Navigation: React.FC = () => {
    React.useEffect(() => {
        let headroom = new Headroom(document.getElementById("navbar-main"));
        headroom.init();
    }, [classes]);

    return (...);
}


答:
.appendChild returns the appended element. In this case your newEl will be a text node after this assignment.

```<code>var newEl = newEl.appendChild(newText);
</code>```

You should remove the assignment and it is fine.

Title: Trouble adding element with text to DOM tree

Body:
.appendChild returns the appended element. In this case your newEl will be a text node after this assignment.

var newEl = newEl.appendChild(newText);

You should remove the assignment and it is fine.


问:
GraphQL error: Internal server error when accessing graphQL
I am using GraphQL with wpgraphql inside a WP setup. I have been using the service without any problems until I updated a Custom Post Type and it stopped working.

message: "Internal server error", category: "internal",

But what is odd is that it still returns the data, along with the error.

Doing the same query in graphiQL works without any flaws. Looking at the request, the only difference is no cookies are sent with the failing request.

I have enabled: define( 'WP_DEBUG', true ); but no new errors are displayed.

The query is rather simple:

```<code>{
  rankings {
    edges {
      node {
        rankingId
        id
        commentStatus
        content
        date
        title
        uri
        link
      }
    }
  }
}
</code>```

答: Use define( 'GRAPHQL_DEBUG', true ); to get the full error message from WPGraphQL

Body:
I am using GraphQL with wpgraphql inside a WP setup. I have been using the service without any problems until I updated a Custom Post Type and it stopped working.

message: "Internal server error", category: "internal",

But what is odd is that it still returns the data, along with the error.

Doing the same query in graphiQL works without any flaws. Looking at the request, the only difference is no cookies are sent with the failing request.

I have enabled: define( 'WP_DEBUG', true ); but no new errors are displayed.

The query is rather simple:

{
  rankings {
    edges {
      node {
        rankingId
        id
        commentStatus
        content
        date
        title
        uri
        link
      }
    }
  }
}


问:
ImportError: No module named lib
I'm trying to open the FoxDot interface with the python -m FoxDot terminal command.
But I get this error:

OS: Linux

```<code>Traceback (most recent call last):
   File "/usr/lib/python2.7/runpy.py", line 163, in _run_module_as_main
     mod_name, _Error)
   File "/usr/lib/python2.7/runpy.py", line 111, in _get_module_details
     __import __ (mod_name) # Do not catch exceptions initializing package
   "FoxDot / __ init__.py" file, line 120, in <module>
     from .lib import *
ImportError: No module named lib
</code>```

How can I solve it?

答: Have you downloaded the lib module? Try to download it using pip install lib then run it again!

Title: ImportError: No module named lib

Body:
I'm trying to open the FoxDot interface with the python -m FoxDot terminal command.
But I get this error:

OS: Linux

Traceback (most recent call last):
   File "/usr/lib/python2.7/runpy.py", line 163, in _run_module_as_main
     mod_name, _Error)
   File "/usr/lib/python2.7/runpy.py", line 111, in _get_module_details
     __import __ (mod_name) # Do not catch exceptions initializing package
   "FoxDot / __ init__.py" file, line 120, in <module>
     from .lib import *
ImportError: No module named lib

How can I solve it?


问:
Question regarding choosing Cloud Provider
When creating an account and choose Azure option, does it mean all the services Cloud Services, Query Processing and Database Storage will all be from Azure? Or S3 for Storage and Cloud Services, Query Processing from Azure?

Does anyone know?

答:
Snowflake as an entire service will use the cloud provider that you choose when creating each account:

Snowflake is provided as Software-as-a-Service (SaaS) that runs completely on cloud infrastructure.

This means that all three layers of Snowflake’s architecture (storage, compute, and cloud services) are deployed and managed entirely on a selected cloud platform.

However, you can continue to load external data from different cloud providers regardless of the chosen cloud provider:

Snowflake supports loading data from files staged in any of the following locations, regardless of the cloud platform for your Snowflake account:

[...]


问:
How to update state with the useState hook
I have a default state that looks like this:

```<code>const [selectedFilters, setSelectedFilters] = useState({movie: 'default' , species : 'default' , planet : 'default'});
</code>```

How do I update the movie value to something else. I tried this :

```<code>  const handleMovieChange  = (e) => {
    console.log(e.target.value)
    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
  }
</code>```

However when I change values this gives me :

```<code>×
TypeError: Cannot read property 'value' of null
(anonymous function)
C:/Users/klmaa/OneDrive/Bureaublad/swcase/client/src/App.js:48
  45 |
  46 |  const handleMovieChange  = (e) => {
  47 |    console.log(e.target.value)
> 48 |    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
     | ^  49 |  }
  50 |
  51 |  console.log(selectedFilters);
</code>```

答:
You don't need the arrow function here. Simply access the normal object selectedFilters and pass the updated value for movie along, creating a new object, and pass this new object to setSelectedFilters:

```<code>setSelectedFilters({...selectedFilters, movie: e.target.value});
</code>```

Body:
I have a default state that looks like this:

const [selectedFilters, setSelectedFilters] = useState({movie: 'default' , species : 'default' , planet : 'default'});

How do I update the movie value to something else. I tried this :

  const handleMovieChange  = (e) => {
    console.log(e.target.value)
    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
  }

However when I change values this gives me :

×
TypeError: Cannot read property 'value' of null
(anonymous function)
C:/Users/klmaa/OneDrive/Bureaublad/swcase/client/src/App.js:48
  45 |
  46 |  const handleMovieChange  = (e) => {
  47 |    console.log(e.target.value)
> 48 |    setSelectedFilters(prevState => ({ ...prevState, movie : e.target.value}));
     | ^  49 |  }
  50 |
  51 |  console.log(selectedFilters);

Body:
You don't need the arrow function here. Simply access the normal object selectedFilters and pass the updated value for movie along, creating a new object, and pass this new object to setSelectedFilters:

setSelectedFilters({...selectedFilters, movie: e.target.value});


问:
Where to configure SSL in micro service architecture
I need to convert monothic application to micro service architecture. Few suggestion/confirmation are required before i finalize the design.

I will be using docker containers and kubernetes. Structure will be like this

Ingress -> Zuul API Gateway--> Microservice

             -> Angular PODS

Ingress Router to route traffic to

Angular PODS where angular code will be present

API Gateway Zuul API Gateway where we will perform Authorization and
Authentication

So my doubt is, for inter service communication do we need to configure SSL ?

答: It depends on the level of security you need for inter-service communication. If that is required, I would recommend to use service mesh for the same. It will give mutual TLS for your services and many other benefits. Istio (https://istio.io/) is the most widely used service mesh.</p>


问:
adonis issue: error: `migration:run` is not a registered command
I Have installed @adonisjs/lucid.
create a migration to use command

adonis make:migration task

** task code**

```<code>'use strict'

const Schema = use('Schema')

class TaskSchema extends Schema {
  up() {
    this.create('tasks', table => {
      table.increments()
      table.timestamps()
      table.string('name')
      table.text('description')
      table.integer('project_id').unsigned()
      table
        .foreign('project_id')
        .references('projects.id')
        .onDelete('cascade')
    })
  }

  down() {
    this.drop('tasks')
  }
}

module.exports = TaskSchema
</code>```

i have run my migration to show this error

```<code>error: `migration:run` is not a registered command
</code>```

**

i have not understand this bug. I know that if not install the
  dependencies  @adonisjs/lucid than show this error but After I
  installed dependencies  why the error occurred

**

答:
What you need here is adonis/cli.

```<code>npm i -g @adonisjs/cli
</code>```

But I think the you don't really need this extra dependencies. Using ace is enough

```<code>node ace make:migration task
</code>```

Body:
I Have installed @adonisjs/lucid.
create a migration to use command

adonis make:migration task

** task code**

'use strict'

const Schema = use('Schema')

class TaskSchema extends Schema {
  up() {
    this.create('tasks', table => {
      table.increments()
      table.timestamps()
      table.string('name')
      table.text('description')
      table.integer('project_id').unsigned()
      table
        .foreign('project_id')
        .references('projects.id')
        .onDelete('cascade')
    })
  }

  down() {
    this.drop('tasks')
  }
}

module.exports = TaskSchema

i have run my migration to show this error

error: `migration:run` is not a registered command

**

i have not understand this bug. I know that if not install the
  dependencies  @adonisjs/lucid than show this error but After I
  installed dependencies  why the error occurred

**

Body:
What you need here is adonis/cli.

npm i -g @adonisjs/cli

But I think the you don't really need this extra dependencies. Using ace is enough

node ace make:migration task


问:
Using protobuf imports (i.e. google/protobuf/timestamp.proto) with wire
I am trying to generate files using the square's Wire. I could run their sample all good, but as soon as I added
import "google/protobuf/timestamp.proto"; to their .proto file
to check how wire treats timestamps, compiler broke with this exception:

Exception in thread "main" java.io.FileNotFoundException: Failed to locate google/protobuf/timestamp.proto in [src/main/proto]

I have protoc in my path ($PATH=...usr/local/bin, protoc is located in there. timestamp.proto is located under /usr/local/include/google/protobuf). I expected wire compiler to use protoc from my system and therefore to be able to use it's includes.

Tried running wire with gradle plugin and using precompiled jar to same result.

UPDATE:
Also tried using gradle plugin in android studio project to same extent.

```<code>* What went wrong:
Execution failed for task ':app:generateProtos'.
> unable to resolve 1 imports:
    google/protobuf/timestamp.proto
  searching 0 proto paths:
</code>```

答:
Ok, after some searching and experimenting, turns out that:

1) Wire doesn't support proto3 syntax (yet)

2) Timestamp is written in proto3 syntax, and so wire just doesn't support it too.

So answer is - you can't import timestamp.proto and use it to generate classes with wire until proto3 support is implemented.

Body:
I am trying to generate files using the square's Wire. I could run their sample all good, but as soon as I added
import "google/protobuf/timestamp.proto"; to their .proto file
to check how wire treats timestamps, compiler broke with this exception:

Exception in thread "main" java.io.FileNotFoundException: Failed to locate google/protobuf/timestamp.proto in [src/main/proto]

I have protoc in my path ($PATH=...usr/local/bin, protoc is located in there. timestamp.proto is located under /usr/local/include/google/protobuf). I expected wire compiler to use protoc from my system and therefore to be able to use it's includes.

Tried running wire with gradle plugin and using precompiled jar to same result.

UPDATE:
Also tried using gradle plugin in android studio project to same extent.

* What went wrong:
Execution failed for task ':app:generateProtos'.
> unable to resolve 1 imports:
    google/protobuf/timestamp.proto
  searching 0 proto paths:


问:
How to apply unmerged upstream pull requests from other forks into my fork?
A project on GitHub that I have a fork of has a new pull requests that I want to pull into my fork that the author has not pulled in yet.

Is there a simple way to apply pull request from other forks into my fork? Is there something else here that I am missing?

答:
What I would do is the following;

```<code>git checkout master
git remote add #NAME# #ADDRESS TO REPO#
git fetch #USERNAME#
git checkout -b test_fork
git rebase #NAME#/#BRANCH#
</code>```

I have now merged the changes into a test branch, named test_fork. So that any changes won't dirty my tree.

Optionally you can use cherry-pick as described above to pick a particular commit if that is more preferable.

Happy travels :)

Body:
What I would do is the following;

git checkout master
git remote add #NAME# #ADDRESS TO REPO#
git fetch #USERNAME#
git checkout -b test_fork
git rebase #NAME#/#BRANCH#

I have now merged the changes into a test branch, named test_fork. So that any changes won't dirty my tree.

Optionally you can use cherry-pick as described above to pick a particular commit if that is more preferable.

Happy travels :)


问:
Passing subarray of 2-dimensional array in FORTRAN-77
I have 2-dimensional array

```<code>real triangle(0:2, 0:1)
</code>```

where "triangle" is an array of vectors (1-dim arrays)
also i have subroutine

```<code>subroutine vecSub(lhs, rhs, result)
real lhs(0:1), rhs(0:1), result(0:1)
    result(0) = lhs(0) - rhs(0)
    result(1) = lhs(1) - rhs(1)
    return
end
</code>```

is there any way to pass one of the vectors from "triangle" variable to this subroutine? Fortran-90 can do this: triangle(0, :) which gives first array of triangle, but i'm allowed to use only FORTRAN-77, so this won't do, any suggestions?

答:
No, not with the current layout of your array, because of two reasons:

Fortran uses an array element order in which the leftmost dimension is contiguous. That is, in an array of size (n,m,l) the distance between elements (the stride) is (1,n,m), measured in units of array elements (that is, not bytes).

F77 does not include assumed-shape arrays a(:) which are generally implemented by passing a small descriptor structure that communicates details like the stride or the number of elements. Instead, you can only use assumed-length arrays a(*) which are normally a pointer to the first element, kind of like C arrays. You have to pass the length as a separate argument, and array elements have to be contiguous

This is the reason why you can "pass a subarray" to an F77 subroutine, as long as that subarray is e.g. a matrix column: elements therein are contiguous.

A possible solution (one that many current Fortran compilers implement) is that when you try to pass a non-contiguous subarray to a function that is not known to accept them, they make a copy of the array, and even write it back in memory if required. This would be equivalent to:

```<code>! Actual array
integer m(3,5)
integer dummy(5)
dummy = m(2,:)
call myF77sub(dummy, 5)
m(2,:) = dummy
</code>```

However, as others are saying, you should try not to call F77 functions directly, but either adapt them to or at least wrap them in more recent Fortran interfaces. Then you can have code like the above in the wrapper, and call that wrapper "normally" from modern Fortran routines. Then you may eventually get around to rewriting the actual implementation in modern Fortran without affecting client code.

Body:
I have 2-dimensional array

real triangle(0:2, 0:1)

where "triangle" is an array of vectors (1-dim arrays)
also i have subroutine

subroutine vecSub(lhs, rhs, result)
real lhs(0:1), rhs(0:1), result(0:1)
    result(0) = lhs(0) - rhs(0)
    result(1) = lhs(1) - rhs(1)
    return
end

is there any way to pass one of the vectors from "triangle" variable to this subroutine? Fortran-90 can do this: triangle(0, :) which gives first array of triangle, but i'm allowed to use only FORTRAN-77, so this won't do, any suggestions?

Body:
No, not with the current layout of your array, because of two reasons:

Fortran uses an array element order in which the leftmost dimension is contiguous. That is, in an array of size (n,m,l) the distance between elements (the stride) is (1,n,m), measured in units of array elements (that is, not bytes).

F77 does not include assumed-shape arrays a(:) which are generally implemented by passing a small descriptor structure that communicates details like the stride or the number of elements. Instead, you can only use assumed-length arrays a(*) which are normally a pointer to the first element, kind of like C arrays. You have to pass the length as a separate argument, and array elements have to be contiguous

This is the reason why you can "pass a subarray" to an F77 subroutine, as long as that subarray is e.g. a matrix column: elements therein are contiguous.

A possible solution (one that many current Fortran compilers implement) is that when you try to pass a non-contiguous subarray to a function that is not known to accept them, they make a copy of the array, and even write it back in memory if required. This would be equivalent to:

! Actual array
integer m(3,5)
integer dummy(5)
dummy = m(2,:)
call myF77sub(dummy, 5)
m(2,:) = dummy

However, as others are saying, you should try not to call F77 functions directly, but either adapt them to or at least wrap them in more recent Fortran interfaces. Then you can have code like the above in the wrapper, and call that wrapper "normally" from modern Fortran routines. Then you may eventually get around to rewriting the actual implementation in modern Fortran without affecting client code.


问:
Select with a ExecuteScalar() not working when i use a variable, always return empty, when i don't use variable it works - C#
When I use a variable, the result of command.ExecuteScalar() it's always empty (blank), I'm not receiving any error messages, just a blank value,
but when I use the same SQL query without using a variable it works.

What I have tried so far:

//variable @num is a long and contais the value = '8131818060'

string teste = num.ToString();

// 1º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + teste + "'";

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 2º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + teste;

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 3º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + num";

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 4º In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = @e164";

SqlCommand command = new SqlCommand(sql, con.conectar());
command.Parameters.Clear();
command.Parameters.AddWithValue("@e164", teste);

//string ip = command.ExecuteScalar() as string;
var ip = (string)command.ExecuteScalar();

MessageBox.Show("IP Value:: " + ip);
con.desconectar();

// 5º In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = @e164";

SqlCommand command = new SqlCommand(sql, con.conectar());
command.Parameters.Add(new SqlParameter
{
    ParameterName = "@e164",
    Value = teste,
}
);

//string ip = command.ExecuteScalar() as string;
var ip = (string)command.ExecuteScalar();

MessageBox.Show("IP Value: " + ip);
con.desconectar();

//6º This one it's the only way it works
// That's the only way it works, When i write the parameter = "8131818060"

string sql = "select Sites_IP_Rede from tblRamais where E164 = 8131818060";

SqlCommand command = new SqlCommand(sql, con.conectar());

string IP = (string)command.ExecuteScalar();

MessageBox.Show("IP Value: " + IP);

//The ip values in this case is "10.101.1.0"
```

<p>E164 is a nvarchar(10)</p>

<p>I've made a test and result 1 is true, so teste is equal to "8131818060"
But result2 is false, "sql" is not equal to "sql2"</p>

```        bool result1 = string.Equals(teste,"8131818060");

        string sql = "select Sites_IP_Rede from tblRamais where E164 = 8131818060";

        string sql2 = "select Sites_IP_Rede from tblRamais where E164 = " + teste;

        bool result2 = string.Equals(sql,"sql2");
```

<p>//following Roeland suggestion
             //I tested that way, and i'm reciving a NullReferenceException error on ip.ToString()
             //System.NullReferenceException: Object reference not set to an instance of an object</p>

```         //num is a long variable pass from the user

         string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + num.ToString() + "'";
         SqlCommand command = new SqlCommand(sql, con.conectar());
         var ip = command.ExecuteScalar();
         con.desconectar();
         MessageBox.Show("IP Value: " + ip.ToString());
```

答:
I tried this example code:

```<code>long test = 8131818060;
string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + test.ToString() + "'";
SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
    InitialCatalog = "xxx",
    DataSource = @"127.0.0.1\V2016",
    UserID = "xxx",
    Password = "xxx"
};
SqlConnection con = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
con.Open();
SqlCommand command = new SqlCommand(sql, con);
var ip = command.ExecuteScalar();
con.Close();
MessageBox.Show("IP Value: " + ip.ToString());
</code>```

Along with this SQL Code:

```<code>CREATE TABLE [dbo].[tblRamais](
    [E164] [nvarchar](10) NOT NULL,
    [Sites_IP_Rede] [varchar](20) NULL,
 CONSTRAINT [PK_tblRamais2] PRIMARY KEY CLUSTERED
(
    [E164] ASC
)
)
INSERT INTO tblRamais SELECT '8131818060','10.101.1.0'
</code>```

The code did return the value of 10.101.1.0

So your first try should be OK.

Your second example will fail if there is any record where column E164 has a non numeric value.

In your third try, this line won't compile:

```<code>string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + num";
</code>```

Your fourth and fifth try are OK too.

When I encounter problems like these, I alway use the SQL Profiler to check the statement SQL Server executed.

Body:
When I use a variable, the result of command.ExecuteScalar() it's always empty (blank), I'm not receiving any error messages, just a blank value,
but when I use the same SQL query without using a variable it works.

What I have tried so far:

//variable @num is a long and contais the value = '8131818060'

string teste = num.ToString();

// 1º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + teste + "'";

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 2º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + teste;

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 3º: In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + num";

command = new SqlCommand(sql, con.conectar());
var ip = (string)command.ExecuteScalar();
con.desconectar();
MessageBox.Show("IP Value: " + ip);

// 4º In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = @e164";

SqlCommand command = new SqlCommand(sql, con.conectar());
command.Parameters.Clear();
command.Parameters.AddWithValue("@e164", teste);

//string ip = command.ExecuteScalar() as string;
var ip = (string)command.ExecuteScalar();

MessageBox.Show("IP Value:: " + ip);
con.desconectar();

// 5º In this case ip value: it's empty

string sql = @"select Sites_IP_Rede from tblRamais where E164 = @e164";

SqlCommand command = new SqlCommand(sql, con.conectar());
command.Parameters.Add(new SqlParameter
{
    ParameterName = "@e164",
    Value = teste,
}
);

//string ip = command.ExecuteScalar() as string;
var ip = (string)command.ExecuteScalar();

MessageBox.Show("IP Value: " + ip);
con.desconectar();

//6º This one it's the only way it works
// That's the only way it works, When i write the parameter = "8131818060"

string sql = "select Sites_IP_Rede from tblRamais where E164 = 8131818060";

SqlCommand command = new SqlCommand(sql, con.conectar());

string IP = (string)command.ExecuteScalar();

MessageBox.Show("IP Value: " + IP);

//The ip values in this case is "10.101.1.0"

E164 is a nvarchar(10)

I've made a test and result 1 is true, so teste is equal to "8131818060"
But result2 is false, "sql" is not equal to "sql2"

        bool result1 = string.Equals(teste,"8131818060");

        string sql = "select Sites_IP_Rede from tblRamais where E164 = 8131818060";

        string sql2 = "select Sites_IP_Rede from tblRamais where E164 = " + teste;

        bool result2 = string.Equals(sql,"sql2");

//following Roeland suggestion
             //I tested that way, and i'm reciving a NullReferenceException error on ip.ToString()
             //System.NullReferenceException: Object reference not set to an instance of an object

         //num is a long variable pass from the user

         string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + num.ToString() + "'";
         SqlCommand command = new SqlCommand(sql, con.conectar());
         var ip = command.ExecuteScalar();
         con.desconectar();
         MessageBox.Show("IP Value: " + ip.ToString());

Body:
I tried this example code:

long test = 8131818060;
string sql = @"select Sites_IP_Rede from tblRamais where E164 = '" + test.ToString() + "'";
SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
    InitialCatalog = "xxx",
    DataSource = @"127.0.0.1\V2016",
    UserID = "xxx",
    Password = "xxx"
};
SqlConnection con = new SqlConnection(sqlConnectionStringBuilder.ConnectionString);
con.Open();
SqlCommand command = new SqlCommand(sql, con);
var ip = command.ExecuteScalar();
con.Close();
MessageBox.Show("IP Value: " + ip.ToString());

Along with this SQL Code:

CREATE TABLE [dbo].[tblRamais](
    [E164] [nvarchar](10) NOT NULL,
    [Sites_IP_Rede] [varchar](20) NULL,
 CONSTRAINT [PK_tblRamais2] PRIMARY KEY CLUSTERED
(
    [E164] ASC
)
)
INSERT INTO tblRamais SELECT '8131818060','10.101.1.0'

The code did return the value of 10.101.1.0

So your first try should be OK.

Your second example will fail if there is any record where column E164 has a non numeric value.

In your third try, this line won't compile:

string sql = @"select Sites_IP_Rede from tblRamais where E164 = " + num";

Your fourth and fifth try are OK too.

When I encounter problems like these, I alway use the SQL Profiler to check the statement SQL Server executed.


问:
Spring Boot- Itext - Error - Worker of type PTagWorker unable to process DivTagWorker
While using IText to process HTML to create a PDF file I get the following error in the logger:

```<code>ERROR 9260 --- [nio-8080-exec-2] c.i.h.attach.impl.DefaultHtmlProcessor   : Worker of type com.itextpdf.html2pdf.attach.impl.tags.PTagWorker unable to process com.itextpdf.html2pdf.attach.impl.tags.DivTagWorker
</code>```

The error is not a typical stack trace error, just a single in the logger. It also doesn't stop execution, and a PDF is generated eventually. Both my HTML and PDF files are rather large, so it's difficult to check piece by piece, but a quick look doesn't seem to show any actual errors in the target file.

Is there a specific reason why this error happens/is shown? And will it eventually prevent a PDF file from being generated?

(All of this is happening in the context of a Spring Boot application. I don't know if that might be relevant).

答:
Even if your HTML file is large, you don't have to check piece by piece and you can make use of binary search approach instead - split your document into two more or less equal pieces and try with the first half of the file, and if the problem reproduces split it further down into two pieces. If the problem does not reproduce for the first half of the file then it should reproduce for the second half of the file and you will continue to split the file pieces into two smaller ones until the file is small enough to see the problem.

As pdfHTML add-on is open source, you can debug the source of the problem instead - just go to the source of PTagWorker#processTagChild and hit the breakpoint at the return false; line (see source on GitHub) - if the result if false then the error in question is logged. From there you will be able to better see the context of the elements triggering the log error by inspecting the invocation one level down the call stack in DefaultHtmlProcessor#visit and namely element local variable that corresponds to an HTML element.

So specific reason can be deducted by using on of the approaches presented above - it can be a bug/missing feature in pdfHTML, or the fact that a block level element is added to a paragraph level element and that was not normalized automatically.

This log error will by itself not prevent a PDF file from being generated, but it can result in some content missing in the resultant PDF, so it it important to find the root cause.

Body:
While using IText to process HTML to create a PDF file I get the following error in the logger:

ERROR 9260 --- [nio-8080-exec-2] c.i.h.attach.impl.DefaultHtmlProcessor   : Worker of type com.itextpdf.html2pdf.attach.impl.tags.PTagWorker unable to process com.itextpdf.html2pdf.attach.impl.tags.DivTagWorker

The error is not a typical stack trace error, just a single in the logger. It also doesn't stop execution, and a PDF is generated eventually. Both my HTML and PDF files are rather large, so it's difficult to check piece by piece, but a quick look doesn't seem to show any actual errors in the target file.

Is there a specific reason why this error happens/is shown? And will it eventually prevent a PDF file from being generated?

(All of this is happening in the context of a Spring Boot application. I don't know if that might be relevant).


问:
How can I generate a HmacSHA256 signature of a string
Is there any way to create a HmacSHA256 signature of a string in php?</p>

答:
I can't answer due to lack of reputation, but @Melomans way in combination with ZPiDER's answer leads to using only

```<code>$hash       = hash_hmac('sha256', $string, $secret);
</code>```

for a correct Datatrans signing

Body:
I can't answer due to lack of reputation, but @Melomans way in combination with ZPiDER's answer leads to using only

$hash       = hash_hmac('sha256', $string, $secret);

for a correct Datatrans signing


问:
Python Keras - Custom Labels in ImageDataGenerator
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

```<code>Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)
</code>```

Below is my initial code:

```<code>import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

 image_width = 256
 image_height = 256

 train_path = 'font_model_data/train'
 valid_path =  'font_model_data/valid'
 test_path = 'font_model_data/test'

  train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width,
 image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)
 print(labels)

#CNN model
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
    Flatten(),
    Dense(**16**, activation='softmax'), # I want to make it 4
])
</code>```

I'm planning to have 4 output nodes in the network:

```<code>4 Output Nodes (4 bits):
Class 01 - 0000
Class 02 - 0001
Class 03 - 0010
Class 04 - 0011
Class 05 - 0100
Class 06 - 0101
Class 07 - 0110
Class 08 - 0111
Class 09 - 1000
Class 10 - 1001
Class 11 - 1010
Class 12 - 1011
Class 13 - 1100
Class 14 - 1101
Class 15 - 1110
Class 16 - 1111
</code>```

But the labels generated by ImageDataGenerator is a 16 bits label

```<code>[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
</code>```

How will I assign a custom label for my classes? I want my labels to be :

```<code> labels = [[0,0,0,0],
 [0,0,0,1],
 [0,0,1,0],
 [0,0,1,1],
 [0,1,0,0],
 [0,1,0,1],
 [0,1,1,0],
 [0,1,1,1],
 [1,0,0,0],
 [1,0,0,1],
 [1,0,1,0],
 [1,0,1,1],
 [1,1,0,0],
 [1,1,0,1],
 [1,1,1,0],
 [1,1,1,1]]
</code>```

The purpose of it is to make the output nodes of my network/ last dense layer from 16 to 4 nodes, thus, less complicated architecture.

答: My answer is no way to do this. You can't turn the output layer to just 4 units as you have 16 classes to classify. If you want to simplify your network, just try to reduce the number of hidden units to see the network is under fit or over fit. If it's overfit, you can reduce the complexity of your network. If it's under fit. It suggests that you need more complex network. If you really want to reduce the number of units in output layer. Maybe one way I can think of is that you can first classify what font is. This needs 4 units. Then detect what style is. This needs other 4 units. Then combine the probabilities of two outputs. I'm not sure whether this will work. You can try it.</p>

Body:
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)

Below is my initial code:

import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

 image_width = 256
 image_height = 256

 train_path = 'font_model_data/train'
 valid_path =  'font_model_data/valid'
 test_path = 'font_model_data/test'

  train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width,
 image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)
 print(labels)

#CNN model
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
    Flatten(),
    Dense(**16**, activation='softmax'), # I want to make it 4
])

I'm planning to have 4 output nodes in the network:

4 Output Nodes (4 bits):
Class 01 - 0000
Class 02 - 0001
Class 03 - 0010
Class 04 - 0011
Class 05 - 0100
Class 06 - 0101
Class 07 - 0110
Class 08 - 0111
Class 09 - 1000
Class 10 - 1001
Class 11 - 1010
Class 12 - 1011
Class 13 - 1100
Class 14 - 1101
Class 15 - 1110
Class 16 - 1111

But the labels generated by ImageDataGenerator is a 16 bits label

[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

How will I assign a custom label for my classes? I want my labels to be :

 labels = [[0,0,0,0],
 [0,0,0,1],
 [0,0,1,0],
 [0,0,1,1],
 [0,1,0,0],
 [0,1,0,1],
 [0,1,1,0],
 [0,1,1,1],
 [1,0,0,0],
 [1,0,0,1],
 [1,0,1,0],
 [1,0,1,1],
 [1,1,0,0],
 [1,1,0,1],
 [1,1,1,0],
 [1,1,1,1]]

The purpose of it is to make the output nodes of my network/ last dense layer from 16 to 4 nodes, thus, less complicated architecture.


问:
Can I preload custom fonts on iPhone to improve performance?
I've added the UIAppFonts entry on my info.plist to enable custom ttf fonts, it works fine.  However when using the font there's also a delay in the UIView the first time it's called, is there a way to preload the fonts or some other technique to avoid this?

Thanks

答: In your application delegate or some other place that is called when the application launches try creating a hidden UILabel that uses your custom font and remove it straight away. That way it will preload the font so that the next time you use a UILabel with that font it won't pay the first time penalty.</p>


答:
If using base R is not a strict requirement dplyr can be your friend:

library(dplyr)

df %>%
    filter(age >= 0
           & income <= 100

#     name age income
# 1 alicia  40    100
# 2 jessie  28     60
```

Title: select sub dataset with specific conditions without using apply & subset functions

Body:
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

 #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA

I would like to do this work without apply and subset functions.

The final dataset that I would like to have is

#    name  age income
# 1 alicia 40  100
# 2 jessie 28  60

By the way, someone can explain me why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?