问:
PHP Function pt_register
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

```<code>function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}
</code>```

Can anyone walk through this in English for me?

答:
The folks who said it's a replacement for register globals are on the right track, but that's not quite what's going on.

Way back when dinosaurs roamed the internet, PHP didn't have $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER, $_ETC super globals.  Instead (in addition to the infamous register globals) there were some regular global arrays named

```<code>$HTTP_GET_VARS
$HTTP_POST_VARS
$HTTP_SERVER_VARS
etc..
</code>```

These arrays, in addition to having unweildy long names, needed to be declared global (i.e., they wern't "super/automatic globals like $_POST, $_GET, etc.) before being used.

What pt_regsiter does is allow you export an individual variable from one of these arrays into the global scope.  So instead of writing

```<code>global      $HTTP_SERVER_VARS
global      $php_self;
$php_self   = $HTTP_SERVER_VARS['PHP_SELF']
</code>```

You could write.

```<code>pt_register('SERVER','PHP_SELF');
</code>```

And you'd have a $php_self variable in the global scope.

Other's have already commented on the specific mechanics, so I'll close with saying it would be stupid to use this function today.

However, it looks like it originated in some GNU code back in 2002.  Given that PHP3 was still in wide use (people were transitioning to PHP4), this function actually made sense.

Most of the coding patterns around PHP at the time relied havily on the global namespace to get things done.  This function actually helped LIMIT problems with register_globals.  According to the notes in the above link, the author wanted you to turn register_globals off, and the use this function to ONLY export those items you needed.

Evil? No.  Incredibly stupid to use in this day and age?  Yes

OwnerDisplayName: HaArD

Title: PHP Function pt_register

Body:
I'm a beginner with PHP, I was exposed to processed HTML forms and I'm learning how to use it to do more and more...

I'm using this function (and based on Google so are a lot of people) but I really want to understand what it's doing....

function pt_register()
{
  $num_args = func_num_args();
   $vars = array();

   if ($num_args >= 2) {
       $method = strtoupper(func_get_arg(0));

       if (($method != 'SESSION') && ($method != 'GET') && ($method != 'POST') && ($method != 'SERVER') && ($method != 'COOKIE') && ($method != 'ENV')) {
           die('The first argument of pt_register must be one of the following: GET, POST, SESSION, SERVER, COOKIE, or ENV');
     }

       $varname = "HTTP_{$method}_VARS";
      global ${$varname};

       for ($i = 1; $i < $num_args; $i++) {
           $parameter = func_get_arg($i);

           if (isset(${$varname}[$parameter])) {
               global $$parameter;
               $$parameter = ${$varname}[$parameter];
          }

       }

   } else {
       die('You must specify at least two arguments');
   }

}

Can anyone walk through this in English for me?

LastEditorDisplayName: RoBorg

Body:
The folks who said it's a replacement for register globals are on the right track, but that's not quite what's going on.

Way back when dinosaurs roamed the internet, PHP didn't have $_POST, $_GET, $_COOKIE, $_SESSION, $_SERVER, $_ETC super globals.  Instead (in addition to the infamous register globals) there were some regular global arrays named

$HTTP_GET_VARS
$HTTP_POST_VARS
$HTTP_SERVER_VARS
etc..

These arrays, in addition to having unweildy long names, needed to be declared global (i.e., they wern't "super/automatic globals like $_POST, $_GET, etc.) before being used.

What pt_regsiter does is allow you export an individual variable from one of these arrays into the global scope.  So instead of writing

global      $HTTP_SERVER_VARS
global      $php_self;
$php_self   = $HTTP_SERVER_VARS['PHP_SELF']

You could write.

pt_register('SERVER','PHP_SELF');

And you'd have a $php_self variable in the global scope.

Other's have already commented on the specific mechanics, so I'll close with saying it would be stupid to use this function today.

However, it looks like it originated in some GNU code back in 2002.  Given that PHP3 was still in wide use (people were transitioning to PHP4), this function actually made sense.

Most of the coding patterns around PHP at the time relied havily on the global namespace to get things done.  This function actually helped LIMIT problems with register_globals.  According to the notes in the above link, the author wanted you to turn register_globals off, and the use this function to ONLY export those items you needed.

Evil? No.  Incredibly stupid to use in this day and age?  Yes

OwnerDisplayName: Alan Storm


来源: stackexchange

问:
How to set default value or current date to the input[type=“date”]
I want to select today date in input type="date"</p>

```<code><input id="date" type="date" name="date" class="form-control" required>
</code>```

答:
Pure JavaScript-version of filling the date of today in a html5-input of type date:

let dateInput = document.getElementById('date');
dateInput.valueAsDate = new Date();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="date" type="date" name="date" class="form-control" required></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to select today date in input type="date"

<input id="date" type="date" name="date" class="form-control" required>

Body:
Pure JavaScript-version of filling the date of today in a html5-input of type date:

let dateInput = document.getElementById('date');
dateInput.valueAsDate = new Date();

<input id="date" type="date" name="date" class="form-control" required>


问:
How to define optional methods in a Swift protocol with Swift parameters?

TL;DR

How can I define optional methods in a swift protocol that accept custom typed parameters?

The case

I understand that the way to define optional methods in a swift protocol is using the @objc flag. Like so:

```<code>@objc protocol someSweetProtocol {
    optional func doSomethingCool()
}
</code>```

But when I wanted to use my custom type for the parameter, like so:

```<code>@objc protocol someSweetProtocol {
    optional func doSomethingCool(: HSCoolPerson)
}
</code>```

I got this error:

Which is not cool.

How can this problem be solved? Also can you explain why this is happening?

Addendum

This is how HSCoolPerson is defined:

```<code>class HSCoolPerson {
    ...
    ...
    ...
}
</code>```

Nothing special there...

答:
you can declare func like that in protocol</p>

```<code>@objc optional func doSomethingCool(: HSCoolPerson)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
TL;DR

How can I define optional methods in a swift protocol that accept custom typed parameters?

The case

I understand that the way to define optional methods in a swift protocol is using the @objc flag. Like so:

@objc protocol someSweetProtocol {
    optional func doSomethingCool()
}

But when I wanted to use my custom type for the parameter, like so:

@objc protocol someSweetProtocol {
    optional func doSomethingCool(: HSCoolPerson)
}

I got this error:

Which is not cool.

How can this problem be solved? Also can you explain why this is happening?

Addendum

This is how HSCoolPerson is defined:

class HSCoolPerson {
    ...
    ...
    ...
}

Nothing special there...

Body:
you can declare func like that in protocol

@objc optional func doSomethingCool(: HSCoolPerson)


问:
Checking to see if a thread has started in MicroPython
I am just trying out some MicroPython scripts on LEGO EV3 unit and I am struggling to find any documentation/examples that tells me how to check if a thread is running.

```<code>def newMethod():
    print("new method")
t1 = threading.Thread(target=newMethod)
while True:
    ...
    if t1.is_alive() is False:
        t1.start()
</code>```

Now this works, apart from the test to see if t1 has been started or not. But it is Python2.7. Thankfully most of it works in microPython apart from the is_alive? I get an error.

```<code>Traceback (most recent call last):
  File "./micro.py", line 79, in <module>
  File "./micro.py", line 73, in <module>
AttributeError: 'Thread' object has no attribute 'is_alive'
</code>```

Do I need to track this manually? or is there a built in method like python 2.7

答:
is_alive is not implemented for any of the ports supporting threads currently (in the official repository, don't know about others). So your options are:

track it manually

use different logic in your code so you don't need it

create a feature request

implement it yourself for the port you use (if you know C this could be relatively easy as thread implementation usually have a built-in way to report their state)

For the last case I got curious and came up with this, for the unix port as I don't have Lego to play with, which adds is_alive to the _thread module. From thereon it should be fairly easy to get it in your Threading class. Note this is just to give you an idea of what it takes, and is untested proof of concept, YMMV. Patch:

```<code>--- a/ports/unix/mpthreadport.c
+++ b/ports/unix/mpthreadport.c
@@ -174,7 +174,20 @@ void mp_thread_start(void) {
     pthread_mutex_unlock(&thread_mutex);
 }

-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+int mp_thread_is_alive(void* id) {
+    int ready = 0;
+    pthread_mutex_lock(&thread_mutex);
+    for (thread_t *th = thread; th != NULL; th = th->next) {
+        if (th->id == (pthread_t)id && th->ready) {
+            ready = 1;
+            break;
+        }
+    }
+    pthread_mutex_unlock(&thread_mutex);
+    return ready;
+}
+
+void* mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
     // default stack size is 8k machine-words
     if (*stack_size == 0) {
         *stack_size = 8192 * BYTES_PER_WORD;
@@ -225,7 +238,7 @@ void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {

     pthread_mutex_unlock(&thread_mutex);

-    return;
+    return (void*) th->id;

 er:
     mp_raise_OSError(ret);
diff --git a/py/modthread.c b/py/modthread.c
index 91237a7..246dd5c 100644
--- a/py/modthread.c
+++ b/py/modthread.c
@@ -264,9 +264,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args)
     th_args->fun = args[0];

     // spawn the thread!
-    mp_thread_create(thread_entry, th_args, &th_args->stack_size);
-
-    return mp_const_none;
+    return mp_obj_new_int_from_uint((uintptr_t)mp_thread_create(thread_entry, th_args, &th_args->stack_size));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);

@@ -275,6 +273,11 @@ STATIC mp_obj_t mod_thread_exit(void) {
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);

+STATIC mp_obj_t mod_thread_is_alive(mp_obj_t id) {
+    return mp_obj_new_bool(mp_thread_is_alive((void*) mp_obj_get_int(id)));
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_thread_is_alive_obj, mod_thread_is_alive);
+
 STATIC mp_obj_t mod_thread_allocate_lock(void) {
     return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
 }
@@ -287,6 +290,7 @@ STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
     { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
     { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
     { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
+    { MP_ROM_QSTR(MP_QSTR_is_alive), MP_ROM_PTR(&mod_thread_is_alive_obj) },
     { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
 };

diff --git a/py/mpthread.h b/py/mpthread.h
index 602df83..46f1a3a 100644
--- a/py/mpthread.h
+++ b/py/mpthread.h
@@ -40,7 +40,8 @@ struct _mp_state_thread_t;

 struct _mp_state_thread_t *mp_thread_get_state(void);
 void mp_thread_set_state(void *state);
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size);
+void* mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size);
+int mp_thread_is_alive(void*);
</code>```

Which enables code like:

```<code>import _thread
import utime

def Entry():
    utime.sleep_ms(1)

t = _thread.start_new_thread(Entry, ())
for i in range(10):
    print('thread alive', _thread.is_alive(t))
</code>```

Which prints True a couple of times, then False.

Body:
I am just trying out some MicroPython scripts on LEGO EV3 unit and I am struggling to find any documentation/examples that tells me how to check if a thread is running.

def newMethod():
    print("new method")
t1 = threading.Thread(target=newMethod)
while True:
    ...
    if t1.is_alive() is False:
        t1.start()

Now this works, apart from the test to see if t1 has been started or not. But it is Python2.7. Thankfully most of it works in microPython apart from the is_alive? I get an error.

Traceback (most recent call last):
  File "./micro.py", line 79, in <module>
  File "./micro.py", line 73, in <module>
AttributeError: 'Thread' object has no attribute 'is_alive'

Do I need to track this manually? or is there a built in method like python 2.7

Body:
is_alive is not implemented for any of the ports supporting threads currently (in the official repository, don't know about others). So your options are:

track it manually

use different logic in your code so you don't need it

create a feature request

implement it yourself for the port you use (if you know C this could be relatively easy as thread implementation usually have a built-in way to report their state)

For the last case I got curious and came up with this, for the unix port as I don't have Lego to play with, which adds is_alive to the _thread module. From thereon it should be fairly easy to get it in your Threading class. Note this is just to give you an idea of what it takes, and is untested proof of concept, YMMV. Patch:

--- a/ports/unix/mpthreadport.c
+++ b/ports/unix/mpthreadport.c
@@ -174,7 +174,20 @@ void mp_thread_start(void) {
     pthread_mutex_unlock(&thread_mutex);
 }

-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
+int mp_thread_is_alive(void* id) {
+    int ready = 0;
+    pthread_mutex_lock(&thread_mutex);
+    for (thread_t *th = thread; th != NULL; th = th->next) {
+        if (th->id == (pthread_t)id && th->ready) {
+            ready = 1;
+            break;
+        }
+    }
+    pthread_mutex_unlock(&thread_mutex);
+    return ready;
+}
+
+void* mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {
     // default stack size is 8k machine-words
     if (*stack_size == 0) {
         *stack_size = 8192 * BYTES_PER_WORD;
@@ -225,7 +238,7 @@ void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) {

     pthread_mutex_unlock(&thread_mutex);

-    return;
+    return (void*) th->id;

 er:
     mp_raise_OSError(ret);
diff --git a/py/modthread.c b/py/modthread.c
index 91237a7..246dd5c 100644
--- a/py/modthread.c
+++ b/py/modthread.c
@@ -264,9 +264,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args)
     th_args->fun = args[0];

     // spawn the thread!
-    mp_thread_create(thread_entry, th_args, &th_args->stack_size);
-
-    return mp_const_none;
+    return mp_obj_new_int_from_uint((uintptr_t)mp_thread_create(thread_entry, th_args, &th_args->stack_size));
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_thread_start_new_thread_obj, 2, 3, mod_thread_start_new_thread);

@@ -275,6 +273,11 @@ STATIC mp_obj_t mod_thread_exit(void) {
 }
 STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_thread_exit_obj, mod_thread_exit);

+STATIC mp_obj_t mod_thread_is_alive(mp_obj_t id) {
+    return mp_obj_new_bool(mp_thread_is_alive((void*) mp_obj_get_int(id)));
+}
+STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_thread_is_alive_obj, mod_thread_is_alive);
+
 STATIC mp_obj_t mod_thread_allocate_lock(void) {
     return MP_OBJ_FROM_PTR(mp_obj_new_thread_lock());
 }
@@ -287,6 +290,7 @@ STATIC const mp_rom_map_elem_t mp_module_thread_globals_table[] = {
     { MP_ROM_QSTR(MP_QSTR_stack_size), MP_ROM_PTR(&mod_thread_stack_size_obj) },
     { MP_ROM_QSTR(MP_QSTR_start_new_thread), MP_ROM_PTR(&mod_thread_start_new_thread_obj) },
     { MP_ROM_QSTR(MP_QSTR_exit), MP_ROM_PTR(&mod_thread_exit_obj) },
+    { MP_ROM_QSTR(MP_QSTR_is_alive), MP_ROM_PTR(&mod_thread_is_alive_obj) },
     { MP_ROM_QSTR(MP_QSTR_allocate_lock), MP_ROM_PTR(&mod_thread_allocate_lock_obj) },
 };

diff --git a/py/mpthread.h b/py/mpthread.h
index 602df83..46f1a3a 100644
--- a/py/mpthread.h
+++ b/py/mpthread.h
@@ -40,7 +40,8 @@ struct _mp_state_thread_t;

 struct _mp_state_thread_t *mp_thread_get_state(void);
 void mp_thread_set_state(void *state);
-void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size);
+void* mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size);
+int mp_thread_is_alive(void*);

Which enables code like:

import _thread
import utime

def Entry():
    utime.sleep_ms(1)

t = _thread.start_new_thread(Entry, ())
for i in range(10):
    print('thread alive', _thread.is_alive(t))

Which prints True a couple of times, then False.


问:
Update deeply nested Array using Nodejs in mongodb
I want to update address based on _id for the nested array object in below document:

```<code>{
  "_id": "fb369348-341b-11e9-9e05-03b09392591c",
  "user": [
    {
      "_id": "fb369349-341b-11e9-9e05-03b09392591c",
      "name": "test1",
      "address": [
        {
          "_id": "fb369350-341b-11e9-9e05-03b09392591c",
          "loc1": "place1, chennai, India",
          "type": "home"
        },
        {
          "_id": "fb369351-341b-11e9-9e05-03b09392591c",
          "loc1": "palce2, chennai, India",
          "type": "work"
        }
      ]
    },
    {},
    {},
    {}
  ]
}
</code>```

I am using below query in mongodb its working fine and the record is getting updated:

```<code>db.user_details.update(
    { "user.address._id": 'fb369350-341b-11e9-9e05-03b09392591c' },
    { $set: {
            "user.$.address.$[i].loc1": "11111111111",
            "user.$.address.$[i].type": "fdfdfddfdfdfdfdfdfdfdf"
            }
    },
    { arrayFilters: [{ "i._id": 'fb369350-341b-11e9-9e05-03b09392591c'}] }
)
</code>```

but when I am trying to use the above query in node js I am getting the error:

TypeError: Cannot read property 'castForQuery' of undefined

Can anyone help me to understand why I am getting a castForQuery error, _id is uuid and saved as string type?

答:
I faced the same problem. In my case everything was right but my mongoose version was not appropriate.

I salved my issue by updating the Mongoose version. Previously I was using mongoose@5.0.15. By the following command, I upgraded my mongoose version.

```<code>npm install mongoose@5.5.11
</code>```

After that, it worked.

Body:
I want to update address based on _id for the nested array object in below document:

{
  "_id": "fb369348-341b-11e9-9e05-03b09392591c",
  "user": [
    {
      "_id": "fb369349-341b-11e9-9e05-03b09392591c",
      "name": "test1",
      "address": [
        {
          "_id": "fb369350-341b-11e9-9e05-03b09392591c",
          "loc1": "place1, chennai, India",
          "type": "home"
        },
        {
          "_id": "fb369351-341b-11e9-9e05-03b09392591c",
          "loc1": "palce2, chennai, India",
          "type": "work"
        }
      ]
    },
    {},
    {},
    {}
  ]
}

I am using below query in mongodb its working fine and the record is getting updated:

db.user_details.update(
    { "user.address._id": 'fb369350-341b-11e9-9e05-03b09392591c' },
    { $set: {
            "user.$.address.$[i].loc1": "11111111111",
            "user.$.address.$[i].type": "fdfdfddfdfdfdfdfdfdfdf"
            }
    },
    { arrayFilters: [{ "i._id": 'fb369350-341b-11e9-9e05-03b09392591c'}] }
)

but when I am trying to use the above query in node js I am getting the error:

TypeError: Cannot read property 'castForQuery' of undefined

Can anyone help me to understand why I am getting a castForQuery error, _id is uuid and saved as string type?

Body:
I faced the same problem. In my case everything was right but my mongoose version was not appropriate.

I salved my issue by updating the Mongoose version. Previously I was using mongoose@5.0.15. By the following command, I upgraded my mongoose version.

npm install mongoose@5.5.11

After that, it worked.


问:
access DOM and change element font and colour

I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

```<code>var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"
</code>```

答:
loading.....

var txt=document.getElementById('d1').getElementsByTagName('p')[0]          var edit=txt.innerHTML//ocnvertobject  to string
var len=txt.innerHTML.length
var index=0 //container for scroll the string and change style each corrector
txt.innerHTML=edit[index].toUpperCase().fontsize(150).fontcolor("red")+edit.slice(index+1,len)
++index
i with this code edit corrector of my string

Body:
I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this

var txt=document.getElementById('d1').getElementsByTagName('p')[0]
            txt.innerHTML="H"
            txt.style.color="red"

Body:
<div id="d1">
    <p>loading.....</p>
</div>
var txt=document.getElementById('d1').getElementsByTagName('p')[0]          var edit=txt.innerHTML//ocnvertobject  to string
var len=txt.innerHTML.length
var index=0 //container for scroll the string and change style each corrector
txt.innerHTML=edit[index].toUpperCase().fontsize(150).fontcolor("red")+edit.slice(index+1,len)
++index
i with this code edit corrector of my string


问:
Mouse missing inside the mobile device emulator in Chrome dev tools, how to get it back?
I'm not sure if something just changed with dev tools with an update or if I accidentally pressed something on the settings but I no longer get the circle mouse indicator inside the mobile emulator. Is there a way to get it back?

Steps to replicate:

Open dev tools (press F12 key)

Toggle the device tool bar (Ctrl + Shift + M, the focused window must be the dev tool bar for this shortcut to work or just click the device icon)

Select "iPhone 6" from the drop down

Mouse into the mobile emulator window

In my case the mouse disappears, how to get it back so I know where I'm clicking?

答:
If you have Intel Graphics. Just go here

Intel Display settings > General > [Display Name] > Quantization Range

Change it from "default" to "full" and the problem will disappear!


问:
How to override main abstract methods from mixins
As you see in example,

I have Core class for distribute the shared variables/methods etc. into the mixins.

Abstract class for defining necessary methods, providing summary about api.

Main class for importing everything like a provider.

There isn't any runtime error of course.

Problem with this approach, mixin methods does not recognize @override annotation.

I want to create granular, clean structure for my packages. What is the best approach for this situation or what is the mistake I'm doing?

```<code>abstract class AbstractCore {
  void foo();

  void bar();
}

class Core {
  var shared;
}

mixin Feature1 on Core {
  @override // not recognized by syntax of course
  void foo() {
    // something with [shared]
  }
}

mixin Feature2 on Core {
  @override // not recognized
  void bar() {
    // yet another thing with [shared]
  }
}

class Main with Core, Feature1, Feature2 implements AbstractCore {}

</code>```

You can accept like:

Core: ApiBase(For sharing Client object, constants, keeping dispose method...)

Feature1: let's say Authentication related Api calls

Feature2: let's say Content related Api calls

Main: Api provider.

答:
Annotations don't have any impact on what the code do. They are just used for readability and tooling.

In your care, it is the analyzer that is complaining about @override, because you're not overriding anything.

Simply remove the @override decorator — it wasn't needed to begin with.

Body:
As you see in example,

I have Core class for distribute the shared variables/methods etc. into the mixins.

Abstract class for defining necessary methods, providing summary about api.

Main class for importing everything like a provider.

There isn't any runtime error of course.

Problem with this approach, mixin methods does not recognize @override annotation.

I want to create granular, clean structure for my packages. What is the best approach for this situation or what is the mistake I'm doing?

abstract class AbstractCore {
  void foo();

  void bar();
}

class Core {
  var shared;
}

mixin Feature1 on Core {
  @override // not recognized by syntax of course
  void foo() {
    // something with [shared]
  }
}

mixin Feature2 on Core {
  @override // not recognized
  void bar() {
    // yet another thing with [shared]
  }
}

class Main with Core, Feature1, Feature2 implements AbstractCore {}

You can accept like:

Core: ApiBase(For sharing Client object, constants, keeping dispose method...)

Feature1: let's say Authentication related Api calls

Feature2: let's say Content related Api calls

Main: Api provider.


问:
Hibernate Performance flush v commit
Im creating a hibernate component to interact with large incoming data to persist, both save(create) and update data with volumes in the million of rows.

I am aware of the main differences around flush v commit, for example flush syncing the "dirty" data into the persistable underlying data, and that flush allows you to sync with the underlying persistable data without actually committing so that the transaction can be rolled back if required. Commit essentially commits all persistable data to the database.

Im creating a hibernate component to interact with large incoming data to persist, both save(create) and update data with volumes in the million of rows.

I am aware of the main differences around flush v commit, for example flush syncing the "dirty" data into the persistable underlying data, and that flush allows you to sync with the underlying persistable data without actually committing so that the transaction can be rolled back if required. Commit essentially commits all persistable data to the database.

Whats a reasonable size to do a batch insert? IS 50 the max amount for reasonable performance so something like:

```<code>for (i < 1000000)
    if(i % 50 ) {
        session.flush()
    }
</code>```

I gather 50 should match the value in the hibernate.jdbc.batch_size 50

答:
It depends on your data. The batch size is a balance between the amount of items that hibernate will keep on its session, and the latency that is involved in making roundtrips to the db for flushing. If your batch size is too small, you'll end up making many roundtrips to the db. If your batch size is too large, you will end up holding many objects in hibernate's session - this can be a problem if your objects are fat.

I would say 50 is a low number: 1M / 50 = 20000 round trips. I would say for you to start with a bigger number and measure the performance. By the way, this applies for batch operations only:  hibernate.jdbc.batch_size is 50 is for regular app transactions.

PS don't forget to clear the hibernate session after flush, or else hibernate will hold the persisted objects in memory even after flush.

Title: Hibernate Performance flush v commit

Body:
Im creating a hibernate component to interact with large incoming data to persist, both save(create) and update data with volumes in the million of rows.

I am aware of the main differences around flush v commit, for example flush syncing the "dirty" data into the persistable underlying data, and that flush allows you to sync with the underlying persistable data without actually committing so that the transaction can be rolled back if required. Commit essentially commits all persistable data to the database.

Im creating a hibernate component to interact with large incoming data to persist, both save(create) and update data with volumes in the million of rows.

I am aware of the main differences around flush v commit, for example flush syncing the "dirty" data into the persistable underlying data, and that flush allows you to sync with the underlying persistable data without actually committing so that the transaction can be rolled back if required. Commit essentially commits all persistable data to the database.

Whats a reasonable size to do a batch insert? IS 50 the max amount for reasonable performance so something like:

for (i < 1000000)
    if(i % 50 ) {
        session.flush()
    }

I gather 50 should match the value in the hibernate.jdbc.batch_size 50


问:
Animate first child of ListView on xamarin forms
Hello fellow developers,

I have a ListView with, you gess it, ViewCells.
As part of the first tutorial on how to work with the app, I need to animate some of the elements of the first viewcell, so the user can understand that clicking in that element will do some stuff.

I tried with MVVM:

```<code><StackLayout x:Name="{Binding CellName}" Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Margin="20">
</code>```

and then

```<code>AccessPage[0].CellName = "TutorialCell";
</code>```

but

```<code>FindByName<ViewCell>("TutorialCell")
</code>```

returns null.

I can only access the item that is binded to the StackLayout, but not the StackLayout itself, so I can:

```<code>element.ScaleTo(1.05, 200);
</code>```

Am I thinking this wrong?
Thank you.

答:
You can also cast:</p>

```<code>ITemplatedItemsView<Cell> templatedItemsView = listView as ITemplatedItemsView<Cell>;
ViewCell firstCell = templatedItemsView.TemplatedItems[0] as ViewCell;
</code>```

Body:
Hello fellow developers,

I have a ListView with, you gess it, ViewCells.
As part of the first tutorial on how to work with the app, I need to animate some of the elements of the first viewcell, so the user can understand that clicking in that element will do some stuff.

I tried with MVVM:

<StackLayout x:Name="{Binding CellName}" Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Margin="20">

and then

AccessPage[0].CellName = "TutorialCell";

but

FindByName<ViewCell>("TutorialCell")

returns null.

I can only access the item that is binded to the StackLayout, but not the StackLayout itself, so I can:

element.ScaleTo(1.05, 200);

Am I thinking this wrong?
Thank you.

Body:
You can also cast:

ITemplatedItemsView<Cell> templatedItemsView = listView as ITemplatedItemsView<Cell>;
ViewCell firstCell = templatedItemsView.TemplatedItems[0] as ViewCell;


问:
Why is admob consent form not loading on actual devices?
I am trying to implement Admob for my iOS app. The form loads on the Xcode simulator devices. I am located in the US, but I have used the following code to test that the Consent SDK is working for European users. When I use this with a simulator, the form and ads load.

```<code>PACConsentInformation.sharedInstance.debugIdentifiers = ["SPECIFIC_TO_MY_DEVICE"]
PACConsentInformation.sharedInstance.debugGeography = PACDebugGeography.EEA
</code>```

The form does not load on my physical device with this configuration. The form also did not load when I used testflight to distribute a test version to a test user in the EU. Subsequently, the ads did not load on "European" devices.

When the form should load, I get an error from the below block of code. Also. I get the error WebKitDomain Error 101. My ATS settings are set up in the plist per the Admob documentation.

```<code>thisForm.load {(_ error: Error?) -> Void in
    if let error = error {
        print("Error loading form: \(error.localizedDescription)")
        //I am getting the error here.
    } else {
        thisForm.present(from: self) { (error, userPrefersAdFree) in
            print("in present handler")
            if let error = error {
                // Handle error.
                print("error presenting: \(error.localizedDescription)")
            } else if userPrefersAdFree {
                //TODO: find a way to disable ads
            } else {
                // Check the user's consent choice.
                //let status = PACConsentInformation.sharedInstance.consentStatus
            }
        }
    }
</code>```

Does anyone know what may be causing these errors with physical devices? I have tried with a real ad id and a test ad id.

答:
Present consent form only if the following equals true</p>

```<code>If requestLocationInEEAOrUnknown == true {
//present consent form
}
else {
//do whatever is needed
}
</code>```

Body:
I am trying to implement Admob for my iOS app. The form loads on the Xcode simulator devices. I am located in the US, but I have used the following code to test that the Consent SDK is working for European users. When I use this with a simulator, the form and ads load.

PACConsentInformation.sharedInstance.debugIdentifiers = ["SPECIFIC_TO_MY_DEVICE"]
PACConsentInformation.sharedInstance.debugGeography = PACDebugGeography.EEA

The form does not load on my physical device with this configuration. The form also did not load when I used testflight to distribute a test version to a test user in the EU. Subsequently, the ads did not load on "European" devices.

When the form should load, I get an error from the below block of code. Also. I get the error WebKitDomain Error 101. My ATS settings are set up in the plist per the Admob documentation.

thisForm.load {(_ error: Error?) -> Void in
    if let error = error {
        print("Error loading form: \(error.localizedDescription)")
        //I am getting the error here.
    } else {
        thisForm.present(from: self) { (error, userPrefersAdFree) in
            print("in present handler")
            if let error = error {
                // Handle error.
                print("error presenting: \(error.localizedDescription)")
            } else if userPrefersAdFree {
                //TODO: find a way to disable ads
            } else {
                // Check the user's consent choice.
                //let status = PACConsentInformation.sharedInstance.consentStatus
            }
        }
    }

Does anyone know what may be causing these errors with physical devices? I have tried with a real ad id and a test ad id.

Body:
Present consent form only if the following equals true

If requestLocationInEEAOrUnknown == true {
//present consent form
}
else {
//do whatever is needed
}


问:
How to fix problems with russian text encoding in rtf output file in Doxygen?
My code contains comments in Russian, and when Doxygen is used to create documentation, it has text such as:</p>

```<code>Classes
•class Rack
Ð¡Ñ‚Ð¾Ð¹ÐºÐ° Ñ Ñ€Ð°Ð¼ÐºÐ°Ð¼Ð¸
</code>```

答:
You can try to change output language to Russian:

Expert -> Project -> OUTPUT_LANGUAGE Russian

Body:
My code contains comments in Russian, and when Doxygen is used to create documentation, it has text such as:

Classes
•class Rack
Ð¡Ñ‚Ð¾Ð¹ÐºÐ° Ñ Ñ€Ð°Ð¼ÐºÐ°Ð¼Ð¸


问:
How to remove the base Lablel use javascript in html?
My website is reverse proxy google (I am in china ,cannot access google  ),
like  this url :

"https://accounts.google.com/SignUp?hl=zh_CN&continue=https://myaccount.google.com/intro"

I want to  remove the base Lablel  use javascript?,But my method doesn't work,Maybe I did something wrong, I don't know why.Thank you very much for any help.

my js method :

document.body.innerHTML = document.body.innerHTML.replace('<base href.*?>','')

Original code like this :

```<code><!doctype html>
<html lang="zh-CN" dir="ltr">
  <head>
    <base href="https://accounts.google.com/">
</code>```

I expect output :

```<code><!doctype html>
  <html lang="zh-CN" dir="ltr">
    <head>
</code>```

答:
I hope this helps.</p>

```<code>var elem = document.getElementsByTagName('base');
elem[0].href = '';
</code>```

Body:
My website is reverse proxy google (I am in china ,cannot access google  ),
like  this url :

"https://accounts.google.com/SignUp?hl=zh_CN&continue=https://myaccount.google.com/intro"

I want to  remove the base Lablel  use javascript?,But my method doesn't work,Maybe I did something wrong, I don't know why.Thank you very much for any help.

my js method :

document.body.innerHTML = document.body.innerHTML.replace('<base href.*?>','')

Original code like this :

<!doctype html>

    <base href="https://accounts.google.com/">

I expect output :

<!doctype html>

Body:
I hope this helps.

var elem = document.getElementsByTagName('base');
elem[0].href = '';


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答:
To answer your title question, you can't.

Pointers are built-in types, you cannot override operators where all operands are built-in types.

Luckily, there's an overload of std::sort that allows you to specify a comparison function (or functor) so the operator< isn't used.

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !


问:
How do I manuever this element on my website
The current code I have is

```<code><div class ="main">
<div id="post" class="post">
                <div class = "upvote_downvote">
                    <div id = "upvote" class = "upvote">
                        <div class="upvote_arrow_tip"></div>

                    </div>
                    <div class = "score">
                        <p>1</p>
                    </div>
                    <div class = "downvote">
                        <div class="downvote_arrow_tip"></div>

                    </div>
                </div>
                <div class = "content">
                    <a class = "name_and_date">
                        <spam class="name">
                            <img class = "pfp" width = "30" height = "30" src="" alt="pfp">
                            <h3 class="first_last_name">FIRST NAME LAST NAME</h3>
                            <p class = "username">@USERNAME</p>
                        </spam>
                        <i class="date_time">DATE &nbsp&nbsp&nbsp&nbsp TIME</i>
                    </a>
                    <p class = "contents">POST CONTENTS</p>
                </div>
            </div>
</div>
</code>```

It is coming out like this:

What I want to happen is the upvote_downvote div to be to the left of the content div. However, when I applied float: left to both divs, the following occured:

The name_and_date container is a flex box, does this cause issues?
And, the border is being applied to the post div.

答: Perhaps use display: inline-block for the container.

Body:
The current code I have is

1

                        <spam class="name">

FIRST NAME LAST NAME

@USERNAME

                        </spam>
                        DATE &nbsp&nbsp&nbsp&nbsp TIME

POST CONTENTS

It is coming out like this:

What I want to happen is the upvote_downvote div to be to the left of the content div. However, when I applied float: left to both divs, the following occured:

The name_and_date container is a flex box, does this cause issues?
And, the border is being applied to the post div.


问:
Pandas - Writing string values to a Dataframe
I have strings stored in 2 variables. I am trying to have this added to an empty Dataframe.

```<code>variable1 = abc
variable2 = def

df = pd.DataFrame(columns=['action'])
</code>```

I am not sure how to have these two variables added to Dataframe df in column labelled action.

Expected output:

```<code>action
abc
def
</code>```

答:
Pass values to list in DataFrame constructor:

```<code>variable1 = 'abc'
variable2 = 'def'

df = pd.DataFrame([variable1, variable2], columns=['action'])
</code>```

Or use dictionary with list:

```<code>df = pd.DataFrame({'action': [variable1, variable2]})

print (df)
  action
0    abc
1    def
</code>```

Body:
I have strings stored in 2 variables. I am trying to have this added to an empty Dataframe.

variable1 = abc
variable2 = def

df = pd.DataFrame(columns=['action'])

I am not sure how to have these two variables added to Dataframe df in column labelled action.

Expected output:

action
abc
def

Body:
Pass values to list in DataFrame constructor:

variable1 = 'abc'
variable2 = 'def'

df = pd.DataFrame([variable1, variable2], columns=['action'])

Or use dictionary with list:

df = pd.DataFrame({'action': [variable1, variable2]})

print (df)
  action
0    abc
1    def


问:
Unexpected behavior of generated bison parser
I created parser via Flex/Bison, which unexpectedly fails during parsing. Here is simplified sample which shows problem

Lexer.l:

```<code>%{
#include "Parser.h"
%}
%option noyywrap nodefault

%%
"foo"               {   return FOO;                          }
"bar"               {   return BAR;                          }
"("                 {   return OP;                           }
")"                 {   return CP;                           }
[ \t\n]+            {   /*    DO NOTHING  */                 }
.                   {   YY_FATAL_ERROR("unknown character"); }
%%
</code>```

And Parser.y (with enabled tracing and verbosity):

```<code>%{
#include <stdio.h>
int yylex();
void yyerror (char const *s);
%}

%debug
%verbose
%error-verbose
%token FOO BAR OP CP

%%
program_expr :   foo_expr bar_expr   {}
;
foo_expr :   /*  NOTHING  */  {}
    |   OP FOO CP           {}
;
bar_expr :   /*  NOTHING  */  {}
    |   OP BAR CP           {}
;
%%

int main(int argc, char** argv)
{
    yydebug = 1;
    yyparse();
    return 0;
}

void yyerror (char const *s) {  fprintf(stderr, "%s\n", s); }
</code>```

But generated parser will fail if I specify input like (bar) - parse tree in that case should contain foo expression which is empty. It reports:

Starting parse

Entering state 0

Reading a token: Next token is token OP ()

Shifting token OP ()

Entering state 1

Reading a token: Next token is token BAR ()

syntax error, unexpected BAR, expecting FOO

Error: popping token OP ()

Stack now 0

Cleanup: discarding lookahead token BAR ()

Stack now 0

Here is piece of text from generated description of shift/reduce automata:

```<code>state 0
    0 $accept: . program_expr $end
    OP  shift, and go to state 1
    OP        [reduce using rule 2 (foo_expr)]
    $default  reduce using rule 2 (foo_expr)
    program_expr  go to state 2
    foo_expr      go to state 3

state 1
    3 foo_expr: OP . FOO CP
    FOO  shift, and go to state 4
state 2
    0 $accept: program_expr . $end
    $end  shift, and go to state 5
state 3
    1 program_expr: foo_expr . bar_expr
    OP  shift, and go to state 6
    $default  reduce using rule 4 (bar_expr)
    bar_expr  go to state 7
</code>```

But I cannot understand meaning/syntax of such states. What's problem with my grammar/parser?

答:
Bison generates by default LALR(1) parsers. LALR(1) stands for look ahead 1 token left to right parser.

Your grammars is not LALR(1). On OP it is not clear if to expect a foo or a bar. That is a reduce/reduce conflict.

Look here:
https://en.wikipedia.org/wiki/LALR_parser

But generally Bison could generate an LR parser. At least a wiki entry here claims that:
https://en.wikipedia.org/wiki/GNU_Bison

Your case is a "mysterious conflict": https://www.gnu.org/software/bison/manual/html_node/Mysterious-Conflicts.html#Mysterious-Conflicts

Body:
I created parser via Flex/Bison, which unexpectedly fails during parsing. Here is simplified sample which shows problem

Lexer.l:

%{
#include "Parser.h"
%}
%option noyywrap nodefault

%%
"foo"               {   return FOO;                          }
"bar"               {   return BAR;                          }
"("                 {   return OP;                           }
")"                 {   return CP;                           }
[ \t\n]+            {   /*    DO NOTHING  */                 }
.                   {   YY_FATAL_ERROR("unknown character"); }
%%

And Parser.y (with enabled tracing and verbosity):

%{
#include <stdio.h>
int yylex();
void yyerror (char const *s);
%}

%debug
%verbose
%error-verbose
%token FOO BAR OP CP

%%
program_expr :   foo_expr bar_expr   {}
;
foo_expr :   /*  NOTHING  */  {}
    |   OP FOO CP           {}
;
bar_expr :   /*  NOTHING  */  {}
    |   OP BAR CP           {}
;
%%

int main(int argc, char** argv)
{
    yydebug = 1;
    yyparse();
    return 0;
}

void yyerror (char const *s) {  fprintf(stderr, "%s\n", s); }

But generated parser will fail if I specify input like (bar) - parse tree in that case should contain foo expression which is empty. It reports:

Starting parse

Entering state 0

Reading a token: Next token is token OP ()

Shifting token OP ()

Entering state 1

Reading a token: Next token is token BAR ()

syntax error, unexpected BAR, expecting FOO

Error: popping token OP ()

Stack now 0

Cleanup: discarding lookahead token BAR ()

Stack now 0

Here is piece of text from generated description of shift/reduce automata:

state 0
    0 $accept: . program_expr $end
    OP  shift, and go to state 1
    OP        [reduce using rule 2 (foo_expr)]
    $default  reduce using rule 2 (foo_expr)
    program_expr  go to state 2
    foo_expr      go to state 3

state 1
    3 foo_expr: OP . FOO CP
    FOO  shift, and go to state 4
state 2
    0 $accept: program_expr . $end
    $end  shift, and go to state 5
state 3
    1 program_expr: foo_expr . bar_expr
    OP  shift, and go to state 6
    $default  reduce using rule 4 (bar_expr)
    bar_expr  go to state 7

But I cannot understand meaning/syntax of such states. What's problem with my grammar/parser?


问:
Start bootstrap-datepicker from current month
I am using bootstrap-datepicker. Following are the steps to reproduce my issue

Go to Demo here

Click on textbox at the bottom to open calendar

Use previous arrow to navigate away from current month (say to January)

Click outside (without selecting any date)

Click textbox again to open calendar

Actual: You'll notice last selected month is displayed (January in this case)

Expected: I need calendar to always start from current Month.

How can I do this?

答:
I also faced the same issue, to resolve this:
 Write a 'hide' event for the datepicker as-</p>

```<code>$("#startdate").datepicker({
    todayBtn:  1,
    autoclose: true,
    }).on('hide', function (selected) {
    $('#startdate').datepicker("setDate",new Date());
  });
</code>```

Body:
I also faced the same issue, to resolve this:
 Write a 'hide' event for the datepicker as-

$("#startdate").datepicker({
    todayBtn:  1,
    autoclose: true,
    }).on('hide', function (selected) {
    $('#startdate').datepicker("setDate",new Date());
  });


答:
If your intent is to clear contents of head tag, this should do:

```<code>document.getElementsByTagName('head')[0].innerHTML = ''
</code>```

If it's just base tag then:

```<code>const headTag = document.getElementsByTagName('head')[0];
const baseTag = headTag.getElementsByTagName('base')[0];
headTag.removeChild(baseTag);
</code>```

Title: How to remove the base Lablel use javascript in html?

Body:
If your intent is to clear contents of head tag, this should do:

document.getElementsByTagName('head')[0].innerHTML = ''

If it's just base tag then:

const headTag = document.getElementsByTagName('head')[0];
const baseTag = headTag.getElementsByTagName('base')[0];
headTag.removeChild(baseTag);


问:
How can I delete all lines from cursor position using vi
I have a file in Linux. I want to delete all lines from cursor position till the EOF. How can I do that using vi editor.</p>

答:
Do something like:

```<code>:1,$d
</code>```

Replace 1 with the number of the line you're on.

: - gets you to command mode

1,$ - indicates a range from the first line to the end

d - the delete command

Body:
Do something like:

:1,$d

Replace 1 with the number of the line you're on.

: - gets you to command mode

1,$ - indicates a range from the first line to the end

d - the delete command


问:
GCP Billing Frontend Instance
I wanted to play a bit with GCP. I have deployed two services:

Spring Boot Java app (simple CRUD) (called api)

React auto-generated app (no changes at all, just POC) (called default)

So, after deploy I made a couple of request to my React app and I was able to see spinning react welcome banner. Hurray! I left project at it was.

After one day (Saturday, 25th) I have received first invoice. Claiming 40 hours of Frontend instance. Screen below. App was deployed at Friday 24th, 1PM. I cannot see any other requests than initial ones.

It is a 4 or 5 days later now and I'm still being charged every day. After 2 days I disabled both apps (not a project).

Even after disabling both apps, Fronted Instance hours keep increasing. GCP claims 184 hours at this moment.

Forecasted total cost is always 0.0.

Can someone help me understand what is going on?

答:
According to App Engine instance billing,

instances are charged per-minute for their uptime

Since the App Engine is already disabled, the instances should be zero and stop the instance billing. Verify this further by:

Go to App Engine > Versions

Instances must be 0. If they are still more than 0, you can open this as an issue here

The Forecasted total cost will always be zero because you still have free credits / promotions. Once these credits are used up, the reflected costs will change.

Title: GCP Billing Frontend Instance


问:
How to pass C/CXX flags to an external project in CMake
I'm using CMake to drive the build of a project, but there are some sub-projects that need to be built using autotools. I use the ExternalProject feature in CMake to build it, but I'm having trouble passing the complete set of default C/CXX flags to the configure script for the subproject.

Currently I just pass CMAKE_C_FLAGS, CMAKE_CXX_FLAGS, etc. The issue is that this does not include the build_type specific flags, which leads to issues when compiling with debug info (for instance), as I have to manually propegate the -g flag.

Current external project config looks like:

```<code>ExternalProject_Add(
  openthread-build
  SOURCE_DIR ${openthread_SOURCE_DIR}
  BINARY_DIR ${openthread_BINARY_DIR}
  CONFIGURE_COMMAND cd ${openthread_SOURCE_DIR}
        COMMAND ${openthread_SOURCE_DIR}/configure ${OPENTHREAD_CONFIGURE_OPTS}
        "CXX=${CMAKE_CXX_COMPILER}"
        "CPP=${CMAKE_C_COMPILER} -E"
        "CC=${CMAKE_C_COMPILER}"
        "AR=${CMAKE_C_COMPILER_AR}"
        "RANLIB=${CMAKE_C_COMPILER_RANLIB}"
        "NM=${CMAKE_NM}"
        "STRIP=${CMAKE_STRIP}"
        "CFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "CPPFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "CXXFLAGS=${CMAKE_CXX_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "LDFLAGS=${CMAKE_EXE_LINKER_FLAGS}"
        "--host=${MACHINE_NAME}"
  BUILD_COMMAND ${OPENTHREAD_MAKE} ${OPENTHREAD_MAKE_ARGS}
  BUILD_ALWAYS ON
  DOWNLOAD_COMMAND  cd ${openthread_SOURCE_DIR} && ./bootstrap
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)
</code>```

Problem lines are the ones like:

```<code>"CFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
</code>```

Which could ideally be something like ${CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}}, but that doesn't work due to case sensitivity of variable names.

```<code>"CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}} ${OPENTHREAD_INCLUDE_ARG}"
</code>```

So I guess the final option is to write a function which forms CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}, converts it to upper and then expands that, but this seems quite clunky.

Is there any simple way to pass the default base set of C/CXX flags to an external project, without the need for manual hard-coding for each build type or adding functions? I expect the default CMAKE_C_FLAGS and the CMAKE_C_FLAGS_* for build type to be included.

答:
I am still open to other answers, but for now I have settled on creating an uppercase version of the build_type, and using that to extract the build_type specific flags.

```<code># get an uppercase version of the build type, for extracting build_type specific flags
if(CMAKE_BUILD_TYPE)
    string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE_UC)
endif()
</code>```

So the individual flag lines look like:

```<code>"CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
</code>```

and the full externalproject call is pretty crowded but looks like:

```<code>ExternalProject_Add(
  openthread-build
  SOURCE_DIR ${openthread_SOURCE_DIR}
  BINARY_DIR ${openthread_BINARY_DIR}
  CONFIGURE_COMMAND cd ${openthread_SOURCE_DIR}
        COMMAND ${openthread_SOURCE_DIR}/configure ${OPENTHREAD_CONFIGURE_OPTS}
        "CXX=${CMAKE_CXX_COMPILER}"
        "CPP=${CMAKE_C_COMPILER} -E"
        "CC=${CMAKE_C_COMPILER}"
        "AR=${CMAKE_C_COMPILER_AR}"
        "RANLIB=${CMAKE_C_COMPILER_RANLIB}"
        "NM=${CMAKE_NM}"
        "STRIP=${CMAKE_STRIP}"
        "CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "CPPFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "CXXFLAGS=${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "LDFLAGS=${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS_${BUILD_TYPE_UC}}"
        "--host=${MACHINE_NAME}"
  BUILD_COMMAND ${OPENTHREAD_MAKE} ${OPENTHREAD_MAKE_ARGS}
  BUILD_ALWAYS ON
  DOWNLOAD_COMMAND  cd ${openthread_SOURCE_DIR} && ./bootstrap
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)
</code>```

Body:
I'm using CMake to drive the build of a project, but there are some sub-projects that need to be built using autotools. I use the ExternalProject feature in CMake to build it, but I'm having trouble passing the complete set of default C/CXX flags to the configure script for the subproject.

Currently I just pass CMAKE_C_FLAGS, CMAKE_CXX_FLAGS, etc. The issue is that this does not include the build_type specific flags, which leads to issues when compiling with debug info (for instance), as I have to manually propegate the -g flag.

Current external project config looks like:

ExternalProject_Add(
  openthread-build
  SOURCE_DIR ${openthread_SOURCE_DIR}
  BINARY_DIR ${openthread_BINARY_DIR}
  CONFIGURE_COMMAND cd ${openthread_SOURCE_DIR}
        COMMAND ${openthread_SOURCE_DIR}/configure ${OPENTHREAD_CONFIGURE_OPTS}
        "CXX=${CMAKE_CXX_COMPILER}"
        "CPP=${CMAKE_C_COMPILER} -E"
        "CC=${CMAKE_C_COMPILER}"
        "AR=${CMAKE_C_COMPILER_AR}"
        "RANLIB=${CMAKE_C_COMPILER_RANLIB}"
        "NM=${CMAKE_NM}"
        "STRIP=${CMAKE_STRIP}"
        "CFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "CPPFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "CXXFLAGS=${CMAKE_CXX_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"
        "LDFLAGS=${CMAKE_EXE_LINKER_FLAGS}"
        "--host=${MACHINE_NAME}"
  BUILD_COMMAND ${OPENTHREAD_MAKE} ${OPENTHREAD_MAKE_ARGS}
  BUILD_ALWAYS ON
  DOWNLOAD_COMMAND  cd ${openthread_SOURCE_DIR} && ./bootstrap
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)

Problem lines are the ones like:

"CFLAGS=${CMAKE_C_FLAGS} ${OPENTHREAD_INCLUDE_ARG}"

Which could ideally be something like ${CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}}, but that doesn't work due to case sensitivity of variable names.

"CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}} ${OPENTHREAD_INCLUDE_ARG}"

So I guess the final option is to write a function which forms CMAKE_C_FLAGS_${CMAKE_BUILD_TYPE}, converts it to upper and then expands that, but this seems quite clunky.

Is there any simple way to pass the default base set of C/CXX flags to an external project, without the need for manual hard-coding for each build type or adding functions? I expect the default CMAKE_C_FLAGS and the CMAKE_C_FLAGS_* for build type to be included.

Body:
I am still open to other answers, but for now I have settled on creating an uppercase version of the build_type, and using that to extract the build_type specific flags.

# get an uppercase version of the build type, for extracting build_type specific flags
if(CMAKE_BUILD_TYPE)
    string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE_UC)
endif()

So the individual flag lines look like:

"CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"

and the full externalproject call is pretty crowded but looks like:

ExternalProject_Add(
  openthread-build
  SOURCE_DIR ${openthread_SOURCE_DIR}
  BINARY_DIR ${openthread_BINARY_DIR}
  CONFIGURE_COMMAND cd ${openthread_SOURCE_DIR}
        COMMAND ${openthread_SOURCE_DIR}/configure ${OPENTHREAD_CONFIGURE_OPTS}
        "CXX=${CMAKE_CXX_COMPILER}"
        "CPP=${CMAKE_C_COMPILER} -E"
        "CC=${CMAKE_C_COMPILER}"
        "AR=${CMAKE_C_COMPILER_AR}"
        "RANLIB=${CMAKE_C_COMPILER_RANLIB}"
        "NM=${CMAKE_NM}"
        "STRIP=${CMAKE_STRIP}"
        "CFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "CPPFLAGS=${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "CXXFLAGS=${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${BUILD_TYPE_UC}} ${OPENTHREAD_INCLUDE_ARG}"
        "LDFLAGS=${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS_${BUILD_TYPE_UC}}"
        "--host=${MACHINE_NAME}"
  BUILD_COMMAND ${OPENTHREAD_MAKE} ${OPENTHREAD_MAKE_ARGS}
  BUILD_ALWAYS ON
  DOWNLOAD_COMMAND  cd ${openthread_SOURCE_DIR} && ./bootstrap
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)


问:
Using a Do-Loop, to read a column of data (numerical & string) and filter the numbers as output into another file
I have an output file, single column, where each 7th line is a string and the others numerical (something like below)

```<code>998.69733
377.29340
142.22397
53.198547
19.743515
7.5493960
timestep:  1
998.69733
377.29340
142.22047
53.188023
19.755905
7.5060229
timestep:  2
998.69733
377.29337
</code>```

I need to read this data into another file, omitting the text and keeping only the numbers and tried a loop to allocate a dummy for my string but I get an error as it does not recognize (AI).

```<code>DO 10 I = 1, 1000
 IF (MOD(I,7) == 0) THEN
  READ (8, FMT= '(AI)') dummy
 END IF
  READ (8,*) val
  WRITE (9,*) val
10 CONTINUE
</code>```

(8 - input file and 9 - output file allocation)

I am quite new to Fortran and spent a lot of time surfing for a solution or at least a similar problem but did not find anything. I would really appreciate some help.

Thank you very much in advance.

答:
Simply use list-directed input with an empty input item list.

Also, the seventh line gets read twice in your loop. Put the read and write of val in an ELSE section, or, alternatively, us the CYCLE statement:

```
DO I = 1, 1000
  IF(MOD(I,7) == 0) THEN
    READ(8,*)
    CYCLE
  END IF
  READ(8,*) val
  WRITE(9,*) val
END DO
```

Body:
I have an output file, single column, where each 7th line is a string and the others numerical (something like below)

998.69733
377.29340
142.22397
53.198547
19.743515
7.5493960
timestep:  1
998.69733
377.29340
142.22047
53.188023
19.755905
7.5060229
timestep:  2
998.69733
377.29337

I need to read this data into another file, omitting the text and keeping only the numbers and tried a loop to allocate a dummy for my string but I get an error as it does not recognize (AI).

DO 10 I = 1, 1000
 IF (MOD(I,7) == 0) THEN
  READ (8, FMT= '(AI)') dummy
 END IF
  READ (8,*) val
  WRITE (9,*) val
10 CONTINUE

(8 - input file and 9 - output file allocation)

I am quite new to Fortran and spent a lot of time surfing for a solution or at least a similar problem but did not find anything. I would really appreciate some help.

Thank you very much in advance.

Body:
Simply use list-directed input with an empty input item list.

Also, the seventh line gets read twice in your loop. Put the read and write of val in an ELSE section, or, alternatively, us the CYCLE statement:

DO I = 1, 1000
  IF(MOD(I,7) == 0) THEN
    READ(8,*)
    CYCLE
  END IF
  READ(8,*) val
  WRITE(9,*) val
END DO


问:
need to select query or delete query to get this result or delete duplicate data
i get data and i want to select or delete query to get this result expected

sql server query

```<code>select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )
</code>```

////
try this query but not ok

with cte AS(
select *,
             row_number() over (order by (select '' )) as seqnum
      from [elo].[dbo].[objkeys]
      where parentid in (select parentid
                         from [elo].[dbo].[objekte] inner join
                              [elo].[dbo].[objkeys]
                               on objid = parentid
                         where objmask = '52' and okeydata like 'approve'
                      )
) Delete cte where seqnum >1

actual result

```<code>parentid    okeyno      okeyname        okeydata
 652          0          NAME             uwk
 652          1         NUMBER             1
 652          2         ALAIETIMAD      approve
 652          51        ELO_FNAME       16.jpg

 653          0         NAME              uwk
 653          1        NUMBER              1
 653          2       ALAIETIMAD         approve
 653         51       ELO_FNAME          16.jpg

 656          0         NAME              b
 656          1        NUMBER             1
 656          2       ALAIETIMAD        approve
 656         51       ELO_FNAME          14.jpg

 657         0      NAME                  b
 657         1      NUMBER                1
 657         2      ALAIETIMAD         approve
 657         51     ELO_FNAME          16.jpg

 661         0      NAME              abdalah
 661         1      NUMBER              1
 661         2      ALAIETIMAD        approve
 661         51     ELO_FNAME         16.jpg

 662         0      NAME             abdalah
 662         1      NUMBER             1
 662         2      ALAIETIMAD       approve
 662         51     ELO_FNAME        16.jpg
</code>```

need result to be

```<code>parentid    okeyno      okeyname        okeydata
 652          0      NAME                 uwk
 652          1     NUMBER                 1
 652          2     ALAIETIMAD         approve
 652          51    ELO_FNAME          16.jpg

 656          0     NAME                 b
 656          1     NUMBER               1
 656          2     ALAIETIMAD       approve
 656         51     ELO_FNAME        14.jpg

 661         0      NAME             abdalah
 661         1      NUMBER             1
 661         2      ALAIETIMAD       approve
 661         51     ELO_FNAME        16.jpg

</code>```

答:
Can you try the following:</p>

```<code>SELECT * FROM
(
select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )
) as t
where parentid in
(
SELECT DISTINCT min(parentid) FROM
(
select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )
) as t2
where okeyname = 'NAME'
group by okeyno,okeyname,okeydata
)
</code>```

Body:
i get data and i want to select or delete query to get this result expected

sql server query

select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )

////
try this query but not ok

with cte AS(
select *,
             row_number() over (order by (select '' )) as seqnum
      from [elo].[dbo].[objkeys]
      where parentid in (select parentid
                         from [elo].[dbo].[objekte] inner join
                              [elo].[dbo].[objkeys]
                               on objid = parentid
                         where objmask = '52' and okeydata like 'approve'
                      )
) Delete cte where seqnum >1

actual result

parentid    okeyno      okeyname        okeydata
 652          0          NAME             uwk
 652          1         NUMBER             1
 652          2         ALAIETIMAD      approve
 652          51        ELO_FNAME       16.jpg

 653          0         NAME              uwk
 653          1        NUMBER              1
 653          2       ALAIETIMAD         approve
 653         51       ELO_FNAME          16.jpg

 656          0         NAME              b
 656          1        NUMBER             1
 656          2       ALAIETIMAD        approve
 656         51       ELO_FNAME          14.jpg

 657         0      NAME                  b
 657         1      NUMBER                1
 657         2      ALAIETIMAD         approve
 657         51     ELO_FNAME          16.jpg

 661         0      NAME              abdalah
 661         1      NUMBER              1
 661         2      ALAIETIMAD        approve
 661         51     ELO_FNAME         16.jpg

 662         0      NAME             abdalah
 662         1      NUMBER             1
 662         2      ALAIETIMAD       approve
 662         51     ELO_FNAME        16.jpg

need result to be

parentid    okeyno      okeyname        okeydata
 652          0      NAME                 uwk
 652          1     NUMBER                 1
 652          2     ALAIETIMAD         approve
 652          51    ELO_FNAME          16.jpg

 656          0     NAME                 b
 656          1     NUMBER               1
 656          2     ALAIETIMAD       approve
 656         51     ELO_FNAME        14.jpg

 661         0      NAME             abdalah
 661         1      NUMBER             1
 661         2      ALAIETIMAD       approve
 661         51     ELO_FNAME        16.jpg

Body:
Can you try the following:

SELECT * FROM
(
select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )
) as t
where parentid in
(
SELECT DISTINCT min(parentid) FROM
(
select *,
         row_number() over (order by (select '' )) as seqnum
  from [elo].[dbo].[objkeys]
  where parentid in (select parentid
                     from [elo].[dbo].[objekte] inner join
                          [elo].[dbo].[objkeys]
                           on objid = parentid
                     where objmask = '52' and okeydata like 'approve'
                  )
) as t2
where okeyname = 'NAME'
group by okeyno,okeyname,okeydata
)


问:
ModelMapper not ignoring null values
I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.

I have tried this but no luck:

```<code>    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        modelMapper.createTypeMap(String.class, Date.class);
        modelMapper.addConverter(new StringToDate());
        modelMapper.addConverter(new DateToString());
        return modelMapper;
    }
</code>```

Then I update my object like this:

```<code>    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        userDocument = this.modelMapper.map(user, UserDocument.class);
        this.usersRepository.save(userDocument);
    }
</code>```

The user object has 1 property set at null while the object userDocument has it with a value, then when I save it in the database that value is gone (because it has transformed into null).

What can be wrong?

Thanks.

答:
Mybatis framework? You have not set selective save --selective

<insert id="insertSelective" parameterType="com.zjl.domain">
    insert into table_name
    <trim prefix="(" suffix=")" suffixOverrides=",">
    <if test="id != null">
    id,
    </if>
    <if test="createDate != null">
    create_date,
    </if>
    <if test="modifiedDate != null">
    modified_date,
    </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
    <if test="id != null">
    #{id,jdbcType=BIGINT},
    </if>
    <if test="createDate != null">
    #{createDate,jdbcType=TIMESTAMP},
    </if>
    <if test="modifiedDate != null">
    #{modifiedDate,jdbcType=TIMESTAMP},
    </if>
    </trim>
</insert>

Title: ModelMapper not ignoring null values

Body:
I want to do a partial update on one of my entities but if one propertie is null then the entity to be updated gets that value set to null too. I want that if a property from the source is null then to keep the one from the source.

I have tried this but no luck:

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
        modelMapper.createTypeMap(String.class, Date.class);
        modelMapper.addConverter(new StringToDate());
        modelMapper.addConverter(new DateToString());
        return modelMapper;
    }

Then I update my object like this:

    @Override
    public void editUser(final User user) {
        UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
                .orElseThrow(UserNotFoundException::new);

        userDocument = this.modelMapper.map(user, UserDocument.class);
        this.usersRepository.save(userDocument);
    }

The user object has 1 property set at null while the object userDocument has it with a value, then when I save it in the database that value is gone (because it has transformed into null).

What can be wrong?

Thanks.


问:
Is it possible to update a For End argument while inside it?
I wanted to change my For "End" argument while inside the For.

For instance:

```<code>ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i
</code>```

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

答:
You could use:</p>

```<code>Option Explicit

Sub test()

    Dim i As Long

    i = 1

    Do Until i > 6

        ThisWorkbook.Worksheets("Sheet1").Cells(i, 1).Value = 20

        i = i + 1

    Loop

End Sub
</code>```

Body:
I wanted to change my For "End" argument while inside the For.

For instance:

ForEnd = 3
for i = 1 To ForEnd
   If Something = "TRUE" Then
      ForEnd = ForEnd + 1
   End If
Next i

This doesn't work because the "End" or "Upper Limit" argument is defined once the code goes through the first line. Even if I change it inside the code it will consider the original value.

Any thoughts?

Thank you.

Body:
You could use:

Option Explicit

Sub test()

    Dim i As Long

    i = 1

    Do Until i > 6

        ThisWorkbook.Worksheets("Sheet1").Cells(i, 1).Value = 20

        i = i + 1

    Loop

End Sub


问:
Escape char in Gitlab Secret Variables
I have a secret var :

But when I do - echo %MySecretVar%, runner displays foo only

How can i escape special chars like ! in Gitlab Secret Vars ?

答:
I was able to use a value with special characters this way:

Define Gitlab CI variable FOO with special characters in the value, e.g. ?!asdf&%fghjkl

In .gitlab-ci.yml define:

```<code>variables:
  bar: '"%FOO%"'
script:
  - echo %bar%
</code>```

This way the variable will stay exactly the way it is typed in your CI variable field.

I'm using Windows batch shell. If you use another shell for script running, the syntax is a little different from %bar%. Check out the syntax here: Gitlab CI reference

Title: Escape char in Gitlab Secret Variables

Body:
I was able to use a value with special characters this way:

Define Gitlab CI variable FOO with special characters in the value, e.g. ?!asdf&%fghjkl

In .gitlab-ci.yml define:

variables:
  bar: '"%FOO%"'
script:
  - echo %bar%

This way the variable will stay exactly the way it is typed in your CI variable field.

I'm using Windows batch shell. If you use another shell for script running, the syntax is a little different from %bar%. Check out the syntax here: Gitlab CI reference


问:
Prisma Creating New Database in MongoDB
I've got Prisma connected to my MongoDB but when I make any mutations, a new database is being created in MongoDB called default_default and data is being added there instead of the database I specified when going through the setup here

https://www.prisma.io/docs/get-started/01-setting-up-prisma-existing-database-JAVASCRIPT-a003/

I'd expect the data to be saved in the database specified in the docker-compose.yml file

```<code>version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.23
    restart: always
    ports:
    - "4466:4466"
    environment:
      PRISMA_CONFIG: |
        port: 4466
        # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security
        # managementApiSecret: my-secret
        databases:
          default:
            connector: mongo
            uri: 'mongodb://host.docker.internal:27017/my-db-name'
</code>```

Has anyone experienced something similar and found a solution?

Thanks

答:
This you do in prisma.config by setting endpoint:

endpoint: http://localhost:4466/graphql/default

This will use database graphq_default

Title: Prisma Creating New Database in MongoDB

Body:
I've got Prisma connected to my MongoDB but when I make any mutations, a new database is being created in MongoDB called default_default and data is being added there instead of the database I specified when going through the setup here

https://www.prisma.io/docs/get-started/01-setting-up-prisma-existing-database-JAVASCRIPT-a003/

I'd expect the data to be saved in the database specified in the docker-compose.yml file

version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.23
    restart: always
    ports:
    - "4466:4466"
    environment:
      PRISMA_CONFIG: |
        port: 4466
        # uncomment the next line and provide the env var PRISMA_MANAGEMENT_API_SECRET=my-secret to activate cluster security
        # managementApiSecret: my-secret
        databases:
          default:
            connector: mongo
            uri: 'mongodb://host.docker.internal:27017/my-db-name'

Has anyone experienced something similar and found a solution?

Thanks


问:
Unable to match pattern when string exists in file
I'm trying to find a line that matches the below pattern in a file. I can see the pattern is output as I expect but it doesn't match.

String in file

```<code>"5/29/2019 12:01:03 PM - Sys - Logged Successfully"
</code>```

Variables

```<code>$pattern = "Logged Successfully"
$datePattern = "5/29/2019"
</code>```

Code - Working - Matches ok

```<code>$reponse = select-string -Path $path\$file -Pattern $pattern -allmatches -simplematch
</code>```

Code - Not Working

```<code>$reponse = select-string -Path $path\$file -Pattern "$($datePattern).*$($pattern)" -allmatches -simplematch
</code>```

Maybe im missing something very simple, any help greatly appreciated.

答: Remove the -simplematch switch from the code sample that is not working and then it will work. You are disabling a regular expression match while using that switch. See this previous SO answer from Mathias R. Jessen where he explains in more detail.

Body:
I'm trying to find a line that matches the below pattern in a file. I can see the pattern is output as I expect but it doesn't match.

String in file

"5/29/2019 12:01:03 PM - Sys - Logged Successfully"

Variables

$pattern = "Logged Successfully"
$datePattern = "5/29/2019"

Code - Working - Matches ok

$reponse = select-string -Path $path\$file -Pattern $pattern -allmatches -simplematch

Code - Not Working

$reponse = select-string -Path $path\$file -Pattern "$($datePattern).*$($pattern)" -allmatches -simplematch

Maybe im missing something very simple, any help greatly appreciated.


问:
How to pass arguments from docker-compose to Dockerfile?
I have a small Dockerfile in the folder backend:

```<code>FROM alpine:latest

ARG FTP_IP
ARG MONGO_IP
ARG QUORUM_IP

RUN apk add --update openjdk8 && mkdir /var/backend/
RUN apk update
COPY license-system-0.0.1-SNAPSHOT.jar /var/backend/
EXPOSE 8080
ENTRYPOINT [ "java", "-jar", "-Dspring.quorum.host=${QUORUM_IP}", "-Dspring.ftp.server=${FTP_IP}", "-Dspring.data.mongodb.host=${MONGO_IP}","/var/backend/license-system-0.0.1-SNAPSHOT.jar" ]
</code>```

And even smaller docker-compose.yml:

```<code>version: "3"
services:
  generator:
    build: backend
    ports:
      - "8080:8080"
</code>```

I am starting this with a bash script:

```<code>#!/usr/bin/env bash

FTP_IP=$1 MONGO_IP=$2 QUORUM_IP=$3 docker-compose up -d
</code>```

Like this:

```<code>start-backend.sh 127.0.0.1 127.0.0.1 http://localhost:22000
</code>```

But it is not working at all... when I call docker inspect on the created container I get:

```<code>"Id": "bd3e05a8fffba6bb7b5c650d1f48c0ed13dca9108e01e1a82ec534a5f19d4393",
        "Created": "2019-05-29T09:38:32.723414205Z",
        "Path": "java",
        "Args": [
            "-jar",
            "-Dspring.quorum.host=${QUORUM_IP}",
            "-Dspring.ftp.server=${FTP_IP}",
            "-Dspring.data.mongodb.host=${MONGO_IP}",
            "/var/backend/license-system-0.0.1-SNAPSHOT.jar"
        ]
</code>```

What am I doing wrong?

答:
in your script start-backend.sh you have used variables FTP_IP,MONGO_IP and QUORUM_IP which are local to the script, export them as env variables and it will work.

Keep in mind Values in the shell take precedence over those specified in the .env file and dockerfile so you might be overwriting the values defined there ...

Body:
I have a small Dockerfile in the folder backend:

FROM alpine:latest

ARG FTP_IP
ARG MONGO_IP
ARG QUORUM_IP

RUN apk add --update openjdk8 && mkdir /var/backend/
RUN apk update
COPY license-system-0.0.1-SNAPSHOT.jar /var/backend/
EXPOSE 8080
ENTRYPOINT [ "java", "-jar", "-Dspring.quorum.host=${QUORUM_IP}", "-Dspring.ftp.server=${FTP_IP}", "-Dspring.data.mongodb.host=${MONGO_IP}","/var/backend/license-system-0.0.1-SNAPSHOT.jar" ]

And even smaller docker-compose.yml:

version: "3"
services:
  generator:
    build: backend
    ports:
      - "8080:8080"

I am starting this with a bash script:

#!/usr/bin/env bash

FTP_IP=$1 MONGO_IP=$2 QUORUM_IP=$3 docker-compose up -d

Like this:

start-backend.sh 127.0.0.1 127.0.0.1 http://localhost:22000

But it is not working at all... when I call docker inspect on the created container I get:

"Id": "bd3e05a8fffba6bb7b5c650d1f48c0ed13dca9108e01e1a82ec534a5f19d4393",
        "Created": "2019-05-29T09:38:32.723414205Z",
        "Path": "java",
        "Args": [
            "-jar",
            "-Dspring.quorum.host=${QUORUM_IP}",
            "-Dspring.ftp.server=${FTP_IP}",
            "-Dspring.data.mongodb.host=${MONGO_IP}",
            "/var/backend/license-system-0.0.1-SNAPSHOT.jar"
        ]

What am I doing wrong?


问:
How to make pipe always work, instead of check changes?
I have a pipe which finds all emoji names and replace them into the icon.
But the problem is that the pipe doesn't change the last character which was added until I type anything. For example (:heart_eyes:) last :heart_eyes: doesn't change before I type anything.
How to make the pipe works all the time, instead of waiting for some changes?

HTML:

```<code><textarea matInput #newMessage color="primary"
mwlTextInputElement
[formControl]="newMessageFormControl"
[value]="newMessageFormControl.value | q9Emoji"
></textarea>`

TS:
transform(value: any): any {
return this.replace(value);
}

replace(value) {
const emojisRegex = new RegExp(':(' +
Object.keys(this.emojiObj).join('|') + '):', 'g');

return value.replace(emojisRegex, (match, text) => this.emojiService.unifiedToNative(this.emojiObj[text]));
}
</code>```

答:
use the two-way binding instead [formControl], this returns a value on every character change and also you can use (keyup)="newMessage".</p>

```<code>[(ngModel)]="newMessage"
</code>```

Body:
I have a pipe which finds all emoji names and replace them into the icon.
But the problem is that the pipe doesn't change the last character which was added until I type anything. For example (:heart_eyes:) last :heart_eyes: doesn't change before I type anything.
How to make the pipe works all the time, instead of waiting for some changes?

HTML:

<textarea matInput #newMessage color="primary"
mwlTextInputElement
[formControl]="newMessageFormControl"
[value]="newMessageFormControl.value | q9Emoji"
></textarea>`

TS:
transform(value: any): any {
return this.replace(value);
}

replace(value) {
const emojisRegex = new RegExp(':(' +
Object.keys(this.emojiObj).join('|') + '):', 'g');

return value.replace(emojisRegex, (match, text) => this.emojiService.unifiedToNative(this.emojiObj[text]));
}

Body:
use the two-way binding instead [formControl], this returns a value on every character change and also you can use (keyup)="newMessage".

[(ngModel)]="newMessage"


问:
NetMQ.FiniteStateMachineException: Rep.XRecv - cannot receive another request
I constantly get NetMQ.FiniteStateMachineException

sure, my code works... the exception does not occur right away... but over the course of a few hours, probably it will happen.

Does anyone know what is going on here to cause this exception?

I'm not really sure why, even though I did read the explanation here: c# - ZeroMQ FiniteStateMachineException in REQ/REP pattern - Stack Overflow

I get a bunch of these:

the exception

```<code>NetMQ.FiniteStateMachineException: Rep.XRecv - cannot receive another request
   at NetMQ.Core.Patterns.Rep.XRecv(Msg& msg)
   at NetMQ.Core.SocketBase.TryRecv(Msg& msg, TimeSpan timeout)
   at NetMQ.NetMQSocket.TryReceive(Msg& msg, TimeSpan timeout)
   at NetMQ.ReceivingSocketExtensions.ReceiveFrameString(IReceivingSocket socket, Encoding encoding, Boolean& more)
   at NinjaTrader.NinjaScript.AddOns.anAddOn.ZeroMQ_Server()
NetMQ.FiniteStateMachineException: Rep.XRecv - cannot receive another request
   at NetMQ.Core.Patterns.Rep.XRecv(Msg& msg)
   at NetMQ.Core.SocketBase.TryRecv(Msg& msg, TimeSpan timeout)
   at NetMQ.NetMQSocket.TryReceive(Msg& msg, TimeSpan timeout)
   at NetMQ.ReceivingSocketExtensions.ReceiveFrameString(IReceivingSocket socket, Encoding encoding, Boolean& more)
   at NinjaTrader.NinjaScript.AddOns.anAddOn.ZeroMQ_Server()
</code>```

my code

        // thread start code

                if (thread == null) {
                    print2("Addon {0}: is starting, listening on port: {1}...", GetType().Name, ZeroPort);
                    thread = new Thread(ZeroMQ_Server);
                    thread.Start();
                }

        // zeroMQ code

        #region TaskCallBack - NetMQ
        // This thread procedure performs the task.
        private void ZeroMQ_Server()
        {
            bool quit = false;
            string bindAddress = "tcp://*:"+ZeroPort;
            try {
                while (!quit) {
                    try {
                        using (var repSocket = new ResponseSocket())
                        {
                            curRepSocket = repSocket;
                            print2("*** BINDING on {0} ***", bindAddress);
                            repSocket.Bind(bindAddress);

                            while (!quit) {
                                try {
                                    Running = true;

                                    var msgStr = repSocket.ReceiveFrameString();
                                    print2("[►] {2} [REP:{0}] {1}", bindAddress, msgStr, DateTime.Now.ToString("HH:mm:ss.fff"));
                                    if (processMsg(msgStr)) {
                                        StringBuilder csv = new StringBuilder();
                                        // string building stuff here

                                        string cs = csv.ToString();
                                        print2("[◄] csv: {0}", cs);
                                        repSocket.SendFrame(cs);
                                    } else {
                                        repSocket.SendFrame("Unrecognized Command: " + msgStr);
                                        break;
                                    }

                                } catch (Exception e) {
                                    quit = isThreadAborted(e);
                                }
                            }
                        }

                    } catch (Exception e) {
                        if (e is AddressAlreadyInUseException) {
                            //print2("");
                        } else quit = isThreadAborted(e);
                    } finally {
                        curRepSocket = null;
                        Running = false;
                    }
                }
            } finally {
                //NetMQConfig.Cleanup();
            }
        }

        private bool isThreadAborted(Exception e) {
            if (e is ThreadAbortException) {
                print2("\n*** thread aborting... ***");
                return true;
            } else {
                print2(e);
                return false;
            }
        }

```

答:
Response socket is a state machine, you must reply to each request.
From the code, it seems that if processMsg throws you don't send anything back, therefore you cannot receive again and get the exception.

It can also if Send failed if the client is gone.

Try to use router instead, like so:

```<code>while (true)
{
    bool more;
    var msg = routerSocket.ReceiveFrameBytes(out more);

    // Forwarding the routing id.
    routerSocket.SendMoreFrame(msg);

    // Bottom, next frame is the message
    if (msg.Length == 0)
        break;
}

// Write your handling here

</code>```

Body:
I constantly get NetMQ.FiniteStateMachineException

sure, my code works... the exception does not occur right away... but over the course of a few hours, probably it will happen.

Does anyone know what is going on here to cause this exception?

I'm not really sure why, even though I did read the explanation here: c# - ZeroMQ FiniteStateMachineException in REQ/REP pattern - Stack Overflow

I get a bunch of these:

the exception

NetMQ.FiniteStateMachineException: Rep.XRecv - cannot receive another request
   at NetMQ.Core.Patterns.Rep.XRecv(Msg& msg)
   at NetMQ.Core.SocketBase.TryRecv(Msg& msg, TimeSpan timeout)
   at NetMQ.NetMQSocket.TryReceive(Msg& msg, TimeSpan timeout)
   at NetMQ.ReceivingSocketExtensions.ReceiveFrameString(IReceivingSocket socket, Encoding encoding, Boolean& more)
   at NinjaTrader.NinjaScript.AddOns.anAddOn.ZeroMQ_Server()
NetMQ.FiniteStateMachineException: Rep.XRecv - cannot receive another request
   at NetMQ.Core.Patterns.Rep.XRecv(Msg& msg)
   at NetMQ.Core.SocketBase.TryRecv(Msg& msg, TimeSpan timeout)
   at NetMQ.NetMQSocket.TryReceive(Msg& msg, TimeSpan timeout)
   at NetMQ.ReceivingSocketExtensions.ReceiveFrameString(IReceivingSocket socket, Encoding encoding, Boolean& more)
   at NinjaTrader.NinjaScript.AddOns.anAddOn.ZeroMQ_Server()

my code

        // thread start code

                if (thread == null) {
                    print2("Addon {0}: is starting, listening on port: {1}...", GetType().Name, ZeroPort);
                    thread = new Thread(ZeroMQ_Server);
                    thread.Start();
                }

        // zeroMQ code

        #region TaskCallBack - NetMQ
        // This thread procedure performs the task.
        private void ZeroMQ_Server()
        {
            bool quit = false;
            string bindAddress = "tcp://*:"+ZeroPort;
            try {
                while (!quit) {
                    try {
                        using (var repSocket = new ResponseSocket())
                        {
                            curRepSocket = repSocket;
                            print2("*** BINDING on {0} ***", bindAddress);
                            repSocket.Bind(bindAddress);

                            while (!quit) {
                                try {
                                    Running = true;

                                    var msgStr = repSocket.ReceiveFrameString();
                                    print2("[►] {2} [REP:{0}] {1}", bindAddress, msgStr, DateTime.Now.ToString("HH:mm:ss.fff"));
                                    if (processMsg(msgStr)) {
                                        StringBuilder csv = new StringBuilder();
                                        // string building stuff here

                                        string cs = csv.ToString();
                                        print2("[◄] csv: {0}", cs);
                                        repSocket.SendFrame(cs);
                                    } else {
                                        repSocket.SendFrame("Unrecognized Command: " + msgStr);
                                        break;
                                    }

                                } catch (Exception e) {
                                    quit = isThreadAborted(e);
                                }
                            }
                        }

                    } catch (Exception e) {
                        if (e is AddressAlreadyInUseException) {
                            //print2("");
                        } else quit = isThreadAborted(e);
                    } finally {
                        curRepSocket = null;
                        Running = false;
                    }
                }
            } finally {
                //NetMQConfig.Cleanup();
            }
        }

        private bool isThreadAborted(Exception e) {
            if (e is ThreadAbortException) {
                print2("\n*** thread aborting... ***");
                return true;
            } else {
                print2(e);
                return false;
            }
        }

Body:
Response socket is a state machine, you must reply to each request.
From the code, it seems that if processMsg throws you don't send anything back, therefore you cannot receive again and get the exception.

It can also if Send failed if the client is gone.

Try to use router instead, like so:

while (true)
{
    bool more;
    var msg = routerSocket.ReceiveFrameBytes(out more);

    // Forwarding the routing id.
    routerSocket.SendMoreFrame(msg);

    // Bottom, next frame is the message
    if (msg.Length == 0)
        break;
}

// Write your handling here