问:
Custom widget js doesn't recognize template from qweb
I try to test custom widget from js reference and I get error in debugger:

Error: QWeb2: Template 'some.template' not found

qweb.xml was properly set in manifest, because when I extend ListController and use another template, it works correctly.

Here is template definition, which I use in qweb.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<template>
    <div t-name="some.template">
        <span class="val"><t t-esc="widget.count"/></span>
        <button>Increment</button>
    </div>
</template>
</code>```

I tried to change <template> -> <templates>, totally removed tag "template" but still get the same error message.

JS:

```<code>odoo.define('working.test', function (require) {
var Widget = require('web.Widget');
var Counter = Widget.extend({
    template: 'some.template',
    events: {
        'click button': '_onClick',
    },
    init: function (parent, value) {
        this._super(parent);
        this.count = value;
    },
    _onClick: function () {
        this.count++;
        this.$('.val').text(this.count);
    },
});

// Create the instance
var counter = new Counter(this, 4);
// Render and insert into DOM
counter.appendTo(".o_nocontent_help");

})
</code>```

Manifest:

```<code># -*- coding: utf-8 -*-
{
    'name': "testwidget",

    'summary': """
        Short (1 phrase/line) summary of the module's purpose, used as
        subtitle on modules listing or apps.openerp.com""",

    'description': """
        Long description of module's purpose
    """,

    'author': "My Company",
    'website': "http://www.yourcompany.com",

    # Categories can be used to filter modules in modules listing
    # Check https://github.com/odoo/odoo/blob/12.0/odoo/addons/base/data/ir_module_category_data.xml
    # for the full list
    'category': 'Uncategorized',
    'version': '0.1',

    # any module necessary for this one to work correctly
    'depends': ['base'],
    'qweb': ['static/qweb.xml'],

    # always loaded
    'data': [
        # 'security/ir.model.access.csv',
        'views/views.xml',
        'views/web_asset.xml',
    ],
    # only loaded in demonstration mode
    'demo': [
        'demo/demo.xml',
    ],
}
</code>```

Any idea how I need to modify this template to make the widget working correctly and in which table in db odoo stores these templates?

答:
```<code>        In Odoo 14 make sure
        dashboard.js
        odoo.define('library_managment.dashboard', function(require) {
            "use strict";

            // alert("hello odoo...............")
             console.log("Hello My Module........!!")

            var widgetRegistry = require('web.widget_registry');
            var Widget = require('web.Widget');

            var Counter = Widget.extend({
            template: 'library_managment.template',
            xmlDependencies: ['/library_managment/static/src/xml/template.xml'],
            events: {
                'click button': '_onClick',
            },
            init: function (parent, value) {

                this._super(parent);
                this.count = 4*9+5;
                 console.log("parent is", parent)
                 console.log("counter is..", this.count)
            },
            _onClick: function () {
                this.count++;
                this.$('.val').text(this.count);
            },

        });

            widgetRegistry.add('library_counter', Counter);
            return Counter;

        });

    template.xml
    add this
    <?xml version="1.0" encoding="UTF-8"?>

    <odoo>
        <div t-name="library_managment.template">
            <span class="val">
                <t t-esc="widget.count"/>
            </span>
            <button class="bg-danger">Increment</button>
        </div>
    </odoo>

then add js file in assets.xml inside youe views
<odoo>
 <template id="assets_backend" name="Library assets" inherit_id="web.assets_backend">
            <xpath expr="." position="inside">
                <script type="text/javascript" src="/library_managment/static/src/js/dashboard.js"></script>
            </xpath>
        </template>
</odoo>
</code>```

then add in manifest like this:
'js': ['/static/src/js/dashboard.js'],
'qweb': ['/static/src/xml/template.xml']

then inside form view add this line
<widget="library_counter"/>

Body:
I try to test custom widget from js reference and I get error in debugger:

Error: QWeb2: Template 'some.template' not found

qweb.xml was properly set in manifest, because when I extend ListController and use another template, it works correctly.

Here is template definition, which I use in qweb.xml:

<?xml version="1.0" encoding="UTF-8"?>
<template>

        <t t-esc="widget.count"/>
        <button>Increment</button>

</template>

I tried to change <template> -> <templates>, totally removed tag "template" but still get the same error message.

JS:

odoo.define('working.test', function (require) {
var Widget = require('web.Widget');
var Counter = Widget.extend({
    template: 'some.template',
    events: {
        'click button': '_onClick',
    },
    init: function (parent, value) {
        this._super(parent);
        this.count = value;
    },
    _onClick: function () {
        this.count++;
        this.$('.val').text(this.count);
    },
});

// Create the instance
var counter = new Counter(this, 4);
// Render and insert into DOM
counter.appendTo(".o_nocontent_help");

})

Manifest:

# -*- coding: utf-8 -*-
{
    'name': "testwidget",

    'summary': """
        Short (1 phrase/line) summary of the module's purpose, used as
        subtitle on modules listing or apps.openerp.com""",

    'description': """
        Long description of module's purpose
    """,

    'author': "My Company",
    'website': "http://www.yourcompany.com",

    # Categories can be used to filter modules in modules listing
    # Check https://github.com/odoo/odoo/blob/12.0/odoo/addons/base/data/ir_module_category_data.xml
    # for the full list
    'category': 'Uncategorized',
    'version': '0.1',

    # any module necessary for this one to work correctly
    'depends': ['base'],
    'qweb': ['static/qweb.xml'],

    # always loaded
    'data': [
        # 'security/ir.model.access.csv',
        'views/views.xml',
        'views/web_asset.xml',
    ],
    # only loaded in demonstration mode
    'demo': [
        'demo/demo.xml',
    ],
}

Any idea how I need to modify this template to make the widget working correctly and in which table in db odoo stores these templates?

Body:
        In Odoo 14 make sure
        dashboard.js
        odoo.define('library_managment.dashboard', function(require) {
            "use strict";

            // alert("hello odoo...............")
             console.log("Hello My Module........!!")

            var widgetRegistry = require('web.widget_registry');
            var Widget = require('web.Widget');

            var Counter = Widget.extend({
            template: 'library_managment.template',
            xmlDependencies: ['/library_managment/static/src/xml/template.xml'],
            events: {
                'click button': '_onClick',
            },
            init: function (parent, value) {

                this._super(parent);
                this.count = 4*9+5;
                 console.log("parent is", parent)
                 console.log("counter is..", this.count)
            },
            _onClick: function () {
                this.count++;
                this.$('.val').text(this.count);
            },

        });

            widgetRegistry.add('library_counter', Counter);
            return Counter;

        });

    template.xml
    add this
    <?xml version="1.0" encoding="UTF-8"?>

    <odoo>
        <div t-name="library_managment.template">
            <span class="val">
                <t t-esc="widget.count"/>
            </span>
            <button class="bg-danger">Increment</button>
        </div>
    </odoo>

then add js file in assets.xml inside youe views
<odoo>
 <template id="assets_backend" name="Library assets" inherit_id="web.assets_backend">
            <xpath expr="." position="inside">
                <script type="text/javascript" src="/library_managment/static/src/js/dashboard.js"></script>
            </xpath>
        </template>
</odoo>

then add in manifest like this:
'js': ['/static/src/js/dashboard.js'],
'qweb': ['/static/src/xml/template.xml']

then inside form view add this line
<widget="library_counter"/>


来源: stackexchange

问:
How to delete a file from physical directory with JavaScript (Windows/IE Only)?
I am dynamically generating an HTML file for the print option.

After the print window has been opened and the file printed, I want to remove the HTML file from the folder.

I need to do this with JavaScript. For this I am using the following code:

```<code>var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFile(strReportFilePath);
myFolder.Delete();`
</code>```

But this only works in IE but not in Firefox, so how do I delete the file with a JavaScript function?

答:
I'm on the look out for just accessing files on the local files and failed to find a way that works cross-browser easily yet. However you might want to try signed Java applets which seemed to be a (though not so smooth) solution.

You also might want to keep track of this

ContentLicense: CC BY-SA 3.0

Body:
I am dynamically generating an HTML file for the print option.

After the print window has been opened and the file printed, I want to remove the HTML file from the folder.

I need to do this with JavaScript. For this I am using the following code:

var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFile(strReportFilePath);
myFolder.Delete();`

But this only works in IE but not in Firefox, so how do I delete the file with a JavaScript function?


问:
node.js store objects in redis
Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple client.set() it's stored as a string. When I try to get value I get [object Object] - just a string.

Any chance to get this working? Here's my code:

```<code>  addSocket : function(sid, socket) {
    client.set(sid, socket);
  },

  getSocket : function(sid) {
    client.get(sid, function(err, reply) {
      // cant't get an object here. All I get is useless string
    });
  },
</code>```

答:
We can store object as a string using JSON.stringyfy(obj); and after we could retrieve original object using JSON.parse(obj);

```<code>const obj = {
   userId: socket.user._id,
   socketId: socket.id,
};
await client.set("user", JSON.stringify(obj));
const usersData = await client.get("user");
</code>```

Title: node.js store objects in redis

Body:
Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple client.set() it's stored as a string. When I try to get value I get [object Object] - just a string.

Any chance to get this working? Here's my code:

  addSocket : function(sid, socket) {
    client.set(sid, socket);
  },

  getSocket : function(sid) {
    client.get(sid, function(err, reply) {
      // cant't get an object here. All I get is useless string
    });
  },

Body:
We can store object as a string using JSON.stringyfy(obj); and after we could retrieve original object using JSON.parse(obj);

const obj = {
   userId: socket.user._id,
   socketId: socket.id,
};
await client.set("user", JSON.stringify(obj));
const usersData = await client.get("user");

ContentLicense: CC BY-SA 4.0


问:
Unique arrays in list python
How can I get the unique arrays from such a list below?

```<code>data =[np.array([ 10, 17]),
       np.array([ 10, 17]),
       np.array([ 1, 17, 34]),
       np.array([ 1, 17, 34]),
       np.array([ 20, 50, 38]),
       np.array([ 20, 50, 38]),
       np.array([ 20, 50, 40])]

expected = [ np.array([ 10, 17]),
             np.array([ 1, 17, 34]),
             np.array([ 20, 50, 38]),
             np.array([ 20, 50, 40])]
</code>```

I applied set(data) but it gave me the error;

TypeError: unhashable type: 'numpy.ndarray'

I have got some ideas like:

Looping and appending an empty list and comparing the next candidate by using '==' with the prior list and so on.

Applying a mathematical operation on the arrays which gives unique output. Then removing the duplicates.

Using tobytes for each array for making them one line. And removing duplicates again.

All sounds inefficient to me. Any easy way to solve it?

答:
numpy arrays are unhashable but tuples are, so you can map them to tuples, cast to set, then map back to numpy arrays.

```<code>out = list(map(np.array, set(map(tuple, data))))
</code>```

If the order the arrays appear in the list is important, you could also use dict.fromkeys:

```<code>out = list(map(np.array, dict.fromkeys(map(tuple, data)).keys()))
</code>```

Output:

```<code>[array([10, 17]),
 array([ 1, 17, 34]),
 array([20, 50, 38]),
 array([20, 50, 40])]
</code>```

Title: Unique arrays in list python

Body:
How can I get the unique arrays from such a list below?

data =[np.array([ 10, 17]),
       np.array([ 10, 17]),
       np.array([ 1, 17, 34]),
       np.array([ 1, 17, 34]),
       np.array([ 20, 50, 38]),
       np.array([ 20, 50, 38]),
       np.array([ 20, 50, 40])]

expected = [ np.array([ 10, 17]),
             np.array([ 1, 17, 34]),
             np.array([ 20, 50, 38]),
             np.array([ 20, 50, 40])]

I applied set(data) but it gave me the error;

TypeError: unhashable type: 'numpy.ndarray'

I have got some ideas like:

Looping and appending an empty list and comparing the next candidate by using '==' with the prior list and so on.

Applying a mathematical operation on the arrays which gives unique output. Then removing the duplicates.

Using tobytes for each array for making them one line. And removing duplicates again.

All sounds inefficient to me. Any easy way to solve it?

Body:
numpy arrays are unhashable but tuples are, so you can map them to tuples, cast to set, then map back to numpy arrays.

out = list(map(np.array, set(map(tuple, data))))

If the order the arrays appear in the list is important, you could also use dict.fromkeys:

out = list(map(np.array, dict.fromkeys(map(tuple, data)).keys()))

Output:

[array([10, 17]),
 array([ 1, 17, 34]),
 array([20, 50, 38]),
 array([20, 50, 40])]


问:
how to avoid default method implementation in swagger codegen interface?
I would like to avoid "default" implementation in interface generate by the maven plugin swagger codegen.
For example, with petstore swagger : http://petstore.swagger.io/v2/swagger.json

I generate interface with maven plugin :

```<code>            <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.2.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>./src/main/resources/swagger/api.yml</inputSpec>
                        <language>spring</language>
                        <generateSupportingFiles>false</generateSupportingFiles>
                        <configOptions>
                            <interfaceOnly>true</interfaceOnly>
                            <java8>true</java8>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

I generate interface like PetApi.java with default implementation of methods :

```<code>    default ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true )  @Valid @RequestBody Pet body) {
    // do some magic!
    return new ResponseEntity<Void>(HttpStatus.OK);
    }
</code>```

I would like to avoid it like

```<code>    ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true )  @Valid @RequestBody Pet body);
</code>```

Is it possible to do it ?

Update March 2020:

According to new OpenAPI Tool openapi-generator

  There is an option with spring (language is DEPRECATED, use generatorName)

skipDefaultInterface

https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/spring.md

答:
As per documentation the following should solve it:</p>
```<code><configOptions>
     <skipDefaultInterface>true</skipDefaultInterface>
</configOptions>
</code>```

Body:
I would like to avoid "default" implementation in interface generate by the maven plugin swagger codegen.
For example, with petstore swagger : http://petstore.swagger.io/v2/swagger.json

I generate interface with maven plugin :

            <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.2.3</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>./src/main/resources/swagger/api.yml</inputSpec>
                        <language>spring</language>
                        <generateSupportingFiles>false</generateSupportingFiles>
                        <configOptions>
                            <interfaceOnly>true</interfaceOnly>
                            <java8>true</java8>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>

I generate interface like PetApi.java with default implementation of methods :

    default ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true )  @Valid @RequestBody Pet body) {
    // do some magic!
    return new ResponseEntity<Void>(HttpStatus.OK);
    }

I would like to avoid it like

    ResponseEntity<Void> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true )  @Valid @RequestBody Pet body);

Is it possible to do it ?

Update March 2020:

According to new OpenAPI Tool openapi-generator

  There is an option with spring (language is DEPRECATED, use generatorName)

skipDefaultInterface

https://github.com/OpenAPITools/openapi-generator/blob/master/docs/generators/spring.md

Body:
As per documentation the following should solve it:

<configOptions>
     <skipDefaultInterface>true</skipDefaultInterface>
</configOptions>


问:
disconnected: no supported authentication methods available (server sent: publickey, gssapi-with-mic)
I don't know what is happening.

I have been able to connect to the server for a couple of days without problems and suddendly I got a frozen window using putty. After that, each time I try to connect, I receive this message:

```<code>disconnected: no supported authentication methods available (server sent: publickey, gssapi-with-mic)
</code>```

I am using putty and puttyagent for private key. I already have uploaded the public key to the server and I was able to connect half an hour ago.

How can I check why it is failing? I haven't change the user or password or anything.

答:
In my case updating both putty and puttygen to the latest version (0.76) solved this issue.

Download latest putty and latest puttygen from https://www.puttygen.com/#Download_PuTTYgen_on_Windows

In puttygen click Load, chose All Files and select your PEM file for your EC2 instance.

Choose SSH-1 (RSA) as a type of key to generate.

Click on Save private key.

In putty in the Auth section click on browse and select your generated private key.

Body:
I don't know what is happening.

I have been able to connect to the server for a couple of days without problems and suddendly I got a frozen window using putty. After that, each time I try to connect, I receive this message:

disconnected: no supported authentication methods available (server sent: publickey, gssapi-with-mic)

I am using putty and puttyagent for private key. I already have uploaded the public key to the server and I was able to connect half an hour ago.

How can I check why it is failing? I haven't change the user or password or anything.


问:
NetworkXError: No <graph> element in GEXF file
I am trying to read a gexf file using nx and get the above error:

```<code>import networkx as nx
nx.read_gexf('KwNet-Journals/KwNet-Journals.gexf')
</code>```

The gexf file can be found here.

答:
I do not take any pride in this answer as it circumvents XML syntax. However, as it gets the job done, I will share it anyway.</p>
```<code>f = io.open("demo.gexf", mode="r", encoding="utf-8")
gexf = f.read()
gexf = gexf.replace('xmlns="http://www.gexf.net/1.3"', 'xmlns="http://www.gexf.net/1.2draft"')\
.replace('version="1.3"',  'version="1.2"')\
.replace('http://www.gexf.net/1.3', 'http://www.gexf.net/1.2')
out = io.open("demo-fixed.gexf", mode='w', encoding="utf-8")
out.write(gexf)

</code>```

Body:
I am trying to read a gexf file using nx and get the above error:

import networkx as nx
nx.read_gexf('KwNet-Journals/KwNet-Journals.gexf')

The gexf file can be found here.

Body:
I do not take any pride in this answer as it circumvents XML syntax. However, as it gets the job done, I will share it anyway.

f = io.open("demo.gexf", mode="r", encoding="utf-8")
gexf = f.read()
gexf = gexf.replace('xmlns="http://www.gexf.net/1.3"', 'xmlns="http://www.gexf.net/1.2draft"')\
.replace('version="1.3"',  'version="1.2"')\
.replace('http://www.gexf.net/1.3', 'http://www.gexf.net/1.2')
out = io.open("demo-fixed.gexf", mode='w', encoding="utf-8")
out.write(gexf)


问:
install pear on WAMP
I tried to install pear

WAMPserver 2.1
OS : win 7

steps I followed from following link
http://chadash.tumblr.com/post/1515528654/how-to-install-php5-pear-lib-on-windows-7

I get a copy of go-pear.phar from http://pear.php.net/go-pear.phar url.

Following is the output

```<code>Are you installing a system-wide PEAR or a local copy?
(system|local) [system] : system

Below is a suggested file layout for your new PEAR installation.  To
change individual locations, type the number in front of the
directory.  Type 'all' to change all of them or simply press Enter to
accept these locations.

 1. Installation base ($prefix)                   : C:\wamp\bin\php\php5.3.3
 2. Temporary directory for processing            : C:\wamp\bin\php\php5.3.3\tmp

 3. Temporary directory for downloads             : C:\wamp\bin\php\php5.3.3\tmp

 4. Binaries directory                            : C:\wamp\bin\php\php5.3.3
 5. PHP code directory ($php_dir)                 : C:\wamp\bin\php\php5.3.3\pea
r
 6. Documentation directory                       : C:\wamp\bin\php\php5.3.3\doc
s
 7. Data directory                                : C:\wamp\bin\php\php5.3.3\dat
a
 8. User-modifiable configuration files directory : C:\wamp\bin\php\php5.3.3\cfg

 9. Public Web Files directory                    : C:\wamp\bin\php\php5.3.3\www

10. Tests directory                               : C:\wamp\bin\php\php5.3.3\tes
ts
11. Name of configuration file                    : C:\Windows\pear.ini
12. Path to CLI php.exe                           : .

1-12, 'all' or Enter to continue:
'".\php.exe"' is not recognized as an internal or external command,
operable program or batch file.

*WARNING*
We found php.exe under ., it uses an unknown SAPI. PEAR commandline
tool has not been tested with it, if you have a CLI (or CGI) php.exe available,
we strongly recommend using it.

Beginning install...
Configuration written to C:\Windows\pear.ini...
Initialized registry...
Preparing to install...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Archive_Tar-1.3.7.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Console_Getopt-1.3.0.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/PEAR-1.9.3.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Structures_Graph-1.0.4.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/XML_Util-1.2.1.tar...
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Archive_Tar-1.3.7\Archive\Tar.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Console_Getopt-1.3.0\Console\Getopt.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Structures_Graph-1.0.4\docs\html\media\banner.css does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \XML_Util-1.2.1\examples\example.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \PEAR-1.9.3\OS\Guess.php does not exist

** WARNING! Old version found at C:\wamp\bin\php\php5.3.3, please remove it or b
e sure to use the new c:\wamp\bin\php\php5.3.3\pear.bat command

The 'pear' command is now at your service at c:\wamp\bin\php\php5.3.3\pear.bat

** The 'pear' command is not currently in your PATH, so you need to
** use 'c:\wamp\bin\php\php5.3.3\pear.bat' until you have added
** 'C:\wamp\bin\php\php5.3.3' to your PATH environment variable.

Run it without parameters to see the available actions, try 'pear list'
to see what packages are installed, or 'pear help' for help.

For more information about PEAR, see:

  http://pear.php.net/faq.php
  http://pear.php.net/manual/

Thanks for using go-pear!

* WINDOWS ENVIRONMENT VARIABLES *
For convenience, a REG file is available under C:\wamp\bin\php\php5.3.3PEAR_ENV.
reg .
This file creates ENV variables for the current user.

Double-click this file to add it to the current user registry.

Press any key to continue . . .

C:\wamp\bin\php\php5.3.3>
</code>```

pear command is still not recognized by the system.

```<code>*WARNING*
We found php.exe under ., it uses an unknown SAPI. PEAR commandline
tool has not been tested with it, if you have a CLI (or CGI) php.exe available,
we strongly recommend using it.
</code>```

There are no such message the author receive. I updated the environmental var and php is running as cli.

Please help.

Regards,

答:
```<code>12. Path to CLI php.exe                           : .

1-12, 'all' or Enter to continue:
'".\php.exe"' is not recognized as an internal or external command,
operable program or batch file.
</code>```

You need to specify the full path to the php.exe file, including php.exe. "." alone is not sufficient.

Title: install pear on WAMP

Body:
I tried to install pear

WAMPserver 2.1
OS : win 7

steps I followed from following link
http://chadash.tumblr.com/post/1515528654/how-to-install-php5-pear-lib-on-windows-7

I get a copy of go-pear.phar from http://pear.php.net/go-pear.phar url.

Following is the output

Are you installing a system-wide PEAR or a local copy?
(system|local) [system] : system

Below is a suggested file layout for your new PEAR installation.  To
change individual locations, type the number in front of the
directory.  Type 'all' to change all of them or simply press Enter to
accept these locations.

 1. Installation base ($prefix)                   : C:\wamp\bin\php\php5.3.3
 2. Temporary directory for processing            : C:\wamp\bin\php\php5.3.3\tmp

 3. Temporary directory for downloads             : C:\wamp\bin\php\php5.3.3\tmp

 4. Binaries directory                            : C:\wamp\bin\php\php5.3.3
 5. PHP code directory ($php_dir)                 : C:\wamp\bin\php\php5.3.3\pea
r
 6. Documentation directory                       : C:\wamp\bin\php\php5.3.3\doc
s
 7. Data directory                                : C:\wamp\bin\php\php5.3.3\dat
a
 8. User-modifiable configuration files directory : C:\wamp\bin\php\php5.3.3\cfg

 9. Public Web Files directory                    : C:\wamp\bin\php\php5.3.3\www

10. Tests directory                               : C:\wamp\bin\php\php5.3.3\tes
ts
11. Name of configuration file                    : C:\Windows\pear.ini
12. Path to CLI php.exe                           : .

1-12, 'all' or Enter to continue:
'".\php.exe"' is not recognized as an internal or external command,
operable program or batch file.

*WARNING*
We found php.exe under ., it uses an unknown SAPI. PEAR commandline
tool has not been tested with it, if you have a CLI (or CGI) php.exe available,
we strongly recommend using it.

Beginning install...
Configuration written to C:\Windows\pear.ini...
Initialized registry...
Preparing to install...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Archive_Tar-1.3.7.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Console_Getopt-1.3.0.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/PEAR-1.9.3.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/Structures_Graph-1.0.4.tar...
installing phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pear.phar/PEAR/go-pear-tarbal
ls/XML_Util-1.2.1.tar...
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Archive_Tar-1.3.7\Archive\Tar.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Console_Getopt-1.3.0\Console\Getopt.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \Structures_Graph-1.0.4\docs\html\media\banner.css does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \XML_Util-1.2.1\examples\example.php does not exist
PHP Warning:  mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/
go-pear.phar/System.php on line 302

Warning: mkdir(): Invalid argument in phar://C:/wamp/bin/php/php5.3.3/PEAR/go-pe
ar.phar/System.php on line 302
ERROR: file \PEAR-1.9.3\OS\Guess.php does not exist

** WARNING! Old version found at C:\wamp\bin\php\php5.3.3, please remove it or b
e sure to use the new c:\wamp\bin\php\php5.3.3\pear.bat command

The 'pear' command is now at your service at c:\wamp\bin\php\php5.3.3\pear.bat

** The 'pear' command is not currently in your PATH, so you need to
** use 'c:\wamp\bin\php\php5.3.3\pear.bat' until you have added
** 'C:\wamp\bin\php\php5.3.3' to your PATH environment variable.

Run it without parameters to see the available actions, try 'pear list'
to see what packages are installed, or 'pear help' for help.

For more information about PEAR, see:

  http://pear.php.net/faq.php
  http://pear.php.net/manual/

Thanks for using go-pear!

* WINDOWS ENVIRONMENT VARIABLES *
For convenience, a REG file is available under C:\wamp\bin\php\php5.3.3PEAR_ENV.
reg .
This file creates ENV variables for the current user.

Double-click this file to add it to the current user registry.

Press any key to continue . . .

C:\wamp\bin\php\php5.3.3>

pear command is still not recognized by the system.

*WARNING*
We found php.exe under ., it uses an unknown SAPI. PEAR commandline
tool has not been tested with it, if you have a CLI (or CGI) php.exe available,
we strongly recommend using it.

There are no such message the author receive. I updated the environmental var and php is running as cli.

Please help.

Regards,

Body:
12. Path to CLI php.exe                           : .

1-12, 'all' or Enter to continue:
'".\php.exe"' is not recognized as an internal or external command,
operable program or batch file.

You need to specify the full path to the php.exe file, including php.exe. "." alone is not sufficient.


问:
Firebase Realtime Database geting User by Email/Name in Android with Java

I want to get a User or just a User UID via email or name. Tried to write the query, but I'm getting all users and then iterating through them and then getting the user but I think it's an expensive task. How can I get only one User/Uid from Realtime Database?

This is what I came up with (But don't think is the best way):

```<code>DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");

Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());

emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {

        for (DataSnapshot child : snapshot.getChildren()) {

            if (child.getValue(User.class).getEmail().equals(client.getEmail())){

                User user = child.getValue(User.class);
            }

        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});
</code>```

答:
According to your last comment:

I have the corresponding details of each user (email, name), and I want to get the UID of one user (no matter which one)

To get a particular user from the database based on a particular email address, the query that you are already using:

```<code>Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
</code>```

Returns only the users who have the field email set to what client.getEmail() returns. For instance, if client.getEmail() returns tedo@gmail.com then you'll get a single result, according to your screenshot, which is the first one. That being said, the following if statement, doesn't make sense to be used:

```<code>if (child.getValue(User.class).getEmail().equals(client.getEmail())){
    User user = child.getValue(User.class);
}
</code>```

Since the key of the user node is represented by the UID, then you should get it like this:

```<code>Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) {
            User user = child.getValue(User.class);
            String uid = child.getKey();

            //Do what you need to do with UID.
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.d("TAG", error.getMessage()); //Never ignore potential errors!
    }
});
</code>```

That's the simplest, cheapest way to query the Realtime Database, in which you return only the elements that you are interested in and that satisfy a particular condition.

Body:
I want to get a User or just a User UID via email or name. Tried to write the query, but I'm getting all users and then iterating through them and then getting the user but I think it's an expensive task. How can I get only one User/Uid from Realtime Database?

This is what I came up with (But don't think is the best way):

DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");

Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());

emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {

        for (DataSnapshot child : snapshot.getChildren()) {

            if (child.getValue(User.class).getEmail().equals(client.getEmail())){

                User user = child.getValue(User.class);
            }

        }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});

Body:
According to your last comment:

I have the corresponding details of each user (email, name), and I want to get the UID of one user (no matter which one)

To get a particular user from the database based on a particular email address, the query that you are already using:

Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());

Returns only the users who have the field email set to what client.getEmail() returns. For instance, if client.getEmail() returns tedo@gmail.com then you'll get a single result, according to your screenshot, which is the first one. That being said, the following if statement, doesn't make sense to be used:

if (child.getValue(User.class).getEmail().equals(client.getEmail())){
    User user = child.getValue(User.class);
}

Since the key of the user node is represented by the UID, then you should get it like this:

Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot child : snapshot.getChildren()) {
            User user = child.getValue(User.class);
            String uid = child.getKey();

            //Do what you need to do with UID.
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.d("TAG", error.getMessage()); //Never ignore potential errors!
    }
});

That's the simplest, cheapest way to query the Realtime Database, in which you return only the elements that you are interested in and that satisfy a particular condition.


问:
Equivalent of the Rstudio `browser()` function in Julia for debugging
I wondered if there is an equivalent to the browser() statement available in RStudio for debugging purposes for Julia (I am using the Juno IDE at the moment).

The R function browser() halts execution and invokes an environment browser when it is called. So, in principle, we can put browser() anywhere in our code to stop in this particular line and see what's stored in the environment at that moment, which is terrific for debugging purposes.

For instance, the code below will stop when i>3. Hence, that's exactly what we will see in the environment browser available in RStudio, where we will observe that i=4 at that moment in the code.

```<code>for (i in 1:5) {
  print(i)
  if (i>3) {
    browser()
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
Called from: eval(ei, envir)
Browse[1]>
</code>```

答:
Infiltrator.jl's @infiltrate seems like the equivalent in Julia:

```<code>julia> using Infiltrator

julia> for i in 1:5
         println(i)
         if i > 3
           @infiltrate
         end
       end
1
2
3
4
Infiltrating top-level scope at REPL[1]:4:

infil> i
4
</code>```

Compared to Debugger.jl's breakpoint, this doesn't slow down program execution at all, at the cost of not allowing you to step further into your program.

Body:
I wondered if there is an equivalent to the browser() statement available in RStudio for debugging purposes for Julia (I am using the Juno IDE at the moment).

The R function browser() halts execution and invokes an environment browser when it is called. So, in principle, we can put browser() anywhere in our code to stop in this particular line and see what's stored in the environment at that moment, which is terrific for debugging purposes.

For instance, the code below will stop when i>3. Hence, that's exactly what we will see in the environment browser available in RStudio, where we will observe that i=4 at that moment in the code.

for (i in 1:5) {
  print(i)
  if (i>3) {
    browser()
  }
}
[1] 1
[1] 2
[1] 3
[1] 4
Called from: eval(ei, envir)
Browse[1]>

Body:
Infiltrator.jl's @infiltrate seems like the equivalent in Julia:

julia> using Infiltrator

julia> for i in 1:5
         println(i)
         if i > 3
           @infiltrate
         end
       end
1
2
3
4
Infiltrating top-level scope at REPL[1]:4:

infil> i
4

Compared to Debugger.jl's breakpoint, this doesn't slow down program execution at all, at the cost of not allowing you to step further into your program.


问:
How to pass data to a text field - FLUTTER
```<code>**[![I want to achieve this, where a calculator input is shown to the user, and the user input and output of calculations is shown inside the text field
</code>```

Please give me suggestions how can I achieve this functionality... ]1]1**

答:
Can you ask more questions or detailed pictures of the initial state and what you want to achieve?

if you want to pass data into a text field you can use Controller
initialization controller example

TextEditingController _yourcontrollerName1 = TextEdititingController;```
</div>
</div>
</p>
<p>inside the widget textfield :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>TextField(
..
controller :_yourcontrollerName1
)</code>```

you can set data with

_yourcontrollerName1.text = your_data_pass```
</div>
</div>
</p>
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>TextEditingController _yourcontrollerName1 = TextEditingController(text:data_your_pass);</code>```

I hope this helps

Body:
**[![I want to achieve this, where a calculator input is shown to the user, and the user input and output of calculations is shown inside the text field

Please give me suggestions how can I achieve this functionality... ]1]1**

Body:
Can you ask more questions or detailed pictures of the initial state and what you want to achieve?

if you want to pass data into a text field you can use Controller
initialization controller example

TextEditingController _yourcontrollerName1 = TextEdititingController;

inside the widget textfield :

TextField(
..
controller :_yourcontrollerName1
)

you can set data with

_yourcontrollerName1.text = your_data_pass

or

TextEditingController _yourcontrollerName1 = TextEditingController(text:data_your_pass);

I hope this helps


问:
Wrong Images loading in some of tableView.dequeueReusableCell
I have the following code for my tableView:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        // Reset the image in the cell
        cell.coverImageView.image = nil

        // Get the recipe that the tableView is asking about
        let recipeInTable = recipe[indexPath.row]

        cell.displayRecipe(recipe: recipeInTable, indexPathRow: indexPath.row)

        return cell
    }
</code>```

This is my custom cell class, where I am caching the image data to pull from:

```<code>class CustomCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var coverImageView: UIImageView!

    var recipeToDisplay:Recipe?
    var recipeToPullFrom:Recipe!

    func displayRecipe(recipe:Recipe, indexPathRow:Int) {

        recipeToPullFrom = recipe

        DispatchQueue.main.async {
            self.titleLabel.text = self.recipeToPullFrom.title

            if self.recipeToPullFrom.image == nil {
                return
            }
            else {
                let urlString = self.recipeToPullFrom.image

                if let imageData = CacheManager.retrieveData(urlString!) {

                    self.coverImageView.image = UIImage(data: imageData)
                    return
                }

                let url = URL(string: urlString!)

                guard url != nil else {
                    print("Could not create url object")
                    return
                }

                let session = URLSession.shared

                let dataTask = session.dataTask(with: url!) { (data, response, error) in

                    if error == nil && data != nil  {

                        CacheManager.saveData(urlString!, data!)

                        if self.recipeToPullFrom.image == urlString {
                            DispatchQueue.main.async {
                                // Display the image data in the imageView
                                self.coverImageView.image = UIImage(data: data!)
                            }
                        }
                        DispatchQueue.main.async {
                            self.coverImageView.image = UIImage(data: data!)
                        }
                    } // End if

                } // End dataTask

                // Kick off the dataTask
                dataTask.resume()
            }
        }
    }
}
</code>```

And finally my Cache Manager:

```<code>class CacheManager {

    static var imageDictionary = [String:Data]()

    static func saveData(_ url:String, _ imageData:Data) {
        // Save the image data along with the url
        imageDictionary[url] = imageData
    }

    static func retrieveData(_ url:String) -> Data? {
        // Return the saved imageData or nil
        return imageDictionary[url]
    }
}
</code>```

From what I've researched, adding the following in my tableView function should have reset the image in my cell before inputting a new one: cell.coverImageView.image = nil.

Is there something I'm missing? I've also noticed that only my images are showing in the wrong cells. Could I be doing something incorrect with retrieving the image data from cache?

Any direction or support is much appreciated!

答:
Since your images are downloaded asynchronously then it can be downloaded after the cell been reused for another object. What you can do:

When your image is ready to be displayed (downloaded) you need to check if it should be displayed in that cell.

Or

You can also hold a reference to the URLSessionDataTask and cancel the it before reusing the cell by overriding the prepareForReuse method.

Body:
I have the following code for my tableView:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        // Reset the image in the cell
        cell.coverImageView.image = nil

        // Get the recipe that the tableView is asking about
        let recipeInTable = recipe[indexPath.row]

        cell.displayRecipe(recipe: recipeInTable, indexPathRow: indexPath.row)

        return cell
    }

This is my custom cell class, where I am caching the image data to pull from:

class CustomCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var coverImageView: UIImageView!

    var recipeToDisplay:Recipe?
    var recipeToPullFrom:Recipe!

    func displayRecipe(recipe:Recipe, indexPathRow:Int) {

        recipeToPullFrom = recipe

        DispatchQueue.main.async {
            self.titleLabel.text = self.recipeToPullFrom.title

            if self.recipeToPullFrom.image == nil {
                return
            }
            else {
                let urlString = self.recipeToPullFrom.image

                if let imageData = CacheManager.retrieveData(urlString!) {

                    self.coverImageView.image = UIImage(data: imageData)
                    return
                }

                let url = URL(string: urlString!)

                guard url != nil else {
                    print("Could not create url object")
                    return
                }

                let session = URLSession.shared

                let dataTask = session.dataTask(with: url!) { (data, response, error) in

                    if error == nil && data != nil  {

                        CacheManager.saveData(urlString!, data!)

                        if self.recipeToPullFrom.image == urlString {
                            DispatchQueue.main.async {
                                // Display the image data in the imageView
                                self.coverImageView.image = UIImage(data: data!)
                            }
                        }
                        DispatchQueue.main.async {
                            self.coverImageView.image = UIImage(data: data!)
                        }
                    } // End if

                } // End dataTask

                // Kick off the dataTask
                dataTask.resume()
            }
        }
    }
}

And finally my Cache Manager:

class CacheManager {

    static var imageDictionary = [String:Data]()

    static func saveData(_ url:String, _ imageData:Data) {
        // Save the image data along with the url
        imageDictionary[url] = imageData
    }

    static func retrieveData(_ url:String) -> Data? {
        // Return the saved imageData or nil
        return imageDictionary[url]
    }
}

From what I've researched, adding the following in my tableView function should have reset the image in my cell before inputting a new one: cell.coverImageView.image = nil.

Is there something I'm missing? I've also noticed that only my images are showing in the wrong cells. Could I be doing something incorrect with retrieving the image data from cache?

Any direction or support is much appreciated!


问:
QToolButton crashes on clicked and window destruction
I have asked the question QWidget::repaint: Recursive repaint detected on Windows in Debug without creation of new threads. It turned out that the crash (on Windows in DEBUG mode) is due the fact that auto-generated ui file contained:

```<code>       <widget class="QToolButton" name="button_logout">
       </widget>
</code>```

which would generate the code

        QToolButton *button_logout;
        button_logout = new QToolButton(widget_session_list);
        button_logout->setObjectName(QString::fromUtf8("button_logout"));
        header_layout->addWidget(button_logout);
```
<p>So having a clicked event due to this connection:</p>
<pre class="lang-cpp prettyprint-override"><code>...
    connect(_ui->button_logout, &QToolButton::clicked, this, &ViewImpl::performLogout);
...

void ViewImpl::performLogout()
{
    emit onLogout();
}
</code>```

led to the crash with  QWidget::repaint: Recursive repaint detected after the window would be hidden and deleted as a reaction on the signal onLogout().

However, I discovered that if I replace the QToolButton with QPushButton I do not get the crash and everything is fixed.

So my question is why? What is wrong with the QToolButton? And why is the problem on Windows in Debug mode and I do not have it on Linux or on Window in Release mode. Honestly, I have already encountered strange crashes on Windows in Debug mode for Qt. E.g., I remember once that QVariantList failed there, so I got rid of it. I must note here that I build against debug qt libraries and tried \MT, \MDd, and \MTd runtime libraries.

答:
Probably your shutdown / logout logic is flawed: I guess, that you delete the object from which you are running your logout code. Try to replace the call to delete() with
deleteLater() and see what happens. For further diagnosis, we'd need more information about your object tree, construction and destruction.

It has absolutely nothing to do with the kind of button you are using, that is absolutely accidental.

Body:
I have asked the question QWidget::repaint: Recursive repaint detected on Windows in Debug without creation of new threads. It turned out that the crash (on Windows in DEBUG mode) is due the fact that auto-generated ui file contained:

       <widget class="QToolButton" name="button_logout">
       </widget>

which would generate the code

        QToolButton *button_logout;
        button_logout = new QToolButton(widget_session_list);
        button_logout->setObjectName(QString::fromUtf8("button_logout"));
        header_layout->addWidget(button_logout);

So having a clicked event due to this connection:

...
    connect(_ui->button_logout, &QToolButton::clicked, this, &ViewImpl::performLogout);
...

void ViewImpl::performLogout()
{
    emit onLogout();
}

led to the crash with  QWidget::repaint: Recursive repaint detected after the window would be hidden and deleted as a reaction on the signal onLogout().

However, I discovered that if I replace the QToolButton with QPushButton I do not get the crash and everything is fixed.

So my question is why? What is wrong with the QToolButton? And why is the problem on Windows in Debug mode and I do not have it on Linux or on Window in Release mode. Honestly, I have already encountered strange crashes on Windows in Debug mode for Qt. E.g., I remember once that QVariantList failed there, so I got rid of it. I must note here that I build against debug qt libraries and tried \MT, \MDd, and \MTd runtime libraries.


问:
What is a equivalent of a merge query(insert/update/delete) is present in the QuestDB?
What is a equivalent of a merge query(insert/update/delete) is present in the QuestDB?

Below is an example for tsql. I would like to understand how to implement the same logic in QuestDB - insert rows for new data and update rows for existing data (if they changed)

https://www.sqlshack.com/understanding-the-sql-merge-statement/
USE SqlShackMergeDemo
GO

```<code>MERGE TargetProducts AS Target
USING SourceProducts    AS Source
ON Source.ProductID = Target.ProductID

-- For Inserts
WHEN NOT MATCHED BY Target THEN
    INSERT (ProductID,ProductName, Price)
    VALUES (Source.ProductID,Source.ProductName, Source.Price)

-- For Updates
WHEN MATCHED THEN UPDATE SET
    Target.ProductName  = Source.ProductName,
    Target.Price        = Source.Price;
</code>```

答:
QuestDB (current v6.2) does not support any form UPDATE or DELETE statements at the moment. The only way to delete data is to drop a partition or truncate table. There is no equivalent for MERGE either.

This is going to change soon.

Body:
What is a equivalent of a merge query(insert/update/delete) is present in the QuestDB?

Below is an example for tsql. I would like to understand how to implement the same logic in QuestDB - insert rows for new data and update rows for existing data (if they changed)

https://www.sqlshack.com/understanding-the-sql-merge-statement/
USE SqlShackMergeDemo
GO

MERGE TargetProducts AS Target
USING SourceProducts    AS Source
ON Source.ProductID = Target.ProductID

-- For Inserts
WHEN NOT MATCHED BY Target THEN
    INSERT (ProductID,ProductName, Price)
    VALUES (Source.ProductID,Source.ProductName, Source.Price)

-- For Updates
WHEN MATCHED THEN UPDATE SET
    Target.ProductName  = Source.ProductName,
    Target.Price        = Source.Price;


问:
OpenVINO GStreamer gvadetect is not applying model
I am super new to OpenVINO and GStreamer. I am trying to apply a pipeline in GStreamer plugin using OpenVINO. I downloaded the model as well it's proc files. I am trying to apply the model and it's proc to a video. For some reason I am not getting any output in the video.

I don't know how to debug the GStreamer pipeline. I added one text overlay for debugging and found out every step is working but the final output is not having any results. I get the same input video as output (with text overlay). Could anyone help me out here?

```<code># Model is downloaded from model downloader's downloader.py
# Model-proc is downloaded from
# https://github.com/openvinotoolkit/dlstreamer_gst/blob/master/samples/model_proc/intel/human_pose_estimation/human-pose-estimation-0001.json

VIDEO_FILE = 'HumanPoseEstimation/Sample_Video/face-demographics-walking.mp4'
ESTIMATION_MODEL = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/FP32/human-pose-estimation-0001.xml"
ESTIMATION_MODEL_PROC = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/human-post-estimation-0001-proc.json"
SINK_LOCATION = "HumanPoseEstimation/output.mp4"

# GStreamer pipeline
GST_PIPELINE = f'''
filesrc location={VIDEO_FILE}
! decodebin
! videoconvert
! queue
! gvaclassify model={ESTIMATION_MODEL} model-proc={ESTIMATION_MODEL_PROC} device=CPU
! queue
! textoverlay text="Human Pose Estimation"
! gvawatermark
! x264enc
! filesink location={SINK_LOCATION}
'''
</code>```

答:
You can use the Human Pose Estimation Sample to run with human-pose-estimation-0001 model.
Refer to human_pose_estimation.sh for the pipeline elements used in the Human Pose Estimation Sample.</p>

Body:
I am super new to OpenVINO and GStreamer. I am trying to apply a pipeline in GStreamer plugin using OpenVINO. I downloaded the model as well it's proc files. I am trying to apply the model and it's proc to a video. For some reason I am not getting any output in the video.

I don't know how to debug the GStreamer pipeline. I added one text overlay for debugging and found out every step is working but the final output is not having any results. I get the same input video as output (with text overlay). Could anyone help me out here?

# Model is downloaded from model downloader's downloader.py
# Model-proc is downloaded from
# https://github.com/openvinotoolkit/dlstreamer_gst/blob/master/samples/model_proc/intel/human_pose_estimation/human-pose-estimation-0001.json

VIDEO_FILE = 'HumanPoseEstimation/Sample_Video/face-demographics-walking.mp4'
ESTIMATION_MODEL = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/FP32/human-pose-estimation-0001.xml"
ESTIMATION_MODEL_PROC = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/human-post-estimation-0001-proc.json"
SINK_LOCATION = "HumanPoseEstimation/output.mp4"

# GStreamer pipeline
GST_PIPELINE = f'''
filesrc location={VIDEO_FILE}
! decodebin
! videoconvert
! queue
! gvaclassify model={ESTIMATION_MODEL} model-proc={ESTIMATION_MODEL_PROC} device=CPU
! queue
! textoverlay text="Human Pose Estimation"
! gvawatermark
! x264enc
! filesink location={SINK_LOCATION}
'''


问:
c++ heuristic for estimating function inlining benefits
In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may be ultimately beyond my control, I am still curious.</p>

答:
If your bottleneck is in a recursive function, and assuming that the level of recursion is not minimal (i.e. average recursion is not just a few levels), you are better off in working with the algorithm in the function rather than with inlining.

Try, if possible, to transform the recursion into a loop or tail-recursion (that can be implicitly transformed into a loop by the compiler), or try to determine where in the function the cost is being spent. Try to minimize the impact of the internal operations (maybe you are dynamically allocating memory that could have auto storage duration, or maybe you can factor a common operation to be performed external to the function in a wrapper and passed in as an extra argument,...)

*EDIT after the comment that recursion was not intended, but rather iteration*

If the compiler has access to the definition of the function, it will make the right decision for you in most cases. If it does not have access to the definition, just move the code around so that it does see it. Maybe make the function a static function to provide an extra hint that it won't be used anywhere else, or even mark it as inline (knowing that this will not force inlining), but avoid using special attributes that will force inlining, as the compiler probably does it better than any simple heuristic that can be produced without looking at the code.


问:
Error and Build Failed while setting up mediapipe on Raspberry Pi 4 (Raspbian OS 64 bit)
I am new to both Raspberry Pi and Mediapipe. I was following these steps: https://spyjetson.blogspot.com/2021/06/installing-mediapipecpu-mode-on.html

But on this step: root@raspberrypi:/usr/local/src/mediapipe# python3 setup.py bdist_wheel

I am getting error and build failed

Error is this:

```<code>ERROR: /usr/local/src/mediapipe/mediapipe/framework/stream_handler/BUILD:95:11: C++ compilation of rule '//mediapipe/framework/stream_handler:default_input_stream_handler' failed (Exit 1): gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG -ffunction-sections ... (remaining 55 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG -ffunction-sections ... (remaining 55 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
In file included from <command-line>:
/usr/include/stdc-predef.h: In substitution of 'template<class _Functor, class, class> std::function<std::unique_ptr<mediapipe::InputStreamHandler>(std::shared_ptr<mediapipe::tool::TagMap>, mediapipe::CalculatorContextManager*, const mediapipe::MediaPipeOptions&, bool)>::function(_Functor) [with _Functor = <missing>; <template-parameter-1-2> = <missing>; <template-parameter-1-3> = <missing>]':
mediapipe/framework/stream_handler/default_input_stream_handler.cc:24:1:   required from here
/usr/include/stdc-predef.h:32:94: internal compiler error: Segmentation fault
   32 |    whether the overall intent is to support these features; otherwise,
      |                                                                                ^
0x7fa3cab217 __libc_start_main
    ../csu/libc-start.c:308
Please submit a full bug report,
with preprocessed source if appropriate.
Please include the complete backtrace with any bug report.
See <file:///usr/share/doc/gcc-10/README.Bugs> for instructions.
Target //mediapipe/modules/face_detection:face_detection_short_range_cpu failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 853.907s, Critical Path: 792.14s
INFO: 990 processes: 130 internal, 860 linux-sandbox.
FAILED: Build did NOT complete successfully
</code>```

答:
In my case it was a GCC issue. I downgraded from 10 to 9 and it compiled.</p>
```<code>sudo apt install gcc-9 g++-9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 100 --slave /usr/bin/g++ g++ /usr/bin/g++-9 --slave /usr/bin/gcov gcov /usr/bin/gcov-9
</code>```

Body:
I am new to both Raspberry Pi and Mediapipe. I was following these steps: https://spyjetson.blogspot.com/2021/06/installing-mediapipecpu-mode-on.html

But on this step: root@raspberrypi:/usr/local/src/mediapipe# python3 setup.py bdist_wheel

I am getting error and build failed

Error is this:

ERROR: /usr/local/src/mediapipe/mediapipe/framework/stream_handler/BUILD:95:11: C++ compilation of rule '//mediapipe/framework/stream_handler:default_input_stream_handler' failed (Exit 1): gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG -ffunction-sections ... (remaining 55 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG -ffunction-sections ... (remaining 55 argument(s) skipped)

Use --sandbox_debug to see verbose messages from the sandbox
In file included from <command-line>:
/usr/include/stdc-predef.h: In substitution of 'template<class _Functor, class, class> std::function<std::unique_ptr<mediapipe::InputStreamHandler>(std::shared_ptr<mediapipe::tool::TagMap>, mediapipe::CalculatorContextManager*, const mediapipe::MediaPipeOptions&, bool)>::function(_Functor) [with _Functor = <missing>; <template-parameter-1-2> = <missing>; <template-parameter-1-3> = <missing>]':
mediapipe/framework/stream_handler/default_input_stream_handler.cc:24:1:   required from here
/usr/include/stdc-predef.h:32:94: internal compiler error: Segmentation fault
   32 |    whether the overall intent is to support these features; otherwise,
      |                                                                                ^
0x7fa3cab217 __libc_start_main
    ../csu/libc-start.c:308
Please submit a full bug report,
with preprocessed source if appropriate.
Please include the complete backtrace with any bug report.
See <file:///usr/share/doc/gcc-10/README.Bugs> for instructions.
Target //mediapipe/modules/face_detection:face_detection_short_range_cpu failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 853.907s, Critical Path: 792.14s
INFO: 990 processes: 130 internal, 860 linux-sandbox.
FAILED: Build did NOT complete successfully

Body:
In my case it was a GCC issue. I downgraded from 10 to 9 and it compiled.

sudo apt install gcc-9 g++-9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 100 --slave /usr/bin/g++ g++ /usr/bin/g++-9 --slave /usr/bin/gcov gcov /usr/bin/gcov-9


问:
How do I replace part of a tree with another tree at the specified index in OCaml?
I have the following tree structure:

type 'a tree =
    | Function of string * 'a tree list  (* function name and arguments *)
    | Terminal of 'a
```
<p>I use this tree structure to construct an abstract syntax tree:</p>
<pre class="lang-ml prettyprint-override"><code>type atoms =
    | Int of int
    | Bool of bool

let t1 = Function ("+", [Function ("*", [Terminal (Int 5);
                                         Terminal (Int 6)]);
                         Function ("sqrt", [Terminal (Int 3)])])

let t2 = Function ("-", [Terminal (Int 4); Terminal (Int 2)])
</code>```

Tree representation of t1:

Tree representation of t2:

Goal: replace one of the subtrees in t1 with t2 at a specified t1 index position. The index position starts at 0 at the root node and is depth-first. In the figures above, I have labelled all the nodes with their index to show this.

For example, replace_subtree t1 4 t2 replaces the subtree at index 4 in t1 with t2, resulting in this tree:

Function ("+", [Function ("*", [Terminal (Int 5);
                                Terminal (Int 6)]);
                Function ("-", [Terminal (Int 4);
                                Terminal (Int 2)])])
```

This is essentially a crossover operation in tree-based genetic programming.

How do I implement replace_subtree in OCaml?

I would strongly prefer a purely functional solution.

Note that this question is similar to How do I replace part of a tree with another tree at the specified index?, except that the programming language in this question is OCaml instead of Scheme/Racket. I have some trouble understanding Scheme/Racket, so I am looking for an OCaml solution.

答:
I have written a solution:

let rec replace_subtree' start_index tree replacement_index replacement
        : (int * 'a tree) =
    (* Returns (max_index, new_tree), where max_index = start_index + number of
       nodes in new_tree - 1, and where the replacement is counted as a single
       node. *)
    if start_index = replacement_index then
        (start_index, replacement)
    else
        match tree with
        | Function (name, args) ->
            (* (start_index + 1) to account for this function node itself. *)
            let (max_index, new_args) = replace_subtree_args (start_index + 1)
                                                             args
                                                             replacement_index
                                                             replacement in
            (max_index, Function (name, new_args))
        | Terminal _ ->
            (start_index, tree)

and replace_subtree_args arg_index args replacement_index replacement
        : (int * 'a tree list) =
    (* `arg_index` is the index of the first item in `args` (note that `args`
       could be empty, however).
       Returns (max_index, replaced_args), where max_index = arg_index +
       number of nodes in all transformed args - 1, and where the replacement is
       counted as a single node. *)
    let rec f arg_index args acc =
        match args with
        | [] -> (arg_index - 1, List.rev acc)
        | arg::rest_args ->
            let (max_index, arg_result) = replace_subtree' arg_index
                                                           arg
                                                           replacement_index
                                                           replacement in
            f (max_index + 1) rest_args (arg_result::acc)
    in
    f arg_index args []

let replace_subtree = replace_subtree' 0
```
<p>Example usage:</p>
<pre class="lang-ml prettyprint-override"><code>let string_of_terminal = function
    | Int x -> string_of_int x
    | Bool b -> string_of_bool b

let rec string_of_tree = function
    | Function (name, args) ->
        "(" ^
        String.concat " " (name::(List.map string_of_tree args)) ^
        ")"
    | Terminal x -> string_of_terminal x

let () =
    List.iter (fun n ->
                  let (max_index, new_tree) = replace_subtree t1 n t2 in
                  print_string ("Index " ^ (string_of_int n) ^ ":  ");
                  print_endline (string_of_tree new_tree))
              (List.init 8 Fun.id)
</code>```

Result:

Index 0:  (- 4 2)
Index 1:  (+ (- 4 2) (sqrt 3))
Index 2:  (+ (* (- 4 2) 6) (sqrt 3))
Index 3:  (+ (* 5 (- 4 2)) (sqrt 3))
Index 4:  (+ (* 5 6) (- 4 2))         ; <- Here.
Index 5:  (+ (* 5 6) (sqrt (- 4 2)))
Index 6:  (+ (* 5 6) (sqrt 3))
Index 7:  (+ (* 5 6) (sqrt 3))
```

Better solutions are most welcome.

Body:
I have the following tree structure:

type 'a tree =
    | Function of string * 'a tree list  (* function name and arguments *)
    | Terminal of 'a

I use this tree structure to construct an abstract syntax tree:

type atoms =
    | Int of int
    | Bool of bool

let t1 = Function ("+", [Function ("*", [Terminal (Int 5);
                                         Terminal (Int 6)]);
                         Function ("sqrt", [Terminal (Int 3)])])

let t2 = Function ("-", [Terminal (Int 4); Terminal (Int 2)])

Tree representation of t1:

Tree representation of t2:

Goal: replace one of the subtrees in t1 with t2 at a specified t1 index position. The index position starts at 0 at the root node and is depth-first. In the figures above, I have labelled all the nodes with their index to show this.

For example, replace_subtree t1 4 t2 replaces the subtree at index 4 in t1 with t2, resulting in this tree:

Function ("+", [Function ("*", [Terminal (Int 5);
                                Terminal (Int 6)]);
                Function ("-", [Terminal (Int 4);
                                Terminal (Int 2)])])

This is essentially a crossover operation in tree-based genetic programming.

How do I implement replace_subtree in OCaml?

I would strongly prefer a purely functional solution.

Note that this question is similar to How do I replace part of a tree with another tree at the specified index?, except that the programming language in this question is OCaml instead of Scheme/Racket. I have some trouble understanding Scheme/Racket, so I am looking for an OCaml solution.

Body:
I have written a solution:

let rec replace_subtree' start_index tree replacement_index replacement
        : (int * 'a tree) =
    (* Returns (max_index, new_tree), where max_index = start_index + number of
       nodes in new_tree - 1, and where the replacement is counted as a single
       node. *)
    if start_index = replacement_index then
        (start_index, replacement)
    else
        match tree with
        | Function (name, args) ->
            (* (start_index + 1) to account for this function node itself. *)
            let (max_index, new_args) = replace_subtree_args (start_index + 1)
                                                             args
                                                             replacement_index
                                                             replacement in
            (max_index, Function (name, new_args))
        | Terminal _ ->
            (start_index, tree)

and replace_subtree_args arg_index args replacement_index replacement
        : (int * 'a tree list) =
    (* `arg_index` is the index of the first item in `args` (note that `args`
       could be empty, however).
       Returns (max_index, replaced_args), where max_index = arg_index +
       number of nodes in all transformed args - 1, and where the replacement is
       counted as a single node. *)
    let rec f arg_index args acc =
        match args with
        | [] -> (arg_index - 1, List.rev acc)
        | arg::rest_args ->
            let (max_index, arg_result) = replace_subtree' arg_index
                                                           arg
                                                           replacement_index
                                                           replacement in
            f (max_index + 1) rest_args (arg_result::acc)
    in
    f arg_index args []

let replace_subtree = replace_subtree' 0

Example usage:

let string_of_terminal = function
    | Int x -> string_of_int x
    | Bool b -> string_of_bool b

let rec string_of_tree = function
    | Function (name, args) ->
        "(" ^
        String.concat " " (name::(List.map string_of_tree args)) ^
        ")"
    | Terminal x -> string_of_terminal x

let () =
    List.iter (fun n ->
                  let (max_index, new_tree) = replace_subtree t1 n t2 in
                  print_string ("Index " ^ (string_of_int n) ^ ":  ");
                  print_endline (string_of_tree new_tree))
              (List.init 8 Fun.id)

Result:

Index 0:  (- 4 2)
Index 1:  (+ (- 4 2) (sqrt 3))
Index 2:  (+ (* (- 4 2) 6) (sqrt 3))
Index 3:  (+ (* 5 (- 4 2)) (sqrt 3))
Index 4:  (+ (* 5 6) (- 4 2))         ; <- Here.
Index 5:  (+ (* 5 6) (sqrt (- 4 2)))
Index 6:  (+ (* 5 6) (sqrt 3))
Index 7:  (+ (* 5 6) (sqrt 3))

Better solutions are most welcome.


问:
How to add Health Probe id TO LB Rule while creating using Terraform
I am trying to add a LB Rule using Terraform but unable to find a way to refer existing probe id ( Health Probe).
Below is my code.</p>
```<code>resource "azurerm_lb_rule" "lb-rules" {
  resource_group_name            = var.lb_rg
  loadbalancer_id                = data.azurerm_lb.lb.id
  name                           = var.LB_Rule_Name
  protocol                       = var.protocol
  frontend_port                  = var.frontend_port
  backend_port                   = var.backend_port
  frontend_ip_configuration_name = var.frontend_ip_configuration_name
  backend_address_pool_ids = [data.azurerm_lb_backend_address_pool.backend.id]
 }
</code>```

答:
From azurerm provider docs:

The following arguments are supported:

...

probe_id - (Optional) A reference to a Probe used by this Load Balancing Rule.

Therefore:

```<code>resource "azurerm_lb_rule" "lb-rules" {
    [...]
    probe_id = azurerm_lb_probe.your_probe.id
}
</code>```

Body:
I am trying to add a LB Rule using Terraform but unable to find a way to refer existing probe id ( Health Probe).
Below is my code.

resource "azurerm_lb_rule" "lb-rules" {
  resource_group_name            = var.lb_rg
  loadbalancer_id                = data.azurerm_lb.lb.id
  name                           = var.LB_Rule_Name
  protocol                       = var.protocol
  frontend_port                  = var.frontend_port
  backend_port                   = var.backend_port
  frontend_ip_configuration_name = var.frontend_ip_configuration_name
  backend_address_pool_ids = [data.azurerm_lb_backend_address_pool.backend.id]
 }

Body:
From azurerm provider docs:

The following arguments are supported:

...

probe_id - (Optional) A reference to a Probe used by this Load Balancing Rule.

Therefore:

resource "azurerm_lb_rule" "lb-rules" {
    [...]
    probe_id = azurerm_lb_probe.your_probe.id
}


问:
Jetpack compose. Date time picker
Does the jetpack compose have the date time picker view or I should create it by myself? I have tried to google it but I couldn't find ready to use component.</p>

答:
You could do something like this

import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener
import java.util.*
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit

@Composable
fun rememberDatePickerDialog(
    @StringRes title: Int,
    select: Date? = null,
    bounds: CalendarConstraints? = null,
    onDateSelected: (Date) -> Unit = {},
): MaterialDatePicker<Long> {
    val datePicker = remember {
        MaterialDatePicker.Builder.datePicker()
            .setSelection((select?.time
                ?: Date().time) + 24.hours.toLong(DurationUnit.MILLISECONDS))
            .setCalendarConstraints(bounds)
            .setTitleText(title)
            .build()
    }

    DisposableEffect(datePicker) {
        val listener = MaterialPickerOnPositiveButtonClickListener<Long> {
            if (it != null) onDateSelected(Date(it))
        }
        datePicker.addOnPositiveButtonClickListener(listener)
        onDispose {
            datePicker.removeOnPositiveButtonClickListener(listener)
        }
    }

    return datePicker
}
```
<p><code>FragmentManager</code> for showing the picker (on button click). <strong>Make sure your activity extends from a <code>FragmentActivity</code> before using the following.</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun rememberFragmentManager(): FragmentManager {
    val context = LocalContext.current
    return remember(context) {
        (context as FragmentActivity).supportFragmentManager
    }
}
</code>```

Example use case.

val DATE_FORMAT = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
var date by remember {
  mutableStateOf(TextFieldValue(DATE_FORMAT.format(Date())))
}
val fragmentManager = rememberFragmentManager()

val datePicker = rememberDatePickerDialog(
    select = DATE_FORMAT.parse(date.text),
    title = R.string.select_date,
) { date = TextFieldValue(DATE_FORMAT.format(it)) }

TextField(
  readOnly = true,
  value = date,
  onValueChange = { date = it },
  trailingIcon = {
    IconButton({ datePicker.show(fragmentManager, "Date") }) {
       Icon(Icons.Default.DateRange,contentDescription = null)
    }
  },
)
```

Title: Jetpack compose. Date time picker

Body:
You could do something like this

import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import com.google.android.material.datepicker.CalendarConstraints
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener
import java.util.*
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit

@Composable
fun rememberDatePickerDialog(
    @StringRes title: Int,
    select: Date? = null,
    bounds: CalendarConstraints? = null,
    onDateSelected: (Date) -> Unit = {},
): MaterialDatePicker<Long> {
    val datePicker = remember {
        MaterialDatePicker.Builder.datePicker()
            .setSelection((select?.time
                ?: Date().time) + 24.hours.toLong(DurationUnit.MILLISECONDS))
            .setCalendarConstraints(bounds)
            .setTitleText(title)
            .build()
    }

    DisposableEffect(datePicker) {
        val listener = MaterialPickerOnPositiveButtonClickListener<Long> {
            if (it != null) onDateSelected(Date(it))
        }
        datePicker.addOnPositiveButtonClickListener(listener)
        onDispose {
            datePicker.removeOnPositiveButtonClickListener(listener)
        }
    }

    return datePicker
}

FragmentManager for showing the picker (on button click). Make sure your activity extends from a FragmentActivity before using the following.

@Composable
fun rememberFragmentManager(): FragmentManager {
    val context = LocalContext.current
    return remember(context) {
        (context as FragmentActivity).supportFragmentManager
    }
}

Example use case.

val DATE_FORMAT = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
var date by remember {
  mutableStateOf(TextFieldValue(DATE_FORMAT.format(Date())))
}
val fragmentManager = rememberFragmentManager()

val datePicker = rememberDatePickerDialog(
    select = DATE_FORMAT.parse(date.text),
    title = R.string.select_date,
) { date = TextFieldValue(DATE_FORMAT.format(it)) }

TextField(
  readOnly = true,
  value = date,
  onValueChange = { date = it },
  trailingIcon = {
    IconButton({ datePicker.show(fragmentManager, "Date") }) {
       Icon(Icons.Default.DateRange,contentDescription = null)
    }
  },
)


问:
How can I store a timestamp in a DBM database?
I am implemening simple file-sharing service. Currently I use a file-based database (as it suits my needs).

```<code>   # somewhere in my cgi script
   sub first_run
    {
      my $dbh = DBI->connect('dbi:DBM:');
      $dbh = DBI->connect("dbi:DBM:", "", "",{ AutoCommit => 1, RaiseError => 1, f_dir=>$DATABASE_DIR} );
      unless ($dbh)
      {
        print "<br>Cannot connect: $DBI::errstr";
        return undef;
      }
      $dbh->do("CREATE TABLE uploads( user_name TEXT,
        file_name TEXT,
        upload_date TEXT ) ");
      $dbh->disconnect( );
    }
</code>```

As you can see I propose to store the upload timestamp as a string, since currently I only have to display it (suppose to use localtime() to get timestamp in a human readable format).
But this seems to me somewhat bad. What if later I'll want to show uploads from some period, etc.

What is the common way of storing timestamps in a DBM database without using third-party, CPAN modules? How can I pull them later and show them to the user (in my situation, convert back to string)?

答:
I would just store the epoch, it's easy to then display it with *localtime* or *strftime*.

 If you really want to be able to browse the content of the DB without having to convert back the epoch, you could store both the numerical value and the *localtime* string (" `1238693517 - Thu Apr  2 19:31:57 2009`"). This makes the data redundant and denormalized, but also makes it easy to inspect, while still being able to process the numerical value. Your call.

OwnerDisplayName: jonny

ContentLicense: CC BY-SA 2.5

Body:
I am implemening simple file-sharing service. Currently I use a file-based database (as it suits my needs).

   # somewhere in my cgi script
   sub first_run
    {
      my $dbh = DBI->connect('dbi:DBM:');
      $dbh = DBI->connect("dbi:DBM:", "", "",{ AutoCommit => 1, RaiseError => 1, f_dir=>$DATABASE_DIR} );
      unless ($dbh)
      {
        print "
Cannot connect: $DBI::errstr";
        return undef;
      }
      $dbh->do("CREATE TABLE uploads( user_name TEXT,
        file_name TEXT,
        upload_date TEXT ) ");
      $dbh->disconnect( );
    }

As you can see I propose to store the upload timestamp as a string, since currently I only have to display it (suppose to use localtime() to get timestamp in a human readable format).
But this seems to me somewhat bad. What if later I'll want to show uploads from some period, etc.

What is the common way of storing timestamps in a DBM database without using third-party, CPAN modules? How can I pull them later and show them to the user (in my situation, convert back to string)?

LastEditorDisplayName: brian d foy

OwnerDisplayName: mirod


问:
destructing an object with references to itself
While debugging a piece of code that was exhausting the memory, I found a very interesting problem, and most importantly I don't know how to fix it.

The application consists roughly of a single Survey object, which contains a number of Question objects. The Question objects contain a reference to the Survey they're in, this is needed to be able to fetch answers from other Questions for instance.

The following loop was causing the memory overflow:

```<code>foreach ( $survey_ids_arr as $survey_id ) {
    $Survey = new Survey( $survey_id );
}
</code>```

Nothing really exotic is happening in the Survey constructor;

fetching its properties from the database

fetching all questions' properties from the database

creating a Question object for each question (passing a reference to $this)

adding all Question objects to an internal array

and from looking at the code, you would say that in each iteration the object is cleared from memory because the $Survey variable is overwritten. Right?? Wrong :)

The memory is piling up as the script goes through the loop - adding memory_get_usage() calls shows that the memory used by the Survey object isn't freed as expected, at the moment another object is assigned to the $Survey variable. Even calling unset( $Survey ) at the end of the loop does not free the memory.

The culprit are the references to $this that are passed to the Question objects upon creation. These references prevent the object to be cleared from memory - as the manual on php.net states:

The destructor method will be called as soon as all references to a particular object are removed

So what prevents the object from being cleaned up, is the references it has in it to itself. Nice, huh? :)

So, the problem is my object is a memory killer. Unfortunately, I can't think of a solution (other than writing an ugly method which clears the questions and calling that from the loop). The destructor in Survey is not an option; as stated above this is not called because the Question objects still have references.

Any ideas? Someone must have run into this problem already - the parent-containing-child-objects is not an uncommon architecture, is it?

答:
So, here is the answer: switch to PHP 5.3, since this issue have been resolved in it. If you have to work with PHP < 5.3.0, it is your responsibility to free objects captured in circle references. One possible aproach is to introduce special method that will strip off links to child objects to allow them be collected by GC

P.S. also might be useful for somebody, Doctrine 1.2 have such a links in models, so it's subject for memory leaks, especially if you fetch lots of entities from your database. If you are facing this issues, try (1) reduce amount of entities fetched (e.g. hydrate as arrays), (2) process entities with raw sql requests.

Body:
While debugging a piece of code that was exhausting the memory, I found a very interesting problem, and most importantly I don't know how to fix it.

The application consists roughly of a single Survey object, which contains a number of Question objects. The Question objects contain a reference to the Survey they're in, this is needed to be able to fetch answers from other Questions for instance.

The following loop was causing the memory overflow:

foreach ( $survey_ids_arr as $survey_id ) {
    $Survey = new Survey( $survey_id );
}

Nothing really exotic is happening in the Survey constructor;

fetching its properties from the database

fetching all questions' properties from the database

creating a Question object for each question (passing a reference to $this)

adding all Question objects to an internal array

and from looking at the code, you would say that in each iteration the object is cleared from memory because the $Survey variable is overwritten. Right?? Wrong :)

The memory is piling up as the script goes through the loop - adding memory_get_usage() calls shows that the memory used by the Survey object isn't freed as expected, at the moment another object is assigned to the $Survey variable. Even calling unset( $Survey ) at the end of the loop does not free the memory.

The culprit are the references to $this that are passed to the Question objects upon creation. These references prevent the object to be cleared from memory - as the manual on php.net states:

The destructor method will be called as soon as all references to a particular object are removed

So what prevents the object from being cleaned up, is the references it has in it to itself. Nice, huh? :)

So, the problem is my object is a memory killer. Unfortunately, I can't think of a solution (other than writing an ugly method which clears the questions and calling that from the loop). The destructor in Survey is not an option; as stated above this is not called because the Question objects still have references.

Any ideas? Someone must have run into this problem already - the parent-containing-child-objects is not an uncommon architecture, is it?


问:
issue cloning repos from github
I'm trying to run the FinRL notebook here but when I try to import the cloned libraries the finrl modules can't be found. I tried to check the file path where it said they were installed but I couldn't locate it in finder. (working on Mac)

Any help would be greatly appreciated!

答:
By default if you clone a repository on Mac, it will be saved on the 'Macintosh HD' drive.
If not, try to find a folder named 'GitHub' on your 'Macintosh HD' drive.

```<code>MacintoshHD/Users/Mac
</code>```

Or the issue might be that you never initialized a new local repository.

If that is the case, the below commands should work :-

```<code>git init

git clone https://github.com/AI4Finance-Foundation/FinRL-Meta.git
</code>```

Title: issue cloning repos from github

Body:
By default if you clone a repository on Mac, it will be saved on the 'Macintosh HD' drive.
If not, try to find a folder named 'GitHub' on your 'Macintosh HD' drive.

MacintoshHD/Users/Mac

Or the issue might be that you never initialized a new local repository.

If that is the case, the below commands should work :-

git init

git clone https://github.com/AI4Finance-Foundation/FinRL-Meta.git


问:
sql select everything with maximum date (that that is smaller than a specific date) without subqueries
I would like to write a sql query where I choose all rows grouped by id where the column date is the latest date for this id but still smaller than for example 16-JUL-2021. I would like to do this without using subqueries (in oracle), is that possible?
I tried the below but it doesn't work.

```<code>SELECT *, max(date)
WHERE date < '16-JUL-2021'
OVER(PARTITION BY id ORDER BY date DESC) as sth
FROM table
</code>```

答:
You can find the maximum date without sub-queries.

SELECT t.*,
       max("DATE") OVER(PARTITION BY id ORDER BY "DATE" DESC) as max_date
FROM   "TABLE" t
WHERE  "DATE" < DATE '2021-07-16'
```
<p>You need a sub-query to filter to only show the row(s) with the maximum date:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   (
  SELECT t.*,
         max("DATE") OVER(PARTITION BY id ORDER BY "DATE" DESC) as max_date
  FROM   "TABLE" t
  WHERE  "DATE" < DATE '2021-07-16'
)
WHERE  "DATE" = max_date;
</code>```

However, you are still only querying the table once using this technique even though it uses a sub-query.

Note DATE and TABLE are reserved words and cannot be used as unquoted identifiers; it would be better practice to use different names for those identifiers.

You could, equivalently use the RANK or DENSE_RANK analytic functions instead of MAX; ROW_NUMBER, however, does not give the same output as it will only return a single row and will not return all tied rows.

SELECT *
FROM   (
  SELECT t.*,
         RANK() OVER(PARTITION BY id ORDER BY "DATE" DESC) as rnk
  FROM   "TABLE" t
  WHERE  "DATE" < DATE '2021-07-16'
)
WHERE  rnk = 1;
```
<p>But you still need a sub-query to filter the rows.</p>
<hr />
<p>If you want to not use a sub-query then you can use:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT id,
       MAX("DATE") AS "DATE",
       MAX(col1) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col1,
       MAX(col2) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col2,
       MAX(col3) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col3
FROM   "TABLE"
GROUP BY id
</code>```

However, that is not quite the same as it will only get a single row per id and will not return multiple rows tied for the greatest date per id.

Body:
I would like to write a sql query where I choose all rows grouped by id where the column date is the latest date for this id but still smaller than for example 16-JUL-2021. I would like to do this without using subqueries (in oracle), is that possible?
I tried the below but it doesn't work.

SELECT *, max(date)
WHERE date < '16-JUL-2021'
OVER(PARTITION BY id ORDER BY date DESC) as sth
FROM table

Body:
You can find the maximum date without sub-queries.

SELECT t.*,
       max("DATE") OVER(PARTITION BY id ORDER BY "DATE" DESC) as max_date
FROM   "TABLE" t
WHERE  "DATE" < DATE '2021-07-16'

You need a sub-query to filter to only show the row(s) with the maximum date:

SELECT *
FROM   (
  SELECT t.*,
         max("DATE") OVER(PARTITION BY id ORDER BY "DATE" DESC) as max_date
  FROM   "TABLE" t
  WHERE  "DATE" < DATE '2021-07-16'
)
WHERE  "DATE" = max_date;

However, you are still only querying the table once using this technique even though it uses a sub-query.

Note DATE and TABLE are reserved words and cannot be used as unquoted identifiers; it would be better practice to use different names for those identifiers.

You could, equivalently use the RANK or DENSE_RANK analytic functions instead of MAX; ROW_NUMBER, however, does not give the same output as it will only return a single row and will not return all tied rows.

SELECT *
FROM   (
  SELECT t.*,
         RANK() OVER(PARTITION BY id ORDER BY "DATE" DESC) as rnk
  FROM   "TABLE" t
  WHERE  "DATE" < DATE '2021-07-16'
)
WHERE  rnk = 1;

But you still need a sub-query to filter the rows.

If you want to not use a sub-query then you can use:

SELECT id,
       MAX("DATE") AS "DATE",
       MAX(col1) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col1,
       MAX(col2) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col2,
       MAX(col3) KEEP (DENSE_RANK LAST ORDER BY "DATE", ROWNUM) AS col3
FROM   "TABLE"
GROUP BY id

However, that is not quite the same as it will only get a single row per id and will not return multiple rows tied for the greatest date per id.


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:

```<code>boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c
</code>```

Be careful when mixing them.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Body:
Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:

boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c

Be careful when mixing them.