问:
How to modify From and Reply To addresses before email is sent out in the Mautic software?
I have been struggling to find way to replace From and Reply To addresses before email is sent out in the Mautic software.

I have created mautic_root/plugins/SenderRandBundle/EventListener/EmailSubscriber.php and its content:

```<code><?php
namespace MauticPlugin\SenderRandBundle\EventListener;

use Doctrine\ORM\EntityManager;
use Mautic\CoreBundle\Helper\EmojiHelper;
use Mautic\CoreBundle\Helper\IpLookupHelper;
use Mautic\CoreBundle\Model\AuditLogModel;
// use Mautic\EmailBundle\EmailEvents;
// use Mautic\EmailBundle\Event as Events;
use Mautic\EmailBundle\Event\TransportWebhookEvent;
use Mautic\EmailBundle\Model\EmailModel;
// use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Translation\TranslatorInterface;

use Mautic\EmailBundle\EmailEvents;
use Mautic\EmailBundle\Event as Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
use MauticPlugin\SenderRandBundle\Integration\Config;

/**
 * Class EmailSubscriber
 */
class EmailSubscriber implements EventSubscriberInterface
{
    /**
     * @var AuditLogModel
     */
    private $auditLogModel;

    /**
     * @var IpLookupHelper
     */
    private $ipLookupHelper;

    /**
     * @var EmailModel
     */
    private $emailModel;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var EntityManager
     */
    private $entityManager;

    private $config;

    public function __construct(
        IpLookupHelper $ipLookupHelper,
        AuditLogModel $auditLogModel,
        EmailModel $emailModel,
        TranslatorInterface $translator,
        EntityManager $entityManager,
        LoggerInterface $logger,
        Config $config
    ) {
        $this->ipLookupHelper = $ipLookupHelper;
        $this->auditLogModel  = $auditLogModel;
        $this->emailModel     = $emailModel;
        $this->translator     = $translator;
        $this->entityManager  = $entityManager;
        $this->logger = $logger;
        $this->config = $config;
    }

    /**
     * @return array
     */
    static public function getSubscribedEvents()
    {
        return array(
            EmailEvents::EMAIL_ON_SEND    => array('onEmailGenerate', 0),
        );
    }

    /**
     * Search and replace with content
     *
     * @param EmailSendEvent $event
     */
    public function onEmailGenerate(Events\EmailSendEvent $event)
    {
        // Check if this plugin is enabled
        if (!$this->config->isPublished()) {
            return;
        }
        $email = $event->getEmail();
        $fromAddress = $email->getFromAddress();
        $replyToAddress = $email->getReplyToAddress();
        if (!$email->getUseOwnerAsMailer()) {
            // Check if email from address contains @sender.rand
            if (strpos($fromAddress, '@sender.rand') !== false) {
                // Get domains from plugin settings
                $domains = explode(',', $this->config->getFeatureSettings()['integration']['domains']);
                if (count($domains) > 0) {
                    // Choose random domain from domains
                    $domain = $domains[array_rand($domains)];
                    // Replace @sender.rand with chosen domain
                    $sender = str_replace('@sender.rand', '@' . $domain, $fromAddress);
                    // Update email from address
                    $email->setFromAddress($sender);
                    // Check if email reply to contains @sender.rand
                    if (strpos($replyToAddress, '@sender.rand') !== false) {
                        // Replace @sender.rand with chosen domain
                        $newReplyToAddress = str_replace('@sender.rand', '@' . $domain, $replyToAddress);
                        // Update email reply to address
                        $email->setReplyToAddress($newReplyToAddress);
                    }
                }
            }
        }
    }
}
</code>```

Currently with this code, I am getting an email which From address is changed as intended, but Reply To address remains unchanged - this is problem I am trying to solve.

What's the best way to modify From and Reply To addresses before email is sent out?

Body:
I have been struggling to find way to replace From and Reply To addresses before email is sent out in the Mautic software.

I have created mautic_root/plugins/SenderRandBundle/EventListener/EmailSubscriber.php and its content:

<?php
namespace MauticPlugin\SenderRandBundle\EventListener;

use Doctrine\ORM\EntityManager;
use Mautic\CoreBundle\Helper\EmojiHelper;
use Mautic\CoreBundle\Helper\IpLookupHelper;
use Mautic\CoreBundle\Model\AuditLogModel;
// use Mautic\EmailBundle\EmailEvents;
// use Mautic\EmailBundle\Event as Events;
use Mautic\EmailBundle\Event\TransportWebhookEvent;
use Mautic\EmailBundle\Model\EmailModel;
// use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Translation\TranslatorInterface;

use Mautic\EmailBundle\EmailEvents;
use Mautic\EmailBundle\Event as Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Psr\Log\LoggerInterface;
use MauticPlugin\SenderRandBundle\Integration\Config;

/**
 * Class EmailSubscriber
 */
class EmailSubscriber implements EventSubscriberInterface
{
    /**
     * @var AuditLogModel
     */
    private $auditLogModel;

    /**
     * @var IpLookupHelper
     */
    private $ipLookupHelper;

    /**
     * @var EmailModel
     */
    private $emailModel;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var EntityManager
     */
    private $entityManager;

    private $config;

    public function __construct(
        IpLookupHelper $ipLookupHelper,
        AuditLogModel $auditLogModel,
        EmailModel $emailModel,
        TranslatorInterface $translator,
        EntityManager $entityManager,
        LoggerInterface $logger,
        Config $config
    ) {
        $this->ipLookupHelper = $ipLookupHelper;
        $this->auditLogModel  = $auditLogModel;
        $this->emailModel     = $emailModel;
        $this->translator     = $translator;
        $this->entityManager  = $entityManager;
        $this->logger = $logger;
        $this->config = $config;
    }

    /**
     * @return array
     */
    static public function getSubscribedEvents()
    {
        return array(
            EmailEvents::EMAIL_ON_SEND    => array('onEmailGenerate', 0),
        );
    }

    /**
     * Search and replace with content
     *
     * @param EmailSendEvent $event
     */
    public function onEmailGenerate(Events\EmailSendEvent $event)
    {
        // Check if this plugin is enabled
        if (!$this->config->isPublished()) {
            return;
        }
        $email = $event->getEmail();
        $fromAddress = $email->getFromAddress();
        $replyToAddress = $email->getReplyToAddress();
        if (!$email->getUseOwnerAsMailer()) {
            // Check if email from address contains @sender.rand
            if (strpos($fromAddress, '@sender.rand') !== false) {
                // Get domains from plugin settings
                $domains = explode(',', $this->config->getFeatureSettings()['integration']['domains']);
                if (count($domains) > 0) {
                    // Choose random domain from domains
                    $domain = $domains[array_rand($domains)];
                    // Replace @sender.rand with chosen domain
                    $sender = str_replace('@sender.rand', '@' . $domain, $fromAddress);
                    // Update email from address
                    $email->setFromAddress($sender);
                    // Check if email reply to contains @sender.rand
                    if (strpos($replyToAddress, '@sender.rand') !== false) {
                        // Replace @sender.rand with chosen domain
                        $newReplyToAddress = str_replace('@sender.rand', '@' . $domain, $replyToAddress);
                        // Update email reply to address
                        $email->setReplyToAddress($newReplyToAddress);
                    }
                }
            }
        }
    }
}

Currently with this code, I am getting an email which From address is changed as intended, but Reply To address remains unchanged - this is problem I am trying to solve.

What's the best way to modify From and Reply To addresses before email is sent out?


来源: stackexchange

问:
npm init doesn't generate package.json file, & I have to close and open the terminal to resolve it every time
npm init generate the package.json file only for the 1st project im creating, and if i want to create another project I have to close and open the terminal to generate the package.json file in the new directory.

After the first time (when it does the problem) the terminal simply does not ask me the questions (such as "name", etc...) and immediately ends the command.

What is the solution to this?
Thanks!

The only way to solve the problem from what I was able to do is to close and reopen the terminal.

ContentLicense: CC BY-SA 4.0


问:
the problem with unlimited horizontal columns in text, browser does not detect right width for parent of columned element
I have the task of making a horizontally scrolling web page.
One part is column texts, and we don't know how many columns it will be depends on the text.

The page will not have vertical scrolling, so we set a fixed height for wrapper of columns

From what I understand, browsers don't calculate the width of text in columns correctly if the width is larger than the width of the window.

I've tried making the width of the .wrapper auto - it's the same as the width of the window;
I've tried purposely making the .outer-wrapper very wide and setting the max-content for the width of the .wrapper - that doesn't work either.

Here's a snippet - https://codepen.io/the_buddha/pen/poKqLpd

```<code><html>
    <body>
        <div class="fixed">
            <div class="outer-wrapper">
                <div class="wrapper">
                    <div class="columns">
                        <p>Private Sale Drop
                          is scheduled from the 28th of April until May 1st. Preferential Sale Drop is scheduled from the 2nd of May
                          until May 15th. Final Private Sale Drop is scheduled from the 16th of May until the 18th of May. Remaining
                          artworks will be available for sale until June 30th at an increased price.
                          The Venetian-born artist Giovanni Battista Piranesi (1720-1778) is best known for his dramatic prints of the
                          architecture and antiquities of his adopted city of Rome, and for the extraordinary flights of spatial fancy
                          in his celebrated series La Carceri (Prisons).
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
</code>```
```<code>body {
    font-size: 20px;
}

.fixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: lavender;
    overflow: auto;
}

.outer-wrapper {
    background: lightblue;
    /*   width: 15000px; */
}

.wrapper {
    width: max-content;
    height: 200px;
    border: 4px solid red;
}

.columns {
    column-fill: auto;
    column-width: 350px;
    column-gap: 90px;
    height: 100%;
}
</code>```

I expect the borders of the .wrapper element to match the column content.

Body:
I have the task of making a horizontally scrolling web page.
One part is column texts, and we don't know how many columns it will be depends on the text.

The page will not have vertical scrolling, so we set a fixed height for wrapper of columns

From what I understand, browsers don't calculate the width of text in columns correctly if the width is larger than the width of the window.

I've tried making the width of the .wrapper auto - it's the same as the width of the window;
I've tried purposely making the .outer-wrapper very wide and setting the max-content for the width of the .wrapper - that doesn't work either.

Here's a snippet - https://codepen.io/the_buddha/pen/poKqLpd

Private Sale Drop
                          is scheduled from the 28th of April until May 1st. Preferential Sale Drop is scheduled from the 2nd of May
                          until May 15th. Final Private Sale Drop is scheduled from the 16th of May until the 18th of May. Remaining
                          artworks will be available for sale until June 30th at an increased price.
                          The Venetian-born artist Giovanni Battista Piranesi (1720-1778) is best known for his dramatic prints of the
                          architecture and antiquities of his adopted city of Rome, and for the extraordinary flights of spatial fancy
                          in his celebrated series La Carceri (Prisons).

body {
    font-size: 20px;
}

.fixed {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: lavender;
    overflow: auto;
}

.outer-wrapper {
    background: lightblue;
    /*   width: 15000px; */
}

.wrapper {
    width: max-content;
    height: 200px;
    border: 4px solid red;
}

.columns {
    column-fill: auto;
    column-width: 350px;
    column-gap: 90px;
    height: 100%;
}

I expect the borders of the .wrapper element to match the column content.


问:
Jest can't do imports outside module with "type":"module"
I am coding a Jest and ReactJS project and encountered a cannot use import statement outside a module error. I ran the command npm test. Here are the details:

```<code>({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                ^^^^^^
    SyntaxError: Cannot use import statement outside a module
</code>```

package.json:

```<code>{
  "name": "frontend",
  "version": "0.1.0",
  "type": "module",
  "private": true,
   ...
}
</code>```

babel.config.cjs:

```<code>module.exports = {
    presets:[
        "@babel/preset-env",
        ["@babel/preset-react", {"runtime": "automatic"}]
    ]
}
</code>```

Dashboard.test.js:

```<code>import { render, screen } from '@testing-library/react';
import Dashboard from '../src/components/Dashboard';

test('renders the landing page', () => {
  render(<Dashboard />);
});
</code>```

Dashboard.js:

```<code>import axios from 'axios';
import { useState, useEffect } from 'react';
import {useNavigate } from "react-router-dom";
import Cookies from 'universal-cookie';

const Dashboard = () => {
    ...
}
export default Dashboard;
</code>```

I'd greatly appreciate any help you provide.

Body:
I am coding a Jest and ReactJS project and encountered a cannot use import statement outside a module error. I ran the command npm test. Here are the details:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                ^^^^^^
    SyntaxError: Cannot use import statement outside a module

package.json:

{
  "name": "frontend",
  "version": "0.1.0",
  "type": "module",
  "private": true,
   ...
}

babel.config.cjs:

module.exports = {
    presets:[
        "@babel/preset-env",
        ["@babel/preset-react", {"runtime": "automatic"}]
    ]
}

Dashboard.test.js:

import { render, screen } from '@testing-library/react';
import Dashboard from '../src/components/Dashboard';

test('renders the landing page', () => {
  render(<Dashboard />);
});

Dashboard.js:

import axios from 'axios';
import { useState, useEffect } from 'react';
import {useNavigate } from "react-router-dom";
import Cookies from 'universal-cookie';

const Dashboard = () => {
    ...
}
export default Dashboard;

I'd greatly appreciate any help you provide.


问:
Vue 2 and Vuelidate 2 - Validating a child component from a custom npm component library
I've been searching the vuelidate-next (and vuelidate 0.x) documentation, github vuelidate repo (issues), and stackoverflow, but haven't really found a solution for this issue that I currently have.

Main issue:

Vuelidate is not collecting all validation $errors and $silentErrors when used with a child component from a custom npm component library.

Context behind this issue:

I am currently building a Vue 2 component library (using the Options API), and using it in another Vue 2 (Options API) project (Parent Vue Project).

When the component library is being tested in Jest and or StoryBook, the v$ setup object appears in the Vue inspector tool, and supplies all the usual information as normal (examples posted below).

However, when the components are packaged for release via npm, then imported into another vue 2 project; the v$ setup object only returns information for vue 2 project instance, and completely ignores the validation for the library components.

All the library components have $autoDirty: true (code example below).

The components from the npm library render and function correctly within the Parent Vue Project, except for the validations through Vuelidate.

The component library has functioning validation as far as I have tested (Validation works perfectly with both Jest and StoryBook).

The components must have the validation rules within the custom npm library, and be validated in a parent wrapper within another project (client has specified this as a requirement, the examples posted below are a simplified representation of the actual code).

The Parent Vue Project code (not component library) looks like this:

```<code><template>
    <div>
        <custom-input-component v-model="textValue"/>
            <span v-if="v$.value.$error" class="field validation-error">
              This field is required
            </span>
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { CustomInputComponent } from '@custom-components-library';

    export default{
        props:{...},
        data(){...},

          setup () {
            return {
              v$: useVuelidate()
            }
          },

        computed:{...}
        methods:{...}
    }
</script>
</code>```

The npm component library package code looks like this:

```<code><template>
    <div>
        <label for="name">Name: </label>
        <input type="text" @input="$emit('input', $event.target.value) :value="value">
    </div>
</template>

<script>
    import { useVuelidate } from '@vuelidate/core';
    import { required } from '@vuelidate/validators';

    export default{
        props:{
            value: {
                type: String,
                default: '',
            }
        },
        setup() {
            return {
              v$: useVuelidate({ $autoDirty: true }),
            };
        },

        validations() {
            return {
              value: {required},
            };
        }
  ...
  }
  </script>
</code>```

v$ validation object in component library ( using Storybook with Vue 2)

```<code>v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...
    value:
        $anyDirty:true
        $commit:function $commit()
        $dirty:true
        $error:true
        $errors:Array[1]
        $externalResults:Array[0]
        $invalid:true
        ...
        required:Object
</code>```

v$ validation object in Parent Vue Project (using Vue 2)

```<code>v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function
    $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...
</code>```

Web browser console errors:

```<code>[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading '$error')"
</code>```

Component library build config:

```<code>{
    "compilerOptions": {
    "target": "es5",
    "module": "esnext"
  }
}
</code>```

Questions:

How can I get the child component to validate in the Parent Vue Project?

My suspicion is that there are potentially two vuelidate instances, and the parent vuelidate object doesn't know about the v$ validation rules in child components?

Is there any way to overcome this, and be able to set validation rules within the npm library based components, and validate them within a parent wrapper within another project?

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

Body:
I've been searching the vuelidate-next (and vuelidate 0.x) documentation, github vuelidate repo (issues), and stackoverflow, but haven't really found a solution for this issue that I currently have.

Main issue:

Vuelidate is not collecting all validation $errors and $silentErrors when used with a child component from a custom npm component library.

Context behind this issue:

I am currently building a Vue 2 component library (using the Options API), and using it in another Vue 2 (Options API) project (Parent Vue Project).

When the component library is being tested in Jest and or StoryBook, the v$ setup object appears in the Vue inspector tool, and supplies all the usual information as normal (examples posted below).

However, when the components are packaged for release via npm, then imported into another vue 2 project; the v$ setup object only returns information for vue 2 project instance, and completely ignores the validation for the library components.

All the library components have $autoDirty: true (code example below).

The components from the npm library render and function correctly within the Parent Vue Project, except for the validations through Vuelidate.

The component library has functioning validation as far as I have tested (Validation works perfectly with both Jest and StoryBook).

The components must have the validation rules within the custom npm library, and be validated in a parent wrapper within another project (client has specified this as a requirement, the examples posted below are a simplified representation of the actual code).

The Parent Vue Project code (not component library) looks like this:

<template>

        <custom-input-component v-model="textValue"/>

              This field is required

</template>

The npm component library package code looks like this:

<template>

        Name:
        <input type="text" @input="$emit('input', $event.target.value) :value="value">

</template>

v$ validation object in component library ( using Storybook with Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...
    value:
        $anyDirty:true
        $commit:function $commit()
        $dirty:true
        $error:true
        $errors:Array[1]
        $externalResults:Array[0]
        $invalid:true
        ...
        required:Object

v$ validation object in Parent Vue Project (using Vue 2)

v$:Object (Computed)
    $anyDirty:true
    $clearExternalResults:function
    $clearExternalResults()
    $commit:function $commit()
    $dirty:true
    $error:false
    $errors:Array[0]
    ...

Web browser console errors:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading '$error')"

Component library build config:

{
    "compilerOptions": {
    "target": "es5",
    "module": "esnext"
  }
}

Questions:

How can I get the child component to validate in the Parent Vue Project?

My suspicion is that there are potentially two vuelidate instances, and the parent vuelidate object doesn't know about the v$ validation rules in child components?

Is there any way to overcome this, and be able to set validation rules within the npm library based components, and validate them within a parent wrapper within another project?


问:
How to encode special characters in HTML (encode, not entitize) but exclude HTML tags
So I'm trying to encode html special characters (like ®, &, ©) I find on the front-end, but I can't figure out how to avoid also encoding HTML tags (like
, or ).

This is what I've tried so far:

var encodedHtml = HttpUtility.HtmlEncode("Encode this: ®, &, © but not this: ")

Console.WriteLine(encodedHtml);

The result is: Encode this: ®, &, © but not this:

The result I want is this: Encode this: ®, &, © but not this:

I've also tried this, based on this post:

var entitizedHtml = HtmlEntity.Entitize("Encode this:®, &, © but not this: ");
Console.WriteLine(entitizedHtml );

The result is:Encode this: ®, &, ® but not this:

The entitized result is close to what I want, but I'm trying to see if I can convert the the HTML special characters to their HTML code versions rather than their HTML entity versions.

Anyone have any suggestions? I'm thinking I might have to figure out how to parse through the string to check for HTML tags, but I'm not too sure what the best way to do that is.


问:
addEventListener on AppNavItem
I am using latest version of Vaadin.
Intended: want to catch an event if AppNavItem (with child elements) is clicked (expanded, toggled).

Code:

```<code>    @JsModule("@vaadin-component-factory/vcf-nav")
    @Tag("vcf-nav-item")
    public class AppNavItem extends Component {

        public AppNavItem(String label) {
            setLabel(label);
        }

        public AppNavItem setExpanded(boolean value) {
            if (value) {
                getElement().setAttribute("expanded", "");
            } else {
                getElement().removeAttribute("expanded");
            }
            return this;
        }

        public AppNavItem setIcon(Component icon) {
            icon.getElement().setAttribute("slot", "prefix");
            int iconElementIndex = getIconElementIndex();
            if (iconElementIndex != -1) {
                getElement().setChild(iconElementIndex, icon.getElement());
            } else {
                getElement().appendChild(icon.getElement());
            }
            return this;
        }
    }

</code>```
```<code>    AppNavItem myItem = new AppNavItem("Project");

    myItem.addAttachListener(e -> {
        System.out.println(e.toString()); // works on page load as expected !
    });
    //projectParent.onEnabledStateChanged(false); // does not work
    //projectParent.onEnabledStateChanged(true); // does not work
    myItem.getElement().addEventListener("onchange", e -> {
        System.out.println(e.getType()); // does not work
    });
    myItem.getElement().addPropertyChangeListener("expanded","onchange",  e -> {
        System.out.println(e.getPropertyName()); // does not work
    });
    myItem.getElement().addEventListener("onchange", e -> {
        System.out.println(e.getType());
    });
    myItem.getElement().addPropertyChangeListener("expanded","onchange",  e -> {
        System.out.println(e.getPropertyName()); // does not work
    });
    myItem.getElement().addPropertyChangeListener("expanded", e -> {
        System.out.println(e.getPropertyName()); // does not work
    });

    myItem.addItem(...);

</code>```

I tried several eventTypes like: click, onclick, change, onchange, ontoggle, ...
Unfortunately, almost nothing works, see comment.
What am I doing wrong ?

I expect to catch an event

Title: addEventListener on AppNavItem

Body:
I am using latest version of Vaadin.
Intended: want to catch an event if AppNavItem (with child elements) is clicked (expanded, toggled).

Code:

    @JsModule("@vaadin-component-factory/vcf-nav")
    @Tag("vcf-nav-item")
    public class AppNavItem extends Component {

        public AppNavItem(String label) {
            setLabel(label);
        }

        public AppNavItem setExpanded(boolean value) {
            if (value) {
                getElement().setAttribute("expanded", "");
            } else {
                getElement().removeAttribute("expanded");
            }
            return this;
        }

        public AppNavItem setIcon(Component icon) {
            icon.getElement().setAttribute("slot", "prefix");
            int iconElementIndex = getIconElementIndex();
            if (iconElementIndex != -1) {
                getElement().setChild(iconElementIndex, icon.getElement());
            } else {
                getElement().appendChild(icon.getElement());
            }
            return this;
        }
    }

    AppNavItem myItem = new AppNavItem("Project");

    myItem.addAttachListener(e -> {
        System.out.println(e.toString()); // works on page load as expected !
    });
    //projectParent.onEnabledStateChanged(false); // does not work
    //projectParent.onEnabledStateChanged(true); // does not work
    myItem.getElement().addEventListener("onchange", e -> {
        System.out.println(e.getType()); // does not work
    });
    myItem.getElement().addPropertyChangeListener("expanded","onchange",  e -> {
        System.out.println(e.getPropertyName()); // does not work
    });
    myItem.getElement().addEventListener("onchange", e -> {
        System.out.println(e.getType());
    });
    myItem.getElement().addPropertyChangeListener("expanded","onchange",  e -> {
        System.out.println(e.getPropertyName()); // does not work
    });
    myItem.getElement().addPropertyChangeListener("expanded", e -> {
        System.out.println(e.getPropertyName()); // does not work
    });

    myItem.addItem(...);

I tried several eventTypes like: click, onclick, change, onchange, ontoggle, ...
Unfortunately, almost nothing works, see comment.
What am I doing wrong ?

I expect to catch an event


问:
SpringData JPA conditionally upsert
I have a sequence of messages need to be converted and saved into database. Messages come out of order and I want to make sure only the latest message is saved into database. Each message has a timestamp.

Say the message is like

```<code>{
    personId: string
    value: string
    timeStampe: BigInteger
}
</code>```

The database schema be like

```<code>personId: string | content : string | timestamp: BigInteger
</code>```

So it's an upsert with condition:

```<code>if `personId` not exists in database, `INSERT` the record,
else if `personId` exists and incoming timestamp > timestamp in database, `UPDATE` the record.
else do nothing
</code>```

for update I can do a find then update, just want to know if there's anyway to do it in one call (something already defined by SpringData JPA?). The database is DB2.

Thanks

Title: SpringData JPA conditionally upsert

Body:
I have a sequence of messages need to be converted and saved into database. Messages come out of order and I want to make sure only the latest message is saved into database. Each message has a timestamp.

Say the message is like

{
    personId: string
    value: string
    timeStampe: BigInteger
}

The database schema be like

personId: string | content : string | timestamp: BigInteger

So it's an upsert with condition:

if `personId` not exists in database, `INSERT` the record,
else if `personId` exists and incoming timestamp > timestamp in database, `UPDATE` the record.
else do nothing

for update I can do a find then update, just want to know if there's anyway to do it in one call (something already defined by SpringData JPA?). The database is DB2.

Thanks


问:
Linear solve warning when simulating deformable object
We are using the deformable_torus example in examples/multibody/deformable_torus modified to use the stanford bunny tetmesh (which we created using TetWild) where the bunny falls from some small hight. The simulation runs fine until the bunny hits the ground at which time we get the following error

[2022-11-28 18:43:40.215] [console] [warning] Linear solve did not converge in Newton iterations in FemSolver.

The simulation seems to stop working at that point and we just get a lot of the same repeated error. Is there a way to change the solver so that the simulation works?

We've tried reducing the number of points in the tetmesh but this seems to still break whenever the object hits the ground


Title: Why will the value not replace when the function is called?

Body:
I’m attempting to make a game called nine men’s morris in python, and I can’t figure out
why the string won’t replace when conditions are satisfied the next time the
gameplay_board() function is called. anyone have any ideas?

I was expecting the value of a1 to be changed from ' ' to ○, but it doesn’t seem to work.

#ring 1
a1="1"
b1="2"
c1="3"
d1="4"
e1="5"
f1="6"
g1="7"
h1="8"

#ring 2
a2="1"
b2="2"
c2="3"
d2="4"
e2="5"
f2="6"
g2="7"
h2="8"

#ring 3
a3="1"
b3="2"
c3="3"
d3="4"
e3="5"
f3="6"
g3="7"
h3="8"

def example_board():
    global a1, b1, c1, d1, e1, f1, g1, h1, a2, b2, c2, d2, e2, f2, g2, h2, a3, b3, c3, d3, e3, f3, g3, h3
    print("\n" +
    a1 + "----------" + b1 + "----------" + c1 + "\n" +
    "|          |          |" + "<---Ring 1" + "\n" +
    "|  " + a2 + "-------" + b2 + "-------" + c2 + "  |" + "\n" +
    "|  |       |       |<---Ring 2" + "\n" +
    "|  |  " + a3 + "----" + b3 + "----" + c3 + "  |  |" + "\n" +
    "|  |  |         |<---Ring 3" + "\n" +
    d1 + "--" + d2 + "--" + d3 + "         " + e3 + "--" + e2 + "--" + e1 + "\n" +
    "|  |  |         |  |  |"  + "\n" +
    "|  |  " + f3 + "----" + g3 + "----" + h3 + "  |  |" + "\n" +
    "|  |       |       |  |" + "\n" +
    "|  " + f2 + "-------" + g2 + "-------" + h2 + "  |" + "\n" +
    "|          |          |" + "\n" +
    f1 + "----------" + g1 + "----------" + h1 + "\n" + "_______________________" + "\n")
    a1=" "
    b1=" "
    c1=" "
    d1=" "
    e1=" "
    f1=" "
    g1=" "
    h1=" "
    a2=" "
    b2=" "
    c2=" "
    d2=" "
    e2=" "
    f2=" "
    g2=" "
    h2=" "
    a3=" "
    b3=" "
    c3=" "
    d3=" "
    e3=" "
    f3=" "
    g3=" "
    h3=" "
example_board()

def gameplay_board():
    print("\n" +
    " " + "----------" + " " + "----------" + " " + "\n" +
    "|          |          |" + "\n" +
    "|  " + " " + "-------" + " " + "-------" + " " + "  |" + "\n" +
    "|  |       |       |  |" + "\n" +
    "|  |  " + " " + "----" + " " + "----" + " " + "  |  |" + "\n" +
    "|  |  |         |  |  |" + "\n" +
    d1 + "--" + d2 + "--" + d3 + "         " + e3 + "--" + e2 + "--" + e1 + "\n" +
    "|  |  |         |  |  |"  + "\n" +
    "|  |  " + f3 + "----" + g3 + "----" + h3 + "  |  |" + "\n" +
    "|  |       |       |  |" + "\n" +
    "|  " + f2 + "-------" + g2 + "-------" + h2 + "  |" + "\n" +
    "|          |          |" + "\n" +
    f1 + "----------" + g1 + "----------" + h1 + "\n" + "_______________________" + "\n")

#gameplay_board()
def update():
    gameplay_board()
turn=1
bpp=0
wpp=0
def place_pieces():
    ringchoice=int(input("Player 1, please select a ring to place your piece on. "))
    if ringchoice==1: #and ringchoice=="one":
        spotchoice=input("Player 1, please chose a spot to place your piece on. ")
        if spotchoice==1:
            a1="○"
gameplay_board()


问:
Why macros are disabled each time I re-start my Excel workbook, even after enabling content...?
Here the context : I'm working on a local workbook (c:) that directly opens a UserForm within the Workbook_Open() Sub. Then, when UserForm is closed, Excel is also automatically closed. Nothing special there.

The problem : Even with a correct setup in my Trust Center Settings (Disable all macros WITH notification), the warning security message pops up again each time I reload that workbook.

Here my code :

```<code>Private Sub Workbook_Open()
    ' modal display of my form
    myUserForm.Show vbModal

    ' upon return from my form, save and close that workbook
    Me.Close savechanges:=True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ' also quit Excel app if no more workbook is opened
    If Application.Workbooks.Count = 1 Then Application.Quit
End Sub
</code>```

I'm pretty sure that's related to the fact that Excel is automatically closed by program, and not by user himself.
For example if I reduce the code to the strict minimum, like :

```<code>Private Sub Workbook_Open()
     myUserForm.Show vbModal ' modal display of my form
End Sub
</code>```

In that situation, so without any Close or Quit, I just fall into my main worksheet when the UserForm is closed, then I just manually close Excel, with or without saving, and that's it, warning popup will not appear next time I'll open that workbook.

I don't know if there is a solution without playing with Trust Locations or All macros enabled.

Any ideas ?

Thanks for your help

Body:
Here the context : I'm working on a local workbook (c:) that directly opens a UserForm within the Workbook_Open() Sub. Then, when UserForm is closed, Excel is also automatically closed. Nothing special there.

The problem : Even with a correct setup in my Trust Center Settings (Disable all macros WITH notification), the warning security message pops up again each time I reload that workbook.

Here my code :

Private Sub Workbook_Open()
    ' modal display of my form
    myUserForm.Show vbModal

    ' upon return from my form, save and close that workbook
    Me.Close savechanges:=True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ' also quit Excel app if no more workbook is opened
    If Application.Workbooks.Count = 1 Then Application.Quit
End Sub

I'm pretty sure that's related to the fact that Excel is automatically closed by program, and not by user himself.
For example if I reduce the code to the strict minimum, like :

Private Sub Workbook_Open()
     myUserForm.Show vbModal ' modal display of my form
End Sub

In that situation, so without any Close or Quit, I just fall into my main worksheet when the UserForm is closed, then I just manually close Excel, with or without saving, and that's it, warning popup will not appear next time I'll open that workbook.

I don't know if there is a solution without playing with Trust Locations or All macros enabled.

Any ideas ?

Thanks for your help


问:
System.InvalidCastException - Specified Cast is not valid
enter image description here

System.InvalidCastException - Specified Cast is not valid

Anyone who can help. please let me know


问:
Painting multiple moving components to JFrame
I'm very new to programming and I've been having a few issues with something I'm working on. I'm trying to create multiple squares that can both move using the "Translate" method that I made. However, only the most recently added component is visible, and I cannot figure out how to add more than one.

```<code>package linerendertest;

import java.awt.*;
import javax.swing.*;

class Square extends JComponent {

    public int[] xPoints = new int[4];
    public int[] yPoints = new int[4];

    Square (int width, int length){

        xPoints[0] = 0;
        xPoints[1] = 0;
        xPoints[2] = width;
        xPoints[3] = width;

        yPoints[0] = 0;
        yPoints[1] = length;
        yPoints[2] = length;
        yPoints[3] = 0;

    }

    @Override
    public void paint(Graphics g){

        g.setColor(Color.MAGENTA);
        //g.drawPolygon(xPoints, yPoints, 4);
        g.fillPolygon(xPoints, yPoints, 4);

    }

    public void translate (int xTranslate, int yTranslate){

        xPoints[0] += xTranslate;
        xPoints[1] += xTranslate;
        xPoints[2] += xTranslate;
        xPoints[3] += xTranslate;
        yPoints[0] += yTranslate;
        yPoints[1] += yTranslate;
        yPoints[2] += yTranslate;
        yPoints[3] += yTranslate;

    }

}

public class LineRenderTest {

    public static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    public static final int centerX = screenSize.width / 2;
    public static final int centerY = screenSize.height / 2;

    public static void main(String[] args) throws InterruptedException {

        Square square = new Square(250, 250);
        Square paddle = new Square(50, 200);

        JFrame frame = new JFrame();
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.black);
        frame.add(square);
        frame.add(paddle);

        frame.setVisible(true);

        int xVelocity = 0;
        int yVelocity = 1;
        square.translate(250, 0);

        while (true) {

            square.translate(xVelocity, yVelocity);
            frame.repaint();
            Thread.sleep(5);

            if(square.yPoints[1] == screenSize.height || square.yPoints[0] == 0){

                yVelocity = -yVelocity;

            }

            if(square.xPoints[2] == screenSize.width || square.xPoints[0] == 0){

                xVelocity = -xVelocity;

            }

        }

    }

}
</code>```

I have tried using BorderLayout.PAGE_START and others similar, but these all place the squares off-screen, and they disappear whenever they are moved.
I have also tried adding the squares to a JPanel first, but this just makes all elements non-visible.

Sorry if some of the terminology I used was not correct. Any other tips would be appreciated!

Body:
I'm very new to programming and I've been having a few issues with something I'm working on. I'm trying to create multiple squares that can both move using the "Translate" method that I made. However, only the most recently added component is visible, and I cannot figure out how to add more than one.

package linerendertest;

import java.awt.*;
import javax.swing.*;

class Square extends JComponent {

    public int[] xPoints = new int[4];
    public int[] yPoints = new int[4];

    Square (int width, int length){

        xPoints[0] = 0;
        xPoints[1] = 0;
        xPoints[2] = width;
        xPoints[3] = width;

        yPoints[0] = 0;
        yPoints[1] = length;
        yPoints[2] = length;
        yPoints[3] = 0;

    }

    @Override
    public void paint(Graphics g){

        g.setColor(Color.MAGENTA);
        //g.drawPolygon(xPoints, yPoints, 4);
        g.fillPolygon(xPoints, yPoints, 4);

    }

    public void translate (int xTranslate, int yTranslate){

        xPoints[0] += xTranslate;
        xPoints[1] += xTranslate;
        xPoints[2] += xTranslate;
        xPoints[3] += xTranslate;
        yPoints[0] += yTranslate;
        yPoints[1] += yTranslate;
        yPoints[2] += yTranslate;
        yPoints[3] += yTranslate;

    }

}

public class LineRenderTest {

    public static final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    public static final int centerX = screenSize.width / 2;
    public static final int centerY = screenSize.height / 2;

    public static void main(String[] args) throws InterruptedException {

        Square square = new Square(250, 250);
        Square paddle = new Square(50, 200);

        JFrame frame = new JFrame();
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.black);
        frame.add(square);
        frame.add(paddle);

        frame.setVisible(true);

        int xVelocity = 0;
        int yVelocity = 1;
        square.translate(250, 0);

        while (true) {

            square.translate(xVelocity, yVelocity);
            frame.repaint();
            Thread.sleep(5);

            if(square.yPoints[1] == screenSize.height || square.yPoints[0] == 0){

                yVelocity = -yVelocity;

            }

            if(square.xPoints[2] == screenSize.width || square.xPoints[0] == 0){

                xVelocity = -xVelocity;

            }

        }

    }

}

I have tried using BorderLayout.PAGE_START and others similar, but these all place the squares off-screen, and they disappear whenever they are moved.
I have also tried adding the squares to a JPanel first, but this just makes all elements non-visible.

Sorry if some of the terminology I used was not correct. Any other tips would be appreciated!


问:
MSSQLToGCSOperator how to create empty file into bucket
we upgrade composer (1.19.13) and aiflow (2.3.3) version at GCP cloud.
in our previous version if the query does not return any data, there is a file empty created by the MSSQLToGCSOperator. But now when query return no data, there is no file created (empty file) into GCP bucket, and I got an error of file not found, at the following task.

I try this code:

```<code>  mssql_to_gcs = MSSQLToGCSOperator(
        task_id='MYSQL_TO_GCS_{0}'.format(TABLE_NAME),
        mssql_conn_id='con_mssql_dba_prd',
        gcp_conn_id='google_cloud_storage_default',
        sql='select_{0}.sql'.format(TABLE_NAME),
        bucket=SOURCE_BUCKET,
        filename='composer/{0}/gcp_{0}{1}.json'.format(TABLE_NAME, DATE_FORMAT),
        dag=dag
     )

using this operator:

from airflow.providers.google.cloud.transfers.mssql_to_gcs import MSSQLToGCSOperator
</code>```

Body:
we upgrade composer (1.19.13) and aiflow (2.3.3) version at GCP cloud.
in our previous version if the query does not return any data, there is a file empty created by the MSSQLToGCSOperator. But now when query return no data, there is no file created (empty file) into GCP bucket, and I got an error of file not found, at the following task.

I try this code:

  mssql_to_gcs = MSSQLToGCSOperator(
        task_id='MYSQL_TO_GCS_{0}'.format(TABLE_NAME),
        mssql_conn_id='con_mssql_dba_prd',
        gcp_conn_id='google_cloud_storage_default',
        sql='select_{0}.sql'.format(TABLE_NAME),
        bucket=SOURCE_BUCKET,
        filename='composer/{0}/gcp_{0}{1}.json'.format(TABLE_NAME, DATE_FORMAT),
        dag=dag
     )

using this operator:

from airflow.providers.google.cloud.transfers.mssql_to_gcs import MSSQLToGCSOperator


问:
Should I shrink multiple factor variables into one?
```<code>* NEW CAR: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* USED CAR: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* FURNITURE: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* RADIO/TV: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* EDUCATION: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* RETRAINING: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
</code>```

So these are some of the variables I have for a new dataset. Since they are related to the purpose behind loan applications, would it be wise to group them under one variable that I could call "Purpose"?

I plan on running a Random Forest Model. I want to try out both ways and I probably will as soon as I conduct an analysis as it is.

To be clear, I've already checked that two variables don't hold a "Yes" in the same row number.

Is there any downside to creating ONE vector/variable that looks like when creating decision trees?:

```<code>c("NEW_CAR", "RADIO/TV", "RETRAINING", "FURNITURE", "USED_CAR", "USED_CAR", "NEW_CAR")
</code>```

I'm worried that there is a major downside as each current variable is binary and a tree can only split into two nodes. Perhaps it doesn't make a difference considering that there could be multiple nodes with a choice between the current variables.

I'm new. Thank you.

Thank You.

Body:
* NEW CAR: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* USED CAR: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* FURNITURE: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* RADIO/TV: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* EDUCATION: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes
* RETRAINING: Purpose for this credit/application? (Binary)
  + 0: No
  + 1: Yes

So these are some of the variables I have for a new dataset. Since they are related to the purpose behind loan applications, would it be wise to group them under one variable that I could call "Purpose"?

I plan on running a Random Forest Model. I want to try out both ways and I probably will as soon as I conduct an analysis as it is.

To be clear, I've already checked that two variables don't hold a "Yes" in the same row number.

Is there any downside to creating ONE vector/variable that looks like when creating decision trees?:

c("NEW_CAR", "RADIO/TV", "RETRAINING", "FURNITURE", "USED_CAR", "USED_CAR", "NEW_CAR")

I'm worried that there is a major downside as each current variable is binary and a tree can only split into two nodes. Perhaps it doesn't make a difference considering that there could be multiple nodes with a choice between the current variables.

I'm new. Thank you.

Thank You.


问:
NLTK not detecting recommendations
I have this practice NLTK script, but for some reason it's not detecting recommendations in the test string.

```<code>import nltk

# Function to extract product/service recommendations from a given string
def extract_recommendations(text):
  # Tokenize the text using NLTK
  tokens = nltk.word_tokenize(text)

  # Use NLTK's named entity chunker to extract named entities
  entities = nltk.ne_chunk(nltk.pos_tag(tokens))

  # Function to check if a chunk is a named entity
  def is_entity(chunk):
    if hasattr(chunk, "label") and chunk.label:
      return True
    return False

  # Iterate over the entities and look for recommendations
  recommendations = []
  for entity in entities:
    if is_entity(entity):
      # Check if the named entity is followed by a verb like "recommend" or "suggest"
      for i in range(len(entities) - 1):
        if entities[i] == entity and (entities[i + 1][0] == "recommend" or entities[i + 1][0] == "suggest"):
          # If a recommendation is found, extract the named entity text
          entity_text = " ".join([token for token, pos in entity.leaves()])
          recommendations.append(entity_text)

  return recommendations

# Test the function
text = "I recommend the iPhone 11. It has a great camera and is very user-friendly. You should definitely consider it if you're in the market for a new phone."
recommendations = extract_recommendations(text)

# Print the recommendations
print("Recommendations:", recommendations)
</code>```

It returns an empty list. What am I doing wrong?

Title: NLTK not detecting recommendations

Body:
I have this practice NLTK script, but for some reason it's not detecting recommendations in the test string.

import nltk

# Function to extract product/service recommendations from a given string
def extract_recommendations(text):
  # Tokenize the text using NLTK
  tokens = nltk.word_tokenize(text)

  # Use NLTK's named entity chunker to extract named entities
  entities = nltk.ne_chunk(nltk.pos_tag(tokens))

  # Function to check if a chunk is a named entity
  def is_entity(chunk):
    if hasattr(chunk, "label") and chunk.label:
      return True
    return False

  # Iterate over the entities and look for recommendations
  recommendations = []
  for entity in entities:
    if is_entity(entity):
      # Check if the named entity is followed by a verb like "recommend" or "suggest"
      for i in range(len(entities) - 1):
        if entities[i] == entity and (entities[i + 1][0] == "recommend" or entities[i + 1][0] == "suggest"):
          # If a recommendation is found, extract the named entity text
          entity_text = " ".join([token for token, pos in entity.leaves()])
          recommendations.append(entity_text)

  return recommendations

# Test the function
text = "I recommend the iPhone 11. It has a great camera and is very user-friendly. You should definitely consider it if you're in the market for a new phone."
recommendations = extract_recommendations(text)

# Print the recommendations
print("Recommendations:", recommendations)

It returns an empty list. What am I doing wrong?


问:
Sync-DbaAvailabilityGroup Not working from a SQL Server agent job
I'm using Sync-DbaAvailabilityGroup to sync jobs and user logins across my avaiablility groups. When I run the Powershell script from powershell it works as expected, however; when I run it from a SQL Server Agent job it succeeds but don't copy any jobs or users over.</p>


问:
Insomnia Client only return `Server is up and running.`
I have a simple API server running on Node.js/Express like below:

server.js

const express = require('express');
const cors = require('cors');

const app = express();

var corsOptions = {
  origin: 'https://localhost:8081',
}

// middlewares
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// testing api
app.get('/', (req, res) => {
  res.json({message: 'hello from API'})
})

const PORT = process.env.PORT || 8080;

// server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```

It works normally both in the browser and Postman.

Browser
Postman

But when I test it on Insomnia it always Server is up and running.

I've downloaded the newest version and reinstalling using it, but it's still not working as expected and keeps returning the Server is up and running. message.

Did I miss something or there is a configuration to resolve this problem? Thanks

Body:
I have a simple API server running on Node.js/Express like below:

server.js

const express = require('express');
const cors = require('cors');

const app = express();

var corsOptions = {
  origin: 'https://localhost:8081',
}

// middlewares
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// testing api
app.get('/', (req, res) => {
  res.json({message: 'hello from API'})
})

const PORT = process.env.PORT || 8080;

// server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

It works normally both in the browser and Postman.

Browser
Postman

But when I test it on Insomnia it always Server is up and running.

I've downloaded the newest version and reinstalling using it, but it's still not working as expected and keeps returning the Server is up and running. message.

Did I miss something or there is a configuration to resolve this problem? Thanks


问:
Why is Chrome adding 2 heights of the viewport of extra space to the bottom of the body on mobile?
Steps to reproduce:

Go to this demo

Open dev tools on Chrome (ensure you are at least on 108 or above)

Toggle the device tool bar

Select any mobile device

Select the body element in dev tools

Witness the fact that there is a lot of extra space after the body.

The same result cannot be reproduced by resizing the browser window, you must use either the device tool bar or a real mobile device.

I have tried Chrome on Linux, Mac, and Android, all face this issue. Firefox on Linux, Mac and Android do not face this issue. Safari on iOS and Mac do not face this issue. So it really is just Chrome.

I'm a bit confused on why this could be happening and how I might be able to fix it.

I have tried playing with overflow settings on the body tag. I have also tried playing with width and height fit-content. Neither have solved this issue for me. Maybe this is a bug with the svh and svw units I am using?


问:
Pass down a tree of unknown length to the end node?
Having a go at Angular for the first time, and I'm struggling to work out how what I want is achievable.

I have made two simple interfaces, a Project type and a folder type.

A project can contain folders and files, a folder can contain folders and files, so the depth of folders within folders in theory knows no bounds.

The files at this point are irrelevant.

Something like:

```<code>interface Project {
    name: string;
    folders: Folder[];
    files: any[]
    openStatus: boolean;
}

interface Folder {
  name: string;
  folders: Folder[];  //Not sure if having 'Folder' within itself is going to cause me problems.
  files: any[];
  openStatus: boolean;
}
</code>```

In my head I picture the structure looking like the below, essentially as you would expect a file directory.

```<code>--Project
 --Folder
  --Folder
   --Folder
    --Folder
     ...
 --Folder
  --Folder
   --Folder
</code>```

I want to create a nav bar which can essentially keep going deeper into the subsequent folders until it gets to the end of the tree.

So I have created this (probable monstrosity):

```<code><ul>
   <li *ngFor="let project of projects; index as i;" class="nav-list">
      <button class="nav-secondary-button" (click)="changeProjectVisibilityStatus(project)">{{ project.name }}</button>
      <div *ngIf="project.folders.length != 0" [hidden]="!project.openStatus">
         <li *ngFor="let folder of project.folders; index as i;">
            <button class="nav-secondary-button" (click)="changeFolderVisibilityStatus(folder)">{{ folder.name }}</button>
            <div *ngIf="folder.folders.length != 0" [hidden]="!folder.openStatus">
               <li *ngFor="let folder of folder.folders; index as i;">
               <button class="nav-secondary-button">{{ folder.name }}</button>
               </li>
            </div>
         </li>
      </div>
   </li>
</ul>
</code>```

This works as I would like, but only to the depth I choose to write it out to, and so I would have to set a hard limit on the depth.

Is there a way of looping until I find the bottom? There isn't a type of ngWhile (is there?!) and I can't see how I can make NgFor do this.

Now I have written this out I'm thinking I might be able to do it with a folder component that displays a folder component within itself if it contains folders, but I feel like the references are going to be circular and cause issues. I will try this out tomorrow evening to see if I get anywhere.

Always appreciative of any insight!

Body:
Having a go at Angular for the first time, and I'm struggling to work out how what I want is achievable.

I have made two simple interfaces, a Project type and a folder type.

A project can contain folders and files, a folder can contain folders and files, so the depth of folders within folders in theory knows no bounds.

The files at this point are irrelevant.

Something like:

interface Project {
    name: string;
    folders: Folder[];
    files: any[]
    openStatus: boolean;
}

interface Folder {
  name: string;
  folders: Folder[];  //Not sure if having 'Folder' within itself is going to cause me problems.
  files: any[];
  openStatus: boolean;
}

In my head I picture the structure looking like the below, essentially as you would expect a file directory.

--Project
 --Folder
  --Folder
   --Folder
    --Folder
     ...
 --Folder
  --Folder
   --Folder

I want to create a nav bar which can essentially keep going deeper into the subsequent folders until it gets to the end of the tree.

So I have created this (probable monstrosity):

      <button class="nav-secondary-button" (click)="changeProjectVisibilityStatus(project)">{{ project.name }}</button>

            <button class="nav-secondary-button" (click)="changeFolderVisibilityStatus(folder)">{{ folder.name }}</button>

               <button class="nav-secondary-button">{{ folder.name }}</button>

This works as I would like, but only to the depth I choose to write it out to, and so I would have to set a hard limit on the depth.

Is there a way of looping until I find the bottom? There isn't a type of ngWhile (is there?!) and I can't see how I can make NgFor do this.

Now I have written this out I'm thinking I might be able to do it with a folder component that displays a folder component within itself if it contains folders, but I feel like the references are going to be circular and cause issues. I will try this out tomorrow evening to see if I get anywhere.

Always appreciative of any insight!


问:
Error at line 0: PL/SQL: Compilation unit analysis terminated Error at line 1: PLS-00302: component 'HD' must be declared
```<code>CREATE OR REPLACE FUNCTION CAL_D (HD IN RESERVATION.HD%TYPE,HA IN RESERVATION.HA%TYPE)RETURN NUMBER IS DUREE NUMBER;
BEGIN
DUREE:=(TO_NUMBER(TO_CHAR (HD, 'D')))-(TO_NUMBER(TO_CHAR (HA, 'D')));
RETURN DUREE;
END ;
</code>```

I DON'T KNOW THE PROBLEM ,PLEASE HELP
RESULT:Error at line 0: PL/SQL: Compilation unit analysis terminated
Error at line 1: PLS-00302: component 'HD' must be declared

Body:
CREATE OR REPLACE FUNCTION CAL_D (HD IN RESERVATION.HD%TYPE,HA IN RESERVATION.HA%TYPE)RETURN NUMBER IS DUREE NUMBER;
BEGIN
DUREE:=(TO_NUMBER(TO_CHAR (HD, 'D')))-(TO_NUMBER(TO_CHAR (HA, 'D')));
RETURN DUREE;
END ;

I DON'T KNOW THE PROBLEM ,PLEASE HELP
RESULT:Error at line 0: PL/SQL: Compilation unit analysis terminated
Error at line 1: PLS-00302: component 'HD' must be declared


问:
Certificate Invalid Issue When Deploying Website
this is my first time deploying website with AWS EC2 instance and am using nginx as server. (Not sure if the language usage is correct here...)

For the certificate, I used CertBot to request one and it seems successfully. I was able to access to my website at https://pincdata.online/ before, but now is throwing this "NET::ERR_CERT_AUTHORITY_INVALID" error. I didn't change anything and this error came out by itself. Sometimes, if I wait for 10 or 30 mins, I'll be able to access the website again, but will still get this weird issue in a short amount of time. It seems like my certificate or SSL is really not stable, like I don't know when it will work or not. enter image description here

I tried to reinstall certbot, renew the certificate, but the issue is still there... not really sure what exactly the problem is and not sure where to debug... One thing I notice is that when the website is working, my certificate look like this enter image description here

And if my certificate is not working, then is like this enter image description here

I thought the certificate will always be the same so feel it's strange...
Not sure if I'm providing enough information, please let me know if there's anything else that I should provide. Thanks.


问:
setOnCheckedChangeListener isn't working when used with a dynamic radioGroup
I have a radioGroup that is populated dynamically since I don't know how many elements are going to be within it (it is being populated by a database). The problem is when I use setOnCheckedChangeListener with it, it won't work at all. I tried creating a toast to see if it's even getting called, and the toast didn't even fire!

Here is a copy of the class that contains the radio group as well as the setOnCheckedChange method:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
    addPayment = v.findViewById(R.id.btn_add_payment);
    totalPaymentTV = v.findViewById(R.id.tv_total_payment);
    radioGroup0 = v.findViewById(R.id.rg_select_subject);
    datePickerTV = v.findViewById(R.id.tv_date_picker);
    radioGroup = v.findViewById(R.id.rg_add_payment);
    numberPicker = v.findViewById(R.id.numberPicker);
    numberPicker.setMinValue(0);
    numberPicker.setMaxValue(10);
    hoursTeached = 0;
    teacherFee = 0;
    date = new String();

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            Toast.makeText(getContext(),"hello ",Toast.LENGTH_SHORT).show();
            schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
                @Override
                public void onChanged(Teacher teacher) {
                    teacherFee = teacher.getFee();
                    totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
                }
            });
        }
    });

    numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker numberPicker, int i, int hours) {
            if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
                schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
                    @Override
                    public void onChanged(Teacher teacher) {
                        teacherFee = teacher.getFee();
                        hoursTeached = hours;
                        totalPaymentTV.setText(teacherFee * hours + " DA");
                    }
                });
            }
        }
    });

    datePickerTV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pickADate();
        }
    });

    schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
                @Override
                public void onChanged(TeacherWithSubjects teacherWithSubjects) {
                    if (teacherWithSubjects.subjects.size() > 1) {
                        openDialog(teacherWithSubjects.subjects, radioGroup0);
                    } else {
                        subject = teacherWithSubjects.subjects.get(0);
                    }
                }
            });
        }
    });

    schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
        @Override
        public void onChanged(List<Teacher> teachers) {
            addRadioButtons(teachers, radioGroup);

        }
    });

    addPayment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (radioGroup.getCheckedRadioButtonId() == -1) {
                Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (subject == null) {
                Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
                return;
            }
            if (date.isEmpty()) {
                Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
                return;
            }
            if(hoursTeached == 0){
                Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
                return;
            }
            SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
            int totalPayment = (hoursTeached*teacherFee);
            schoolViewModel.addPayment(new Payment(crossRef,date,hoursTeached,totalPayment));
        }
    });

    return v;
}

private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
    for (Teacher i : teachers) {
        //instantiate...
        RadioButton radioButton = new RadioButton(getContext());
        //set the values that you would otherwise hardcode in the xml...
        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = 25;
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        radioButton.setLayoutParams(params);
        //label the button...
        radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
        radioButton.setMinWidth(250);
        radioButton.setBackgroundResource(R.drawable.custom_checkbox);
        radioButton.setElevation(16);
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setText(i.getTeacherName());
        radioButton.setPadding(50, 100, 50, 100);
        radioButton.setButtonDrawable(R.drawable.custom_checkbox);
        radioButton.setId(i.getTeacherId());
        //add it to the group.
        radioGroup.addView(radioButton);
    }
}

void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
    dialog = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.choose_teached_subject_dialog);
    dialog.setCancelable(false);
    radioGroup = dialog.findViewById(R.id.rg_select_subject);
    Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
    Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
    //populate the checkBox
    for (int i = 0; i < subjects.size(); i++) {
        RadioButton radioButton1 = new RadioButton(dialog.getContext());
        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = 25;
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        radioButton1.setLayoutParams(params);
        radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
        radioButton1.setMinWidth(250);
        radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
        radioButton1.setElevation(16);
        radioButton1.setGravity(Gravity.CENTER);
        radioButton1.setId(i);
        radioButton1.setText(subjects.get(i).getSubjectName());
        radioButton1.setPadding(50, 100, 50, 100);
        radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
        //add it to the group.
        radioGroup.addView(radioButton1);
    }
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            dummySubject = subjects.get(i);
            Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
        }
    });
    confirmSubject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dummySubject == null) {
                Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
            } else {
                subject = dummySubject;
                dummySubject = null;
                dialog.dismiss();
            }
        }
    });
    cancelSubject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dummySubject = null;
            dialog.dismiss();
        }
    });

    dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
    dialog.getWindow().setGravity(Gravity.CENTER);
    dialog.show();
}

void pickADate() {
    DatePickerDialog datePickerDialog = new DatePickerDialog(
            getContext(), this,
            Calendar.getInstance().get(Calendar.YEAR),
            Calendar.getInstance().get(Calendar.MONTH),
            Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
    );
    datePickerDialog.show();
}

@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
    date = day + "/" + (month + 1) + "/" + year;
    datePickerTV.setText(date);
}
}
</code>```

Body:
I have a radioGroup that is populated dynamically since I don't know how many elements are going to be within it (it is being populated by a database). The problem is when I use setOnCheckedChangeListener with it, it won't work at all. I tried creating a toast to see if it's even getting called, and the toast didn't even fire!

Here is a copy of the class that contains the radio group as well as the setOnCheckedChange method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_add_payment, container, false);
    addPayment = v.findViewById(R.id.btn_add_payment);
    totalPaymentTV = v.findViewById(R.id.tv_total_payment);
    radioGroup0 = v.findViewById(R.id.rg_select_subject);
    datePickerTV = v.findViewById(R.id.tv_date_picker);
    radioGroup = v.findViewById(R.id.rg_add_payment);
    numberPicker = v.findViewById(R.id.numberPicker);
    numberPicker.setMinValue(0);
    numberPicker.setMaxValue(10);
    hoursTeached = 0;
    teacherFee = 0;
    date = new String();

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            Toast.makeText(getContext(),"hello ",Toast.LENGTH_SHORT).show();
            schoolViewModel.getTeacherByID(i).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
                @Override
                public void onChanged(Teacher teacher) {
                    teacherFee = teacher.getFee();
                    totalPaymentTV.setText(teacherFee * hoursTeached + " DA");
                }
            });
        }
    });

    numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker numberPicker, int i, int hours) {
            if (!(radioGroup.getCheckedRadioButtonId() == -1)) {
                schoolViewModel.getTeacherByID(radioGroup.getCheckedRadioButtonId()).observe(getViewLifecycleOwner(), new Observer<Teacher>() {
                    @Override
                    public void onChanged(Teacher teacher) {
                        teacherFee = teacher.getFee();
                        hoursTeached = hours;
                        totalPaymentTV.setText(teacherFee * hours + " DA");
                    }
                });
            }
        }
    });

    datePickerTV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pickADate();
        }
    });

    schoolViewModel = new ViewModelProvider(this).get(SchoolViewModel.class);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            schoolViewModel.getSingleTeacherWithSubjects(i).observe(getViewLifecycleOwner(), new Observer<TeacherWithSubjects>() {
                @Override
                public void onChanged(TeacherWithSubjects teacherWithSubjects) {
                    if (teacherWithSubjects.subjects.size() > 1) {
                        openDialog(teacherWithSubjects.subjects, radioGroup0);
                    } else {
                        subject = teacherWithSubjects.subjects.get(0);
                    }
                }
            });
        }
    });

    schoolViewModel.getAllTeachers().observe(getViewLifecycleOwner(), new Observer<List<Teacher>>() {
        @Override
        public void onChanged(List<Teacher> teachers) {
            addRadioButtons(teachers, radioGroup);

        }
    });

    addPayment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (radioGroup.getCheckedRadioButtonId() == -1) {
                Toast.makeText(getContext(), "Choose a Teacher!!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (subject == null) {
                Toast.makeText(getContext(), "Choose a Subject", Toast.LENGTH_SHORT).show();
                return;
            }
            if (date.isEmpty()) {
                Toast.makeText(getContext(), "Pick a Date", Toast.LENGTH_SHORT).show();
                return;
            }
            if(hoursTeached == 0){
                Toast.makeText(getContext(),"Choose how many hours have been teached!!",Toast.LENGTH_SHORT).show();
                return;
            }
            SubjectTeacherCrossRef crossRef = new SubjectTeacherCrossRef(subject.getSubjectName(),radioGroup.getCheckedRadioButtonId());
            int totalPayment = (hoursTeached*teacherFee);
            schoolViewModel.addPayment(new Payment(crossRef,date,hoursTeached,totalPayment));
        }
    });

    return v;
}

private void addRadioButtons(List<Teacher> teachers, RadioGroup radioGroup) {
    for (Teacher i : teachers) {
        //instantiate...
        RadioButton radioButton = new RadioButton(getContext());
        //set the values that you would otherwise hardcode in the xml...
        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = 25;
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        radioButton.setLayoutParams(params);
        //label the button...
        radioButton.setBackground(new ColorDrawable(Color.TRANSPARENT));
        radioButton.setMinWidth(250);
        radioButton.setBackgroundResource(R.drawable.custom_checkbox);
        radioButton.setElevation(16);
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setText(i.getTeacherName());
        radioButton.setPadding(50, 100, 50, 100);
        radioButton.setButtonDrawable(R.drawable.custom_checkbox);
        radioButton.setId(i.getTeacherId());
        //add it to the group.
        radioGroup.addView(radioButton);
    }
}

void openDialog(List<Subject> subjects, RadioGroup radioGroup) {
    dialog = new Dialog(getContext());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.choose_teached_subject_dialog);
    dialog.setCancelable(false);
    radioGroup = dialog.findViewById(R.id.rg_select_subject);
    Button confirmSubject = dialog.findViewById(R.id.btn_choose_subject);
    Button cancelSubject = dialog.findViewById(R.id.btn_dont_choose_subject);
    //populate the checkBox
    for (int i = 0; i < subjects.size(); i++) {
        RadioButton radioButton1 = new RadioButton(dialog.getContext());
        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        params.bottomMargin = 25;
        params.leftMargin = 20;
        params.rightMargin = 20;
        params.topMargin = 20;
        radioButton1.setLayoutParams(params);
        radioButton1.setBackground(new ColorDrawable(Color.TRANSPARENT));
        radioButton1.setMinWidth(250);
        radioButton1.setBackgroundResource(R.drawable.custom_checkbox);
        radioButton1.setElevation(16);
        radioButton1.setGravity(Gravity.CENTER);
        radioButton1.setId(i);
        radioButton1.setText(subjects.get(i).getSubjectName());
        radioButton1.setPadding(50, 100, 50, 100);
        radioButton1.setButtonDrawable(R.drawable.custom_checkbox);
        //add it to the group.
        radioGroup.addView(radioButton1);
    }
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            dummySubject = subjects.get(i);
            Toast.makeText(getContext(), dummySubject.getSubjectName(), Toast.LENGTH_SHORT).show();
        }
    });
    confirmSubject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dummySubject == null) {
                Toast.makeText(getContext(), "Choose A Subject", Toast.LENGTH_SHORT).show();
            } else {
                subject = dummySubject;
                dummySubject = null;
                dialog.dismiss();
            }
        }
    });
    cancelSubject.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dummySubject = null;
            dialog.dismiss();
        }
    });

    dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
    dialog.getWindow().setGravity(Gravity.CENTER);
    dialog.show();
}

void pickADate() {
    DatePickerDialog datePickerDialog = new DatePickerDialog(
            getContext(), this,
            Calendar.getInstance().get(Calendar.YEAR),
            Calendar.getInstance().get(Calendar.MONTH),
            Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
    );
    datePickerDialog.show();
}

@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
    date = day + "/" + (month + 1) + "/" + year;
    datePickerTV.setText(date);
}
}


问:
How to add columns to an existing Athena table using Avro storage
I have an existing Athena table (w/ hive-style partitions) that's using the Avro SerDe. When I first created the table, I declared the Athena schema as well as the Athena avro.schema.literal schema per AWS instructions. Everything has been working great.

I now wish to add new columns that will apply going forward but not be present on the old partitions. I tried a basic ADD COLUMNS command that claims to succeed but has no impact on SHOW CREATE TABLE. I then wondered if I needed to change the Avro schema declaration as well, which I attempted to do but discovered that ALTER TABLE SET SERDEPROPERTIES DDL is not supported in Athena.

AWS claims I should be able to add columns when using Avro, but at this point I'm unsure how to do it. Even if I'm willing to drop the table metadata and redeclare all of the partitions, I'm not sure how to do it right since the schema is different on the historical partitions.

Looking for high-level guidance on the steps to be taken. Documentation is scant and Athena seems to be lacking support for commands that are referenced in this same scenario in vanilla Hive world. Thanks for any insights.


问:
Replicate pandas quarterly resample with monthly resample
Is there a way to replicate df.resample('QS') using monthly resample?

For example

```<code>index = pd.date_range('1/2/2000', periods=11, freq='MS')
series = pd.Series(range(11), index=index)
series.resample('QS').sum()
</code>```

Gives me

```<code>2000-01-01     1
2000-04-01     9
2000-07-01    18
2000-10-01    27
</code>```

But

```<code>series.resample('3MS', origin='2000-04-01').sum()
</code>```

Gives me

```<code>2000-02-01     3
2000-05-01    12
2000-08-01    21
2000-11-01    19
</code>```

Expected output is

```<code>2000-01-01     1
2000-04-01     9
2000-07-01    18
2000-10-01    27
</code>```

Body:
Is there a way to replicate df.resample('QS') using monthly resample?

For example

index = pd.date_range('1/2/2000', periods=11, freq='MS')
series = pd.Series(range(11), index=index)
series.resample('QS').sum()

Gives me

2000-01-01     1
2000-04-01     9
2000-07-01    18
2000-10-01    27

But

series.resample('3MS', origin='2000-04-01').sum()

Gives me

2000-02-01     3
2000-05-01    12
2000-08-01    21
2000-11-01    19

Expected output is

2000-01-01     1
2000-04-01     9
2000-07-01    18
2000-10-01    27


问:
Using optim to estimate 3-parameters log-normal by MLE
I need your help. I am having problems to estimate the parameters of the following data in R using optim. I am always getting a error message of the the following type:

```<code>Warning: NaNs producedError in optim(par = c(0, 1, -2), nll, method = "L-BFGS-B", upper = c(Inf,  :
  L-BFGS-B needs finite values of 'fn'
</code>```

Could you please take a look and tell what i am doing wrong? Thanks

The code I am using is the following:

```<code>X <- rlnorm3(n=1000, meanlog = 0, sdlog = 1, threshold = -2)

nll <- function(theta) {
  N <- length(X)
  m <- theta[1]
  s <- theta[2]
  a <- theta[3]
  e_1 <- log(X - a) - m
  e_2 <- log(X - a)
  nll <- -0.5 * N * log(2 * pi) - N * log(s) - (t(e_1) %*% e_1) / 2 * s ^ 2 - (t(e_2) %*% e_2)
  return(-nll)
}

optim(par=c(0, 1, -2), nll, method="L-BFGS-B", upper = c(Inf, Inf, min(X)))

</code>```

Body:
I need your help. I am having problems to estimate the parameters of the following data in R using optim. I am always getting a error message of the the following type:

Warning: NaNs producedError in optim(par = c(0, 1, -2), nll, method = "L-BFGS-B", upper = c(Inf,  :
  L-BFGS-B needs finite values of 'fn'

Could you please take a look and tell what i am doing wrong? Thanks

The code I am using is the following:

X <- rlnorm3(n=1000, meanlog = 0, sdlog = 1, threshold = -2)

nll <- function(theta) {
  N <- length(X)
  m <- theta[1]
  s <- theta[2]
  a <- theta[3]
  e_1 <- log(X - a) - m
  e_2 <- log(X - a)
  nll <- -0.5 * N * log(2 * pi) - N * log(s) - (t(e_1) %*% e_1) / 2 * s ^ 2 - (t(e_2) %*% e_2)
  return(-nll)
}

optim(par=c(0, 1, -2), nll, method="L-BFGS-B", upper = c(Inf, Inf, min(X)))


问:
How to close app after 3 wrong login using sqlite tries in xamarin?
```<code>
</code>```
```<code>private void Button_Clicked_1(object sender, EventArgs e) //Login Buttom
        {
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "UserDatabase.db");
            var db = new SQLiteConnection(dbpath);
            var myQuery = db.Table<RegUserTable>().Where(u => u.UserName.Equals(EntryUserName.Text) && u.Password.Equals(EntryPassword.Text)).Any();
            if (myQuery)
            {
                App.Current.MainPage = new NavigationPage(new HomePage());
            }
            else
            {
                var result = DisplayAlert("Error", "La contraseña o el usuario son incorrectos", "OK");
                Navigation.PushAsync(new LoginPage());

            }

        }
    }
}
</code>```
```<code>
</code>```

Im using sqlite. I just want the aplication to shut down when the user fails the login 3 times

Body:
private void Button_Clicked_1(object sender, EventArgs e) //Login Buttom
        {
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "UserDatabase.db");
            var db = new SQLiteConnection(dbpath);
            var myQuery = db.Table<RegUserTable>().Where(u => u.UserName.Equals(EntryUserName.Text) && u.Password.Equals(EntryPassword.Text)).Any();
            if (myQuery)
            {
                App.Current.MainPage = new NavigationPage(new HomePage());
            }
            else
            {
                var result = DisplayAlert("Error", "La contraseña o el usuario son incorrectos", "OK");
                Navigation.PushAsync(new LoginPage());

            }

        }
    }
}

Im using sqlite. I just want the aplication to shut down when the user fails the login 3 times


问:
Trying to make a set of class objects go in a circle in Pixi JS
I want my snake to go around in a circle when [A] or [D] are pressed and go straight when they aren't.

For some reason what happens instead is that I press the keys and it switches between going up, right, both, and then neither.

Here's my relevant code, it's the part of my gameLoop function that determines the snake's movement
`

```<code>window.addEventListener('keypress', e => {
        console.log(e);
        if(e.code === "KeyD" )
        {
          angle -=1;
          if(angle >360 )
          {
            angle = angle%360;
          }
          /*if(angle <0 )
          {
            angle == 360;
          }*/
          console.log("Angle: " + angle);

        }
        if(e.code === "KeyA")
        {
          angle +=1;
          if(angle >360 )
          {
            angle = angle%360;
          }
          /*if(angle <0 )
          {
            angle == 360;
          }*/
          console.log("Angle: " + angle);

        }
      })

      //initialize speed multiplyer var
      //let v = 5;
      let v= .1;
      for (let i = 0; i < segments.length; i++)
        {
        segments[i].y += v*  Math.floor(Math.cos(angle),16); //today I learned that Javascript can't do trigonometry correctly due to rounding errors
        console.log("X:"+segments[i].x + "Angle: " + angle);
        segments[i].x -= v*   Math.floor(Math.sin(angle),16);
        console.log("Y:"+segments[i].y + "Angle: " + angle);

        }
</code>```

`

Body:
I want my snake to go around in a circle when [A] or [D] are pressed and go straight when they aren't.

For some reason what happens instead is that I press the keys and it switches between going up, right, both, and then neither.

Here's my relevant code, it's the part of my gameLoop function that determines the snake's movement
`

window.addEventListener('keypress', e => {
        console.log(e);
        if(e.code === "KeyD" )
        {
          angle -=1;
          if(angle >360 )
          {
            angle = angle%360;
          }
          /*if(angle <0 )
          {
            angle == 360;
          }*/
          console.log("Angle: " + angle);

        }
        if(e.code === "KeyA")
        {
          angle +=1;
          if(angle >360 )
          {
            angle = angle%360;
          }
          /*if(angle <0 )
          {
            angle == 360;
          }*/
          console.log("Angle: " + angle);

        }
      })

      //initialize speed multiplyer var
      //let v = 5;
      let v= .1;
      for (let i = 0; i < segments.length; i++)
        {
        segments[i].y += v*  Math.floor(Math.cos(angle),16); //today I learned that Javascript can't do trigonometry correctly due to rounding errors
        console.log("X:"+segments[i].x + "Angle: " + angle);
        segments[i].x -= v*   Math.floor(Math.sin(angle),16);
        console.log("Y:"+segments[i].y + "Angle: " + angle);

        }

`


问:
Java refuse to connect to locahost server

Starting server with npm json-server on host locahost and port 3001

Java refuses to connect to http://localhost:3000 and returns a Connection refused error

Npm json-server

```<code>json-server file.json --port=3000
</code>```
```<code>
import org.springframework.web.client.RestTemplate;

public class AuctionService {

    public static String API_BASE_URL = "http://localhost:3000/auctions/";
    private RestTemplate restTemplate = new RestTemplate();

    public Auction[] getAllAuctions() {
        // call api here
        Auction[] res = restTemplate.getForObject(API_BASE_URL, Auction[].class);

        return res;
    }
}
</code>```

Error

```<code>Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:3000/auctions/": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:748)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1075)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1009)
        at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
        at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
        at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:739)
</code>```

Here is my request when I do it via java w/
WireShark

and here is my request when I interact with it throught a web browser w/
WireShark

Reinstalling java

Disabiling firewall

Checked if port was listening and up

Able to access localhost via browser, but not in code

Can access public apis

Body:
Starting server with npm json-server on host locahost and port 3001

Java refuses to connect to http://localhost:3000 and returns a Connection refused error

Npm json-server

json-server file.json --port=3000

import org.springframework.web.client.RestTemplate;

public class AuctionService {

    public static String API_BASE_URL = "http://localhost:3000/auctions/";
    private RestTemplate restTemplate = new RestTemplate();

    public Auction[] getAllAuctions() {
        // call api here
        Auction[] res = restTemplate.getForObject(API_BASE_URL, Auction[].class);

        return res;
    }
}

Error

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:3000/auctions/": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:748)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1075)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1009)
        at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
        at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
        at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:739)

Here is my request when I do it via java w/
WireShark

and here is my request when I interact with it throught a web browser w/
WireShark

Reinstalling java

Disabiling firewall

Checked if port was listening and up

Able to access localhost via browser, but not in code

Can access public apis


问:
Android studio Kotlin error: has no zero argument constructor
I have a class named MyWebview is used to load URL, and I call it in MainActivity. But something went wrong. I don't know where is the problem, only if MyWebview has parameters(URL and the page I wanna go back) there is an error:has no zero argument constructor.
This is MyWebview.

class MyWebview(url:String, lastPage:Class<*>?) : AppCompatActivity() {
    val lastPage = lastPage
    val myURL : String = url
    val webview : WebView by lazy { findViewById(R.id.webview) }
    val closeButton : TextView by lazy { findViewById(R.id.close_webview) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)

        webViewSetup()
        closeButton.setOnClickListener{
            val intent = Intent(this, lastPage)
            startActivity(intent)
        }
    }

    private fun webViewSetup() {
        webview.webViewClient = WebViewClient()
        webview.apply {
            loadUrl(myURL)
            settings.javaScriptEnabled = true
            settings.safeBrowsingEnabled = true
            settings.allowContentAccess = true
        }
    }

    override fun onBackPressed() {
        if(webview.canGoBack()) {
            webview.goBack()
        } else {
            super.onBackPressed()
        }
    }
}
```
<p>This is MainActivity</p>
<pre class="lang-kotlin prettyprint-override"><code>iButton.setOnClickListener {
            val myWebview = MyWebview("https://www.google.com/", MainActivity::class.java)
            val intent = Intent(this, myWebview::class.java)
            startActivity(intent)
        }
</code>```

And this is error message.

```<code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.starlingmedical.pete/com.starlingmedical.pete.webview.MyWebview}: java.lang.InstantiationException: java.lang.Class<com.starlingmedical.pete.webview.MyWebview> has no zero argument constructor
</code>```

Thank you in advance.

Body:
I have a class named MyWebview is used to load URL, and I call it in MainActivity. But something went wrong. I don't know where is the problem, only if MyWebview has parameters(URL and the page I wanna go back) there is an error:has no zero argument constructor.
This is MyWebview.

class MyWebview(url:String, lastPage:Class<*>?) : AppCompatActivity() {
    val lastPage = lastPage
    val myURL : String = url
    val webview : WebView by lazy { findViewById(R.id.webview) }
    val closeButton : TextView by lazy { findViewById(R.id.close_webview) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)

        webViewSetup()
        closeButton.setOnClickListener{
            val intent = Intent(this, lastPage)
            startActivity(intent)
        }
    }

    private fun webViewSetup() {
        webview.webViewClient = WebViewClient()
        webview.apply {
            loadUrl(myURL)
            settings.javaScriptEnabled = true
            settings.safeBrowsingEnabled = true
            settings.allowContentAccess = true
        }
    }

    override fun onBackPressed() {
        if(webview.canGoBack()) {
            webview.goBack()
        } else {
            super.onBackPressed()
        }
    }
}

This is MainActivity

iButton.setOnClickListener {
            val myWebview = MyWebview("https://www.google.com/", MainActivity::class.java)
            val intent = Intent(this, myWebview::class.java)
            startActivity(intent)
        }

And this is error message.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.starlingmedical.pete/com.starlingmedical.pete.webview.MyWebview}: java.lang.InstantiationException: java.lang.Class<com.starlingmedical.pete.webview.MyWebview> has no zero argument constructor

Thank you in advance.


问:
[guitar]Setting output levels for chained effect pedals
I have a  MetalZone mt-2w  -->  Mooer Groove Loop --> Mooer Radar --> Zoom H4n

Is it better to set the individual pedal output dials to max, and reduce a
ny clipping by lowering the H4n's recording level, or lower the outputs and increase the H4n's recording level?

Is it an 'artistic' (going by how it sounds) decision, or is there an 'electrical' / acoustic  (can't think of a better term) procedure ?

Mike