问:
How to add a hamburger menu using css and javascript?
I have this javascript code I am using to add a hamburger menu in my webpage

```<code>const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", mobileMenu);

function mobileMenu() {
    hamburger.classList.toggle("active");
    Menu.classList.toggle("active");
}

menuLink.forEach(n => n.addEventListener("click", closeMenu));
function closeMenu() {
    hamburger.classList.remove("active");
    Menu.classList.remove("active");
}
</code>```

and i want to add a hamburger menu so webpage would be responsive for small devices.. no errors are occurring but still no results are being showed when i run my code.
how can i change this code in order to work

const Menu = document.getElementById('navbar__list');
const sections = document.querySelectorAll('section');
/**
 * End Global Variables
 */

// build the nav
NavBuilder = () => {
  //to loop from section 1 to 4 and add sections to navigation
  for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `${DataNav}`;
    Menu.appendChild(liElem);
  }
}
NavBuilder();

//when scroll add your-active class to section and class active to navigation bar elements
window.addEventListener('scroll', () => {
  sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
      s.classList.add('your-active-class');
      // add class active to navugation in order to highlight the navigation when scrolling
      document.querySelector(`a[href="#${s.id}"]`).classList.add("active");

      // otherwise, remove the class
    } else {
      s.classList.remove('your-active-class');
      document.querySelector(`a[href="#${s.id}"]`).classList.remove("active");

    }
  });

});

//set style to highlight active navigation bar elements
const menuLink = document.querySelectorAll(".menu__link");
addStyle = () => {
  menuLink.forEach((anchor) => {
    anchor.addEventListener("click", function() {
      menuLink.forEach((anchor) => {
        anchor.classList.remove("active");
      });
      anchor.classList.add("active");
    });
  });
}
addStyle();

scrollFunction = () => {
  const menuLink = document.querySelectorAll(".menu__link");
  menuLink.forEach((anchor) => {
    anchor.addEventListener("click", function(event) {
      event.preventDefault();
      document.querySelector(anchor.getAttribute("href")).scrollIntoView({
        behavior: "smooth",
      });
    });
  });
};
scrollFunction();

const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", mobileMenu);

function mobileMenu() {
  hamburger.classList.toggle("active");
  Menu.classList.toggle("active");
}

menuLink.forEach(n => n.addEventListener("click", closeMenu));

function closeMenu() {
  hamburger.classList.remove("active");
  Menu.classList.remove("active");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media only screen and (max-width: 768px) {
  .navbar__list {
    position: fixed;
    left: -100%;
    top: 5rem;
    flex-direction: column;
    background-color: #fff;
    width: 100%;
    border-radius: 10px;
    text-align: center;
    transition: 0.3s;
    box-shadow: 0 10px 27px rgba(0, 0, 0, 0.05);
  }
  .navbar__list.active {
    left: 0;
  }
  .hamburger {
    display: block;
    cursor: pointer;
  }
}

.navbar__menu ul {
  padding: 2px;
  padding-left: 0;
  margin: 0;
  text-align: left;
  background-color: gray;
}

.navbar__menu li {
  display: inline-block;
}

.navbar__menu .menu__link {
  display: inline-block;
  padding: 7px;
  font-weight: bold;
  text-decoration: none;
  color: #fff;
}

.navbar__menu .menu__link:hover {
  background: #333;
  color: #fff;
  transition: ease 0.3s all;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

```

答:
In the solution below I just focused on creating  elements dynamically and applying the .active class style by firing their click events. There are undefined behaviors in the solution you developed:

You tried to use the sections variable in many places even though the
 element is not defined.

The local variable s used in the for loop is not defined using the let or var keywords.

You must add  elements to
 elements and
 elements as child nodes to
 for its current style to be applicable.

The page height must be greater than 100% for the scroll event to be triggered.

To capture the click events of dynamically created elements, you need a more specialized technique than the classical method.

const Menu = document.getElementById('navbar__list');
const sections = document.querySelectorAll('section');
const menuLink = document.querySelectorAll(".menu__link");

/* The structure you are using does not allow the creation of  elements because the
 element is not defined. */
NavBuilder = (counter) => {
  for (let s = 1; s <= counter ; s++) {
    let liElement = document.createElement('li');
    let aElement = document.createElement('a');
    let textNode = document.createTextNode(s);

    aElement.className = "menu__link";
    aElement.setAttribute("href", "#");
    aElement.appendChild(textNode);
    aElement.setAttribute("id", `${s}`);
    liElement.appendChild(aElement);
    Menu.appendChild(liElement);
  }
}

/* I used jQuery to catch "click" events as the  elements are created dynamically. */
$(document).on('click', '.menu__link', function() {
  console.clear();
  console.log(this);

  $('.menu__link').removeClass("active");
  $(this).addClass("active");
});

/* The  elements are created when the page loads. */
window.addEventListener('load', function(e) {
  NavBuilder(10);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar__menu ul {
  padding: 2px;
  padding-left: 0;
  margin: 0;
  text-align: left;
  background-color: gray;
}

.active {
  color: red !important;
}

.navbar__menu li {
  display: inline-block;
}

.navbar__menu .menu__link {
  display: inline-block;
  padding: 7px;
  font-weight: bold;
  text-decoration: none;
  color: #fff;
}

.navbar__menu .menu__link:hover {
  background: #333;
  color: #fff;
  transition: ease 0.3s all;
}

@media only screen and (max-width: 768px) {
  .navbar__list {
    position: fixed;
    left: -100%;
    top: 5rem;
    flex-direction: column;
    background-color: #fff;
    width: 100%;
    border-radius: 10px;
    text-align: center;
    transition: 0.3s;
    box-shadow: 0 10px 27px rgba(0, 0, 0, 0.05);
  }
  .navbar__list.active {
    left: 0;
  }
  .hamburger {
    display: block;
    cursor: pointer;
  }
}</code>```

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

```

Body:
I have this javascript code I am using to add a hamburger menu in my webpage

const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", mobileMenu);

function mobileMenu() {
    hamburger.classList.toggle("active");
    Menu.classList.toggle("active");
}

menuLink.forEach(n => n.addEventListener("click", closeMenu));
function closeMenu() {
    hamburger.classList.remove("active");
    Menu.classList.remove("active");
}

and i want to add a hamburger menu so webpage would be responsive for small devices.. no errors are occurring but still no results are being showed when i run my code.
how can i change this code in order to work

const Menu = document.getElementById('navbar__list');
const sections = document.querySelectorAll('section');
/**
 * End Global Variables
 */

// build the nav
NavBuilder = () => {
  //to loop from section 1 to 4 and add sections to navigation
  for (s = 0; s < sections.length; s++) {
    const liElem = document.createElement('li');
    //const divElem = document.createElement("div");
    const Id = sections[s].id;
    const DataNav = sections[s].dataset.nav;
    liElem.innerHTML = `<a class="menu__link" href="#${Id}">${DataNav}</a>`;
    Menu.appendChild(liElem);
  }
}
NavBuilder();

//when scroll add your-active class to section and class active to navigation bar elements
window.addEventListener('scroll', () => {
  sections.forEach(s => {
    const topDistance = s.getBoundingClientRect().top;
    // if the distance to the top is between 0-150px
    if (topDistance >= 0 && topDistance < 150) {
      s.classList.add('your-active-class');
      // add class active to navugation in order to highlight the navigation when scrolling
      document.querySelector(`a[href="#${s.id}"]`).classList.add("active");

      // otherwise, remove the class
    } else {
      s.classList.remove('your-active-class');
      document.querySelector(`a[href="#${s.id}"]`).classList.remove("active");

    }
  });

});

//set style to highlight active navigation bar elements
const menuLink = document.querySelectorAll(".menu__link");
addStyle = () => {
  menuLink.forEach((anchor) => {
    anchor.addEventListener("click", function() {
      menuLink.forEach((anchor) => {
        anchor.classList.remove("active");
      });
      anchor.classList.add("active");
    });
  });
}
addStyle();

scrollFunction = () => {
  const menuLink = document.querySelectorAll(".menu__link");
  menuLink.forEach((anchor) => {
    anchor.addEventListener("click", function(event) {
      event.preventDefault();
      document.querySelector(anchor.getAttribute("href")).scrollIntoView({
        behavior: "smooth",
      });
    });
  });
};
scrollFunction();

const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", mobileMenu);

function mobileMenu() {
  hamburger.classList.toggle("active");
  Menu.classList.toggle("active");
}

menuLink.forEach(n => n.addEventListener("click", closeMenu));

function closeMenu() {
  hamburger.classList.remove("active");
  Menu.classList.remove("active");
}

@media only screen and (max-width: 768px) {
  .navbar__list {
    position: fixed;
    left: -100%;
    top: 5rem;
    flex-direction: column;
    background-color: #fff;
    width: 100%;
    border-radius: 10px;
    text-align: center;
    transition: 0.3s;
    box-shadow: 0 10px 27px rgba(0, 0, 0, 0.05);
  }
  .navbar__list.active {
    left: 0;
  }
  .hamburger {
    display: block;
    cursor: pointer;
  }
}

.navbar__menu ul {
  padding: 2px;
  padding-left: 0;
  margin: 0;
  text-align: left;
  background-color: gray;
}

.navbar__menu li {
  display: inline-block;
}

.navbar__menu .menu__link {
  display: inline-block;
  padding: 7px;
  font-weight: bold;
  text-decoration: none;
  color: #fff;
}

.navbar__menu .menu__link:hover {
  background: #333;
  color: #fff;
  transition: ease 0.3s all;
}

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

Body:
In the solution below I just focused on creating <a> elements dynamically and applying the .active class style by firing their click events. There are undefined behaviors in the solution you developed:

You tried to use the sections variable in many places even though the <section> element is not defined.

The local variable s used in the for loop is not defined using the let or var keywords.

You must add <a> elements to <li> elements and <li> elements as child nodes to <ul> for its current style to be applicable.

The page height must be greater than 100% for the scroll event to be triggered.

To capture the click events of dynamically created elements, you need a more specialized technique than the classical method.

const Menu = document.getElementById('navbar__list');
const sections = document.querySelectorAll('section');
const menuLink = document.querySelectorAll(".menu__link");

/* The structure you are using does not allow the creation of <a> elements because the <section> element is not defined. */
NavBuilder = (counter) => {
  for (let s = 1; s <= counter ; s++) {
    let liElement = document.createElement('li');
    let aElement = document.createElement('a');
    let textNode = document.createTextNode(s);

    aElement.className = "menu__link";
    aElement.setAttribute("href", "#");
    aElement.appendChild(textNode);
    aElement.setAttribute("id", `${s}`);
    liElement.appendChild(aElement);
    Menu.appendChild(liElement);
  }
}

/* I used jQuery to catch "click" events as the <a> elements are created dynamically. */
$(document).on('click', '.menu__link', function() {
  console.clear();
  console.log(this);

  $('.menu__link').removeClass("active");
  $(this).addClass("active");
});

/* The <a> elements are created when the page loads. */
window.addEventListener('load', function(e) {
  NavBuilder(10);
});

.navbar__menu ul {
  padding: 2px;
  padding-left: 0;
  margin: 0;
  text-align: left;
  background-color: gray;
}

.active {
  color: red !important;
}

.navbar__menu li {
  display: inline-block;
}

.navbar__menu .menu__link {
  display: inline-block;
  padding: 7px;
  font-weight: bold;
  text-decoration: none;
  color: #fff;
}

.navbar__menu .menu__link:hover {
  background: #333;
  color: #fff;
  transition: ease 0.3s all;
}

@media only screen and (max-width: 768px) {
  .navbar__list {
    position: fixed;
    left: -100%;
    top: 5rem;
    flex-direction: column;
    background-color: #fff;
    width: 100%;
    border-radius: 10px;
    text-align: center;
    transition: 0.3s;
    box-shadow: 0 10px 27px rgba(0, 0, 0, 0.05);
  }
  .navbar__list.active {
    left: 0;
  }
  .hamburger {
    display: block;
    cursor: pointer;
  }
}

<link href="https://fonts.googleapis.com/css?family=Fira+Sans:900|Merriweather&display=swap" rel="stylesheet">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<header class="page__header">
  <nav class="navbar__menu">
    <ul id="navbar__list">
    <!--
      <li><a class="menu__link" href="#">First</a></li>
      <li><a class="menu__link" href="#">Second</a></li>
      <li><a class="menu__link" href="#">Thirth</a></li>
     -->
    </ul>

    <div class="hamburger">
      <span class="bar"></span>
      <span class="bar"></span>
      <span class="bar"></span>
    </div>
  </nav>
</header>


来源: stackexchange

问:
ES6 Iterate over class methods
Given this class; how would i iterate over the methods that it includes?

```<code>class Animal {
    constructor(type){
        this.animalType = type;
    }
    getAnimalType(){
        console.log('this.animalType: ', this.animalType );
    }
}

let cat = window.cat = new Animal('cat')
</code>```

What I have tried is the following with no success:

```<code>for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}
</code>```

答:
A way to do it getting inherited methods without the Object methods and optionally the getters:

const getMethods = (obj, getters) => {
  const orig = obj
  let keys = []
  do {
    keys = keys.concat(Object.getOwnPropertyNames(obj))
    if (!getters)
      keys = keys.filter(k => !(Object.getOwnPropertyDescriptor(obj, k) || {}).get)
    obj = Object.getPrototypeOf(obj)
  } while (obj && obj.constructor && obj.constructor.name !== 'Object')
  return Array.from(new Set(keys))
    .filter(k => k !== 'constructor' && typeof orig[k] === 'function')
}
```

ContentLicense: CC BY-SA 3.0

Title: ES6 Iterate over class methods

Body:
Given this class; how would i iterate over the methods that it includes?

class Animal {
    constructor(type){
        this.animalType = type;
    }
    getAnimalType(){
        console.log('this.animalType: ', this.animalType );
    }
}

let cat = window.cat = new Animal('cat')

What I have tried is the following with no success:

for (var each in Object.getPrototypeOf(cat) ){
    console.log(each);
}

ContentLicense: CC BY-SA 4.0


问:
detected and connect scanner barcode winson model WGI-311 in windows form c#
I have barcode scanner device
I want detect and connect this device in my application (windows form c#)
but ,I don't know how will be connect

please help me

答:
You haven't to. Let me explain: your device (I think is USB) is already connected to windows, so it is working like another keyboard.
Just set the cursor to a textBox or whatever might accept entry if you are on windows Forms or use Console.ReadLine() if you use a console app.

```<code>// for a console app: example (you'll see the entry twice of course!)
class Program
{
    static void Main(string[] args)
    {
        string inputCode = Console.ReadLine();
        Console.WriteLine(inputCode);
        Console.ReadKey();
    }
}
</code>```

When you run this, just scan a barcode and it will show the scanned string (twice: one for the keyboard, the other from the variable output).

For a Windows.Forms app, I suggest your code sets the focus to an empty field as a TextBox and you use its KeyDown event to test if a string has come in. Note that your scanner should be able to perform a CR or CR-LF at the end of the scan (this was also applicable to the console app example for the Console.ReadLine() to exit).

Here's an example: put 2 text boxes (textBox1 and textBox2) in your form.

```<code>    // This will give focus and place cursor on textBox2 at form start (normally, it would be on the first textBox created)
    public Form1()
    {
        InitializeComponent();
        textBox2.Select();
        textBox2.KeyDown += TextBox2_KeyDown;
    }

    private void textBox2_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // This will copy to the textBox1 the incoming scanned barcode
            textBox1.Text = textBox2.Text;
        }
    }
</code>```

Of course, these are only examples to show the flow. Don't use 2 text containers with the same content in real life!

After your first comment:
Put a listBox in your Form and a button to trigger this:

```<code>    private void button3_Click(object sender, EventArgs e)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Keyboard");

        foreach (ManagementObject keyboard in searcher.Get())
        {
            foreach (PropertyData prop in keyboard.Properties)
            {
                if (prop.Value != null)
                {
                    listBox1.Items.Add(prop.Value);
                    // later, use: if (Convert.ToString(prop.Value).Contains("your device")) to check the presence
                }
            }
        }
    }
</code>```

Add this at the beggining:

```<code>using System.Management;
</code>```

This will show you the devices connected to your computer. By plugging/unplugging, note the reference of the scanner (or the USB dongle), and later you can test if it is connected or not.

Please comment again if you need further help.

Body:
You haven't to. Let me explain: your device (I think is USB) is already connected to windows, so it is working like another keyboard.
Just set the cursor to a textBox or whatever might accept entry if you are on windows Forms or use Console.ReadLine() if you use a console app.

// for a console app: example (you'll see the entry twice of course!)
class Program
{
    static void Main(string[] args)
    {
        string inputCode = Console.ReadLine();
        Console.WriteLine(inputCode);
        Console.ReadKey();
    }
}

When you run this, just scan a barcode and it will show the scanned string (twice: one for the keyboard, the other from the variable output).

For a Windows.Forms app, I suggest your code sets the focus to an empty field as a TextBox and you use its KeyDown event to test if a string has come in. Note that your scanner should be able to perform a CR or CR-LF at the end of the scan (this was also applicable to the console app example for the Console.ReadLine() to exit).

Here's an example: put 2 text boxes (textBox1 and textBox2) in your form.

    // This will give focus and place cursor on textBox2 at form start (normally, it would be on the first textBox created)
    public Form1()
    {
        InitializeComponent();
        textBox2.Select();
        textBox2.KeyDown += TextBox2_KeyDown;
    }

    private void textBox2_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // This will copy to the textBox1 the incoming scanned barcode
            textBox1.Text = textBox2.Text;
        }
    }

Of course, these are only examples to show the flow. Don't use 2 text containers with the same content in real life!

After your first comment:
Put a listBox in your Form and a button to trigger this:

    private void button3_Click(object sender, EventArgs e)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Keyboard");

        foreach (ManagementObject keyboard in searcher.Get())
        {
            foreach (PropertyData prop in keyboard.Properties)
            {
                if (prop.Value != null)
                {
                    listBox1.Items.Add(prop.Value);
                    // later, use: if (Convert.ToString(prop.Value).Contains("your device")) to check the presence
                }
            }
        }
    }

Add this at the beggining:

using System.Management;

This will show you the devices connected to your computer. By plugging/unplugging, note the reference of the scanner (or the USB dongle), and later you can test if it is connected or not.

Please comment again if you need further help.


问:
Create an array from input field values with Flex 4.5
I have not been able to find any documentation and searches return useless docs not involving what I want to do.

I want to take the text entered by the user, and when they click Add Record it adds the text to the array. The list box at the bottom displays each item in the array in the order it was entered.

I am just a beginner with a basic understanding of how the code is written, but I have no idea which things to use in order to take the text, make it into a string, add it to the array, and display the array in the list.

答:
The trick here is to just use the buttons click event to add an item to the ArrayCollection you use to provide the data to your list. Here's the sample I just came up with which does what I think you are asking:</p>

```<code><s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    title="HomeView">

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        [Bindable]
        private var _records:ArrayCollection = new ArrayCollection();

        protected function addRecord(event:MouseEvent):void
        {
            if(textInput.text != "") {
                _records.addItem(textInput.text);
            }
        }
    ]]>
</fx:Script>

<s:TextInput id="textInput" left="10" right="10" top="5" prompt="Enter Text" />
<s:Button top="64" label="Add Record" horizontalCenter="0" click="addRecord(event)" />
<s:List left="10" right="10" top="132" bottom="5" dataProvider="{_records}" />
</s:View>
</code>```

Body:
The trick here is to just use the buttons click event to add an item to the ArrayCollection you use to provide the data to your list. Here's the sample I just came up with which does what I think you are asking:

<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    title="HomeView">

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        [Bindable]
        private var _records:ArrayCollection = new ArrayCollection();

        protected function addRecord(event:MouseEvent):void
        {
            if(textInput.text != "") {
                _records.addItem(textInput.text);
            }
        }
    ]]>
</fx:Script>

<s:TextInput id="textInput" left="10" right="10" top="5" prompt="Enter Text" />
<s:Button top="64" label="Add Record" horizontalCenter="0" click="addRecord(event)" />
<s:List left="10" right="10" top="132" bottom="5" dataProvider="{_records}" />
</s:View>


问:
Alternative where I do not have to pass image as object
I was implementing lazy loading the following way

file.html

file.ts
image0 = '../../../../assets/images/about/example.png';

Is there a way where I can directly pass the path for lazy loading without making it an object in the "ts" file.
Ps Don't recommend loading="lazy", it does not do the work

答:
img src path start with /, this means root of static server folder

image0 = '/assets/images/about/example.png'


问:
Is there a way to get next day price?
I am new to Pine Script. I need to draw support and resistance line. The rules for resistance is as follow :

```<code>If today's closing price is greater than Previous (Day-1) closing price  AND
   today's closing price is greater than Next (Day+1) closing price AND
   today's closing price is greater than Next (Day+2) closing price AND
   today's closing price is greater than Next (Day+3) closing price   then
   Resistance is today's closing price
else
   Resistance is previous (Day-1) closing price
</code>```

I don't know how to get Day+1, Day+2, Day+3 Price in pine script.

答:
You can not forward reference in pine so you have to refactor the logical operation from the perspective of close(day + 3) being the current close.</p>
```<code>resistance = close[3] > close and close[3] > close[1] and close[3] > close[2] and close[3] > close[4] ? close[3] : close[4]
</code>```

Title: Is there a way to get next day price?

Body:
I am new to Pine Script. I need to draw support and resistance line. The rules for resistance is as follow :

If today's closing price is greater than Previous (Day-1) closing price  AND
   today's closing price is greater than Next (Day+1) closing price AND
   today's closing price is greater than Next (Day+2) closing price AND
   today's closing price is greater than Next (Day+3) closing price   then
   Resistance is today's closing price
else
   Resistance is previous (Day-1) closing price

I don't know how to get Day+1, Day+2, Day+3 Price in pine script.

Body:
You can not forward reference in pine so you have to refactor the logical operation from the perspective of close(day + 3) being the current close.

resistance = close[3] > close and close[3] > close[1] and close[3] > close[2] and close[3] > close[4] ? close[3] : close[4]


问:
r pkgdown docsearch algolia
I am having trouble understanding how to implement the docsearch snippet into my github pages (I am using bootstrap 3).

From the package documentation:

Once you have published your pkgdown website, submit the pkgdown site URL to Docsearch. DONE

Put the value of the apiKey and indexName parameters into your site _pkgdown.yml. DONE

Given my lack of knowledge, I am now having hard time understanding this.

The Docsearch\Algolia emailed me:

CSS

Copy this snippet at the end of the HTML head tag

```<code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@alpha"/>```

```
<blockquote>
<p><strong>JavaScript</strong></p>
<p>Copy this snippet at the end of the HTML <code>body</code> tag</p>
</blockquote>
```

```

QUESTION:
Shall I copy these snippets on every html page generated by pkgdown or there is an automatic way to do so?

答:
According to the documentation, the best way to include custom HTML like this is to add it to your _pkgdown.yml file under these options:

template:
  includes:
    in_header:
    after_body:
```
<p>So in your case, you should do something like this:</p>
<pre class="lang-yaml prettyprint-override"><code>template:
  include:
    in_header: |
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@alpha"/>```

    after_body: |

```

Note that this feature was added about 4 months ago, so there's a chance it won't work with Bootstrap 3 or old versions of pkgdown. If this doesn't work, the old way of doing this was to:

Add a folder called pkgdown/templates

Add in-header.html and after-body.html in that folder

Place your CSS code in in-header.html and your JavaScript in after-body.html

Rebuild the site

I hope one of these works for you.

Title: r pkgdown docsearch algolia

Body:
I am having trouble understanding how to implement the docsearch snippet into my github pages (I am using bootstrap 3).

From the package documentation:

Once you have published your pkgdown website, submit the pkgdown site URL to Docsearch. DONE

Put the value of the apiKey and indexName parameters into your site _pkgdown.yml. DONE

Given my lack of knowledge, I am now having hard time understanding this.

The Docsearch\Algolia emailed me:

CSS

Copy this snippet at the end of the HTML head tag

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@alpha"/>

JavaScript

Copy this snippet at the end of the HTML body tag

QUESTION:
Shall I copy these snippets on every html page generated by pkgdown or there is an automatic way to do so?

Body:
According to the documentation, the best way to include custom HTML like this is to add it to your _pkgdown.yml file under these options:

template:
  includes:
    in_header: <!-- inserted at the end of the head -->
    after_body: <!-- inserted at the end of the body -->

So in your case, you should do something like this:

template:
  include:
    in_header: |
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@docsearch/css@alpha"/></pre></li>
    after_body: |
      <script src="https://cdn.jsdelivr.net/npm/@docsearch/js@alpha"></script>
      <script type="text/javascript">
        docsearch({
          appId: xxxxxx,
          apiKey: xxxxxx,
          indexName: xxxxxx,
          container: '### REPLACE ME WITH A CONTAINER (e.g. div) ###'
          debug: false // Set debug to true if you want to inspect the modal
        });
      </script>

Note that this feature was added about 4 months ago, so there's a chance it won't work with Bootstrap 3 or old versions of pkgdown. If this doesn't work, the old way of doing this was to:

Add a folder called pkgdown/templates

Add in-header.html and after-body.html in that folder

Place your CSS code in in-header.html and your JavaScript in after-body.html

Rebuild the site

I hope one of these works for you.


问:
Who has access to my S3 bucket and its objects?
How can I easily and accurately evaluate access permissions via the Amazon S3 management console or from boto3, to ensure that I am the only person who has access to my bucket and all of its objects?

I am aware that access to my bucket/objects can be given either through a Bucket Policy or ACL. However, ACL access can be given per object, so it is not clear to me how to fully review who has access, even to a single object in the bucket.

答:
I think the other answer answers most of the options in a very good detail.
But usually each bucket contains either public data, non-public data or sensitive data. For any bucket which should not contain public data just disable it and the CloudFormation

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-s3-bucket.html

mentions this https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-publicaccessblockconfiguration.html for restricting public access.

Additionally the bucket supports encryption, when you allow KMS encryption you can also control access to data via the KMS key. That is something worth to consider for sensitive data.

Otherwise - yes, it is really hard to make sure there is no policy in the account which would not allow any user in your account to get access to something they should not have access to. One way how to do it may be to just control who can modify the the IAM policies (the iam:* permissions). There are also automatic tools to control policies and find vulnerabilities. For just one purpose it is not that hard to create one too.

Even if the bucket is completely private, the objects can be made public by other means - typically via CloudFront.


问:
XSD - allow element type as integer OR empty
I need to be able to set a simple element type as an integer but allow it to also be empty.  This example sends an error if its empty and a blank field is not an integer.  How can I get round this?  </p>

```<code><xsd:element name="weight" type="xsd:integer"/>
</code>```

答:
You need to set the "nillable" attribute as true:

```<code><xsd:element name="weight" type="xsd:integer" nillable="true"/>
</code>```

See the XML Schema Primer.

Body:
I need to be able to set a simple element type as an integer but allow it to also be empty.  This example sends an error if its empty and a blank field is not an integer.  How can I get round this?

<xsd:element name="weight" type="xsd:integer"/>

Body:
You need to set the "nillable" attribute as true:

<xsd:element name="weight" type="xsd:integer" nillable="true"/>

See the XML Schema Primer.


问:
Why does deploying my smart contract fail with : Failure: Tx Failed: Keyset failure (keys-any):
Despite using a unique module name (e.g. THIS was not the issue at hand), deploying my smart contract on kadena's testnet failed with the following error message:

: Failure: Tx Failed: Keyset failure (keys-any): '[my keyset name]

The only way to achieve a success was to assign a separate account that I control as the gas payer.
To elaborate for new developers:

When you hit "Deploy" in Chainweaver and fill out the form on the first page of the pop-up, you move to the SIGN tab and choose an account separate from the SENDER to pay for the gas fee.

In the following image we have two keys, red and green. Green is the sender, red is the gas payer. This is a configuration that has worked for me.

It is not clear to me, however, why this is the case or if there is a better solution.

Thank you in advance.

答: I don't think the answer above is correct. The desktop edition does indeed disable the use of unrestricted signing for a key as soon as you select it for a managed capability.


问:
Flink missing windows generated on some partitions
I am trying to write a small Flink dataflow to understand more how it works and I am facing a strange situation where each time I run it, I am getting inconsistent outputs. Sometimes some  records that I am expecting are missing. Keep in mind this is just a toy example I am building to learn the concepts of the DataStream API.

I have a dataset of around 7600 rows in CSV format like that look like this:

```<code>Date,Country,City,Specie,count,min,max,median,variance
28/06/2021,GR,Athens,no2,116,0.5,58.9,5.5,2824.39
28/06/2021,GR,Athens,wind-speed,133,0.1,11.2,3,96.69
28/06/2021,GR,Athens,dew,24,14,20,18,35.92
28/06/2021,GR,Athens,temperature,141,24.4,38.4,30.5,123.18
28/06/2021,GR,Athens,pm25,116,34,85,68,702.29
</code>```

Full dataset here: https://pastebin.com/rknnRnPc

There are no special characters or quotes, so a simple String split will work fine.

The date range for each city spans from 28/06/2021 to 03/10/2021.

I am reading it using the DataStream API:

final DataStream<String> source = env.readTextFile("data.csv");

Each row is mapped to a simple POJO as follows:

```<code>public class CityMetric {

    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    private final LocalDate localDate;
    private final String country;
    private final String city;
    private final String reading;
    private final int count;
    private final double min;
    private final double max;
    private final double median;
    private final double variance;

    private CityMetric(LocalDate localDate, String country, String city, String reading, int count, double min, double max, double median, double variance) {
        this.localDate = localDate;
        this.country = country;
        this.city = city;
        this.reading = reading;
        this.count = count;
        this.min = min;
        this.max = max;
        this.median = median;
        this.variance = variance;
    }

    public static CityMetric fromArray(String[] arr) {
        LocalDate date = LocalDate.parse(arr[0], dateFormatter);
        int count = Integer.parseInt(arr[4]);
        double min = Double.parseDouble(arr[5]);
        double max = Double.parseDouble(arr[6]);
        double median = Double.parseDouble(arr[7]);
        double variance = Double.parseDouble(arr[8]);

        return new CityMetric(date, arr[1], arr[2], arr[3], count, min, max, median, variance);
    }

    public long getTimestamp() {
        return getLocalDate()
                .atStartOfDay()
                .toInstant(ZoneOffset.UTC)
                .toEpochMilli();
    }

//getters follow
</code>```

The records are all in order of date, so I have this to set the event time and watermark:

```<code>   final WatermarkStrategy<CityMetric> cityMetricWatermarkStrategy =
            WatermarkStrategy.<CityMetric>forMonotonousTimestamps()  //we know they are sorted by time
                    .withTimestampAssigner((cityMetric, l) -> cityMetric.getTimestamp());
</code>```

I have a StreamingFileSink on a Tuple4 to output the date range, city and average:

```<code>  final StreamingFileSink<Tuple4<LocalDate, LocalDate, String, Double>> fileSink =
        StreamingFileSink.forRowFormat(
                new Path("airquality"),
                new SimpleStringEncoder<Tuple4<LocalDate, LocalDate, String, Double>>("UTF-8"))
            .build();
</code>```

And finally I have the dataflow as follows:

```<code> source
        .map(s -> s.split(",")) //split the CSV row into its fields
        .filter(arr -> !arr[0].startsWith("Date")) // if it starts with Date it means it is the top header
        .map(CityMetric::fromArray)  //create the object from the fields
        .assignTimestampsAndWatermarks(cityMetricWatermarkStrategy) // we use the date as the event time
        .filter(cm -> cm.getReading().equals("pm25")) // we want air quality of fine particulate matter pm2.5
        .keyBy(CityMetric::getCity) // partition by city name
        .window(TumblingEventTimeWindows.of(Time.days(7))) //windows of 7 days
        .aggregate(new CityAverageAggregate()) // average the values
        .name("cityair")
        .addSink(fileSink); //output each partition to a file
</code>```

The CityAverageAggregate just accumulates the sum and count, and keeps track of the earliest and latest dates of the range it is covering.

```<code>public class CityAverageAggregate
    implements AggregateFunction<
        CityMetric, CityAverageAggregate.AverageAccumulator, Tuple4<LocalDate, LocalDate, String, Double>> {

  @Override
  public AverageAccumulator createAccumulator() {
    return new AverageAccumulator();
  }

  @Override
  public AverageAccumulator add(CityMetric cityMetric, AverageAccumulator averageAccumulator) {
    return averageAccumulator.add(
        cityMetric.getCity(), cityMetric.getLocalDate(), cityMetric.getMedian());
  }

  @Override
  public Tuple4<LocalDate, LocalDate, String, Double> getResult(
      AverageAccumulator averageAccumulator) {
    return Tuple4.of(
        averageAccumulator.getStart(),
        averageAccumulator.getEnd(),
        averageAccumulator.getCity(),
        averageAccumulator.average());
  }

  @Override
  public AverageAccumulator merge(AverageAccumulator acc1, AverageAccumulator acc2) {
    return acc1.merge(acc2);
  }

  public static class AverageAccumulator {
    private final String city;
    private final LocalDate start;
    private final LocalDate end;
    private final long count;
    private final double sum;

    public AverageAccumulator() {
      city = "";
      count = 0;
      sum = 0;
      start = null;
      end = null;
    }

    AverageAccumulator(String city, LocalDate start, LocalDate end, long count, double sum) {
      this.city = city;
      this.count = count;
      this.sum = sum;
      this.start = start;
      this.end = end;
    }

    public AverageAccumulator add(String city, LocalDate eventDate, double value) {
      //make sure our dataflow is correct and we are summing data from the same city
      if (!this.city.equals("") && !this.city.equals(city)) {
        throw new IllegalArgumentException(city + " does not match " + this.city);
      }

      return new AverageAccumulator(
          city,
          earliest(this.start, eventDate),
          latest(this.end, eventDate),
          this.count + 1,
          this.sum + value);
    }

    public AverageAccumulator merge(AverageAccumulator that) {
      LocalDate mergedStart = earliest(this.start, that.start);
      LocalDate mergedEnd = latest(this.end, that.end);
      return new AverageAccumulator(
          this.city, mergedStart, mergedEnd, this.count + that.count, this.sum + that.sum);
    }

    private LocalDate earliest(LocalDate d1, LocalDate d2) {
      if (d1 == null) {
        return d2;
      } else if (d2 == null) {
        return d1;
      } else {
        return d1.isBefore(d2) ? d1 : d2;
      }
    }

    private LocalDate latest(LocalDate d1, LocalDate d2) {
      if (d1 == null) {
        return d2;
      } else if (d2 == null) {
        return d1;
      } else {
        return d1.isAfter(d2) ? d1 : d2;
      }
    }

    public double average() {
      return sum / count;
    }

    public String getCity() {
      return city;
    }

    public LocalDate getStart() {
      return start;
    }

    public LocalDate getEnd() {
      return end;
    }
  }
}
</code>```

Problem:

The problem I am facing is that sometimes I do not get all the windows I am expecting. This does not always happen, sometimes consecutive runs output a different result, so I am suspecting there is some race condition somewhere.

For example, in one of the partition file output I sometimes get:

```<code>(2021-07-12,2021-07-14,Belgrade,56.666666666666664)
(2021-07-15,2021-07-21,Belgrade,56.0)
(2021-07-22,2021-07-28,Belgrade,57.285714285714285)
(2021-07-29,2021-08-04,Belgrade,43.57142857142857)
(2021-08-05,2021-08-11,Belgrade,35.42857142857143)
(2021-08-12,2021-08-18,Belgrade,43.42857142857143)
(2021-08-19,2021-08-25,Belgrade,36.857142857142854)
(2021-08-26,2021-09-01,Belgrade,50.285714285714285)
(2021-09-02,2021-09-08,Belgrade,46.285714285714285)
(2021-09-09,2021-09-15,Belgrade,54.857142857142854)
(2021-09-16,2021-09-22,Belgrade,56.714285714285715)
(2021-09-23,2021-09-29,Belgrade,59.285714285714285)
(2021-09-30,2021-10-03,Belgrade,61.5)
</code>```

While sometimes I get the full set:

```<code>(2021-06-28,2021-06-30,Belgrade,48.666666666666664)
(2021-07-01,2021-07-07,Belgrade,41.142857142857146)
(2021-07-08,2021-07-14,Belgrade,52.857142857142854)
(2021-07-15,2021-07-21,Belgrade,56.0)
(2021-07-22,2021-07-28,Belgrade,57.285714285714285)
(2021-07-29,2021-08-04,Belgrade,43.57142857142857)
(2021-08-05,2021-08-11,Belgrade,35.42857142857143)
(2021-08-12,2021-08-18,Belgrade,43.42857142857143)
(2021-08-19,2021-08-25,Belgrade,36.857142857142854)
(2021-08-26,2021-09-01,Belgrade,50.285714285714285)
(2021-09-02,2021-09-08,Belgrade,46.285714285714285)
(2021-09-09,2021-09-15,Belgrade,54.857142857142854)
(2021-09-16,2021-09-22,Belgrade,56.714285714285715)
(2021-09-23,2021-09-29,Belgrade,59.285714285714285)
(2021-09-30,2021-10-03,Belgrade,61.5)
</code>```

Is there anything evidently wrong in my dataflow pipeline? Can't figure out why this would happen. It doesn't always happen on the same city either.

What could be happening?

UPDATE

So it seems that when I disabled Watermarks the problem didn't happen any more. I changed the WatermarkStrategy to the following:

```<code>    final WatermarkStrategy<CityMetric> cityMetricWatermarkStrategy =
            WatermarkStrategy.<CityMetric>noWatermarks()
                             .withTimestampAssigner((cityMetric, l) -> cityMetric.getTimestamp());
</code>```

And so far I have been getting consistent results. When I checked the documentation it says that:

static  WatermarkStrategy noWatermarks()

Creates a watermark strategy that generates no watermarks at all. This may be useful in scenarios that do pure processing-time based stream processing.

But I am not doing processing-time based stream processing, I am doing event-time processing.

Why would forMonotonousTimestamps() have the strange behaviour I was seeing? Indeed my timestamps are monotonically increasing (the noWatermarks strategy wouldn't work if they weren't), but somehow changing this does not work well with my scenario.

Is there anything I am missing with the way things work in Flink?

答:
Flink doesn't support per-key watermarking. Each parallel task generates watermarks independently, based on observing all of the events flowing through that task.

So the reason this isn't working with the forMonotonousTimestamps watermark strategy is that the input is not actually in order by timestamp. It is temporally sorted within each city, but not globally. This is then going to result in some records being late, but unpredictably so, depending on exactly when watermarks are generated. These late events are being ignored by the windows that should contain them.

You can address this in a number of ways:

(1) Use a forBoundedOutOfOrderness watermark strategy with a duration sufficient to account for the actual out-of-order-ness in the dataset. Given that the data looks something like this:

```<code>03/10/2021,GR,Athens,pressure,60,1017.9,1040.6,1020.9,542.4
28/06/2021,US,Atlanta,co,24,1.4,7.3,2.2,19.05
</code>```

that will require an out-of-order-ness duration of approximately 100 days.

(2) Configure the windows to have sufficient allowed lateness. This will result in some of the windows being triggered multiple times -- once when the watermark indicates they can close, and again each time a late event is added to the window.

(3) Use the noWatermarks strategy. This will lead to the job only producing results if and when it reaches the end of its input file(s). For a continuous streaming job this wouldn't be workable, but for finite (bounded) inputs this can work.

(4) Run the job in RuntimeExecutionMode.BATCH mode. Then the job will only produce results at the end, after having consumed all of its input. This will run the job with a more optimized runtime designed for batch workloads, but the outcome should be the same as with (3).

(5) Change the input so it isn't out-of-order.

Body:
I am trying to write a small Flink dataflow to understand more how it works and I am facing a strange situation where each time I run it, I am getting inconsistent outputs. Sometimes some  records that I am expecting are missing. Keep in mind this is just a toy example I am building to learn the concepts of the DataStream API.

I have a dataset of around 7600 rows in CSV format like that look like this:

Date,Country,City,Specie,count,min,max,median,variance
28/06/2021,GR,Athens,no2,116,0.5,58.9,5.5,2824.39
28/06/2021,GR,Athens,wind-speed,133,0.1,11.2,3,96.69
28/06/2021,GR,Athens,dew,24,14,20,18,35.92
28/06/2021,GR,Athens,temperature,141,24.4,38.4,30.5,123.18
28/06/2021,GR,Athens,pm25,116,34,85,68,702.29

Full dataset here: https://pastebin.com/rknnRnPc

There are no special characters or quotes, so a simple String split will work fine.

The date range for each city spans from 28/06/2021 to 03/10/2021.

I am reading it using the DataStream API:

final DataStream<String> source = env.readTextFile("data.csv");

Each row is mapped to a simple POJO as follows:

public class CityMetric {

    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

    private final LocalDate localDate;
    private final String country;
    private final String city;
    private final String reading;
    private final int count;
    private final double min;
    private final double max;
    private final double median;
    private final double variance;

    private CityMetric(LocalDate localDate, String country, String city, String reading, int count, double min, double max, double median, double variance) {
        this.localDate = localDate;
        this.country = country;
        this.city = city;
        this.reading = reading;
        this.count = count;
        this.min = min;
        this.max = max;
        this.median = median;
        this.variance = variance;
    }

    public static CityMetric fromArray(String[] arr) {
        LocalDate date = LocalDate.parse(arr[0], dateFormatter);
        int count = Integer.parseInt(arr[4]);
        double min = Double.parseDouble(arr[5]);
        double max = Double.parseDouble(arr[6]);
        double median = Double.parseDouble(arr[7]);
        double variance = Double.parseDouble(arr[8]);

        return new CityMetric(date, arr[1], arr[2], arr[3], count, min, max, median, variance);
    }

    public long getTimestamp() {
        return getLocalDate()
                .atStartOfDay()
                .toInstant(ZoneOffset.UTC)
                .toEpochMilli();
    }

//getters follow

The records are all in order of date, so I have this to set the event time and watermark:

   final WatermarkStrategy<CityMetric> cityMetricWatermarkStrategy =
            WatermarkStrategy.<CityMetric>forMonotonousTimestamps()  //we know they are sorted by time
                    .withTimestampAssigner((cityMetric, l) -> cityMetric.getTimestamp());

I have a StreamingFileSink on a Tuple4 to output the date range, city and average:

  final StreamingFileSink<Tuple4<LocalDate, LocalDate, String, Double>> fileSink =
        StreamingFileSink.forRowFormat(
                new Path("airquality"),
                new SimpleStringEncoder<Tuple4<LocalDate, LocalDate, String, Double>>("UTF-8"))
            .build();

And finally I have the dataflow as follows:

 source
        .map(s -> s.split(",")) //split the CSV row into its fields
        .filter(arr -> !arr[0].startsWith("Date")) // if it starts with Date it means it is the top header
        .map(CityMetric::fromArray)  //create the object from the fields
        .assignTimestampsAndWatermarks(cityMetricWatermarkStrategy) // we use the date as the event time
        .filter(cm -> cm.getReading().equals("pm25")) // we want air quality of fine particulate matter pm2.5
        .keyBy(CityMetric::getCity) // partition by city name
        .window(TumblingEventTimeWindows.of(Time.days(7))) //windows of 7 days
        .aggregate(new CityAverageAggregate()) // average the values
        .name("cityair")
        .addSink(fileSink); //output each partition to a file

The CityAverageAggregate just accumulates the sum and count, and keeps track of the earliest and latest dates of the range it is covering.

public class CityAverageAggregate
    implements AggregateFunction<
        CityMetric, CityAverageAggregate.AverageAccumulator, Tuple4<LocalDate, LocalDate, String, Double>> {

  @Override
  public AverageAccumulator createAccumulator() {
    return new AverageAccumulator();
  }

  @Override
  public AverageAccumulator add(CityMetric cityMetric, AverageAccumulator averageAccumulator) {
    return averageAccumulator.add(
        cityMetric.getCity(), cityMetric.getLocalDate(), cityMetric.getMedian());
  }

  @Override
  public Tuple4<LocalDate, LocalDate, String, Double> getResult(
      AverageAccumulator averageAccumulator) {
    return Tuple4.of(
        averageAccumulator.getStart(),
        averageAccumulator.getEnd(),
        averageAccumulator.getCity(),
        averageAccumulator.average());
  }

  @Override
  public AverageAccumulator merge(AverageAccumulator acc1, AverageAccumulator acc2) {
    return acc1.merge(acc2);
  }

  public static class AverageAccumulator {
    private final String city;
    private final LocalDate start;
    private final LocalDate end;
    private final long count;
    private final double sum;

    public AverageAccumulator() {
      city = "";
      count = 0;
      sum = 0;
      start = null;
      end = null;
    }

    AverageAccumulator(String city, LocalDate start, LocalDate end, long count, double sum) {
      this.city = city;
      this.count = count;
      this.sum = sum;
      this.start = start;
      this.end = end;
    }

    public AverageAccumulator add(String city, LocalDate eventDate, double value) {
      //make sure our dataflow is correct and we are summing data from the same city
      if (!this.city.equals("") && !this.city.equals(city)) {
        throw new IllegalArgumentException(city + " does not match " + this.city);
      }

      return new AverageAccumulator(
          city,
          earliest(this.start, eventDate),
          latest(this.end, eventDate),
          this.count + 1,
          this.sum + value);
    }

    public AverageAccumulator merge(AverageAccumulator that) {
      LocalDate mergedStart = earliest(this.start, that.start);
      LocalDate mergedEnd = latest(this.end, that.end);
      return new AverageAccumulator(
          this.city, mergedStart, mergedEnd, this.count + that.count, this.sum + that.sum);
    }

    private LocalDate earliest(LocalDate d1, LocalDate d2) {
      if (d1 == null) {
        return d2;
      } else if (d2 == null) {
        return d1;
      } else {
        return d1.isBefore(d2) ? d1 : d2;
      }
    }

    private LocalDate latest(LocalDate d1, LocalDate d2) {
      if (d1 == null) {
        return d2;
      } else if (d2 == null) {
        return d1;
      } else {
        return d1.isAfter(d2) ? d1 : d2;
      }
    }

    public double average() {
      return sum / count;
    }

    public String getCity() {
      return city;
    }

    public LocalDate getStart() {
      return start;
    }

    public LocalDate getEnd() {
      return end;
    }
  }
}

Problem:

The problem I am facing is that sometimes I do not get all the windows I am expecting. This does not always happen, sometimes consecutive runs output a different result, so I am suspecting there is some race condition somewhere.

For example, in one of the partition file output I sometimes get:

(2021-07-12,2021-07-14,Belgrade,56.666666666666664)
(2021-07-15,2021-07-21,Belgrade,56.0)
(2021-07-22,2021-07-28,Belgrade,57.285714285714285)
(2021-07-29,2021-08-04,Belgrade,43.57142857142857)
(2021-08-05,2021-08-11,Belgrade,35.42857142857143)
(2021-08-12,2021-08-18,Belgrade,43.42857142857143)
(2021-08-19,2021-08-25,Belgrade,36.857142857142854)
(2021-08-26,2021-09-01,Belgrade,50.285714285714285)
(2021-09-02,2021-09-08,Belgrade,46.285714285714285)
(2021-09-09,2021-09-15,Belgrade,54.857142857142854)
(2021-09-16,2021-09-22,Belgrade,56.714285714285715)
(2021-09-23,2021-09-29,Belgrade,59.285714285714285)
(2021-09-30,2021-10-03,Belgrade,61.5)

While sometimes I get the full set:

(2021-06-28,2021-06-30,Belgrade,48.666666666666664)
(2021-07-01,2021-07-07,Belgrade,41.142857142857146)
(2021-07-08,2021-07-14,Belgrade,52.857142857142854)
(2021-07-15,2021-07-21,Belgrade,56.0)
(2021-07-22,2021-07-28,Belgrade,57.285714285714285)
(2021-07-29,2021-08-04,Belgrade,43.57142857142857)
(2021-08-05,2021-08-11,Belgrade,35.42857142857143)
(2021-08-12,2021-08-18,Belgrade,43.42857142857143)
(2021-08-19,2021-08-25,Belgrade,36.857142857142854)
(2021-08-26,2021-09-01,Belgrade,50.285714285714285)
(2021-09-02,2021-09-08,Belgrade,46.285714285714285)
(2021-09-09,2021-09-15,Belgrade,54.857142857142854)
(2021-09-16,2021-09-22,Belgrade,56.714285714285715)
(2021-09-23,2021-09-29,Belgrade,59.285714285714285)
(2021-09-30,2021-10-03,Belgrade,61.5)

Is there anything evidently wrong in my dataflow pipeline? Can't figure out why this would happen. It doesn't always happen on the same city either.

What could be happening?

UPDATE

So it seems that when I disabled Watermarks the problem didn't happen any more. I changed the WatermarkStrategy to the following:

    final WatermarkStrategy<CityMetric> cityMetricWatermarkStrategy =
            WatermarkStrategy.<CityMetric>noWatermarks()
                             .withTimestampAssigner((cityMetric, l) -> cityMetric.getTimestamp());

And so far I have been getting consistent results. When I checked the documentation it says that:

static  WatermarkStrategy noWatermarks()

Creates a watermark strategy that generates no watermarks at all. This may be useful in scenarios that do pure processing-time based stream processing.

But I am not doing processing-time based stream processing, I am doing event-time processing.

Why would forMonotonousTimestamps() have the strange behaviour I was seeing? Indeed my timestamps are monotonically increasing (the noWatermarks strategy wouldn't work if they weren't), but somehow changing this does not work well with my scenario.

Is there anything I am missing with the way things work in Flink?

Body:
Flink doesn't support per-key watermarking. Each parallel task generates watermarks independently, based on observing all of the events flowing through that task.

So the reason this isn't working with the forMonotonousTimestamps watermark strategy is that the input is not actually in order by timestamp. It is temporally sorted within each city, but not globally. This is then going to result in some records being late, but unpredictably so, depending on exactly when watermarks are generated. These late events are being ignored by the windows that should contain them.

You can address this in a number of ways:

(1) Use a forBoundedOutOfOrderness watermark strategy with a duration sufficient to account for the actual out-of-order-ness in the dataset. Given that the data looks something like this:

03/10/2021,GR,Athens,pressure,60,1017.9,1040.6,1020.9,542.4
28/06/2021,US,Atlanta,co,24,1.4,7.3,2.2,19.05

that will require an out-of-order-ness duration of approximately 100 days.

(2) Configure the windows to have sufficient allowed lateness. This will result in some of the windows being triggered multiple times -- once when the watermark indicates they can close, and again each time a late event is added to the window.

(3) Use the noWatermarks strategy. This will lead to the job only producing results if and when it reaches the end of its input file(s). For a continuous streaming job this wouldn't be workable, but for finite (bounded) inputs this can work.

(4) Run the job in RuntimeExecutionMode.BATCH mode. Then the job will only produce results at the end, after having consumed all of its input. This will run the job with a more optimized runtime designed for batch workloads, but the outcome should be the same as with (3).

(5) Change the input so it isn't out-of-order.


问:
How can I convert a midi file to wav in python?
I'm using this in Colab:

```<code>   !sudo apt install -y fluidsynth
   import fluidsynth
   pip install midi2audio
   from midi2audio import FluidSynth
   fs = FluidSynth()
   fs.midi_to_audio('/content/MIDI-Unprocessed_SMF_02_R1_2004_01-05_ORIG_MID--AUDIO_02_R1_2004_05_Track05_wav.midi', 'output.wav')
</code>```

But when the procedure ends, the file does not contain any signal. If I analyze the file with librosa and pyplot I get this:
enter image description here

Thank you in advance

答:
When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '.' and replace the last entry by the new extension you want. You can do this using the os.rename method. </p>
```<code>import os
my_file = 'my_file.mif'
base=os.path.splitext(my_file)[0]
os.rename(my_file, base + '.wav')
</code>```

Body:
I'm using this in Colab:

   !sudo apt install -y fluidsynth
   import fluidsynth
   pip install midi2audio
   from midi2audio import FluidSynth
   fs = FluidSynth()
   fs.midi_to_audio('/content/MIDI-Unprocessed_SMF_02_R1_2004_01-05_ORIG_MID--AUDIO_02_R1_2004_05_Track05_wav.midi', 'output.wav')

But when the procedure ends, the file does not contain any signal. If I analyze the file with librosa and pyplot I get this:
enter image description here

Thank you in advance

Body:
When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '.' and replace the last entry by the new extension you want. You can do this using the os.rename method.

import os
my_file = 'my_file.mif'
base=os.path.splitext(my_file)[0]
os.rename(my_file, base + '.wav')


问:
security group aws specific ip http/https blocks everything
I've follow the documentation of I've read https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html

and I want to create a security group in AWS which allows only one IP access to ports 80 or 443, but AWS is blocking everything even the IP which should have access when I apply this group.

We are using nginx in the ec2 server and the certificate was created with certbot

答:
Edit the inbound rule to be only lock out any other port to the instance ip address only, while you open 443 and 80 to everyone.
eg. if ur ec2 instance public ip is 13.255.77.8 and you don't want port 5000 to be accessible to the public, create a custom tcp with your that is only acessible to that port ie mapping port 5000 to this ip - 13.255.77.8/32</p>


问:
No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() in Flutter and Firebase
I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login, or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem?

This is an excerpt of my code

```<code>class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Center(
        child: Container(
          child: RaisedButton(
            onPressed: () {
              FirebaseAuth.instance.signOut().then((value) {
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            LoginScreen()));
              });
            },
            child: Text("Logout"),
          )
        )
      )
    );
  }
}
</code>```

Below is the thrown exception

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

When the exception was thrown, this was the stack:

#0      MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1      Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2      FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3      _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24     _invoke1 (dart:ui/hooks.dart:267:10)
#25     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
```

答:
On my case, I added web support to my existing project.
The one thing which solved the issue is,

In the web/index.html file

Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0

Snippet

```<code><script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
 <script>
  var firebaseConfig = {
   ....
   }
</code>```

Body:
I am building a Flutter application and I have integrated Firebase, but I keep getting this error when I click on a button either to register, login, or logout. I have seen other people have asked the same question, but none seems to work for me. I am using Flutter and Android Studio. How can I fix this problem?

This is an excerpt of my code

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Center(
        child: Container(
          child: RaisedButton(
            onPressed: () {
              FirebaseAuth.instance.signOut().then((value) {
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) =>
                            LoginScreen()));
              });
            },
            child: Text("Logout"),
          )
        )
      )
    );
  }
}

Below is the thrown exception

══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

When the exception was thrown, this was the stack:

#0      MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1      Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2      FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3      _HomeScreenState.build.<anonymous closure> (package:cosytok/screens/home.dart:20:28)
#4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
#5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
#6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#7      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#8      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
#9      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:219:7)
#10     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:477:9)
#11     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:78:12)
#12     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:124:9)
#13     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
#14     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:122:18)
#15     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:108:7)
#16     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:220:19)
#17     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
#18     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
#19     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
#20     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
#24     _invoke1 (dart:ui/hooks.dart:267:10)
#25     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
(elided 3 frames from dart:async)

Handler: "onTap"
Recognizer:
  TapGestureRecognizer#f0104
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by gesture ═══════════════════════════════════════════════════════════════
The following FirebaseException was thrown while handling a gesture:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

Body:
On my case, I added web support to my existing project.
The one thing which solved the issue is,

In the web/index.html file

Changing the verison of all the firebase sdk imports from 9.6.6 to 8.10.0

Snippet

<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app-check.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"></script>
 <script>
  var firebaseConfig = {
   ....
   }


问:
Cannot get Android Market Licensing (LVL) working reliably. Almost always returns RETRY
I am trying to get android licensing to work in my first Android application.

I have followed the online guides and have integrated the LVL Code using the ServerManagedPolicy.

Regardless of what license test response I set in the developer console I almost always (9 times out of 10) get a LicenseResponse.RETRY. Because DEFAULT_MAX_RETRIES = "0" this is always converted into NOT_LICENSED

I've tried:

turning WiFi On / Off

running paid apps I bought (they all work!)

unplugging the usb

running in a vm and my real phone

I always get the same result. On the few occasions that I've had a licensed response it has not had any of the extras attached to increase the max retries. I think this is the crux of the problem - the first time I try and license I have no retry or validity period toleration in the default settings.

How can I get this working reliably?

Edit 1

Found this in the logs. Does this imply there is a problem connecting to the android market app?

```<code>08-18 21:12:16.071: INFO/LICENSE(10852): checkLicense
08-18 21:12:17.271: INFO/LicenseChecker(10852): Binding to licensing service.
08-18 21:12:17.281: WARN/ActivityManager(80): Unable to start service Intent { act=licensing.ILicensingService }: not found
08-18 21:12:17.281: ERROR/LicenseChecker(10852): Could not bind to service.
08-18 21:12:17.301: INFO/LICENSE(10852): dontAllow
</code>```

答:
There are two things that might help you:

Assuming you are using the Developer Console to simulate a response, it sometimes takes more than a few minutes to refresh the response you got from previous tries. So if you simulated a FAILED response, you probably need to wait for a while before you can receive a SUCCESS response. Sometimes even rebooting your device will not help so you just have to wait.

The LVL mechanism has some issues and even on users' devices you might get a FAILED response when there is no internet connection for a while on the device, or some other network error. What I recommend is to have several retries on top of the LVL built-in retries as I found it can't be trusted and prone to errors. It would probably reduce the number of false-negative reports you'll get from your users...

Body:
I am trying to get android licensing to work in my first Android application.

I have followed the online guides and have integrated the LVL Code using the ServerManagedPolicy.

Regardless of what license test response I set in the developer console I almost always (9 times out of 10) get a LicenseResponse.RETRY. Because DEFAULT_MAX_RETRIES = "0" this is always converted into NOT_LICENSED

I've tried:

turning WiFi On / Off

running paid apps I bought (they all work!)

unplugging the usb

running in a vm and my real phone

I always get the same result. On the few occasions that I've had a licensed response it has not had any of the extras attached to increase the max retries. I think this is the crux of the problem - the first time I try and license I have no retry or validity period toleration in the default settings.

How can I get this working reliably?

Edit 1

Found this in the logs. Does this imply there is a problem connecting to the android market app?

08-18 21:12:16.071: INFO/LICENSE(10852): checkLicense
08-18 21:12:17.271: INFO/LicenseChecker(10852): Binding to licensing service.
08-18 21:12:17.281: WARN/ActivityManager(80): Unable to start service Intent { act=licensing.ILicensingService }: not found
08-18 21:12:17.281: ERROR/LicenseChecker(10852): Could not bind to service.
08-18 21:12:17.301: INFO/LICENSE(10852): dontAllow


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 96 Current browser version is 98.0
Error tracelogs:

```<code>DevTools listening on ws://127.0.0.1:54791/devtools/browser/6f264bcc-d44a-40d9-b6cf-
8b1655c97ccd
Traceback (most recent call last):
File "c:\Users\alsgn\OneDrive\desktop\mypython\getselenium\dc\findbulletins.py", line 11, in
<module>
browser = webdriver.Chrome()
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__
RemoteWebDriver.__init__(
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This
version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path C:\Program
Files\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
    Ordinal0 [0x00FF6903+2517251]
    Ordinal0 [0x00F8F8E1+2095329]
    Ordinal0 [0x00E92848+1058888]
    Ordinal0 [0x00EB0B9D+1182621]
    Ordinal0 [0x00EACA60+1165920]
    Ordinal0 [0x00EAA2CF+1155791]
    Ordinal0 [0x00EDAAAF+1354415]
    Ordinal0 [0x00EDA71A+1353498]
    Ordinal0 [0x00ED639B+1336219]
    Ordinal0 [0x00EB27A7+1189799]
    Ordinal0 [0x00EB3609+1193481]
    GetHandleVerifier [0x01185904+1577972]
    GetHandleVerifier [0x01230B97+2279047]
    GetHandleVerifier [0x01086D09+534521]
    GetHandleVerifier [0x01085DB9+530601]
    Ordinal0 [0x00F94FF9+2117625]
    Ordinal0 [0x00F998A8+2136232]
    Ordinal0 [0x00F999E2+2136546]
    Ordinal0 [0x00FA3541+2176321]
    BaseThreadInitThunk [0x755AFA29+25]
    RtlGetAppContainerNamedObjectPath [0x775C7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x775C7A6E+238]
</code>```

The code that I ran was okay in 2 days ago, but now, the code have been showed this error.
Please say how to solve this problem. I wonder why it ran well before.

答:
I also get this error message cause I forgot to turn of chrome updates. I used chromedriver 98.0.4758.80 but now my chrome is 98.0.4758.82. So you'll receive this or a samebased message even if you update to the latest chromedriver 98.0.4758.80 which I use.

For me there are two solutions and first of all turn chrome update services off.

wait for new chromedriver update supporting 98.0.4758.82

downgrade chrome to version 98.0.4758.80 - I am still struggling performing the downgrade.

Maybe somebody can explain how to downgrade chrome to an earlier version. Otherwise we need to wait for the update of the chromedriver.

Body:
Error tracelogs:

DevTools listening on ws://127.0.0.1:54791/devtools/browser/6f264bcc-d44a-40d9-b6cf-
8b1655c97ccd
Traceback (most recent call last):
File "c:\Users\alsgn\OneDrive\desktop\mypython\getselenium\dc\findbulletins.py", line 11, in
<module>
browser = webdriver.Chrome()
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__
RemoteWebDriver.__init__(
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This
version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path C:\Program
Files\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
    Ordinal0 [0x00FF6903+2517251]
    Ordinal0 [0x00F8F8E1+2095329]
    Ordinal0 [0x00E92848+1058888]
    Ordinal0 [0x00EB0B9D+1182621]
    Ordinal0 [0x00EACA60+1165920]
    Ordinal0 [0x00EAA2CF+1155791]
    Ordinal0 [0x00EDAAAF+1354415]
    Ordinal0 [0x00EDA71A+1353498]
    Ordinal0 [0x00ED639B+1336219]
    Ordinal0 [0x00EB27A7+1189799]
    Ordinal0 [0x00EB3609+1193481]
    GetHandleVerifier [0x01185904+1577972]
    GetHandleVerifier [0x01230B97+2279047]
    GetHandleVerifier [0x01086D09+534521]
    GetHandleVerifier [0x01085DB9+530601]
    Ordinal0 [0x00F94FF9+2117625]
    Ordinal0 [0x00F998A8+2136232]
    Ordinal0 [0x00F999E2+2136546]
    Ordinal0 [0x00FA3541+2176321]
    BaseThreadInitThunk [0x755AFA29+25]
    RtlGetAppContainerNamedObjectPath [0x775C7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x775C7A6E+238]

The code that I ran was okay in 2 days ago, but now, the code have been showed this error.
Please say how to solve this problem. I wonder why it ran well before.


问:
Sequelize Bad Field Error on Eager loading after changing association
```<code>// Include Sequelize module.
const Sequelize = require('sequelize')

// Import sequelize object,
// Database connection pool managed by Sequelize.
const sequelize = require('./database.js')

const User = require('./User.js');
const Product = require('./Product.js');

// Define method takes two arrguments
// 1st - name of table
// 2nd - columns inside the table
const FavoriteProduct = sequelize.define('favorite_product', {

    favorite_id:{

        // Sequelize module has INTEGER Data_Type.
        type:Sequelize.INTEGER,

        autoIncrement:true,

        allowNull:false,

        primaryKey:true
    },

    createdAt: Sequelize.DATE,

    //no dates

}, {
    updatedAt: false
});

User.hasMany(FavoriteProduct, { foreignKey: 'user_id'} );
Product.hasMany(FavoriteProduct, { foreignKey: 'product_id'} );

FavoriteProduct.belongsTo(Product, { foreignKey: 'product_id'});
FavoriteProduct.belongsTo(User, { foriegnKey: 'user_id'})

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

Previously I had this model as a BelongsToMany model, with both Product and User->belongToMany through FavoriteProduct. I changed it because the eager loading of FavoriteProduct was not working when trying to load from products. I now have a new issue, attempting to eager load the new table throws this error:

```<code>    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlState": "42S22",
    "sqlMessage": "Unknown column 'favorite_product.userUserId' in 'field list'",
</code>```

I don't know why this occurred, but it must be because I attempted to switch from a belongsToMany association without doing any migrations. There are no extra columns in the database or anything like that.

Does anyone know how to fix this field issue without deleting the table?

For reference, I am simply doing this:

```<code>await Product.findOne({
        include: [{
            model: FavoriteProduct,
            required: false,
        }]
</code>```

答:
You need to correct the association FavoriteProduct.belongsTo(User: you misspelt the option foreignKey by indicating foriegnKey.

FavoriteProduct.belongsTo(User, { foreignKey: 'user_id'})
```

Body:
// Include Sequelize module.
const Sequelize = require('sequelize')

// Import sequelize object,
// Database connection pool managed by Sequelize.
const sequelize = require('./database.js')

const User = require('./User.js');
const Product = require('./Product.js');

// Define method takes two arrguments
// 1st - name of table
// 2nd - columns inside the table
const FavoriteProduct = sequelize.define('favorite_product', {

    favorite_id:{

        // Sequelize module has INTEGER Data_Type.
        type:Sequelize.INTEGER,

        autoIncrement:true,

        allowNull:false,

        primaryKey:true
    },

    createdAt: Sequelize.DATE,

    //no dates

}, {
    updatedAt: false
});

User.hasMany(FavoriteProduct, { foreignKey: 'user_id'} );
Product.hasMany(FavoriteProduct, { foreignKey: 'product_id'} );

FavoriteProduct.belongsTo(Product, { foreignKey: 'product_id'});
FavoriteProduct.belongsTo(User, { foriegnKey: 'user_id'})

module.exports = FavoriteProduct

Previously I had this model as a BelongsToMany model, with both Product and User->belongToMany through FavoriteProduct. I changed it because the eager loading of FavoriteProduct was not working when trying to load from products. I now have a new issue, attempting to eager load the new table throws this error:

    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlState": "42S22",
    "sqlMessage": "Unknown column 'favorite_product.userUserId' in 'field list'",

I don't know why this occurred, but it must be because I attempted to switch from a belongsToMany association without doing any migrations. There are no extra columns in the database or anything like that.

Does anyone know how to fix this field issue without deleting the table?

For reference, I am simply doing this:

await Product.findOne({
        include: [{
            model: FavoriteProduct,
            required: false,
        }]


问:
How to update with function in laravel query builder
I'm doing a query and want to update the data, but I want to do a math operation first. How to simplify it?

my code below:

```<code>$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update([
'sisa' => $total,
]);

</code>```

答:
you don't need to do another query for updating, simply:

```<code>$Rpodetail->update(['sisa' => $total]);
</code>```

you can also use this answer for direct access to column values.

Body:
I'm doing a query and want to update the data, but I want to do a math operation first. How to simplify it?

my code below:

$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update([
'sisa' => $total,
]);

Body:
you don't need to do another query for updating, simply:

$Rpodetail->update(['sisa' => $total]);

you can also use this answer for direct access to column values.


问:
What happened to net.minecraft.class_746?
I am working on a fabric mod with java that requires commands such as ".command" and to do so requires my program accesses sent messages. After looking at some code by other people that have done what I am trying to do, I notice that they all use net.minecraft.class_746 as a mixin. I have been trying to as well on Minecraft 1.18.1 but after going through the net.minecraft directory, I found that there is only class_6567 and class_6148 as well as many other packages. I have been digging through the other files but I have not found anything to achieve what I want. I am not able to find anything to access all sent messages. Any help would be appreciated. Thanks!</p>

答:
After about an hour of digging, I found the ClientPlayerEntity class. It seems to work just like class_746 and I was able to get my desired result. If anyone needs it, here is a basic portion of code:</p>
```<code>@Mixin( ClientPlayerEntity.class )
public class ChatMixin {

    @Inject(method={"sendChatMessage"}, at={@At("HEAD")}, cancellable=true)
    public void sendChatMessage(final String message, final CallbackInfo ci) {
        if(message.equalsIgnoreCase(".command")) {
            ci.cancel();
        }
    }
}
</code>```

Body:
After about an hour of digging, I found the ClientPlayerEntity class. It seems to work just like class_746 and I was able to get my desired result. If anyone needs it, here is a basic portion of code:

@Mixin( ClientPlayerEntity.class )
public class ChatMixin {

    @Inject(method={"sendChatMessage"}, at={@At("HEAD")}, cancellable=true)
    public void sendChatMessage(final String message, final CallbackInfo ci) {
        if(message.equalsIgnoreCase(".command")) {
            ci.cancel();
        }
    }
}


问:
Silverlight Business Application - File Size
Looking at the silverlight business application, it seems to add a number of libraries specific to Input Forms and the like.

Am I right in saying that creating Complex classes results in these forms being generated automatically?

Looking at the file size of the basic Silverlight business application XAP file, it's around 412Kb. Is there a way to reduce that size?

Regards,
Jacques

答:
You can re-zip the XAP file, but that is only a 20% saving generally at best.

Using the PRISM pattern and a modular approach, we managed to get our initial page load down to around 150Kb (the entire app is over 4Mb). The rest of the modules continue to stream down in the background so we get something on-screen very fast.

If you intend to build a large application, PRISM and/or MEF is the way to go. It has an additional learning curve but it results in very modular apps (great for team development/maintenance).


问:
Can you create a generic Tkinter app that takes a .txt file of widget specifications?
I have just began coding with tkinter in Python and was wondering if there was a way to create a generic Tkinter driver with a root and mainloop that can read in a text file or maybe even a JSON or something that can populate the window with widgets based on said file.

For example, a text file with a structure like:

```<code>Frame: row=0; column=0, padx=2, pady=2;
Label: row=0, column=0, padx=2, pady=2, text=Some Text;
Combobox: row=1, column=0, padx=2, pady=2, values=('val1', 'val2'), variable=my_var;
Button: row=2, column=0, padx=2, pady=2, command=my_func(): print(my_var.get())
</code>```

答:
Other toolkits like Qt and GTK3 have this built-in, but not tkinter. It is something that came into fashion long after tk was created, when GUI-builders became a thing.

Would it be possible to write something like this? Yes.

Personally, I would not think this so convenient. Because the file containing the description of the layout would have to be distributed with the application and put in a place where the application can find it. That is tricky to implement in a way that works on multiple platforms. Look at the sysconfig module; there are several places where you could store things depending on the platform. Some of those would require elevated permissions to install files there.

In fact, for one of my small GTK3 programs (gtk-razer), I even compressed the .glade file and ran it through base85encode so I could include it in my script. Basically this was done to avoid that problem!

Body:
I have just began coding with tkinter in Python and was wondering if there was a way to create a generic Tkinter driver with a root and mainloop that can read in a text file or maybe even a JSON or something that can populate the window with widgets based on said file.

For example, a text file with a structure like:

Frame: row=0; column=0, padx=2, pady=2;
Label: row=0, column=0, padx=2, pady=2, text=Some Text;
Combobox: row=1, column=0, padx=2, pady=2, values=('val1', 'val2'), variable=my_var;
Button: row=2, column=0, padx=2, pady=2, command=my_func(): print(my_var.get())


问:
Efficient Node Enumeration, SceneKit SWIFT
I have a very large tree structure of nodes for some of my animation models. As such, the below code can sometimes filter through 1000+ nodes. If I'm doing that quickly, it can overwhelm my app. Is there a way to confine the rootNode search to only the top level or two and not the entire tree structure?</p>
```<code>self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
            if node.name == "myRootNode" {
         //This is the node to manipulate
      }

}
</code>```

答:
This here is an example of how to filter the rootNode (the node containing all the nodes from your scene setup). It will filter the rootNode only.

You can run the same filter method on any childNode (just as you need)

```<code>sceneView.scene?.rootNode.childNodes.filter({ $0.name == "yourNodeName" }).forEach({
    // $0 is your filtered node
    print($0.name)
})
</code>```

Body:
I have a very large tree structure of nodes for some of my animation models. As such, the below code can sometimes filter through 1000+ nodes. If I'm doing that quickly, it can overwhelm my app. Is there a way to confine the rootNode search to only the top level or two and not the entire tree structure?

self.sceneView.scene.rootNode.enumerateChildNodes { (node, stop) in
            if node.name == "myRootNode" {
         //This is the node to manipulate
      }

}

Body:
This here is an example of how to filter the rootNode (the node containing all the nodes from your scene setup). It will filter the rootNode only.

You can run the same filter method on any childNode (just as you need)

sceneView.scene?.rootNode.childNodes.filter({ $0.name == "yourNodeName" }).forEach({
    // $0 is your filtered node
    print($0.name)
})


问:
How to convert lmdb file to PySpark Image DataFrame?
I have a lmdb file whose value contains jpeg image data in binary string format. I want to save all the images to a folder and create a PySpark DataFrame to do my analysis. I am doing this because I want to train a Mask RCNN model on TensorFlow using this data.

I have two questions:

Is it a good idea? (I am considering it because this way I will be able to do distributed training and inference.)

How do I do it?

One way I can go about achieving this: Save images one by one to a folder and then read that folder as a PySpark Image DataFrame.

import io
from PIL import Image

for key, value in lmdb_data:
    with io.BytesIO(value ) as f:
        image = Image.open(f)
        # The image is of class JpegImageFile
        image.load()
        image.save(f"/tmp/lmdb_images/{key}.{image.format.lower()}")

df = spark.read.format("image").load("/tmp/lmdb_images/")
df.display()
```

Is there any other, more efficient/elegant way to do it?

答:
I can only comment on the PIL side of things because I don't use PySpark.

If your lmbd data is already a JPEG-encoded image, there is no point decoding it into a PIL Image and then re-encoding it back to JPEG to save it to disk. You might as well just write the JPEG you already have to disk. Untested, but it will look something like:

```<code>for key, value in lmdb_data:
    with open(f"/tmp/...", "wb") as f:
       f.write(value)
</code>```

Body:
I have a lmdb file whose value contains jpeg image data in binary string format. I want to save all the images to a folder and create a PySpark DataFrame to do my analysis. I am doing this because I want to train a Mask RCNN model on TensorFlow using this data.

I have two questions:

Is it a good idea? (I am considering it because this way I will be able to do distributed training and inference.)

How do I do it?

One way I can go about achieving this: Save images one by one to a folder and then read that folder as a PySpark Image DataFrame.

import io
from PIL import Image

for key, value in lmdb_data:
    with io.BytesIO(value ) as f:
        image = Image.open(f)
        # The image is of class JpegImageFile
        image.load()
        image.save(f"/tmp/lmdb_images/{key}.{image.format.lower()}")

df = spark.read.format("image").load("/tmp/lmdb_images/")
df.display()

Is there any other, more efficient/elegant way to do it?

Body:
I can only comment on the PIL side of things because I don't use PySpark.

If your lmbd data is already a JPEG-encoded image, there is no point decoding it into a PIL Image and then re-encoding it back to JPEG to save it to disk. You might as well just write the JPEG you already have to disk. Untested, but it will look something like:

for key, value in lmdb_data:
    with open(f"/tmp/...", "wb") as f:
       f.write(value)