问:
Why is non-existent image working on kubernetes deployment
First I have created two different version of image as below

docker image ls

```<code>REPOSITORY     |    TAG      |    IMAGE ID
isaac88/posts  |    0.0.1    |    xxx
isaac88/posts  |    0.0.5    |    yyy
</code>```

Then I created a kubernetes deployment file as below

posts-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts:0.0.1
```

<p>If you noticed, I specified version of image in deployment yaml file. by swapping the version between <code>0.0.1</code> and <code>0.0.5</code> and executed below commands to see the differences</p>

<ol>
<li><code>kubectl apply -f posts-depl.yaml</code></li>
<li><code>kubectl get pods</code></li>
<li><code>kubectl logs xxxxxxxxx</code></li>
</ol>

<p>Everything works fine so far.</p>

<p>Now I've tried to remove <code>0.0.1</code> from the deployment yaml, i'm wondering on how it behaves since I do not have a latest version being tagged to my docker image. I've verified using <code>docker image ls</code></p>

<p>Below is my latest <code>yaml</code></p>

<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts
</code>```

After removed the version, I've ran kubectl apply -f posts-depl.yaml and surprisingly it is able to create the deployment successfully, and I went ahead and executed kubectl logs xxxxx on latest pods created, I see the logs which are belongs to version 0.0.1. I don't understand the reason behind

答:
That's probably because the deployment is still using the old image. Check if there was failed image pull event by using kubectl get events and deployment history using kubectl rollout history deployment.v1.apps/posts-depl.

Check which image is currently being used in the deployment by kubectl describe deployment posts-depl

Body:
First I have created two different version of image as below

docker image ls

REPOSITORY     |    TAG      |    IMAGE ID
isaac88/posts  |    0.0.1    |    xxx
isaac88/posts  |    0.0.5    |    yyy

Then I created a kubernetes deployment file as below

posts-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts:0.0.1

If you noticed, I specified version of image in deployment yaml file. by swapping the version between 0.0.1 and 0.0.5 and executed below commands to see the differences

kubectl apply -f posts-depl.yaml

kubectl get pods

kubectl logs xxxxxxxxx

Everything works fine so far.

Now I've tried to remove 0.0.1 from the deployment yaml, i'm wondering on how it behaves since I do not have a latest version being tagged to my docker image. I've verified using docker image ls

Below is my latest yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts

After removed the version, I've ran kubectl apply -f posts-depl.yaml and surprisingly it is able to create the deployment successfully, and I went ahead and executed kubectl logs xxxxx on latest pods created, I see the logs which are belongs to version 0.0.1. I don't understand the reason behind


来源: stackexchange

问:
Count digits of number without loop C++
I have to count the number of digits in a number.

I  divide the number to 10 until I get 0. Each iteration increments the counter.

```<code>int num;
cin>>num;
while(num > 0)
{
  counter++;
  num = num / 10;
}
</code>```

The challenge is not using any loops or recursion, just an if statement.

Is it possible?

答:
You can find the length of an integer just by doing it as follows:</p>

```<code>int countDigits(int *num){
    int count =0;
    while(*num>0){
        count++;
        *num /=10;
    }
    return count;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Count digits of number without loop C++

Body:
I have to count the number of digits in a number.

I  divide the number to 10 until I get 0. Each iteration increments the counter.

int num;
cin>>num;
while(num > 0)
{
  counter++;
  num = num / 10;
}

The challenge is not using any loops or recursion, just an if statement.

Is it possible?

Body:
You can find the length of an integer just by doing it as follows:

int countDigits(int *num){
    int count =0;
    while(*num>0){
        count++;
        *num /=10;
    }
    return count;
}

ContentLicense: CC BY-SA 4.0


问:
Unable to login Spring Security - always redirects me back to login page
Could you please advise what is wrong in configuration. I can't login with correct credentials, it always redirects me back to login page (code 302). When type http://localhost:8080 - Spring Security redirects to /login, after form submitting redirects back to /login.</p>

```<code>protected void configure (AuthenticationManagerBuilder builder) throws Exception {
    builder.inMemoryAuthentication().withUser("user").password("{noop}12345").roles("USER");
}

protected void configure (HttpSecurity http) throws Exception {

    http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll().defaultSuccessUrl("/start.html").loginProcessingUrl("/authenticateMe");
</code>```

```<code>@GetMapping("/login")
    public String showLogin () {
        return "index";
    }

    @PostMapping("/authenticateMe")
    public String login () {
        return "start";
    }
</code>```

```<code><body>

  <form method="post" th:action="@{/authenticateMe}"  class="login">
    <p>
        <label th:for="username">Username: </label>
        <input type="text" th:name="username" id="username"/>
    </p>

    <p>
        <label th:for="password">Password: </label>
        <input type="password" th:name="password" id="password"/>
    </p>

</code>```

答:
The path which returns login form, on same url login form should be submitted so that spring can validate input credentials and permit the access.
In your case, login form is returned on /login but form is getting submitted to authenticateMe which is why spring security can not authenticate it and is redirecting to login form again.

You can change form action to /login and spring will take care of redirecting to /start as you have registered it as success handler

Body:
Could you please advise what is wrong in configuration. I can't login with correct credentials, it always redirects me back to login page (code 302). When type http://localhost:8080 - Spring Security redirects to /login, after form submitting redirects back to /login.

protected void configure (AuthenticationManagerBuilder builder) throws Exception {
    builder.inMemoryAuthentication().withUser("user").password("{noop}12345").roles("USER");
}

protected void configure (HttpSecurity http) throws Exception {

    http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll().defaultSuccessUrl("/start.html").loginProcessingUrl("/authenticateMe");

@GetMapping("/login")
    public String showLogin () {
        return "index";
    }

    @PostMapping("/authenticateMe")
    public String login () {
        return "start";
    }

  <form method="post" th:action="@{/authenticateMe}"  class="login">

        Username:
        <input type="text" th:name="username" id="username"/>

        Password:
        <input type="password" th:name="password" id="password"/>


问:
Casting to unsigned without specifying a type
```<code>#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}
</code>```

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?

答:
unsigned is short for writing unsigned int, so unsigned and unsigned int are the same type.

unsigned size_t does not exist; size_t is already unsigned.

why doesn't it turn into an 8 byte unsigned variable?

Because ints are commonly 32 bit or 4 bytes.

If you want fixed width integers you can use stdint.h which defines uint32_t, int32_t etc.

Body:
#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?


问:
Conditional isn't working while checking input type int
Well I'm very very new to python programming and still learning.So I tried to create a function where I used len to count the number of letters in a string.But since, len  doesn't work for integers I set up conditionals so that it would return a message saying "integers don't have length".
But I'm not getting the message even when I type an integer. please help me to solve this.
here is my code:

```<code>def Length_String(L):
    if type(L) == int:
        return "sorry,integers don't have length"
    else:
        return len(L)
x = input()
y = Length_String(x)
print(y)
</code>```

It's not that important but still I want to know what is causing the conditional not to work. please help me.

答:
In Python input() returns string no matter what you enter. So you don't need to check if the entered value is an int. If you still want to check it, you could do it with isinstance function:

```<code>if isinstance(L, int):
    return "sorry,integers don't have length"
</code>```

Body:
Well I'm very very new to python programming and still learning.So I tried to create a function where I used len to count the number of letters in a string.But since, len  doesn't work for integers I set up conditionals so that it would return a message saying "integers don't have length".
But I'm not getting the message even when I type an integer. please help me to solve this.
here is my code:

def Length_String(L):
    if type(L) == int:
        return "sorry,integers don't have length"
    else:
        return len(L)
x = input()
y = Length_String(x)
print(y)

It's not that important but still I want to know what is causing the conditional not to work. please help me.

Body:
In Python input() returns string no matter what you enter. So you don't need to check if the entered value is an int. If you still want to check it, you could do it with isinstance function:

if isinstance(L, int):
    return "sorry,integers don't have length"


问:
How to move the file pointer to next character through "ifstream" without "getting" any character, just like "fseek" does?
seekg uses ios as the second argument, and ios can be set to end or beg or some other values as shown here: http://www.cplusplus.com/reference/iostream/ios/

I just want the pointer to move to the next character, how is that to be accomplished through ifstream?

EDIT
Well, the problem is that I want a function in ifstream similar to fseek, which moves the pointer without reading anything.

答:
```<code>ifstream fin(...);
// ...

fin.get(); // <--- move one character
// or
fin.ignore(); // <--- move one character
</code>```


答:
Note you can always type help(whatever) in a Python prompt to read some useful stuff about it:

input(...)

```<code>input([prompt]) -> string

Read a string from standard input.  The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled.  The prompt string, if given,
is printed without a trailing newline before reading.
</code>```

So you always get a string. One way to see if this string could be converted to an integer is:

```<code>try:
     int(L)
     return "Error, this is an integer!"
except ValueError:
    return len(L)
</code>```

Of course, this won't work for floats, so there maybe more checks you want to do (or just use float(L)). Another way

```<code>if L.isnumeric(): # or isdigit or isdecimal
    return "Error, this is a number!"
return L
</code>```

Here it's worth mention that in addition to the help which can show methods you can always type dir(something) in a Python prompt so see some useful methods in a list.

Title: Conditional isn't working while checking input type int

Body:
Note you can always type help(whatever) in a Python prompt to read some useful stuff about it:

input(...)

input([prompt]) -> string

Read a string from standard input.  The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled.  The prompt string, if given,
is printed without a trailing newline before reading.

So you always get a string. One way to see if this string could be converted to an integer is:

try:
     int(L)
     return "Error, this is an integer!"
except ValueError:
    return len(L)

Of course, this won't work for floats, so there maybe more checks you want to do (or just use float(L)). Another way

if L.isnumeric(): # or isdigit or isdecimal
    return "Error, this is a number!"
return L

Here it's worth mention that in addition to the help which can show methods you can always type dir(something) in a Python prompt so see some useful methods in a list.


问:
Behaviour of require (static + dynamic) [ RAKU ]
My question is related to the behaviour of require when used with static or dynamic resolution of the desired namespace.

I'll try to present my understanding of things:

[ 1 ] Use "require" with a literal

```<code>    { require MODULE; }
</code>```

In this case the compiler checks to see if MODULE has already been declared as a symbol.
If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

```<code>{
    my $response = ::('MODULE');  # this happens at runtime
    say $response.^name;          # MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

    try require MODULE;           # although the execution order of require comes after the lookup,
                                  # the placeholder package creation was done during compilation and the package is present in the current scope during run-time
}
</code>```

[ 2 ] Use "require" with a String

```<code>    { try require 'FILE_PATH'; }
</code>```

In this case "require" is trying to find (at run-time) a file that is defined by the filename declared in the string.
If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

[ 3 ] Use "require" with a dynamic lookup

```<code>    { try require ::('MODULE'); }
</code>```

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

When we use "require" with "dynamic lookup" then the core functionality of the dynamic lookup is "melted" in a new routine that behaves differently than we would expect.

The fact is that the result of the "dynamic lookup" routine is either a symbol or a Failure.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

So obviously "require" isn't behaving like a "normal" subroutine in that sense.

As the result of my line of thought the combination of require + dynamic lookup resembles the following construct:

```<code>{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }
</code>```

My concern is my understanding of case [3].

How does require + dynamic lookup work? (analytically speaking - what are the steps followed by the compiler at first and then by the runtime?)

[ Post Scriptum ]

I agree with @raiph that "require" is NOT a subroutine and that it is deeply integrated in the language.

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't
bother fixing anything at compile time)

To provide the string that will be used to search for symbols,
    namespaces, files or repository content

@raiph states that he thinks that "require" does a lookup after a successful load.

My only objection about that is that when we load the same library "require" doesn't throw any exception.

Is it silently ignoring the loaded library?
Why bother doing so much work when it can check first that the same namespace is already in use?

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

To demostrate that I conducted the following:

In ./lib directory I place two libraries, the "foo.pm6" which is a unit definition of "foo" with a class A defined in it:

```<code>file "foo.pm6" contents:
-----------------------------------
unit module foo;

class A is export {}
</code>```

and another library "other.pm6" that has inside a definition of "foo" this time with a different class B defined in it.

```<code>file "other.pm6" contents:
-----------------------------------
module foo {
    class B is export {}
}
</code>```

The raku program file contains the following:

```<code>use lib <lib>;

my $name = 'other';           # select one of {'other', 'foo'}

require ::('foo') <A>;        ########> Initial package loading

my $a = try ::('foo::A').new;
say '(1) ' ~ $a.^name;        # (1) foo::A

$a = ::('A').new;
say '(2) ' ~ $a.^name;        # (2) foo::A

try require ::($name);        # if $name eq 'other' => throws exception, if $name eq 'foo' => does nothing
with $! {.say};               # P6M Merging GLOBAL symbols failed: duplicate definition of symbol foo ...

$a = try ::('foo::A').new;
say '(3) ' ~ $a.^name;        # (3) foo::A

$a = ::('A').new;
say '(4) ' ~ $a.^name;        # (4) foo::A
</code>```

From the example above we see that when we try to reload the foo namespace, hidden in a file with a different name (just to trick raku) it throws an exception.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

By the way, checking about this, I stumbled upon a strange behaviour. It's the following:

If we use "use foo;" in line: "Initial package loading" instead of "require ::('foo') ;", we get the following results:

```<code>(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) Any
(4) foo::A
</code>```

The lookup of 'foo::A' in (3) doesn't find anything !!!

Furthermore if I change the library file: "other.pm6" with the following (class A instead of B - as in the foo.pm6)

```<code>file "other.pm6" contents:
-----------------------------------
module foo {
    class A is export {}
}
</code>```

the result seem to revert to the expected:

```<code>(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) foo::A
(4) foo::A
</code>```

Is it a bug or something else that I'm missing?

答:
Rewritten to correspond to the third version of your answer.

[ 1 ] Use "require" with a literal

In this case the compiler checks to see if MODULE has already been declared as a symbol. If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

To be a bit more specific, the require keyword, and the code generated by it4, does the work.

And the only reason it's created the symbol is so that one can write that identifier and the code will compile. If require didn't do that then code that uses the identifier would fail to compile even if the require FOO would have succeeded:

```<code>require FOO;
my FOO $bar; # Type 'FOO' is not declared
</code>```

# MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

MODULE does exist. And the lookup succeeds. It returns the value bound to the MODULE symbol, which is the placeholder package that require put there during the compilation phase.

# although the execution order of require comes after the lookup

The execution of require's compilation-phase actions came before the lookup which happens during the run phase.

[ 2 ] Use "require" with a String**

If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

I think the only declaration of symbols require does is the ones the code writer has explicitly written as static identifiers as part of the require statement. Examples:

require MODULE ;       --> MODULE and A.

require 'MODULE.pm6' ; --> A.

require ::('MODULE') ; --> A.

Aiui the MLS1, as part of symbol merging (P6M), declares further symbols as necessary. But this work isn't being done by require. It's done by MLS on its behalf. And it isn't peculiar to require. It's the same (sort of) work that happens during the compile-phase as a result of a use statement.

[ 3 ] Use "require" with a dynamic lookup

```<code>{ try require ::('MODULE'); }
</code>```

I have code that is an attempt to demonstrate that this does not do a lookup before attempting to load the module.2

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

require is not a routine, normal or otherwise.

```<code>say require MODULE;   # Undeclared name:
                            MODULE used at line 1
                      # Undeclared routine:
                            require used at line 1
</code>```

If you search for require in the official doc you'll see it's not listed in the Routine Reference section but rather the Modules part of the Language Reference. It's a keyword, a statement, a special part of the language that the compiler understands.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

The result of a dynamic lookup is the value bound to a Symbol, if it's declared, or Failure otherwise:

```<code>my $variable = 42;
say ::('$variable');           # 42
say ::('nonsense') ~~ Failure; # True
</code>```

$variable is not a Namespace.

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

Given the code I wrote tracking dynamic lookup of the value of ::('MODULE')2 it looks likely to me that there is no dynamic lookup of it by any code, whether require or the MLS, if the module loading fails.

That in turn implies that it only happens, if at all, during or after (successful) loading of a module. So either the MLS is doing it (seems most likely), or, perhaps, require is doing it after the module has been successfully loaded (seems unlikely but I'm not yet ready to 100% eliminate it).

{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }

I think I've proven that there is either no lookup at all by require or the MLS, or, if it does it, it's only after a module has been successfully loaded.

what are the steps followed by the compiler at first and then by the runtime?

This answer is of course an attempt to answer that but my brief compiler code analysis may be of some help.3 (Though clicking the link to see the actual code in Actions.nqp is not for the faint of heart!)

[ Post Scriptum ]

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't bother fixing anything at compile time)

To provide the string that will be used to search for symbols, namespaces, files or repository content

I think it only does 2, just a package name that's passed to the MLS.

when we load the same library "require" doesn't throw any exception. Is it silently ignoring the loaded library?

I don't think require knows anything about it. It hands it off to the MLS and then picks up after the MLS has done its thing. I don't think require can tell the difference between when MLS does a successful fresh load and when it just skips the load. All it knows is whether MLS says all is good or there's an exception.

Why bother doing so much work when it can check first that the same namespace is already in use?

Why bother doing any work when the MLS already does it, and require is going to invoke the MLS anyway? Doing anything is wasted effort.

All require has to do is deal with the compile-phase symbols the user has explicitly typed in the require statement. It can't ask the MLS to deal with those because it's got nothing to do with a successful module load, and that's the only scenario in which the MLS goes fiddling with symbols.

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

Try this:

```<code>require ::('foo');
require ::('other');
</code>```

Now try it again when you change the unit module foo; in foo.pm6 and other.pm6 to unit module bar;. You'll still get the same exception, but the symbol will be bar. How can require know about bar? It can't. The exception is coming from the MLS and the symbol is only known about by the MLS.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

Unless you count the MLS as part of require, I trust you can now see that your "maybe" qualification was wise. :)

I stumbled upon a strange behaviour ... The lookup of 'foo::A' in (3) doesn't find anything !!!

I've got an explanation for that. I'm not saying it's right, but it doesn't seem too strange to me as I write this:

The use statement loads the foo.pm6 package. It defines a package foo, which contains a class A, and exports A. That results in a symbol in the importing lexical scope foo, which is bound to a package, which package contains a symbol A. It also results in another symbol in the importing lexical scope, A.

The require statement loads the other.pm6 package. It defines a package foo, which contains a class B, and exports B. That results in rebinding the foo symbol in the importing lexical scope to a different package, namely the new package containing the symbol B. It also results in another symbol in the importing lexical scope, B.

The earlier A hangs around. (In other words the P6M symbol merging process doesn't include removing symbols.) But foo::A, which is looked up in the package bound to the foo symbol, no longer exists, because the package bound to the foo symbol is now the one from the other.pm6 package, having overwritten the one from the foo.pm6 package.

In the meantime there's another oddity:

```<code>try require ::($name);
with $! {.say};             # No such symbol 'other' ...
</code>```

I think this reflects require doing a (failed) lookup after a successful module load.

Note that this message does not appear if the module fails to load; this seems to again confirm my thinking (and code2) that require does not do any lookup until after a successful load (if that; I still don't have a strong sense about whether it's the MLS that's doing this stuff or the require; the code4 is too complex for me atm).

Responses to your comments

From your comments on this answer:

Its like we get as the result of the amalgamation of require + 'dynamic lookup formulation' an enhanced dynamic lookup like this { ::('something') :if_not_found_as_namespace_check_repositories_and_load }

That doesn't ring true for me for various reasons.

For example, presume there's a package foo declared as module foo { our sub bar is export { say 99 } } that will successfully load if required. Now consider this code:

```<code>my \foo = 42;
say ::('foo');             # 42
require ::('foo') <&bar>;
say foo;                   # 42
bar;                       # 99
</code>```

This makes sense to me. It won't have loaded a package whose name is42. It won't have looked up the symbol foo. It will have loaded the package whose name is foo. And while it presumably will have looked up symbol foo after loading the package, it won't have installed a symbol foo because there's already one.

Footnotes

1 By Module Loading Subsystem I mean the various parts that, given a module name, do things like searching the local file system, or a database, checking precompilation directories, invoking compilation, and merging symbols if a module successfully loads. I don't know where the boundaries are between the parts, and the parts and the compiler. But I'm confident they are not part of require but merely invoked by it.

2 Run this code:

```<code>my \MODULE =
  { my $v;
    Proxy.new:
      FETCH => method { say "get name: $v"; $v },
      STORE => method ($n) { say "set name: $n"; $v = $n }}();

MODULE = 'unseen by `require`';
say ::('MODULE');

use lib '.';
say 'about to `require`';
require ::('MODULE');
</code>```

3 We start with the relevant match in Raku's Grammar.nqp file:

```<code>  rule statement_control:sym<require> {
        <sym>
        [
        | <module_name>
        | <file=.variable>
        | <!sigil> <file=.term>
        ]
        <EXPR>?
    }
</code>```

The code seems to follow what we expect -- a require keyword followed by either:

a package identifier (<module_name>); or

a <variable> (eg $foo); or

a <term> that doesn't start with a <sigil>.

We're interested in the <module_name> branch. It calls token module_name which calls token longname which calls token name:

```<code>token name {
        [
        | <identifier> <morename>*
        | <morename>+
        ]
}
</code>```

Clearly ::('foo') doesn't begin with an <identifier>. So it's token morename. I'll cut out a few uninteresting lines to leave:

```<code>{ try require ::('MODULE'); }
</code>```0

Bingo. That'll match ::(, in particular the :dba('indirect name') '(' ~ ')' [ <.ws> <EXPR> ] bit.

So at this point we'll have captured:

```<code>{ try require ::('MODULE'); }
</code>```1

A short while later the statement_control:sym<require> token will be about to succeed. So at that point it will call the corresponding action method in Actions.nqp...

4 In Actions.nqp we find the action corresponding to token statement_control:sym<require>, namely method statement_control:sym<require>. The opening if $<module_name> { conditional will be True, leading to running this code:

```<code>{ try require ::('MODULE'); }
</code>```2

It looks to me like this code is dissecting the result of parsing ::('foo'), and binding AST corresponding to that dissection to $target_package, rather than bothering to do a lookup or prepare a run-time lookup.

If I'm right, the ::('foo') does not need to be anything more than 9 characters that require gets to interpret however it fancies interpreting them. There's no necessary implication here it does any particular thing, such as a lookup, as it constructs the package loading code.

The latter half of the action does do lookups. There are lines like this:

```<code>?? self.make_indirect_lookup($longname.components())
</code>```

and given the routine name I presume that that is doing a lookup, perhaps as part of where require attempts to add a package symbol if the package load succeeds.

Body:
My question is related to the behaviour of require when used with static or dynamic resolution of the desired namespace.

I'll try to present my understanding of things:

[ 1 ] Use "require" with a literal

    { require MODULE; }

In this case the compiler checks to see if MODULE has already been declared as a symbol.
If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

{
    my $response = ::('MODULE');  # this happens at runtime
    say $response.^name;          # MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

    try require MODULE;           # although the execution order of require comes after the lookup,
                                  # the placeholder package creation was done during compilation and the package is present in the current scope during run-time
}

[ 2 ] Use "require" with a String

    { try require 'FILE_PATH'; }

In this case "require" is trying to find (at run-time) a file that is defined by the filename declared in the string.
If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

[ 3 ] Use "require" with a dynamic lookup

    { try require ::('MODULE'); }

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

When we use "require" with "dynamic lookup" then the core functionality of the dynamic lookup is "melted" in a new routine that behaves differently than we would expect.

The fact is that the result of the "dynamic lookup" routine is either a symbol or a Failure.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

So obviously "require" isn't behaving like a "normal" subroutine in that sense.

As the result of my line of thought the combination of require + dynamic lookup resembles the following construct:

{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }

My concern is my understanding of case [3].

How does require + dynamic lookup work? (analytically speaking - what are the steps followed by the compiler at first and then by the runtime?)

[ Post Scriptum ]

I agree with @raiph that "require" is NOT a subroutine and that it is deeply integrated in the language.

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't
bother fixing anything at compile time)

To provide the string that will be used to search for symbols,
    namespaces, files or repository content

@raiph states that he thinks that "require" does a lookup after a successful load.

My only objection about that is that when we load the same library "require" doesn't throw any exception.

Is it silently ignoring the loaded library?
Why bother doing so much work when it can check first that the same namespace is already in use?

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

To demostrate that I conducted the following:

In ./lib directory I place two libraries, the "foo.pm6" which is a unit definition of "foo" with a class A defined in it:

file "foo.pm6" contents:
-----------------------------------
unit module foo;

class A is export {}

and another library "other.pm6" that has inside a definition of "foo" this time with a different class B defined in it.

file "other.pm6" contents:
-----------------------------------
module foo {
    class B is export {}
}

The raku program file contains the following:

use lib <lib>;

my $name = 'other';           # select one of {'other', 'foo'}

require ::('foo') ;        ########> Initial package loading

my $a = try ::('foo::A').new;
say '(1) ' ~ $a.^name;        # (1) foo::A

$a = ::('A').new;
say '(2) ' ~ $a.^name;        # (2) foo::A

try require ::($name);        # if $name eq 'other' => throws exception, if $name eq 'foo' => does nothing
with $! {.say};               # P6M Merging GLOBAL symbols failed: duplicate definition of symbol foo ...

$a = try ::('foo::A').new;
say '(3) ' ~ $a.^name;        # (3) foo::A

$a = ::('A').new;
say '(4) ' ~ $a.^name;        # (4) foo::A

From the example above we see that when we try to reload the foo namespace, hidden in a file with a different name (just to trick raku) it throws an exception.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

By the way, checking about this, I stumbled upon a strange behaviour. It's the following:

If we use "use foo;" in line: "Initial package loading" instead of "require ::('foo') ;", we get the following results:

(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) Any
(4) foo::A

The lookup of 'foo::A' in (3) doesn't find anything !!!

Furthermore if I change the library file: "other.pm6" with the following (class A instead of B - as in the foo.pm6)

file "other.pm6" contents:
-----------------------------------
module foo {
    class A is export {}
}

the result seem to revert to the expected:

(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) foo::A
(4) foo::A

Is it a bug or something else that I'm missing?

Body:
Rewritten to correspond to the third version of your answer.

[ 1 ] Use "require" with a literal

In this case the compiler checks to see if MODULE has already been declared as a symbol. If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

To be a bit more specific, the require keyword, and the code generated by it4, does the work.

And the only reason it's created the symbol is so that one can write that identifier and the code will compile. If require didn't do that then code that uses the identifier would fail to compile even if the require FOO would have succeeded:

require FOO;
my FOO $bar; # Type 'FOO' is not declared

# MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

MODULE does exist. And the lookup succeeds. It returns the value bound to the MODULE symbol, which is the placeholder package that require put there during the compilation phase.

# although the execution order of require comes after the lookup

The execution of require's compilation-phase actions came before the lookup which happens during the run phase.

[ 2 ] Use "require" with a String**

If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

I think the only declaration of symbols require does is the ones the code writer has explicitly written as static identifiers as part of the require statement. Examples:

require MODULE <A>;       --> MODULE and A.

require 'MODULE.pm6' <A>; --> A.

require ::('MODULE') <A>; --> A.

Aiui the MLS1, as part of symbol merging (P6M), declares further symbols as necessary. But this work isn't being done by require. It's done by MLS on its behalf. And it isn't peculiar to require. It's the same (sort of) work that happens during the compile-phase as a result of a use statement.

[ 3 ] Use "require" with a dynamic lookup

{ try require ::('MODULE'); }

I have code that is an attempt to demonstrate that this does not do a lookup before attempting to load the module.2

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

require is not a routine, normal or otherwise.

say require MODULE;   # Undeclared name:
                            MODULE used at line 1
                      # Undeclared routine:
                            require used at line 1

If you search for require in the official doc you'll see it's not listed in the Routine Reference section but rather the Modules part of the Language Reference. It's a keyword, a statement, a special part of the language that the compiler understands.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

The result of a dynamic lookup is the value bound to a Symbol, if it's declared, or Failure otherwise:

my $variable = 42;
say ::('$variable');           # 42
say ::('nonsense') ~~ Failure; # True

$variable is not a Namespace.

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

Given the code I wrote tracking dynamic lookup of the value of ::('MODULE')2 it looks likely to me that there is no dynamic lookup of it by any code, whether require or the MLS, if the module loading fails.

That in turn implies that it only happens, if at all, during or after (successful) loading of a module. So either the MLS is doing it (seems most likely), or, perhaps, require is doing it after the module has been successfully loaded (seems unlikely but I'm not yet ready to 100% eliminate it).

{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }

I think I've proven that there is either no lookup at all by require or the MLS, or, if it does it, it's only after a module has been successfully loaded.

what are the steps followed by the compiler at first and then by the runtime?

This answer is of course an attempt to answer that but my brief compiler code analysis may be of some help.3 (Though clicking the link to see the actual code in Actions.nqp is not for the faint of heart!)

[ Post Scriptum ]

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't bother fixing anything at compile time)

To provide the string that will be used to search for symbols, namespaces, files or repository content

I think it only does 2, just a package name that's passed to the MLS.

when we load the same library "require" doesn't throw any exception. Is it silently ignoring the loaded library?

I don't think require knows anything about it. It hands it off to the MLS and then picks up after the MLS has done its thing. I don't think require can tell the difference between when MLS does a successful fresh load and when it just skips the load. All it knows is whether MLS says all is good or there's an exception.

Why bother doing so much work when it can check first that the same namespace is already in use?

Why bother doing any work when the MLS already does it, and require is going to invoke the MLS anyway? Doing anything is wasted effort.

All require has to do is deal with the compile-phase symbols the user has explicitly typed in the require statement. It can't ask the MLS to deal with those because it's got nothing to do with a successful module load, and that's the only scenario in which the MLS goes fiddling with symbols.

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

Try this:

require ::('foo');
require ::('other');

Now try it again when you change the unit module foo; in foo.pm6 and other.pm6 to unit module bar;. You'll still get the same exception, but the symbol will be bar. How can require know about bar? It can't. The exception is coming from the MLS and the symbol is only known about by the MLS.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

Unless you count the MLS as part of require, I trust you can now see that your "maybe" qualification was wise. :)

I stumbled upon a strange behaviour ... The lookup of 'foo::A' in (3) doesn't find anything !!!

I've got an explanation for that. I'm not saying it's right, but it doesn't seem too strange to me as I write this:

The use statement loads the foo.pm6 package. It defines a package foo, which contains a class A, and exports A. That results in a symbol in the importing lexical scope foo, which is bound to a package, which package contains a symbol A. It also results in another symbol in the importing lexical scope, A.

The require statement loads the other.pm6 package. It defines a package foo, which contains a class B, and exports B. That results in rebinding the foo symbol in the importing lexical scope to a different package, namely the new package containing the symbol B. It also results in another symbol in the importing lexical scope, B.

The earlier A hangs around. (In other words the P6M symbol merging process doesn't include removing symbols.) But foo::A, which is looked up in the package bound to the foo symbol, no longer exists, because the package bound to the foo symbol is now the one from the other.pm6 package, having overwritten the one from the foo.pm6 package.

In the meantime there's another oddity:

try require ::($name);
with $! {.say};             # No such symbol 'other' ...

I think this reflects require doing a (failed) lookup after a successful module load.

Note that this message does not appear if the module fails to load; this seems to again confirm my thinking (and code2) that require does not do any lookup until after a successful load (if that; I still don't have a strong sense about whether it's the MLS that's doing this stuff or the require; the code4 is too complex for me atm).

Responses to your comments

From your comments on this answer:

Its like we get as the result of the amalgamation of require + 'dynamic lookup formulation' an enhanced dynamic lookup like this { ::('something') :if_not_found_as_namespace_check_repositories_and_load }

That doesn't ring true for me for various reasons.

For example, presume there's a package foo declared as module foo { our sub bar is export { say 99 } } that will successfully load if required. Now consider this code:

my \foo = 42;
say ::('foo');             # 42
require ::('foo') <&bar>;
say foo;                   # 42
bar;                       # 99

This makes sense to me. It won't have loaded a package whose name is42. It won't have looked up the symbol foo. It will have loaded the package whose name is foo. And while it presumably will have looked up symbol foo after loading the package, it won't have installed a symbol foo because there's already one.

Footnotes

1 By Module Loading Subsystem I mean the various parts that, given a module name, do things like searching the local file system, or a database, checking precompilation directories, invoking compilation, and merging symbols if a module successfully loads. I don't know where the boundaries are between the parts, and the parts and the compiler. But I'm confident they are not part of require but merely invoked by it.

2 Run this code:

my \MODULE =
  { my $v;
    Proxy.new:
      FETCH => method { say "get name: $v"; $v },
      STORE => method ($n) { say "set name: $n"; $v = $n }}();

MODULE = 'unseen by `require`';
say ::('MODULE');

use lib '.';
say 'about to `require`';
require ::('MODULE');

3 We start with the relevant match in Raku's Grammar.nqp file:

  rule statement_control:sym<require> {
        <sym>
        [
        | <module_name>
        | <file=.variable>
        | <!sigil> <file=.term>
        ]
        <EXPR>?
    }

The code seems to follow what we expect -- a require keyword followed by either:

a package identifier (<module_name>); or

a <variable> (eg $foo); or

a <term> that doesn't start with a <sigil>.

We're interested in the <module_name> branch. It calls token module_name which calls token longname which calls token name:

token name {
        [
        | <identifier> <morename>*
        | <morename>+
        ]
}

Clearly ::('foo') doesn't begin with an <identifier>. So it's token morename. I'll cut out a few uninteresting lines to leave:

    token morename {
        '::'
        [
        ||  <?before '(' | <.alpha> >
            [
            | <identifier>
            | :dba('indirect name') '(' ~ ')' [ <.ws> <EXPR> ]
            ]
        ]?
    }

Bingo. That'll match ::(, in particular the :dba('indirect name') '(' ~ ')' [ <.ws> <EXPR> ] bit.

So at this point we'll have captured:

statement_control:sym<require><module_name><longname><name><morename><EXPR>

A short while later the statement_control:sym<require> token will be about to succeed. So at that point it will call the corresponding action method in Actions.nqp...

4 In Actions.nqp we find the action corresponding to token statement_control:sym<require>, namely method statement_control:sym<require>. The opening if $<module_name> { conditional will be True, leading to running this code:

$longname := $*W.dissect_longname($<module_name><longname>);
$target_package := $longname.name_past;

It looks to me like this code is dissecting the result of parsing ::('foo'), and binding AST corresponding to that dissection to $target_package, rather than bothering to do a lookup or prepare a run-time lookup.

If I'm right, the ::('foo') does not need to be anything more than 9 characters that require gets to interpret however it fancies interpreting them. There's no necessary implication here it does any particular thing, such as a lookup, as it constructs the package loading code.

The latter half of the action does do lookups. There are lines like this:

?? self.make_indirect_lookup($longname.components())

and given the routine name I presume that that is doing a lookup, perhaps as part of where require attempts to add a package symbol if the package load succeeds.


问:
Xml - PCDATA invalid Char value 2
"PCDATA invalid Char value 2" error in XML file I generate using chrome. I would like to fix it, however I don't understand what "Char value 2" is. Is there some sort of list of Char values in XMLs that are not supported, so I can view them and fix this issue.

I am using Saxy parser in Elixir.

I reviewed that thread: PHP generated XML shows invalid Char value 27 message but it didn't help me

答: If you have any special character in XML file, that must be encapsulated with <![CDATA[<special chracter]]> atleast.

Title: Xml - PCDATA invalid Char value 2


问:
How can I dock a div in IE 8?
you amazingly kind and intelligent people.  Consider the following HTML:

```<code><html>
<body>
    <div id="Panel1" style="position: absolute; bottom: 0; right: 0; top: 0;
        width: 259; background-color: #00FF00">
        <input type="button" style="position: absolute;
            left: 161; top: 30; width: 75; height: 25" tabindex="3"/>
    </div>
</body>
</html>
</code>```

What I'm doing here is docking the div to the right hand side of the screen so that it extends from the top to the bottom.  This works perfectly in Google Chrome, but not in IE8.

I've uploaded the page here http://losthobbit.net/temp/testdoc.html  in order to make your life just a little bit easier.

Any idea as to how I can get this working in IE?

Thanks!

答:
I must be losing it in my old age...

All I have to do is set the height to 100%.

Title: How can I dock a div in IE 8?

Body:
you amazingly kind and intelligent people.  Consider the following HTML:

        <input type="button" style="position: absolute;
            left: 161; top: 30; width: 75; height: 25" tabindex="3"/>

What I'm doing here is docking the div to the right hand side of the screen so that it extends from the top to the bottom.  This works perfectly in Google Chrome, but not in IE8.

I've uploaded the page here http://losthobbit.net/temp/testdoc.html  in order to make your life just a little bit easier.

Any idea as to how I can get this working in IE?

Thanks!


问:
How to share the created outlook plugin to someone without publishing it?
I'm new to outlook plugin development. I just created a sample plugin and I wanted it to share it with my friend But the files are in my local.

The reason behind I don't post my code here since its very basic and taken from the outlook doc itself. There is nothing more than that.

My question is, Is there any way to install it through js /manifest file on their mail? The sample plugin has some dependency files(script and images).

What should I do?

答:
In short, you need to publish your web app to any web server which can be accessible to your friend and give him a manifest to sideload an add-in. See Side loading an Outlook javascript add-in for more information.

The Sideload Outlook add-ins for testing article describes how to sideload add-in in Microsoft Office without putting the add-in into the catalog.


问:
Compare the first word of a page title to an array in Javascript
the following code gets the page title, compares it with data in array and outputs me a final value

```<code>var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);
</code>```

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

```<code>var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);
</code>```

but it doesn't work. What is wrong with my code ?
thanks

答:
The test cases in which it succeeds contain words such as blue, blueberry, berry blue in the array.

Just replace your test function with this

```<code>function testfunction(array, variable){
   let indexCaptured = '';
   array.forEach((res, index) => {
      if(res.includes(variable)) {
         indexCaptured = array[index+2]
      }
   });
   return indexCaptured;
}
</code>```

Body:
the following code gets the page title, compares it with data in array and outputs me a final value

var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);

but it doesn't work. What is wrong with my code ?
thanks

Body:
The test cases in which it succeeds contain words such as blue, blueberry, berry blue in the array.

Just replace your test function with this

function testfunction(array, variable){
   let indexCaptured = '';
   array.forEach((res, index) => {
      if(res.includes(variable)) {
         indexCaptured = array[index+2]
      }
   });
   return indexCaptured;
}


问:
How do I get the value of a child div
Good day,
I would like to ask how I can get the value from price. Neither of them has a unique id so it makes things hard for a noob like me. Any suggestions? Thanks.</p>

```<code><div class="modal">
    <span class="name">$</span>
    <span class="price">0.04</span>
    <hr style="background: linear-gradient(to right, #ffc82d , #ffff73);">
    <div class="weapon" style="background-image: url('assets/img/free_case_item.png');"></div>
</div>
</code>```

答:
You can do it with pure JavaScript using DOM manipulation.

Assuming you only have one element with the price class: document.getElementsByClassName("price").item(0).innerText.

Ideally you would give it an ID (e.g. price): document.getElementById("price").innerText

Title: How do I get the value of a child div

Body:
Good day,
I would like to ask how I can get the value from price. Neither of them has a unique id so it makes things hard for a noob like me. Any suggestions? Thanks.

    $
    0.04


问:
Why does c++ std::hash create a functor struct and can it be called without creating a struct each time
I'm writing a program that needs to perform a lot of hashes very fast, and in a threadsafe way. For whatever reason c++'s std::hash seems to require constructing a functor every time you want to hash a value

```<code>std::hash<std::string>{}(data);
</code>```

I'm quite concerned about the overhead of allocating an entire struct every time I want to hash a value, but I don't understand the actual reason a functor is even necessary in this context.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

```<code>std::hash<std::string> strHash;
strHash(data1);
strHash(data2);
</code>```

Is re-using one hash struct going to be threadsafe? And if not, how would I make it more threadsafe?

答:
but I don't understand the actual reason a functor is even necessary in this context.

There is a good reasons why std::hash is a functor and not a function and that is that it can have state.  The C++ standard allows for salted hashes so that each execution of the same program can create different hashed values for the same original value.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

```<code>std::hash<std::string> strHash;
strHash(data1);
strHash(data2);
</code>```

Yes, that code is safe.  You don't need to construct a hash every time you want to hash something.  It's okay to create a single hash object and use that for all of the hashes you need (in a singly threaded environment).

Is re-using one hash struct going to be threadsafe? And if not, how would I make it more threadsafe?

Depends on the use but most likely not.  std::hash has no thread safety guarantees so you need to protect the access to it using a mutex or some other synchronization technique.  Or you could just use one hash object per thread as they are required to give the same output for the same input.  This gives you a little extra space overhead but now you don't have any synchronization overhead which could be costly.

Body:
I'm writing a program that needs to perform a lot of hashes very fast, and in a threadsafe way. For whatever reason c++'s std::hash seems to require constructing a functor every time you want to hash a value

std::hash<std::string>{}(data);

I'm quite concerned about the overhead of allocating an entire struct every time I want to hash a value, but I don't understand the actual reason a functor is even necessary in this context.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

std::hash<std::string> strHash;
strHash(data1);
strHash(data2);

Is re-using one hash struct going to be threadsafe? And if not, how would I make it more threadsafe?

Body:
but I don't understand the actual reason a functor is even necessary in this context.

There is a good reasons why std::hash is a functor and not a function and that is that it can have state.  The C++ standard allows for salted hashes so that each execution of the same program can create different hashed values for the same original value.

Is it safe / correct to create one hash struct then call its operator() multiple different times?

std::hash<std::string> strHash;
strHash(data1);
strHash(data2);

Yes, that code is safe.  You don't need to construct a hash every time you want to hash something.  It's okay to create a single hash object and use that for all of the hashes you need (in a singly threaded environment).

Is re-using one hash struct going to be threadsafe? And if not, how would I make it more threadsafe?

Depends on the use but most likely not.  std::hash has no thread safety guarantees so you need to protect the access to it using a mutex or some other synchronization technique.  Or you could just use one hash object per thread as they are required to give the same output for the same input.  This gives you a little extra space overhead but now you don't have any synchronization overhead which could be costly.


问:
Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
Lets say that I have a </p>

```<code>class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}
</code>```

<p>Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer. </p>

答:
If you want the compiler to enforce this, then declare the member function const:

```<code>bool contains(string word) const
{
    ...
}
</code>```

A const function is not allowed to modify its member variables, and can only call other const member functions (either its own, or those of its member variables).

The exception to this rule is if the member variable is declared as mutable.  [But mutable should not be used as a general-purpose const workaround; it's only really meant for when situations where the "observable" state of an object should be const, but internal implementation (such as reference-counting or lazy evaluation) still needs to change.]

Note also that const does not propagate through e.g. pointers.

So in summary:

```<code>class Thingy
{
public:
    void apple() const;
    void banana();
};

class Blah
{
private:
    Thingy t;
    int *p;
    mutable int a;

public:
    Blah() { p = new int; *p = 5; }
    ~Blah() { delete p; }

    void bar() const {}
    void baz() {}

    void foo() const
    {
        p = new int;  // INVALID: p is const in this context
        *p = 10;      // VALID: *p isn't const

        baz();        // INVALID: baz() is not declared const
        bar();        // VALID: bar() is declared const

        t.banana();   // INVALID: Thingy::banana() is not declared const
        t.apple();    // VALID: Thingy::apple() is declared const

        a = 42;       // VALID: a is declared mutable
    }
};
</code>```

Body:
Lets say that I have a

class Dictionary
{
vector<string> words;
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I would like it to work with any number of data members.
P.S. I know i have no public: and private:, I left it out intentionally to make code shorter and problem clearer.

Body:
If you want the compiler to enforce this, then declare the member function const:

bool contains(string word) const
{
    ...
}

A const function is not allowed to modify its member variables, and can only call other const member functions (either its own, or those of its member variables).

The exception to this rule is if the member variable is declared as mutable.  [But mutable should not be used as a general-purpose const workaround; it's only really meant for when situations where the "observable" state of an object should be const, but internal implementation (such as reference-counting or lazy evaluation) still needs to change.]

Note also that const does not propagate through e.g. pointers.

So in summary:

class Thingy
{
public:
    void apple() const;
    void banana();
};

class Blah
{
private:
    Thingy t;
    int *p;
    mutable int a;

public:
    Blah() { p = new int; *p = 5; }
    ~Blah() { delete p; }

    void bar() const {}
    void baz() {}

    void foo() const
    {
        p = new int;  // INVALID: p is const in this context
        *p = 10;      // VALID: *p isn't const

        baz();        // INVALID: baz() is not declared const
        bar();        // VALID: bar() is declared const

        t.banana();   // INVALID: Thingy::banana() is not declared const
        t.apple();    // VALID: Thingy::apple() is declared const

        a = 42;       // VALID: a is declared mutable
    }
};


问:
How to reference a resource file from a Model in ASP.Net Core (3.1)?
So, I read all about the new localization system in ASP.Net Core (3.1) and successfully made use of the IStringLocalizer<MyController> and the IViewLocalizer<MyView>. I also could use the localization for the [DisplayName("Property description") in Models.

Below what I seem unable to do:
In good old .Net Framework I could do this:

```<code> public class Month
{
    public int MonthNumber { get; set; }

    public string  Name
    {
        get
        {
            switch(MonthNumber)
            {
                case 1:
                    return Properties.Resources.Jan;
                case 2:
                    return Properties.Resources.Feb;
                default:
                    return "?";
            }
        }
    }
</code>```

But how can I do this in a Model in ASP.Net Core 3.1?

答:
You need to inject IStringLocalizer to the class:

public class Month
{
    public int MonthNumber { get; set; }

    private readonly IStringLocalizer Localizer;

    public Month(IStringLocalizer localizer)
    {
        Localizer = localizer;
    }

    public string  Name
    {
       get
       {
           switch(MonthNumber)
           {
               case 1:
                  return Localizer["Jan"];
               case 2:
                   return Localizer["Feb"]
               default:
                   return "?";
           }
       }
    }
}
```

<p>Another approach can be done by adding localized month names for the numbers in the resource file, so:</p>

<pre class="lang-cs prettyprint-override"><code>var monthName = Localizer["4"];
// result: April for English culture
// or Nisan for Turkish culture
</code>```

Just for clarification;

The resource key can have three types of access modifiers:

Internal

Public

No code generation

If the key is marked with Internal or Public you can access it as you mentioned, because the compiler will auto generate a static class .cs linked to the relevant resource file with the key names as accessible properties.

But the common approach with Asp.Net Core is to work with Shared resources, and shared resource has the access modifier as No code generation; so thats mean no peoperty keys will be generated at the backend (.cs will not be generated). And in this case you have to inject the IStringLocalizer or whatever locaizer in use to the class.

So changing the key access modifier to Internal or Public can work as well, but it is not a best practice ;)

Body:
So, I read all about the new localization system in ASP.Net Core (3.1) and successfully made use of the IStringLocalizer<MyController> and the IViewLocalizer<MyView>. I also could use the localization for the [DisplayName("Property description") in Models.

Below what I seem unable to do:
In good old .Net Framework I could do this:

 public class Month
{
    public int MonthNumber { get; set; }

    public string  Name
    {
        get
        {
            switch(MonthNumber)
            {
                case 1:
                    return Properties.Resources.Jan;
                case 2:
                    return Properties.Resources.Feb;
                default:
                    return "?";
            }
        }
    }

But how can I do this in a Model in ASP.Net Core 3.1?

Body:
You need to inject IStringLocalizer to the class:

public class Month
{
    public int MonthNumber { get; set; }

    private readonly IStringLocalizer Localizer;

    public Month(IStringLocalizer localizer)
    {
        Localizer = localizer;
    }

    public string  Name
    {
       get
       {
           switch(MonthNumber)
           {
               case 1:
                  return Localizer["Jan"];
               case 2:
                   return Localizer["Feb"]
               default:
                   return "?";
           }
       }
    }
}

Another approach can be done by adding localized month names for the numbers in the resource file, so:

var monthName = Localizer["4"];
// result: April for English culture
// or Nisan for Turkish culture

Just for clarification;

The resource key can have three types of access modifiers:

Internal

Public

No code generation

If the key is marked with Internal or Public you can access it as you mentioned, because the compiler will auto generate a static class .cs linked to the relevant resource file with the key names as accessible properties.

But the common approach with Asp.Net Core is to work with Shared resources, and shared resource has the access modifier as No code generation; so thats mean no peoperty keys will be generated at the backend (.cs will not be generated). And in this case you have to inject the IStringLocalizer or whatever locaizer in use to the class.

So changing the key access modifier to Internal or Public can work as well, but it is not a best practice ;)


问:
Bash process substitution used as an option value
I'm trying to run

docker-compose --env-file <(cat file1.env <(echo -e "\n\n") file2.env) config
```

docker-compose expects --env-file to be a file. I need to use (concatenate) two files.

Running docker-compose --env-file file_any.env config works well.

Running cat file1.env <(echo -e "\n\n") file2.env separately outputs valid result.

But it somehow doesn't work with docker-compose.

What am I doing wrong?

答:
You don't need an additional process substitution. The outer process substitution captures the standard output of all the commands it wraps, so you aren't limited to a single cat command.

```<code>docker-compose --env-file <( cat file1.env; printf '\n\n'; cat file2.env) config
</code>```

Unfortunately, docker-compose requires the argument to --env-file be a real file. The value of the argument is passed directly to Environment.from_env_file, which makes an explicit check via env_vars_from_file:

```<code>def env_vars_from_file(filename, interpolate=True):
    """
    Read in a line delimited file of environment variables.
    """
    if not os.path.exists(filename):
        raise EnvFileNotFound("Couldn't find env file: {}".format(filename))
    <b>elif not os.path.isfile(filename):
        raise EnvFileNotFound("{} is not a file.".format(filename))</b>
    ...</code>```

Body:
I'm trying to run

docker-compose --env-file <(cat file1.env <(echo -e "\n\n") file2.env) config

docker-compose expects --env-file to be a file. I need to use (concatenate) two files.

Running docker-compose --env-file file_any.env config works well.

Running cat file1.env <(echo -e "\n\n") file2.env separately outputs valid result.

But it somehow doesn't work with docker-compose.

What am I doing wrong?

Body:
You don't need an additional process substitution. The outer process substitution captures the standard output of all the commands it wraps, so you aren't limited to a single cat command.

docker-compose --env-file <( cat file1.env; printf '\n\n'; cat file2.env) config

Unfortunately, docker-compose requires the argument to --env-file be a real file. The value of the argument is passed directly to Environment.from_env_file, which makes an explicit check via env_vars_from_file:

def env_vars_from_file(filename, interpolate=True):
    """
    Read in a line delimited file of environment variables.
    """
    if not os.path.exists(filename):
        raise EnvFileNotFound("Couldn't find env file: {}".format(filename))
    elif not os.path.isfile(filename):
        raise EnvFileNotFound("{} is not a file.".format(filename))
    ...


问:
How do I send a get request from my Api to a Xamarin forms app?
Currently I am working on a Schoolproject and I need to send a Notification to a self written Xamarin Forms App from my API. It all runs on a local network and the App can already communicate with the Api, now i want my api to send a notification to my phone if a specific event turns true. How do I do this? (Oh and I am using Python flask for my API, if u need this Information)</p>

答:
Use Push notification for it. As soon as there is a need to call
mobile app from web server send a push notification. Handle the push
notification on application side to make a call to web api as soon as
it receives the push notification with specific payload.

Use Web Sockets if server events are too frequent.


问:
Selecting between timestamps pandas
Hello I cannot understand why this code does not select rows between dates. It shows me same dataset from first date 2004. Here is my code below:

```<code>import pandas as pd
from pandas import DataFrame
import datetime
from matplotlib import pyplot as plt

df1 = pd.read_csv('time_series_15min_singleindex.csv',header=0,index_col=0,parse_dates=True)
df=DataFrame(df1,columns['utc_timestamp','DE_solar_generation_actual','DE_wind_onshore_generation_actual']

df['utc_timestamp'] = pd.to_datetime(df['utc_timestamp'],utc=True)

start_date=pd.to_datetime('2008-12-31',utc=True)
end_date=pd.to_datetime('2009-01-01',utc=True)
df[df['utc_timestamp'].between(start_date,end_date)]
df.plot()
</code>```

答:
You forget assign back, use:</p>

```<code>df = df[df['utc_timestamp'].between(start_date,end_date)]
</code>```

Title: Selecting between timestamps pandas

Body:
Hello I cannot understand why this code does not select rows between dates. It shows me same dataset from first date 2004. Here is my code below:

import pandas as pd
from pandas import DataFrame
import datetime
from matplotlib import pyplot as plt

df1 = pd.read_csv('time_series_15min_singleindex.csv',header=0,index_col=0,parse_dates=True)
df=DataFrame(df1,columns['utc_timestamp','DE_solar_generation_actual','DE_wind_onshore_generation_actual']

df['utc_timestamp'] = pd.to_datetime(df['utc_timestamp'],utc=True)

start_date=pd.to_datetime('2008-12-31',utc=True)
end_date=pd.to_datetime('2009-01-01',utc=True)
df[df['utc_timestamp'].between(start_date,end_date)]
df.plot()

Body:
You forget assign back, use:

df = df[df['utc_timestamp'].between(start_date,end_date)]


问:
password issue during build ios app with Phonegap
i want to build an ios app with phonegap and my p12 and cer files are located in
github public link.
these files has no password and when i want to submit p12 file to phonegap it require a password.
is there any way to build ios app with these files on phonegap?

the files are located here :
https://github.com/MohamadKh75/iOS_Development_Certificates

答: If there is no password in your p12 file, just press OK and it should work. Else you need to create a new certificate.</p>


问:
How to run a Qt application?
I have been using Qt creator to make applications using the Qt libraries. I can run these applications by just clicking the play button, but I want to learn how to make applications run just by double clicking on a .exe. So how can I do this?</p>

答:
If you have built a 'release' version of your program, copy it and the following DLL's from qt\bin to a directory:

QtCore4.dll, QtGui4.dll and mingwm10.dll (if you are compiling with gcc and minGW).

If you are running a 'debug' build, you will need the debug versions of the Qt DLLs. They have the same name but with a 'd' at the end of the name.

There may be other Qt DLLs you will have to copy depending on Qt modules you are using in your program.

You can find out more from this page (Qt docs website) Deploying Qt Applications

OwnerDisplayName: Lucas Aardvark

ContentLicense: CC BY-SA 2.5

Title: How to run a Qt application?


问:
How can I set Select by default in Spinner
I am to set select by default in spinner view. how can I do this </p>

<p>Please Help </p>

答:
```<code>Spinner.setSelection(int position);
</code>```

<p>refer this </p>

Body:
I am to set select by default in spinner view. how can I do this

Please Help

Body:
Spinner.setSelection(int position);

refer this


问:
How can I pass data from child component to parent component in Reactjs?
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

```<code> const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}
</code>```

This was the parent component and the following code is for "timer" component.

```<code>import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (
        <div style={style}>
            <h1>{timer}</h1>
        </div>
      );
}

export default Timer;
</code>```

答:
You can pass function as prop to child component.</p>

```<code>const Parent = () => {
    const [dataState, updateState] = useState('');

    const handler = (data) => {
        updateState(data)
    }

    return (
         <Child someHandlerProp={handler}/>
    )
}

const Child = (props) => {
    return (
        <button onClick={() => props.someHandlerProp('some data')}>Button</button>
    )
}
</code>```

Body:
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

 const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}

This was the parent component and the following code is for "timer" component.

import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (

{timer}

      );
}

export default Timer;

Body:
You can pass function as prop to child component.

const Parent = () => {
    const [dataState, updateState] = useState('');

    const handler = (data) => {
        updateState(data)
    }

    return (
         <Child someHandlerProp={handler}/>
    )
}

const Child = (props) => {
    return (
        <button onClick={() => props.someHandlerProp('some data')}>Button</button>
    )
}


问:
Docker trust: how to sign image without pushing it to repository
We run private docker registry, and I am trying to use notary to add image signing. I have notary set up, and Docker client can sign images as it pushes to the registry.

My problem is that we do not push to the same registry name we are pulling from. We use Nexus for hosting our docker images, and this is an artifact of the Nexus way of running private registry.

We push to docker-registry-publish.example.com  and pull from docker-registry.example.com

We cannot push to docker-registry.example.com

I cannot find a way to have docker, or notary, sign an image without pushing it first. What I would like to be able to do is something like this:

```<code>docker push docker-registry-publish.example.com/team1/app1:1.0
docker tag docker-registry-publish.example.com/team1/app1:1.00 docker-registry.example.com/team1/app1:1.0
$some_way_to_sign docker-registry.example.com/team1/app1:1.0
</code>```

There is no 'docker sign' command, the only way for docker to sign an image is to push it, as far as I know. 'notary sign' needs a file, and I do not know how to feed it a docker image.

Is there a way to have either docker, or notary, just do the signing?

Thank you!

答:
These are the steps I would do.

First, generate the key using docker trust key generate and name it ${key}

Then, load the key and add the signer for the image

```<code>docker trust key load --name ${key} ${key}.pub
docker trust signer add --key ${key}.pub ${key} docker-registry-publish.example.com/team1/app1:1.0
</code>```

Next, build the image:

```<code>docker build --disable-content-trust=true -t docker-registry-publish.example.com/team1/app1:1.0 .
</code>```

And then, sign the image:

```<code>docker trust sign docker-registry-publish.example.com/team1/app1:1.0
</code>```

Verify the keys and signature:

```<code>docker trust inspect --pretty docker-registry-publish.example.com/team1/app1:1.0
</code>```

And, finally, push it:

```<code>docker push docker-registry-publish.example.com/team1/app1:1.0
</code>```

Body:
We run private docker registry, and I am trying to use notary to add image signing. I have notary set up, and Docker client can sign images as it pushes to the registry.

My problem is that we do not push to the same registry name we are pulling from. We use Nexus for hosting our docker images, and this is an artifact of the Nexus way of running private registry.

We push to docker-registry-publish.example.com  and pull from docker-registry.example.com

We cannot push to docker-registry.example.com

I cannot find a way to have docker, or notary, sign an image without pushing it first. What I would like to be able to do is something like this:

docker push docker-registry-publish.example.com/team1/app1:1.0
docker tag docker-registry-publish.example.com/team1/app1:1.00 docker-registry.example.com/team1/app1:1.0
$some_way_to_sign docker-registry.example.com/team1/app1:1.0

There is no 'docker sign' command, the only way for docker to sign an image is to push it, as far as I know. 'notary sign' needs a file, and I do not know how to feed it a docker image.

Is there a way to have either docker, or notary, just do the signing?

Thank you!

Body:
These are the steps I would do.

First, generate the key using docker trust key generate and name it ${key}

Then, load the key and add the signer for the image

docker trust key load --name ${key} ${key}.pub
docker trust signer add --key ${key}.pub ${key} docker-registry-publish.example.com/team1/app1:1.0

Next, build the image:

docker build --disable-content-trust=true -t docker-registry-publish.example.com/team1/app1:1.0 .

And then, sign the image:

docker trust sign docker-registry-publish.example.com/team1/app1:1.0

Verify the keys and signature:

docker trust inspect --pretty docker-registry-publish.example.com/team1/app1:1.0

And, finally, push it:

docker push docker-registry-publish.example.com/team1/app1:1.0


问:
MS SQL Server 2016, Filestream
I'm trying to turn on for use filestream in ms sql server. But I have  follow problem. After I enabled option "Allow remote clients to have streaming access to FILESTREAM data" in sql server properties the  ms sql server service  will create share folder only for user NT Authority\Authenticated users, okey. Next step I tried to open that share folder from my domain network but access was denied. How I can fix it?</p>

答:
SQL Server FileTable no access to Share

SQL needs to grant your context access. FILESTREAM location is a place, to grant access a an object is needed (FILE TABLE)
http://assets.red-gate.com/community/books/art-of-ss-filestream.pdf
This resource may be helpful to get the full understanding you need.

Title: MS SQL Server 2016, Filestream


问:
Automatically attach SQL Server database during/after installation
Please tell me how can we attach SQL Server database (SQL Server 2005) during installation or after installation using c#.net (desktop application). We can create a form to get details of connection string (user id, pass, server name etc..) . please tell me how can we automatically attach database with SQL Server using .net</p>

答:
You should add a Service-Based Database to your project as shown:

This way you will an app.config setting for automatic Db Attach as well :

 All that you will need to do after that is change the database server instance name.


问:
C# GetFiles with Date Filter
Is there a more efficient way to populate a list of file names from a directory with a date filter?

Currently, I'm doing this:

```<code>foreach (FileInfo flInfo in directory.GetFiles())
{
    DateTime yesterday = DateTime.Today.AddDays(-1);
    String name = flInfo.Name.Substring(3,4);
    DateTime creationTime = flInfo.CreationTime;
    if (creationTime.Date == yesterday.Date)
       yesterdaysList.Add(name);
}
</code>```

This goes through every file in the folder, and I feel like there should be a more
efficient way.

答:
I use : </p>

```<code>DirectoryInfo dI = new DirectoryInfo(fileLocation);
var files = dI.GetFiles().Where(i=>i.CreationTime>=dateFrom && i.CreationTime<=dateTo);
</code>```

OwnerDisplayName: Ben Johns

Title: C# GetFiles with Date Filter

Body:
Is there a more efficient way to populate a list of file names from a directory with a date filter?

Currently, I'm doing this:

foreach (FileInfo flInfo in directory.GetFiles())
{
    DateTime yesterday = DateTime.Today.AddDays(-1);
    String name = flInfo.Name.Substring(3,4);
    DateTime creationTime = flInfo.CreationTime;
    if (creationTime.Date == yesterday.Date)
       yesterdaysList.Add(name);
}

This goes through every file in the folder, and I feel like there should be a more
efficient way.

Body:
I use :

DirectoryInfo dI = new DirectoryInfo(fileLocation);
var files = dI.GetFiles().Where(i=>i.CreationTime>=dateFrom && i.CreationTime<=dateTo);


问:
"... has insufficient rank for batching." What is the problem with this 3 line code?
this is my first question here.
I've been wanting to create a dataset with the popular IMDb dataset for learning purpose. The directories are as follows: .../train/pos/  and .../train/neg/ . I created a function which will merge text files with its labels and getting a error. I need your help to debug!

```<code>def datasetcreate(filepath, label):
    filepaths = tf.data.Dataset.list_files(filepath)
    return tf.stack([tf.data.Dataset.from_tensor_slices((_, tf.constant(label, dtype='int32'))) for _ in tf.data.TextLineDataset(filepaths)])
datasetcreate(['aclImdb/train/pos/*.txt'],1)
</code>```

And this is the error I'm getting:

```<code>ValueError: Value tf.Tensor(b'An American in Paris was, in many ways, the ultimate.....dancers of all time.', shape=(), dtype=string) has insufficient rank for batching.
</code>```

Why does this happen and what can I do to get rid of this? Thanks.

答:
Your code has two problems:

First, the way you load your TextLineDatasets, your loaded tensors contain string objects, which have an empty shape associated, i.e. a rank of zero. The rank of a tensor is the length of the shape property.

Secondly, you are trying to stack two tensors with different rank, which is would throw another error because, a sentence (a sequence of tokens) has a rank of 1 and the label as scalar has a rank of 0.

If you just need the dataset, I recommend to use the Tensorflow Dataset package, which has many ready-to-use datasets available.

If want to solve your particular problem, one way to fix your data pipeline is by using Datasest.interleave and the Dataset.zip functions.

# load positive sentences
filepaths = list(tf.data.Dataset.list_files('aclImdb/train/pos/*.txt'))
sentences_ds = tf.data.Dataset.from_tensor_slices(filepaths)
sentences_ds = sentences_ds.interleave(lambda text_file: tf.data.TextLineDataset(text_file) )
sentences_ds = sentences_ds.map( lambda text: tf.strings.split(text) )

# dataset for labels, create 1 label per file
labels = tf.constant(1, dtype="int32", shape=(len(filepaths)))
label_ds = tf.data.Dataset.from_tensor_slices(labels)

# combine text with label datasets
dataset =  tf.data.Dataset.zip( (sentences_ds, label_ds) )

print( list(dataset.as_numpy_iterator() ))
```

First, you use the interleave function to combine multiple text datasets to one dataset. Next, you use tf.strings.split to split each text to its tokens. Then, you create a dataset for your positive labels. Finally, you combine the two datasets using zip.

IMPORTANT: To train/run any DL models on your dataset, you will likely need further pre-processing for your sentences, e.g. build a vocabulary and train word-embeddings.

Body:
this is my first question here.
I've been wanting to create a dataset with the popular IMDb dataset for learning purpose. The directories are as follows: .../train/pos/  and .../train/neg/ . I created a function which will merge text files with its labels and getting a error. I need your help to debug!

def datasetcreate(filepath, label):
    filepaths = tf.data.Dataset.list_files(filepath)
    return tf.stack([tf.data.Dataset.from_tensor_slices((_, tf.constant(label, dtype='int32'))) for _ in tf.data.TextLineDataset(filepaths)])
datasetcreate(['aclImdb/train/pos/*.txt'],1)

And this is the error I'm getting:

ValueError: Value tf.Tensor(b'An American in Paris was, in many ways, the ultimate.....dancers of all time.', shape=(), dtype=string) has insufficient rank for batching.

Why does this happen and what can I do to get rid of this? Thanks.

Body:
Your code has two problems:

First, the way you load your TextLineDatasets, your loaded tensors contain string objects, which have an empty shape associated, i.e. a rank of zero. The rank of a tensor is the length of the shape property.

Secondly, you are trying to stack two tensors with different rank, which is would throw another error because, a sentence (a sequence of tokens) has a rank of 1 and the label as scalar has a rank of 0.

If you just need the dataset, I recommend to use the Tensorflow Dataset package, which has many ready-to-use datasets available.

If want to solve your particular problem, one way to fix your data pipeline is by using Datasest.interleave and the Dataset.zip functions.

# load positive sentences
filepaths = list(tf.data.Dataset.list_files('aclImdb/train/pos/*.txt'))
sentences_ds = tf.data.Dataset.from_tensor_slices(filepaths)
sentences_ds = sentences_ds.interleave(lambda text_file: tf.data.TextLineDataset(text_file) )
sentences_ds = sentences_ds.map( lambda text: tf.strings.split(text) )

# dataset for labels, create 1 label per file
labels = tf.constant(1, dtype="int32", shape=(len(filepaths)))
label_ds = tf.data.Dataset.from_tensor_slices(labels)

# combine text with label datasets
dataset =  tf.data.Dataset.zip( (sentences_ds, label_ds) )

print( list(dataset.as_numpy_iterator() ))

First, you use the interleave function to combine multiple text datasets to one dataset. Next, you use tf.strings.split to split each text to its tokens. Then, you create a dataset for your positive labels. Finally, you combine the two datasets using zip.

IMPORTANT: To train/run any DL models on your dataset, you will likely need further pre-processing for your sentences, e.g. build a vocabulary and train word-embeddings.


问:
Mobile Foundation Migration Studio - Supported Eclipse versions
https://mobilefirstplatform.ibmcloud.com/blog/2020/04/23/mobile-foundation-migration-studio-announce/

What is the supported version of eclipse to install this plug-in?   It says same as V7.1.

答:
The list of supported versions of Eclipse can be found at

https://www.ibm.com/software/reports/compatibility/clarity-reports/report/html/softwareReqsForProduct?deliverableId=46183B706BEA11E48038141DE954FC88&osPlatforms=AIX%7CLinux%7CMac%20OS%7CMobile%20OS%7CSolaris%7CWindows&duComponentIds=D005

Use this link to generate report above.


问:
Hibernate HQL issue expecting IDENT found "*"
I need get all data from relative table so I'm using something like this (i would use it in sql)

```<code>    private static final String SELECT_OOPR_TO_SEND = "SELECT R.* " +
                                                      "FROM offerOrderProjectRel R, offerOrder O, project P " +
                                                      "WHERE P.id = R.project_id and O.id = R.offer_order_id " +
                                                      "and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')" ;
;

    @SuppressWarnings("unchecked")
    public List<OfferOrderProjectRel> findAllOfferOrderToSendToSalesmans() {
        Query q = getSession().createQuery(SELECT_OOPR_TO_SEND);
        List<OfferOrderProjectRel> list = q.list();
        return list;
    }
</code>```

After lauching this code i'm getting that error :

org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT,
found '**' near line 1, column 10 [SELECT R.* FROM offerOrderProjectRel
R, offerOrder O, project P WHERE P.id = R.project_id and O.id =
R.offer_order_id and O.type = 'ORDER' and (P.status = 'PENDING' or
P.status ='PROTECTED')]

So how can I obtain all data from column R with hibernate?

答:
For people that received the "expecting IDENT found “*”" error when using org.springframework.data.jpa.repository.Query and found this question I'll add that you can change the nativeQuery flag to true:

```<code>@Query(value = "SELECT * FROM table1", nativeQuery = true)
List<Object> myFindAll();
</code>```

Body:
I need get all data from relative table so I'm using something like this (i would use it in sql)

    private static final String SELECT_OOPR_TO_SEND = "SELECT R.* " +
                                                      "FROM offerOrderProjectRel R, offerOrder O, project P " +
                                                      "WHERE P.id = R.project_id and O.id = R.offer_order_id " +
                                                      "and O.type = 'ORDER' and (P.status = 'PENDING' or P.status ='PROTECTED')" ;
;

    @SuppressWarnings("unchecked")
    public List<OfferOrderProjectRel> findAllOfferOrderToSendToSalesmans() {
        Query q = getSession().createQuery(SELECT_OOPR_TO_SEND);
        List<OfferOrderProjectRel> list = q.list();
        return list;
    }

After lauching this code i'm getting that error :

org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT,
found '**' near line 1, column 10 [SELECT R.* FROM offerOrderProjectRel
R, offerOrder O, project P WHERE P.id = R.project_id and O.id =
R.offer_order_id and O.type = 'ORDER' and (P.status = 'PENDING' or
P.status ='PROTECTED')]

So how can I obtain all data from column R with hibernate?

Body:
For people that received the "expecting IDENT found “*”" error when using org.springframework.data.jpa.repository.Query and found this question I'll add that you can change the nativeQuery flag to true:

@Query(value = "SELECT * FROM table1", nativeQuery = true)
List<Object> myFindAll();