问:
Stop people having my website loaded on multiple tabs
I want users to browse my site from only one tab in their browser. How can this be done? Would I use javascript and cookies?

For example, I have a website: www.example.com - and I want my clients to only be able to visit the site from one single tab in one browser. If they open another tab and load the site (or a subpage of the site) - I want an alert "Can't open multiple instances", and then redirect them to an error page.

Once thing to note - if the user changes the address from www.example.com/action/door/mine.aspx to www.example.com - that should work fine, because the user is in the same (original) tab.

Any help will be appreciated. Thanks in advance.

答:
Extending rehman_00001's answer to handle the case where you want the alert on the new tabs instead.

const channel = new BroadcastChannel('tab');
let isOriginal = true;

channel.postMessage('another-tab');
// note that listener is added after posting the message

channel.addEventListener('message', (msg) => {
    if (msg.data === 'another-tab' && isOriginal) {
        // message received from 2nd tab
        // reply to all new tabs that the website is already open
        channel.postMessage('already-open');
    }
    if (msg.data === 'already-open') {
        isOriginal = false;
        // message received from original tab
        // replace this with whatever logic you need
        alert('Cannot open multiple instances');
    }
});```


来源: stackexchange

问:
react autocomplete how to stop first call and complete the second
I have an autocomplete form that receives a list, I would like that when I type in the search field every time I insert a letter the previous call is canceled and continues with the new call, I have tried with throttling but nothing to do ... I am using react with mui how could I do?

this is my function:

```<code>const myFunction= throttle(350, false, (value) => {
  axios.get(url, {
    params: {
      q: value,
    }
  })
  .then((response) => {
    doSomething(response.data);
  })
})
</code>```

I would like to achieve this result

Thank you so much

答:
Call the function when length of value is greater than equal to 2.

I misunderstood the question earlier.
I am editing my original answer:

There are few ways to approach this:

Use third party lib like RTK-query or react-query. They provide functions like cancel, pause & resume to interact with queries. You can use this feature to cancel last query/mutation.

The second one is manual approach and I assume above libraries use the same technique. You can use AbortController to replicate the same result.

ContentLicense: CC BY-SA 4.0

Body:
I have an autocomplete form that receives a list, I would like that when I type in the search field every time I insert a letter the previous call is canceled and continues with the new call, I have tried with throttling but nothing to do ... I am using react with mui how could I do?

this is my function:

const myFunction= throttle(350, false, (value) => {
  axios.get(url, {
    params: {
      q: value,
    }
  })
  .then((response) => {
    doSomething(response.data);
  })
})

I would like to achieve this result

Thank you so much


问:
How do I Extract Version ID from POM inside Jenkins Declarative and Scripted pipelines?
I've created a pipeline and using the embedded groovy pipeline script definition and can't seem to get the version ID of the project from the POM. I tried this which works in a groovy console but on in the Jenkins build pipeline script:

```<code>def project = new XmlSlurper().parse(new File("pom.xml"))
def pomv = project.version.toString()
</code>```

According to the documentation Jenkins has a $POM_VERSION but the value doesn't have anything in it when I assign it to a variable and echo it out.

```<code>def pomv = "$POM_VERSION"
</code>```

OR

```<code>def pomv = '$POM_VERSION"
</code>```

答:
jenkins pipeline add this stage.
more see</p>
```<code>    stage('info')
    {
        steps
        {
            script
            {
                def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
                def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true

            }

        }
    }
</code>```

Body:
I've created a pipeline and using the embedded groovy pipeline script definition and can't seem to get the version ID of the project from the POM. I tried this which works in a groovy console but on in the Jenkins build pipeline script:

def project = new XmlSlurper().parse(new File("pom.xml"))
def pomv = project.version.toString()

According to the documentation Jenkins has a $POM_VERSION but the value doesn't have anything in it when I assign it to a variable and echo it out.

def pomv = "$POM_VERSION"

OR

def pomv = '$POM_VERSION"

Body:
jenkins pipeline add this stage.
more see

    stage('info')
    {
        steps
        {
            script
            {
                def version = sh script: 'mvn help:evaluate -Dexpression=project.version -q -DforceStdout', returnStdout: true
                def artifactId = sh script: 'mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout', returnStdout: true

            }

        }
    }


答:
One option is my {gratia} package:

library('dplyr')
library('gratia')
# can't handle gamm objects just yet so extract the $gam compoents
ma <- mod_a$gam
mb <- mod_b$gam
```
<p>then use <code>compare_smooths()</code> which has methods for <code>gam</code> objects</p>
<pre class="lang-r prettyprint-override"><code>compare_smooths(ma, mb)
</code>```

this returns a nested tibble

r$> compare_smooths(ma, mb)
# A tibble: 6 × 5
  model smooth       type  by    data
  <chr> <chr>        <chr> <chr> <list>
1 ma    s(variable1) TPRS  NA    <tibble [100 × 3]>
2 mb    s(variable1) TPRS  NA    <tibble [100 × 3]>
3 ma    s(variable2) TPRS  NA    <tibble [100 × 3]>
4 mb    s(variable2) TPRS  NA    <tibble [100 × 3]>
5 ma    s(variable3) TPRS  NA    <tibble [100 × 3]>
6 mb    s(variable3) TPRS  NA    <tibble [100 × 3]>
```
<p>which has a <code>draw()</code> method:</p>
<pre class="lang-r prettyprint-override"><code>compare_smooths(ma, mb) %>%
  draw()
</code>```

which produces

If you want to do it for a specific smooth use the smooths argument

r$> compare_smooths(ma, mb, smooths = "s(variable1)")
# A tibble: 2 × 5
  model smooth       type  by    data
  <chr> <chr>        <chr> <chr> <list>
1 ma    s(variable1) TPRS  NA    <tibble [100 × 3]>
2 mb    s(variable1) TPRS  NA    <tibble [100 × 3]>
```
<p>I will add a method for <code>gamm</code> objects so you in future should be able to just do</p>
<pre class="lang-r prettyprint-override"><code>compare_smooths(mod_a, mod_b)
</code>```

Title: Combine two gamm outputs in same graph?

Body:
The axis and variables are the same, but the original data frame is different

mod_a <- gamm(Response ~ s(variable1) + s(variable2) + s(variable3), data=df1)
mod_b <- gamm(Response ~ s(variable1) + s(variable2) + s(variable3), data=df2)

How do I combine them into one plot and color code them for each? so it looks something like this (picture below)? So that the plot shows both mod_a and mod_b even though they are originally from different data frames?

Sample dataset:

df1 <- data.frame (Response = c(00, 17, 03, 23, 02, 21, 24, 21, 16, 24, 15, 28, 07, 30, 11, 07, 21, 14, 10, 05, 14, 17, 02, 03, 18, 28, 05, 16, 14, 02, 18, 26, 30, 06, 11, 06, 25, 03, 20, 19, 30, 16, 24, 12, 22, 20, 23, 20, 14, 26),
                   variable1 = c(26, 00, 26, 03, 29, 25, 18, 24, 22, 17, 18, 15, 20, 23, 29, 17, 02, 21, 25, 05, 28, 17, 13, 03, 29, 01, 12, 06, 05, 09, 04, 17, 12, 27, 25, 14, 06, 05, 05, 06, 01, 26, 26, 08, 19, 25, 30, 29, 18, 07),
                   variable2 = c(08, 03, 22, 09, 10, 00, 06, 22, 23, 02, 06, 08, 19, 06, 29, 27, 14, 24, 01, 08, 15, 10, 24, 04, 27, 09, 19, 20, 16, 04, 00, 02, 26, 21, 09, 26, 29, 19, 03, 19, 30, 14, 26, 28, 28, 15, 11, 19, 08, 07),
                   variable3 = c(12, 07, 15, 21, 23, 19, 02, 00, 28, 27, 08, 22, 04, 18, 14, 18, 15, 20, 27, 19, 24, 07, 05, 26, 05, 28, 21, 26, 22, 30, 18, 01, 19, 05, 24, 18, 29, 15, 06, 11, 19, 13, 16, 07, 22, 08, 27, 17, 21, 25),
                   variable4 = c(07, 21, 24, 16, 30, 14, 27, 14, 24, 13, 28, 15, 11, 24, 19, 12, 02, 30, 19, 27, 03, 12, 23, 16, 17, 12, 04, 17, 01, 07, 29, 12, 03, 20, 04, 27, 19, 10, 18, 08, 15, 29, 11, 03, 16, 08, 11, 19, 25, 13),
                   variable5 = c("sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5"))

df2 <- data.frame (Response  = c(24, 29, 16, 03, 01, 04, 08, 03, 17, 09, 27, 11, 28, 02, 11, 15, 26, 12, 05, 03, 06, 06, 11, 24, 19, 25, 07, 14, 29, 02, 04, 27, 15, 06, 18, 10, 30, 16, 17, 22, 07, 24, 02, 24, 17, 09, 00, 20, 06, 27),
                   variable1 = c(22, 11, 19, 08, 03, 16, 04, 20, 12, 25, 08, 21, 04, 07, 09, 28, 25, 04, 27, 17, 00, 22, 29, 08, 17, 06, 12, 16, 08, 00, 16, 24, 20, 09, 10, 10, 04, 24, 11, 00, 07, 21, 15, 11, 05, 00, 07, 05, 25, 03),
                   variable2 = c(11, 21, 01, 06, 18, 22, 10, 19, 26, 16, 12, 08, 18, 11, 25, 16, 16, 25, 02, 29, 22, 02, 01, 03, 10, 08, 16, 19, 07, 10, 05, 17, 04, 24, 20, 29, 23, 00, 01, 18, 10, 24, 15, 09, 14, 26, 30, 30, 04, 29),
                   variable3 = c(15, 06, 24, 29, 04, 07, 26, 14, 21, 15, 18, 02, 27, 09, 09, 24, 09, 15, 23, 15, 09, 13, 08, 07, 14, 03, 03, 07, 27, 21, 06, 30, 03, 03, 27, 11, 01, 05, 03, 14, 10, 20, 30, 10, 22, 23, 03, 30, 30, 25),
                   variable4 = c(03, 22, 10, 07, 23, 08, 12, 06, 25, 17, 12, 28, 21, 28, 18, 21, 15, 17, 23, 10, 11, 21, 12, 10, 26, 04, 18, 18, 26, 25, 20, 02, 15, 28, 17, 04, 14, 28, 01, 13, 16, 05, 14, 02, 06, 15, 16, 26, 29, 07),
                   variable5 = c("sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5","sq1", "sq2", "sq3", "sq4", "sq5"))

library(mgcv)
mod_a <- gamm(Response ~ s(variable1) + s(variable2) + s(variable3), data=df1)
mod_b <- gamm(Response ~ s(variable1) + s(variable2) + s(variable3), data=df2)

plot(mod_a$gam, pages = 1, shade = T, shade.col = 'gray', residuals = T)
plot(mod_b$gam, pages = 1, shade = T, shade.col = 'gray', residuals = T)

Body:
One option is my {gratia} package:

library('dplyr')
library('gratia')
# can't handle gamm objects just yet so extract the $gam compoents
ma <- mod_a$gam
mb <- mod_b$gam

then use compare_smooths() which has methods for gam objects

compare_smooths(ma, mb)

this returns a nested tibble

r$> compare_smooths(ma, mb)
# A tibble: 6 × 5
  model smooth       type  by    data
  <chr> <chr>        <chr> <chr> <list>
1 ma    s(variable1) TPRS  NA    <tibble [100 × 3]>
2 mb    s(variable1) TPRS  NA    <tibble [100 × 3]>
3 ma    s(variable2) TPRS  NA    <tibble [100 × 3]>
4 mb    s(variable2) TPRS  NA    <tibble [100 × 3]>
5 ma    s(variable3) TPRS  NA    <tibble [100 × 3]>
6 mb    s(variable3) TPRS  NA    <tibble [100 × 3]>

which has a draw() method:

compare_smooths(ma, mb) %>%
  draw()

which produces

If you want to do it for a specific smooth use the smooths argument

r$> compare_smooths(ma, mb, smooths = "s(variable1)")
# A tibble: 2 × 5
  model smooth       type  by    data
  <chr> <chr>        <chr> <chr> <list>
1 ma    s(variable1) TPRS  NA    <tibble [100 × 3]>
2 mb    s(variable1) TPRS  NA    <tibble [100 × 3]>

I will add a method for gamm objects so you in future should be able to just do

compare_smooths(mod_a, mod_b)


问:
IOException "Cyclic Rendundancy Check" FileStream.CopyTo using C#.Net
I have some C# code that uses FileStreams to open a PhysicalDrive and take an image of the whole disk, but s consistently throwing an IOException with the message "Data error (cyclic redundancy check)." After copying about 121MB of a 128MB disk.

```<code>    using Microsoft.Win32.SafeHandles;
    using System.IO;
    using System;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    protected static extern SafeFileHandle CreateFile(
        string lpFileName,
        uint dwDesiredAccess,
        uint dwShareMode,
        IntPtr SecurityAttributes,
        uint dwCreationDisposition,
        uint dwFlagsAndAttributes,
        IntPtr hTemplateFile
    );

public void MakeImage()
{

    SafeFileHandle TheDevice = null;
    try
    {
    TheDevice = CreateFile(@"\\.\PHYSICALDRIVE1", (uint)FileAccess.Read, (uint)0, IntPtr.Zero, (uint)FileMode.Open, (uint)FILE_ATTRIBUTE_SYSTEM, IntPtr.Zero);
        if (TheDevice.IsInvalid) { throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error()); }
        using (FileStream Dest = System.IO.File.Open("output.bin", FileMode.Create))
        {
            using (FileStream Src = new FileStream(TheDevice, FileAccess.Read))
            {
                Src.CopyTo(Dest);
                Src.Close();
            }
            Dest.Close();
        }
    }
    catch(Exception Ex)
    {
        //Here is where i am getting the IOException
        //Handle error..
    }
    finally
    {
        if (TheDevice != null)
        {
            if (!TheDevice.IsClosed)
                TheDevice.Close();
            TheDevice.Dispose();
        }
    }
}
</code>```

I have run Scan Disk on the Drive in question and there doesn't appear to be anything wrong with it. If I change the first Param of CreateFile to just read a partition (not what I want to do), then the image is created fine.

This is a follow up to Windows C# implementation of linux dd command that I've been trying to do.

UPDATE:

Further investigations show that the error has something do with not being able to get or know the Src.Length property. I changed my code to copy byte by byte and keep a count, it errors after 126959616 bytes, which is 1 byte more than the total size of the image produced by dd.

答:
The cyclic redundancy check, or "CRC" error indicates that the disk is corrupt or damaged in some way probably a bad spot on the disk. If you're seeing it when trying to copy a file it could be that the bad spot may be in the file itself.

Try copying the file to some other disk and see if that works.

ContentLicense: CC BY-SA 3.0

Body:
I have some C# code that uses FileStreams to open a PhysicalDrive and take an image of the whole disk, but s consistently throwing an IOException with the message "Data error (cyclic redundancy check)." After copying about 121MB of a 128MB disk.

    using Microsoft.Win32.SafeHandles;
    using System.IO;
    using System;

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    protected static extern SafeFileHandle CreateFile(
        string lpFileName,
        uint dwDesiredAccess,
        uint dwShareMode,
        IntPtr SecurityAttributes,
        uint dwCreationDisposition,
        uint dwFlagsAndAttributes,
        IntPtr hTemplateFile
    );

public void MakeImage()
{

    SafeFileHandle TheDevice = null;
    try
    {
    TheDevice = CreateFile(@"\\.\PHYSICALDRIVE1", (uint)FileAccess.Read, (uint)0, IntPtr.Zero, (uint)FileMode.Open, (uint)FILE_ATTRIBUTE_SYSTEM, IntPtr.Zero);
        if (TheDevice.IsInvalid) { throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error()); }
        using (FileStream Dest = System.IO.File.Open("output.bin", FileMode.Create))
        {
            using (FileStream Src = new FileStream(TheDevice, FileAccess.Read))
            {
                Src.CopyTo(Dest);
                Src.Close();
            }
            Dest.Close();
        }
    }
    catch(Exception Ex)
    {
        //Here is where i am getting the IOException
        //Handle error..
    }
    finally
    {
        if (TheDevice != null)
        {
            if (!TheDevice.IsClosed)
                TheDevice.Close();
            TheDevice.Dispose();
        }
    }
}

I have run Scan Disk on the Drive in question and there doesn't appear to be anything wrong with it. If I change the first Param of CreateFile to just read a partition (not what I want to do), then the image is created fine.

This is a follow up to Windows C# implementation of linux dd command that I've been trying to do.

UPDATE:

Further investigations show that the error has something do with not being able to get or know the Src.Length property. I changed my code to copy byte by byte and keep a count, it errors after 126959616 bytes, which is 1 byte more than the total size of the image produced by dd.


问:
Is it ok to inject additional data into a module's scope? Or: What are the possibilities of managing/exposing module scoped state from/to the outside?
I am designing Javascript modules using the Revealing Module Pattern. In my html I have onmouseover="Test.OnLoad()". I need a callback after that is completed. I set the callback with Test.Callback. Is there a better way to do this? I basically need to write a lot of JavaScript modules and want to keep the functionality encapsulated. Thanks!

const Test = (function () {
  const items = [];
  let callBack;

  function handleOnLoad() {
    items.push({ name: "Test" });
    callBack(items);
  }
  function setCallBack(cb) {
    callBack = cb;
  }

  return{
    OnLoad: handleOnLoad,
    CallBack: setCallBack
  };
}());

Test.CallBack(function(items) {
  console.log(`Item 0: ${ items[0].name }, items.length: ${ items.length }`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }
.test { display: inline-block; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }</code>```

mouseover test
```

答:
The OP's approach is one way of achieving the goal of a customizable callback with items access while keeping items entirely encapsulated within its module scope.

Another approach could be a getter which exposes an (maybe even immutable) items copy into public. Any callback related implementation (if it was just for the sake o the items encapsulation) then was not necessary.

In order to not accidentally alter/mutate encapsulated data, it mostly already is good enough to not pass the encapsulated reference but a shallow copy of such data. Sometimes, and if appropriate/available, one might even pass a full clone.

Of cause one has to change the mouseover handling too ...

const Test = (function () {
  const items = [];

  function handleOnLoad() {
    items.push({ name: `Test_${ items.length + 1 }` });
  }
  function getItems() {
    return (typeof structuredClone === 'function')
      && structuredClone(items) // a full `items` clone.
      || [...items];  // not the `items` reference ...
                      // but just a shallow copy of it.
  }

  return{
    OnLoad: handleOnLoad,
    getItems,
  };
}());

function logLastItemName(items) {
  console.log(`last item name: ${ items.at(-1).name }, items.length: ${ items.length }`);
}

function init() {
  document
    .querySelector('.test.event-listener')
    .addEventListener('mouseover', (/*evt*/) => {
      Test.OnLoad();
      logLastItemName(Test.getItems());
    });
}
init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }
.test { display: inline-block; margin-right: 20px; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }</code>```

inline-script mouseover test

event-listener mouseover test
```
</div>
</div>
</p>
<p>Letting modules feature exactly a single public function which creates custom callbacks is yet another way to go.</p>
<p>Maybe it's even the to be favored solution since one neither needs to inject any data into the module nor does one have to implement a getter function for a controlled <code>items</code> access.</p>
<p>The creator function takes a single argument, the custom function which later gets passed the <code>items</code> reference, and returns a function which is wrapped around the module's and the custom handler part.</p>
<p>Another advantage is the possibility to create as many customized but module or <code>items</code> related handlers as one is in need for.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Test = (function () {
  const items = [];

  function writeItem() {
    items.push({ name: `Test_${ items.length + 1 }` });
  }

  function createLoadHandler(customCallback) {
    return function handleLoad (/*evt*/) {

      writeItem();
      customCallback(items);
    }
  }

  return{
    createLoadHandler
  };
}());

function logLastItemName(items) {
  console.log(`last item name: ${ items.at(-1).name }, items.length: ${ items.length }`);
}
const customLoadHandler = Test.createLoadHandler(logLastItemName);

function init() {
  document
    .querySelector('.test.event-listener')
    .addEventListener('mouseover', customLoadHandler);
}
init();</code>```

body { margin: 0; }
.test { display: inline-block; margin-right: 20px; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div
  class="test inline-script"
  onmouseover="customLoadHandler();"
>inline-script mouseover test</div>

<div class="test event-listener">event-listener mouseover test</div></code>```

Body:
I am designing Javascript modules using the Revealing Module Pattern. In my html I have onmouseover="Test.OnLoad()". I need a callback after that is completed. I set the callback with Test.Callback. Is there a better way to do this? I basically need to write a lot of JavaScript modules and want to keep the functionality encapsulated. Thanks!

const Test = (function () {
  const items = [];
  let callBack;

  function handleOnLoad() {
    items.push({ name: "Test" });
    callBack(items);
  }
  function setCallBack(cb) {
    callBack = cb;
  }

  return{
    OnLoad: handleOnLoad,
    CallBack: setCallBack
  };
}());

Test.CallBack(function(items) {
  console.log(`Item 0: ${ items[0].name }, items.length: ${ items.length }`);
});

body { margin: 0; }
.test { display: inline-block; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }

mouseover test

Body:
The OP's approach is one way of achieving the goal of a customizable callback with items access while keeping items entirely encapsulated within its module scope.

Another approach could be a getter which exposes an (maybe even immutable) items copy into public. Any callback related implementation (if it was just for the sake o the items encapsulation) then was not necessary.

In order to not accidentally alter/mutate encapsulated data, it mostly already is good enough to not pass the encapsulated reference but a shallow copy of such data. Sometimes, and if appropriate/available, one might even pass a full clone.

Of cause one has to change the mouseover handling too ...

const Test = (function () {
  const items = [];

  function handleOnLoad() {
    items.push({ name: `Test_${ items.length + 1 }` });
  }
  function getItems() {
    return (typeof structuredClone === 'function')
      && structuredClone(items) // a full `items` clone.
      || [...items];  // not the `items` reference ...
                      // but just a shallow copy of it.
  }

  return{
    OnLoad: handleOnLoad,
    getItems,
  };
}());

function logLastItemName(items) {
  console.log(`last item name: ${ items.at(-1).name }, items.length: ${ items.length }`);
}

function init() {
  document
    .querySelector('.test.event-listener')
    .addEventListener('mouseover', (/*evt*/) => {
      Test.OnLoad();
      logLastItemName(Test.getItems());
    });
}
init();

body { margin: 0; }
.test { display: inline-block; margin-right: 20px; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }

<div
  class="test inline-script"
  onmouseover="Test.OnLoad(); logLastItemName(Test.getItems());"
>inline-script mouseover test</div>

<div class="test event-listener">event-listener mouseover test</div>

Letting modules feature exactly a single public function which creates custom callbacks is yet another way to go.

Maybe it's even the to be favored solution since one neither needs to inject any data into the module nor does one have to implement a getter function for a controlled items access.

The creator function takes a single argument, the custom function which later gets passed the items reference, and returns a function which is wrapped around the module's and the custom handler part.

Another advantage is the possibility to create as many customized but module or items related handlers as one is in need for.

const Test = (function () {
  const items = [];

  function writeItem() {
    items.push({ name: `Test_${ items.length + 1 }` });
  }

  function createLoadHandler(customCallback) {
    return function handleLoad (/*evt*/) {

      writeItem();
      customCallback(items);
    }
  }

  return{
    createLoadHandler
  };
}());

function logLastItemName(items) {
  console.log(`last item name: ${ items.at(-1).name }, items.length: ${ items.length }`);
}
const customLoadHandler = Test.createLoadHandler(logLastItemName);

function init() {
  document
    .querySelector('.test.event-listener')
    .addEventListener('mouseover', customLoadHandler);
}
init();

body { margin: 0; }
.test { display: inline-block; margin-right: 20px; }
.test:hover { cursor: pointer; }
.as-console-wrapper { min-height: 88%!important; }

<div
  class="test inline-script"
  onmouseover="customLoadHandler();"
>inline-script mouseover test</div>

<div class="test event-listener">event-listener mouseover test</div>


问:
Use of SharedFlow in Android kotlin
Hey I am learning flow in kotlin. I am learning about MutableStateFlow and MutableSharedFlow. I tried to learn MutableStateFlow in real world example. But I am unable to get the MutableSharedFlow example, which place it suits more. I tried some MutableStateFlow

For example when we are fetching data from api we can use seal class to populate accordingly .

LoggedState.kt

```<code>sealed class LoggedState {
    data class OnSuccess(val data: List<XYZ>) : LoggedState()
    object OnEmpty : LoggedState()
    data class IsLoading(val isLoading: Boolean = true) : LoggedState()
    data class OnError(val message: String) : LoggedState()
}
</code>```

SettingsViewModel.kt

```<code>class SettingsViewModel : ViewModel() {

 var loggedMutableStateFlow = MutableStateFlow<LoggedState>(LoggedState.OnEmpty)

 fun fetchData(){
   val result = dataRepository.getLogged()
                result.handleResult(
                    onSuccess = { response ->
                        val data = response?.items
                        if (!data.isNullOrEmpty()) {
                            loggedMutableStateFlow.value = LoggedState.OnSuccess(data)
                        } else {
                            loggedMutableStateFlow.value = LoggedState.OnEmpty
                        }
                    },
                    onError = {
                        loggedMutableStateFlow.value = LoggedState.OnError(it.message)
                    }
                )
 }

}
</code>```

Activit.kt

```<code>lifecycleScope.launchWhenCreated {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                viewModel.loggedMutableStateFlow.collect { state ->
                    when (state) {
                        is LoggedState.OnEmpty -> {
                           // view gone
                        }
                        is LoggedState.OnSuccess -> {
                            // show ui
                        }
                        is LoggedState.IsLoading -> {
                            // show spinner
                        }
                        is LoggedState.OnError-> {
                            // show error message
                        }
                    }
                }
            }
        }
</code>```

I all get the MutableStateFlow example. Can someone guide me how to do MutableSharedFlow in real world examples. Also I am curious about parameters

replay

extraBufferCapacity

onBufferOverflow

Thanks

答:
MutableStateFlow is similar to MutableLiveData, both have .value to access the value or to change the value.

MutableSharedFlow is similar to SingleLiveEvent, used for observing instant-state changes.

More example and tutorial you can check out this video: https://youtu.be/6Jc6-INantQ

Title: Use of SharedFlow in Android kotlin

Body:
Hey I am learning flow in kotlin. I am learning about MutableStateFlow and MutableSharedFlow. I tried to learn MutableStateFlow in real world example. But I am unable to get the MutableSharedFlow example, which place it suits more. I tried some MutableStateFlow

For example when we are fetching data from api we can use seal class to populate accordingly .

LoggedState.kt

sealed class LoggedState {
    data class OnSuccess(val data: List<XYZ>) : LoggedState()
    object OnEmpty : LoggedState()
    data class IsLoading(val isLoading: Boolean = true) : LoggedState()
    data class OnError(val message: String) : LoggedState()
}

SettingsViewModel.kt

class SettingsViewModel : ViewModel() {

 var loggedMutableStateFlow = MutableStateFlow<LoggedState>(LoggedState.OnEmpty)

 fun fetchData(){
   val result = dataRepository.getLogged()
                result.handleResult(
                    onSuccess = { response ->
                        val data = response?.items
                        if (!data.isNullOrEmpty()) {
                            loggedMutableStateFlow.value = LoggedState.OnSuccess(data)
                        } else {
                            loggedMutableStateFlow.value = LoggedState.OnEmpty
                        }
                    },
                    onError = {
                        loggedMutableStateFlow.value = LoggedState.OnError(it.message)
                    }
                )
 }

}

Activit.kt

lifecycleScope.launchWhenCreated {
            repeatOnLifecycle(Lifecycle.State.CREATED) {
                viewModel.loggedMutableStateFlow.collect { state ->
                    when (state) {
                        is LoggedState.OnEmpty -> {
                           // view gone
                        }
                        is LoggedState.OnSuccess -> {
                            // show ui
                        }
                        is LoggedState.IsLoading -> {
                            // show spinner
                        }
                        is LoggedState.OnError-> {
                            // show error message
                        }
                    }
                }
            }
        }

I all get the MutableStateFlow example. Can someone guide me how to do MutableSharedFlow in real world examples. Also I am curious about parameters

replay

extraBufferCapacity

onBufferOverflow

Thanks


问:
What does "this" mean for ViewPagers?
I am making a page listener, I've seen a view people do this:

```<code>ViewPager.addOnPageChangeListener(this);
</code>```

What does that mean? What does that code even do, seems like nothing? I thought "this" meant the current Activity or context but I feel like the above code is not doing anything.

答:
It means it is referring to a onPageChangeListner object which u need to create sepearately. So you will have to create a OnPageChangeListener like this:

```<code>ViewPager.OnPageChangeListener()  pageChangeListener = new ViewPager.OnPageChangeListener() {}
</code>```

And then use it like:

```<code>ViewPager.addOnPageChangeListener(this)
</code>```

So basically this means the reference of the onPageChangeListener object

Title: What does "this" mean for ViewPagers?

Body:
I am making a page listener, I've seen a view people do this:

ViewPager.addOnPageChangeListener(this);

What does that mean? What does that code even do, seems like nothing? I thought "this" meant the current Activity or context but I feel like the above code is not doing anything.

Body:
It means it is referring to a onPageChangeListner object which u need to create sepearately. So you will have to create a OnPageChangeListener like this:

ViewPager.OnPageChangeListener()  pageChangeListener = new ViewPager.OnPageChangeListener() {}

And then use it like:

ViewPager.addOnPageChangeListener(this)

So basically this means the reference of the onPageChangeListener object


问:
How to obtain the left, right, top and bottom position of scroll in a div in HTML with Javascript
I would like to draw a
 box with fixed height, width and scrollbars and register the location of the scrolled view. I have found the function scrollTop but don't know how to get the bottom scroll location.

Which CSS do I need to draw the box with scrollbars?

How can I access the left, right, top and bottom position inside (relative to) the box with Javascript?

I would use these 4 numbers to draw a
 inside.

答:
Starting with your second question:
scrollTop is the vertical position (in px) of the scrollbar, relative to the top position. So if your scrollbar is at the very top, scrollTop = 0.
It's the same for scrollLeft, but horizontal.
You can set these values via js to bring the scrollbar to a certain position programmatically.
So, if you want to know when the scrollbar is on top, you simply register an event listener for scrolling and wait for scrollTop = 0.
To check if the scrollbar is at the very bottom, you need a bit of calculation since you need to know the scroll height of the container (scroll height - scrollTop = 0).

See the following code (using jquery but it also works with plain js) which fires an event when the scrollbar reaches start or end position (this is for horizontal scrolling, so you have to replace "left" with "top" and "width" with "height"):

```<code> $('#yourDivId').on('scroll', function () {
    if (scrollbarIsAtStart($(this))) {
        $(document).trigger("scrollbar.left");
    }
    if (scrollbarIsAtEnd(this, $(this))) {
        $(document).trigger("scrollbar.right");
    }
})

const scrollbarIsAtStart = (jQuery) => {
    if (jQuery.scrollLeft() == 0) {
        return true;
    }
    return false;
}

const scrollbarIsAtEnd = (e, jquery) => {
    //Minus one, probably rounding issue!?
    if (jquery.width() + jquery.scrollLeft() >= e.scrollWidth - 1) {
        return true;
    }
    return false;
}
</code>```

So there are two events triggered, one for the scrollbar reaching start position, one for the end of the container. Now, you can listen to these events and handle them:

```<code>$(document)
    .on('scrollbar.left', {}, function (event) {
    //do whatever you want to do
})
</code>```

Regarding your first question, I'm not a css expert, but if I look at bootstraps table-responsive class (which enables horizental scrolling), it looks like this:

```<code>.table-responsive {
    display: block;
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}
</code>```

Vertical scrolling is enabled by default if you define a fixed height on your div and the data exceeds this size. You can of course override the width with a fixed value or a different percentage.

Body:
Starting with your second question:
scrollTop is the vertical position (in px) of the scrollbar, relative to the top position. So if your scrollbar is at the very top, scrollTop = 0.
It's the same for scrollLeft, but horizontal.
You can set these values via js to bring the scrollbar to a certain position programmatically.
So, if you want to know when the scrollbar is on top, you simply register an event listener for scrolling and wait for scrollTop = 0.
To check if the scrollbar is at the very bottom, you need a bit of calculation since you need to know the scroll height of the container (scroll height - scrollTop = 0).

See the following code (using jquery but it also works with plain js) which fires an event when the scrollbar reaches start or end position (this is for horizontal scrolling, so you have to replace "left" with "top" and "width" with "height"):

 $('#yourDivId').on('scroll', function () {
    if (scrollbarIsAtStart($(this))) {
        $(document).trigger("scrollbar.left");
    }
    if (scrollbarIsAtEnd(this, $(this))) {
        $(document).trigger("scrollbar.right");
    }
})

const scrollbarIsAtStart = (jQuery) => {
    if (jQuery.scrollLeft() == 0) {
        return true;
    }
    return false;
}

const scrollbarIsAtEnd = (e, jquery) => {
    //Minus one, probably rounding issue!?
    if (jquery.width() + jquery.scrollLeft() >= e.scrollWidth - 1) {
        return true;
    }
    return false;
}

So there are two events triggered, one for the scrollbar reaching start position, one for the end of the container. Now, you can listen to these events and handle them:

$(document)
    .on('scrollbar.left', {}, function (event) {
    //do whatever you want to do
})

Regarding your first question, I'm not a css expert, but if I look at bootstraps table-responsive class (which enables horizental scrolling), it looks like this:

.table-responsive {
    display: block;
    width: 100%;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

Vertical scrolling is enabled by default if you define a fixed height on your div and the data exceeds this size. You can of course override the width with a fixed value or a different percentage.


问:
Cloning existing python project anyjson setup command error
I have this project shared to me via github, after I clone and run this steps:

```<code>python -m venv ./venv
venv\scripts\activate
pip install -r requirements.txt
</code>```

in pip install -r:

It gives me this errors:

```<code> error in anyjson setup command: use_2to3 is invalid.

ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3)
ERROR: No matching distribution found for anyjson==0.3.3
</code>```

Here is what inside the requirements.txt

```<code>  amqp==1.4.9
anyjson==0.3.3
billiard==3.3.0.23
celery==3.1.25
certifi==2019.3.9
chardet==3.0.4
dj-database-url==0.5.0
Django==2.0.13
django-appconf==1.0.3
django-axes==1.7.0
django-celery==3.2.2
django-compressor==2.2
django-crispy-forms==1.7.2
django-dynamic-formsets==0.0.8
django-polymorphic==2.1.2
django-reversion==3.0.1
djangorestframework==3.7.4
ffs==0.0.8.2
gunicorn==20.0.4
idna==2.7
Jinja2==2.10
kombu==3.0.37
letter==0.5
MarkupSafe==1.1.1
opal==0.14.2
Pillow==8.1.0
psycopg2==2.8.6
python-dateutil==2.7.5
pytz==2019.1
rcssmin==1.0.6
requests==2.20.1
rjsmin==1.0.12
six==1.12.0
urllib3==1.24.3
whitenoise==4.1.4
mysqlclient==2.0.3
cryptography==3.4.1
</code>```

Already tried removing anyjson from requirements.txt but still gives me error. What Am I missing here?

答:
There was a breaking change in the setuptools package that's causing this error. This will require a config change on our side, downgrading setuptools to a version prior 58 like:</p>
```<code>pip install "setuptools<58"
</code>```

Body:
I have this project shared to me via github, after I clone and run this steps:

python -m venv ./venv
venv\scripts\activate
pip install -r requirements.txt

in pip install -r:

It gives me this errors:

 error in anyjson setup command: use_2to3 is invalid.

ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3)
ERROR: No matching distribution found for anyjson==0.3.3

Here is what inside the requirements.txt

  amqp==1.4.9
anyjson==0.3.3
billiard==3.3.0.23
celery==3.1.25
certifi==2019.3.9
chardet==3.0.4
dj-database-url==0.5.0
Django==2.0.13
django-appconf==1.0.3
django-axes==1.7.0
django-celery==3.2.2
django-compressor==2.2
django-crispy-forms==1.7.2
django-dynamic-formsets==0.0.8
django-polymorphic==2.1.2
django-reversion==3.0.1
djangorestframework==3.7.4
ffs==0.0.8.2
gunicorn==20.0.4
idna==2.7
Jinja2==2.10
kombu==3.0.37
letter==0.5
MarkupSafe==1.1.1
opal==0.14.2
Pillow==8.1.0
psycopg2==2.8.6
python-dateutil==2.7.5
pytz==2019.1
rcssmin==1.0.6
requests==2.20.1
rjsmin==1.0.12
six==1.12.0
urllib3==1.24.3
whitenoise==4.1.4
mysqlclient==2.0.3
cryptography==3.4.1

Already tried removing anyjson from requirements.txt but still gives me error. What Am I missing here?

Body:
There was a breaking change in the setuptools package that's causing this error. This will require a config change on our side, downgrading setuptools to a version prior 58 like:

pip install "setuptools<58"


问:
How to compile and link callback class (for ROS messages)
Essentially I have defined a class to handle my callbacks, with the declarations and definitions split between a header and source file. However I am having troubles compiling a file which then uses said callback (despite me attempted to link the object file of the callback), specifically I get a linker error:

```<code>[ 98%] Linking CXX executable /home/salih/documents/university/3/6001/code/devel/lib/sdr_ros/sdr_ros
/usr/bin/ld: CMakeFiles/sdr_ros.dir/src/sdr_ros.cpp.o: in function `main':
sdr_ros.cpp:(.text+0x41e): undefined reference to `sdr_ros::TravelInfoCallback::callback(boost::shared_ptr<sdr_ros::TravelInfo_<std::allocator<void> > const> const&)'
collect2: error: ld returned 1 exit status
</code>```

Package is called sdr_ros & the message it's dealing with is called TravelInfo which is stored in the msg directory.

include/travel_info_callback.hpp (Header file):

```<code>#ifndef TRAVEL_INFO_CALLBACK_HPP
#define TRAVEL_INFO_CALLBACK_HPP
#pragma once

#include <tuple>

#include "sdr_ros/TravelInfo.h" // message itself

/**
  * @brief This file contains declarations for callback functionality which processes TravelInfo ROS message
  */

namespace sdr_ros {

    class TravelInfoCallback {
        /**
          * @brief TravelInfoCallback - class to store values returned by callback pertaining to distance / angles changes
          */
        private:
            float _delta_x, _delta_y, _delta_z ;

            float _yaw, _pitch, _roll ;

        public:
            /**
              * @brief TravelInfoCallback - constructor initialises class values
              */
            TravelInfoCallback() noexcept ;

            /**
              * @brief distance - method returning tuple of distance travelled along x, y, z
              * @return std::tuple<float, float, float> - value pertaining to distance travelled along x, y, z axis
              */
            ::std::tuple<float, float, float> distance() const noexcept ;

            /**
              * @brief heading - method returning tuple of euler angles yaw, pitch, roll
              * @return std::tuple<float, float, float> - value pertaining to distance travelled around the (yaw) z, (pitch) y, (roll) x axis
              */
            ::std::tuple<float, float, float> heading() const noexcept ;

            /**
              * @brief callback - method extracting distance travelled and heading angle from ROS message
              * @param const sdr_ros::TravelInfoConstPtr& - const reference to boost shared pointer to ROS message storing distance travelled and heading angle
              */
            void callback(const TravelInfoConstPtr&) noexcept ;

            // below are defaulted and deleted methods
            TravelInfoCallback(const TravelInfoCallback&) = delete ;
            TravelInfoCallback& operator=(const TravelInfoCallback&) = delete ;
            TravelInfoCallback(TravelInfoCallback&&) = delete ;
            TravelInfoCallback&& operator=(TravelInfoCallback&&) = delete ;
            ~TravelInfoCallback() noexcept = default ;
    } ;

}

#endif // TRAVEL_INFO_HPP
</code>```

src/travel_info.cpp

```<code>#include <tuple>

#include "sdr_ros/TravelInfo.h" // message itself

#include "travel_info_callback.hpp"

/**
  * @brief This file contains defintions for callback functionality which processes travel_info ROS message
  */

sdr_ros::TravelInfoCallback::TravelInfoCallback() noexcept : _delta_x(0.f), _delta_y(0.f), _delta_z(0.f), _yaw(0.f), _pitch(0.f), _roll(0.f) {} ;

std::tuple<float, float, float> sdr_ros::TravelInfoCallback::distance() const noexcept
{
    return std::tuple<float, float, float>{
        this->_delta_x, this->_delta_y, this->_delta_z
    } ;
}

std::tuple<float, float, float> sdr_ros::TravelInfoCallback::heading() const noexcept
{
    return std::tuple<float, float, float>{
        this->_yaw, this->_pitch, this->_roll
    } ;
}

inline void sdr_ros::TravelInfoCallback::callback(const sdr_ros::TravelInfoConstPtr& travel_info) noexcept
{
    this->_delta_x = travel_info->delta_x ;
    this->_delta_y = travel_info->delta_y ;
    this->_delta_z = travel_info->delta_z ;
    this->_yaw = travel_info->yaw ;
    this->_pitch = travel_info->pitch ;
    this->_roll = travel_info->roll ;
}
</code>```

src/sdr_ros (source code using callback)

```<code>#include <ros/ros.h>
#include <ros/console.h>
#include <ros/callback_queue.h>

#include <string>
#include <cmath>

#include <geometry_msgs/Pose.h>

#include "sdr_ros/TravelInfo.h"

#include "preprocessing.hpp"
#include "pose.hpp"
#include "travel_info_callback.hpp"

/**
  * @brief This file serves as the ROS node which reads from the network and calls relevant functionality to calculate and distribute pose information
  */

int main(int argc, char** argv)
{
    /* Initialisation */
    const std::string node_name = "sdr_ros" ;
    ros::init(argc, argv, node_name); ROS_INFO_STREAM(node_name << " running") ; // initialise ROS node
    ros::NodeHandle nh("~") ; // handle to ROS communications (topics, services)

    sdr::Pose pose ;
    std::string initial_pose_file ;
    if(nh.getParam("initial_pose_file", initial_pose_file))
    {
        pose = sdr::extract_initial_pose(initial_pose_file) ;
    }

    sdr_ros::TravelInfoCallback cb ; // callback object with methods
    ros::Subscriber sub = nh.subscribe<sdr_ros::TravelInfo>("/travel_info", 100, &sdr_ros::TravelInfoCallback::callback, &cb) ; // subscribe to topic distance_info

    geometry_msgs::Pose pose_msg ;
    ros::Publisher pub = nh.advertise<geometry_msgs::Pose>("/odometry", 1) ; // publishes information about where car as XYZ, orientation as quaternion

    /* Main functionality */
    while(ros::ok()) // while ROS is running - the actual useful computation
    {
        /* Get info */
        if(ros::getGlobalCallbackQueue()->callOne() == ros::CallbackQueue::CallOneResult::Empty) continue ;
        // ^ we can't simply use `ros::spinOnce` as there's no indication of an empty queue, meaning we'd be processing the same message multiple times, exponentially increasing predicted distance.

        const auto [delta_x, delta_y, delta_z] = cb.distance() ;
        if(!delta_x && !delta_y && !delta_z)
        {
            continue ; // no point processing odom when we haven't moved
        }
        const auto [yaw, pitch, roll] = cb.heading() ;

        pose.update_position(delta_x, delta_y, delta_z) ;
        pose.update_orientation(yaw, pitch, roll) ;

        pose_msg.position.x = pose.position()(0,0) ;
        pose_msg.position.y = pose.position()(0,1) ;
        pose_msg.position.z = pose.position()(0,2) ;
        pose_msg.orientation.x = pose.orientation().x() ;
        pose_msg.orientation.y = pose.orientation().y() ;
        pose_msg.orientation.z = pose.orientation().z() ;
        pose_msg.orientation.w = pose.orientation().w() ;

        ROS_INFO_STREAM("Current position: " << pose_msg.position) ;
        ROS_INFO_STREAM("Current orientation: " << pose_msg.orientation << '\n') ;

        /* Publish odometry */
        pub.publish(pose_msg) ;
    }

    /* E(nd) O(f) P(rogram) */
    return 0 ;
}
</code>```

CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.2)
project(sdr_ros)

## Compile as C++20, supported in ROS Kinetic and newer
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_CXX_FLAGS "-Wall -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(CMAKE_CXX_FLAGS_RELEASE "-O0")

find_package(Eigen3 REQUIRED)

################################################
##    Find catkin macros and libraries        ##
################################################
find_package(catkin REQUIRED COMPONENTS
    roscpp
    rospy
    std_msgs
    tf
    nav_msgs
    genmsg
    message_generation
)

## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)

################################################
## Declare ROS messages, services and actions ##
################################################

## Generate messages in the 'msg' folder
add_message_files(
    DIRECTORY
        msg
    FILES
        TravelInfo.msg
)

## Generate services in the 'srv' folder
#add_service_files(
#    FILES
#)

## Generate added messages and services with any dependencies listed here
generate_messages(
    DEPENDENCIES
        std_msgs
        geometry_msgs
)

###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
#    INCLUDE_DIRS
#        include
#        ${EIGEN3_INCLUDE_DIR}
#        libraries/sdr/include/
    CATKIN_DEPENDS
        message_runtime
)

###########
## Build ##
###########

add_subdirectory(libraries/sdr)

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
    include
    libraries/sdr/include/
    ${EIGEN3_INCLUDE_DIR}
    ${catkin_INCLUDE_DIRS}
)

## Declare a C++ executable
add_library(travel_info_callback ${CMAKE_CURRENT_SOURCE_DIR}/src/travel_info_callback.cpp)
target_include_directories(travel_info_callback PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(travel_info_callback ${catkin_LIBRARIES})
add_dependencies(travel_info_callback sdr_ros_generate_messages_cpp)

add_executable(sdr_ros src/sdr_ros.cpp)
target_link_libraries(sdr_ros ${catkin_LIBRARIES} travel_info_callback detailed_exception.o preprocessing.o pose.o yaml-cpp)
add_dependencies(sdr_ros sdr_ros_generate_messages_cpp)
</code>```

I hope I've given enough information and that someone can help. Much appreciated

答:
Your message types are wrong. When setting up the subscriber you're giving it a type of sdr_ros::TravelInfo, however the callback definition takes in sdr_ros::TravelInfoConstPtr as a parameter. Instead in your callback you want the ConstPtr generated by the message so change the signature to

```<code>sdr_ros::TravelInfoCallback::callback(const sdr_ros::TravelInfo::ConstPtr& travel_info)
</code>```

Body:
Essentially I have defined a class to handle my callbacks, with the declarations and definitions split between a header and source file. However I am having troubles compiling a file which then uses said callback (despite me attempted to link the object file of the callback), specifically I get a linker error:

[ 98%] Linking CXX executable /home/salih/documents/university/3/6001/code/devel/lib/sdr_ros/sdr_ros
/usr/bin/ld: CMakeFiles/sdr_ros.dir/src/sdr_ros.cpp.o: in function `main':
sdr_ros.cpp:(.text+0x41e): undefined reference to `sdr_ros::TravelInfoCallback::callback(boost::shared_ptr<sdr_ros::TravelInfo_<std::allocator<void> > const> const&)'
collect2: error: ld returned 1 exit status

Package is called sdr_ros & the message it's dealing with is called TravelInfo which is stored in the msg directory.

include/travel_info_callback.hpp (Header file):

#ifndef TRAVEL_INFO_CALLBACK_HPP
#define TRAVEL_INFO_CALLBACK_HPP
#pragma once

#include <tuple>

#include "sdr_ros/TravelInfo.h" // message itself

/**
  * @brief This file contains declarations for callback functionality which processes TravelInfo ROS message
  */

namespace sdr_ros {

    class TravelInfoCallback {
        /**
          * @brief TravelInfoCallback - class to store values returned by callback pertaining to distance / angles changes
          */
        private:
            float _delta_x, _delta_y, _delta_z ;

            float _yaw, _pitch, _roll ;

        public:
            /**
              * @brief TravelInfoCallback - constructor initialises class values
              */
            TravelInfoCallback() noexcept ;

            /**
              * @brief distance - method returning tuple of distance travelled along x, y, z
              * @return std::tuple<float, float, float> - value pertaining to distance travelled along x, y, z axis
              */
            ::std::tuple<float, float, float> distance() const noexcept ;

            /**
              * @brief heading - method returning tuple of euler angles yaw, pitch, roll
              * @return std::tuple<float, float, float> - value pertaining to distance travelled around the (yaw) z, (pitch) y, (roll) x axis
              */
            ::std::tuple<float, float, float> heading() const noexcept ;

            /**
              * @brief callback - method extracting distance travelled and heading angle from ROS message
              * @param const sdr_ros::TravelInfoConstPtr& - const reference to boost shared pointer to ROS message storing distance travelled and heading angle
              */
            void callback(const TravelInfoConstPtr&) noexcept ;

            // below are defaulted and deleted methods
            TravelInfoCallback(const TravelInfoCallback&) = delete ;
            TravelInfoCallback& operator=(const TravelInfoCallback&) = delete ;
            TravelInfoCallback(TravelInfoCallback&&) = delete ;
            TravelInfoCallback&& operator=(TravelInfoCallback&&) = delete ;
            ~TravelInfoCallback() noexcept = default ;
    } ;

}

#endif // TRAVEL_INFO_HPP

src/travel_info.cpp

#include <tuple>

#include "sdr_ros/TravelInfo.h" // message itself

#include "travel_info_callback.hpp"

/**
  * @brief This file contains defintions for callback functionality which processes travel_info ROS message
  */

sdr_ros::TravelInfoCallback::TravelInfoCallback() noexcept : _delta_x(0.f), _delta_y(0.f), _delta_z(0.f), _yaw(0.f), _pitch(0.f), _roll(0.f) {} ;

std::tuple<float, float, float> sdr_ros::TravelInfoCallback::distance() const noexcept
{
    return std::tuple<float, float, float>{
        this->_delta_x, this->_delta_y, this->_delta_z
    } ;
}

std::tuple<float, float, float> sdr_ros::TravelInfoCallback::heading() const noexcept
{
    return std::tuple<float, float, float>{
        this->_yaw, this->_pitch, this->_roll
    } ;
}

inline void sdr_ros::TravelInfoCallback::callback(const sdr_ros::TravelInfoConstPtr& travel_info) noexcept
{
    this->_delta_x = travel_info->delta_x ;
    this->_delta_y = travel_info->delta_y ;
    this->_delta_z = travel_info->delta_z ;
    this->_yaw = travel_info->yaw ;
    this->_pitch = travel_info->pitch ;
    this->_roll = travel_info->roll ;
}

src/sdr_ros (source code using callback)

#include <ros/ros.h>
#include <ros/console.h>
#include <ros/callback_queue.h>

#include <string>
#include <cmath>

#include <geometry_msgs/Pose.h>

#include "sdr_ros/TravelInfo.h"

#include "preprocessing.hpp"
#include "pose.hpp"
#include "travel_info_callback.hpp"

/**
  * @brief This file serves as the ROS node which reads from the network and calls relevant functionality to calculate and distribute pose information
  */

int main(int argc, char** argv)
{
    /* Initialisation */
    const std::string node_name = "sdr_ros" ;
    ros::init(argc, argv, node_name); ROS_INFO_STREAM(node_name << " running") ; // initialise ROS node
    ros::NodeHandle nh("~") ; // handle to ROS communications (topics, services)

    sdr::Pose pose ;
    std::string initial_pose_file ;
    if(nh.getParam("initial_pose_file", initial_pose_file))
    {
        pose = sdr::extract_initial_pose(initial_pose_file) ;
    }

    sdr_ros::TravelInfoCallback cb ; // callback object with methods
    ros::Subscriber sub = nh.subscribe<sdr_ros::TravelInfo>("/travel_info", 100, &sdr_ros::TravelInfoCallback::callback, &cb) ; // subscribe to topic distance_info

    geometry_msgs::Pose pose_msg ;
    ros::Publisher pub = nh.advertise<geometry_msgs::Pose>("/odometry", 1) ; // publishes information about where car as XYZ, orientation as quaternion

    /* Main functionality */
    while(ros::ok()) // while ROS is running - the actual useful computation
    {
        /* Get info */
        if(ros::getGlobalCallbackQueue()->callOne() == ros::CallbackQueue::CallOneResult::Empty) continue ;
        // ^ we can't simply use `ros::spinOnce` as there's no indication of an empty queue, meaning we'd be processing the same message multiple times, exponentially increasing predicted distance.

        const auto [delta_x, delta_y, delta_z] = cb.distance() ;
        if(!delta_x && !delta_y && !delta_z)
        {
            continue ; // no point processing odom when we haven't moved
        }
        const auto [yaw, pitch, roll] = cb.heading() ;

        pose.update_position(delta_x, delta_y, delta_z) ;
        pose.update_orientation(yaw, pitch, roll) ;

        pose_msg.position.x = pose.position()(0,0) ;
        pose_msg.position.y = pose.position()(0,1) ;
        pose_msg.position.z = pose.position()(0,2) ;
        pose_msg.orientation.x = pose.orientation().x() ;
        pose_msg.orientation.y = pose.orientation().y() ;
        pose_msg.orientation.z = pose.orientation().z() ;
        pose_msg.orientation.w = pose.orientation().w() ;

        ROS_INFO_STREAM("Current position: " << pose_msg.position) ;
        ROS_INFO_STREAM("Current orientation: " << pose_msg.orientation << '\n') ;

        /* Publish odometry */
        pub.publish(pose_msg) ;
    }

    /* E(nd) O(f) P(rogram) */
    return 0 ;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.2)
project(sdr_ros)

## Compile as C++20, supported in ROS Kinetic and newer
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(CMAKE_CXX_FLAGS "-Wall -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "-g")
set(CMAKE_CXX_FLAGS_RELEASE "-O0")

find_package(Eigen3 REQUIRED)

################################################
##    Find catkin macros and libraries        ##
################################################
find_package(catkin REQUIRED COMPONENTS
    roscpp
    rospy
    std_msgs
    tf
    nav_msgs
    genmsg
    message_generation
)

## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)

################################################
## Declare ROS messages, services and actions ##
################################################

## Generate messages in the 'msg' folder
add_message_files(
    DIRECTORY
        msg
    FILES
        TravelInfo.msg
)

## Generate services in the 'srv' folder
#add_service_files(
#    FILES
#)

## Generate added messages and services with any dependencies listed here
generate_messages(
    DEPENDENCIES
        std_msgs
        geometry_msgs
)

###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
#    INCLUDE_DIRS
#        include
#        ${EIGEN3_INCLUDE_DIR}
#        libraries/sdr/include/
    CATKIN_DEPENDS
        message_runtime
)

###########
## Build ##
###########

add_subdirectory(libraries/sdr)

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
    include
    libraries/sdr/include/
    ${EIGEN3_INCLUDE_DIR}
    ${catkin_INCLUDE_DIRS}
)

## Declare a C++ executable
add_library(travel_info_callback ${CMAKE_CURRENT_SOURCE_DIR}/src/travel_info_callback.cpp)
target_include_directories(travel_info_callback PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(travel_info_callback ${catkin_LIBRARIES})
add_dependencies(travel_info_callback sdr_ros_generate_messages_cpp)

add_executable(sdr_ros src/sdr_ros.cpp)
target_link_libraries(sdr_ros ${catkin_LIBRARIES} travel_info_callback detailed_exception.o preprocessing.o pose.o yaml-cpp)
add_dependencies(sdr_ros sdr_ros_generate_messages_cpp)

I hope I've given enough information and that someone can help. Much appreciated

Body:
Your message types are wrong. When setting up the subscriber you're giving it a type of sdr_ros::TravelInfo, however the callback definition takes in sdr_ros::TravelInfoConstPtr as a parameter. Instead in your callback you want the ConstPtr generated by the message so change the signature to

sdr_ros::TravelInfoCallback::callback(const sdr_ros::TravelInfo::ConstPtr& travel_info)


问:
Invalidation of the cache from L1 cache
Suppose that a cache line with variable X is simultaneously uploaded to L1d of CPU0 and L1d of CPU1. After changing the value of X from CPU0, when CPU1's L1d cache line is invalidated, Is it impossible for CPU1 to copy the variable X from CPU0's L1d cache if CPU0 has a cache line with X? And even if this is not the case, I want to know if there are cases where CPU0 brings in CPU1'</p>

答:
How would you copy from an L1 whose copy has been invalidated?  It no longer has a copy of the line.

But anyway, pretty sure the first place that gets checked after an L1d miss is the local L2, then shared L3.

On a Skylake-server or later (thus non-inclusive L3), I think an L3 miss would get reloaded from DRAM, unless the line was in Modified state in another core.

Otherwise, on client chips and earlier Xeons, an L3 miss is impossible if any core has a valid copy, because it's inclusive.  (Really old chips, before Nehalem, also didn't have inclusive last-level cache, e.g. Core2's L2)

See also Which cache mapping technique is used in intel core i7 processor?

When you say "If we invalidate the cache in one core", I'm not sure if you just mean having it evicted from that cache, e.g. to make room for something else, or if you mean running an instruction like clflush.  Or if you mean that core did a store and thus had to do a Read For Ownership (RFO) to get MESI exclusive ownership of the line (i.e. invalidate all other copies) so it can commit a store from the store buffer to L1d.

Title: Invalidation of the cache from L1 cache


问:
Azure Service Principal create new certificate with PowerShell
How can i create a new certificate for my service principal in azure with powershell?

答:
Have you referred to the online documentation already? This gives a step by step process using powershell.

This is creating a self signed certificate but for production, you should get one which is signed by a Certificate Authority(CA) LINK.


问:
TeleBot how to use bot.polling and other functions
When I use bot.polling() the timed_messages never get called
is there a way to make this thing work
that way I can look for sent messages and send a timed automatic message</p>
```<code>import telebot
import cryptocompare
from datetime import datetime

API_KEY = ""
bot = telebot.TeleBot(API_KEY)

@bot.message_handler(regexp="bitcoin")
def bitcoin(message):
    price = cryptocompare.get_price('BTC', 'USD')
    bot.reply_to(message, price['BTC']['USD'])

def timed_messages(prices, current_time):
    if current_time == "9:00:00":
        bot.send_message(-1001236909935, "Good Morning (9:00): \n" + prices)
    if current_time == "12:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (12:00): \n" + prices)
    if current_time == "15:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (15:00): \n" + prices)
    if current_time == "18:00:00":
        bot.send_message(-1001236909935, "Good Evening (18:00): \n" + prices)
    if current_time == "00:00:00":
        bot.send_message(-1001236909935, "Good Night (00:00): \n" + prices)

if __name__ == '__main__':
    while True:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
        timed_messages(prices, current_time)
        bot.polling()

</code>```

答:
You can use asyncio to achieve what you want.

import it first

import asyncio
```
<p>Then change your code like this:</p>
<pre class="lang-py prettyprint-override"><code>async def timed_messages_worker():
    while True:
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
            timed_messages(prices, current_time)
            await asyncio.sleep(1)

asyncio.create_task(timed_messages_worker)
asyncio.get_event_loop().run_until_complete(bot.polling())
</code>```

Body:
When I use bot.polling() the timed_messages never get called
is there a way to make this thing work
that way I can look for sent messages and send a timed automatic message

import telebot
import cryptocompare
from datetime import datetime

API_KEY = ""
bot = telebot.TeleBot(API_KEY)

@bot.message_handler(regexp="bitcoin")
def bitcoin(message):
    price = cryptocompare.get_price('BTC', 'USD')
    bot.reply_to(message, price['BTC']['USD'])

def timed_messages(prices, current_time):
    if current_time == "9:00:00":
        bot.send_message(-1001236909935, "Good Morning (9:00): \n" + prices)
    if current_time == "12:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (12:00): \n" + prices)
    if current_time == "15:00:00":
        bot.send_message(-1001236909935, "Good Afternoon (15:00): \n" + prices)
    if current_time == "18:00:00":
        bot.send_message(-1001236909935, "Good Evening (18:00): \n" + prices)
    if current_time == "00:00:00":
        bot.send_message(-1001236909935, "Good Night (00:00): \n" + prices)

if __name__ == '__main__':
    while True:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
        timed_messages(prices, current_time)
        bot.polling()

Body:
You can use asyncio to achieve what you want.

import it first

import asyncio

Then change your code like this:

async def timed_messages_worker():
    while True:
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            prices = "Bitcoin: " + str(1) + "\n" + "DogeCoin: " + str(2) + "\n" + "HNT: " + str(3)
            timed_messages(prices, current_time)
            await asyncio.sleep(1)

asyncio.create_task(timed_messages_worker)
asyncio.get_event_loop().run_until_complete(bot.polling())


问:
How can this warning of InteropServices.SEHException be real?
I prevent unmanaged C++ exceptions from escaping from my C++/CLI code by wrapping unmanaged calls with exception frames where I catch const std::exception&.  But I've got a code-path in which the unmanaged C++ throw immediately triggers a warning of SEHException, even though there is clearly a catch clause higher up the stack frame in C++/CLI to intercept it.

I do not understand where the SEHException can be happening.  I am wondering if it is real at all.

Here is the C++ code throwing the exception way down in the call stack.

```<code>StringMap ParseTopLevelMap(std::istream& in)
{
    StringMap yamlmap;
    if (!TryParseTopLevelMap(in, yamlmap))
        throw std::runtime_error("Unable to parse map");  // Causes SEHException warning.

    return yamlmap;
}
</code>```

The moment I make the throw above, I immediately get this output in the output window:

```<code>Exception thrown: 'System.Runtime.InteropServices.SEHException' in MyCompany.Sdk_v143.dll
</code>```

But I very clearly have a catch(const std::exception& ex) higher up in the call frame in C++/CLI and it does get invoked. Here it is (Note that catch)

```<code>bool ScanContext::TryLoad(GsScan^ scan, String^ path, [SRI::Out]ScanContext^% ctx)
{
    try
    {
        ctx = nullptr;
        auto sPath= ToSdk(name);
        ctx =  gcnew ScanContext(scan, gs::LoadScanContext(scan->sdkScan(), sPath));
    }
    catch (const std::exception& ex)
    {
        std::cerr << ex.what() << std::endl;     // This DOES execute
    }

    return ctx != nullptr; // If we did not throw, this is non-null and we succeeded.
}
</code>```

So the catch clause above does get invoked,  the error output message gets dumped, and control returns normally back to my managed C# code that called into the C++/CLI.

So where did the SEHException go?

To double-check, I set the Exceptions dialog to actually break on SEHException.  And it sure did.
This is the call stack at the point it breaks.   My C++ code is in the process of throwing std::runtime_error

```<code>    ntdll.dll!NtWaitForSingleObject()   Unknown
    KernelBase.dll!WaitForSingleObjectEx()  Unknown
    ntdll.dll!RtlpExecuteHandlerForException()  Unknown
    ntdll.dll!RtlDispatchException()    Unknown
    ntdll.dll!KiUserExceptionDispatch() Unknown
    KernelBase.dll!RaiseException() Unknown
>   vcruntime140d.dll!_CxxThrowException(void * pExceptionObject, const _s__ThrowInfo * pThrowInfo) Line 75 C++
    gscored_v143.dll!gs::detail::YAML::ParseTopLevelMap(std::basic_istream<char,std::char_traits<char>> & in) Line 298  C++
    gscored_v143.dll!gs::ScanContext::loadContent(std::basic_istream<char,std::char_traits<char>> & is, const std::string & loadFolder) Line 172    C++
    gscored_v143.dll!gs::ScanContext::loadContent(std::basic_istream<char,std::char_traits<char>> & is) Line 63 C++
    gscored_v143.dll!gs::ScanContext::Load(const std::shared_ptr<gs::Scan> & scan, const std::string & name) Line 884   C++
    gscored_v143.dll!gs::LoadScanContext(const std::shared_ptr<gs::Scan> & scan, const std::string & name) Line 310 C++
    [Managed to Native Transition]
    MyCompany.Sdk_v143.dll!MyCompany::Sdk::ScanContext::TryLoad(MyCompany::Sdk::Scan^ scan, System::String^ name, MyCompany::Sdk::ScanContext^% ctx) Line 660   C++
    MyCompany.Services.dll!MyCompany.Services.ScanService.GetScanContext(MyCompany.Sdk.Scan scan, string name) Line 1725    C#

</code>```

Is this all just a false warning?

答:
Interesting.

It's not at all obvious from the documentation exactly what's going on here, but there's an interesting article over at Code Project which explains how (unmanaged) C++ exceptions are handled by the Microsoft compiler.  Basically, when you call throw an SEH exception is generated (via RaiseException) which is then caught and mapped to a C++ exception by the runtime library.

The question now is how that is mapped to a managed C++ exception so that you can catch it in managed code, and the mechanics behind that is not at all clear, but SEHException obviously fits into it somehow.

Perhaps the .NET framework catches your unmanaged throw via its own try ... catch block and calls RaiseException again with a different exception code (one that corresponds to / results in an SEHException), and that's what you're trapping in the debugger.  It then catches that (via __try ... __except) and uses some sort of magic to generate a managed code exception.  Something like that, anyway.

As for whether you need to be concerned about this, the documentation goes on to say:

Note that the SEHException class does not cause unmanaged C++ exception destructors to be called. To ensure that unmanaged C++ exception destructors are called, use the following syntax in the catch block.

```<code>C#
catch
{
     // Handle catch here.
}
</code>```

Now I'm really not sure what they mean by 'C++ exception destructors' (I didn't know there was such a thing) but it may be that yamlmap doesn't get properly destroyed.  I'd be surprised if that were true, but it might be worth checking.  It also doesn't make sense to me to handle the exception in managed code.  Maybe that's just a typo.

Returning to that Code Project article, it cites the fact that the exception code for the SEH exception raised by an unmanaged C++ throw is 0xE06D7363.  If you break on that, you might learn a bit more about all this.  And then again, maybe not.

Body:
I prevent unmanaged C++ exceptions from escaping from my C++/CLI code by wrapping unmanaged calls with exception frames where I catch const std::exception&.  But I've got a code-path in which the unmanaged C++ throw immediately triggers a warning of SEHException, even though there is clearly a catch clause higher up the stack frame in C++/CLI to intercept it.

I do not understand where the SEHException can be happening.  I am wondering if it is real at all.

Here is the C++ code throwing the exception way down in the call stack.

StringMap ParseTopLevelMap(std::istream& in)
{
    StringMap yamlmap;
    if (!TryParseTopLevelMap(in, yamlmap))
        throw std::runtime_error("Unable to parse map");  // Causes SEHException warning.

    return yamlmap;
}

The moment I make the throw above, I immediately get this output in the output window:

Exception thrown: 'System.Runtime.InteropServices.SEHException' in MyCompany.Sdk_v143.dll

But I very clearly have a catch(const std::exception& ex) higher up in the call frame in C++/CLI and it does get invoked. Here it is (Note that catch)

bool ScanContext::TryLoad(GsScan^ scan, String^ path, [SRI::Out]ScanContext^% ctx)
{
    try
    {
        ctx = nullptr;
        auto sPath= ToSdk(name);
        ctx =  gcnew ScanContext(scan, gs::LoadScanContext(scan->sdkScan(), sPath));
    }
    catch (const std::exception& ex)
    {
        std::cerr << ex.what() << std::endl;     // This DOES execute
    }

    return ctx != nullptr; // If we did not throw, this is non-null and we succeeded.
}

So the catch clause above does get invoked,  the error output message gets dumped, and control returns normally back to my managed C# code that called into the C++/CLI.

So where did the SEHException go?

To double-check, I set the Exceptions dialog to actually break on SEHException.  And it sure did.
This is the call stack at the point it breaks.   My C++ code is in the process of throwing std::runtime_error

    ntdll.dll!NtWaitForSingleObject()   Unknown
    KernelBase.dll!WaitForSingleObjectEx()  Unknown
    ntdll.dll!RtlpExecuteHandlerForException()  Unknown
    ntdll.dll!RtlDispatchException()    Unknown
    ntdll.dll!KiUserExceptionDispatch() Unknown
    KernelBase.dll!RaiseException() Unknown
>   vcruntime140d.dll!_CxxThrowException(void * pExceptionObject, const _s__ThrowInfo * pThrowInfo) Line 75 C++
    gscored_v143.dll!gs::detail::YAML::ParseTopLevelMap(std::basic_istream<char,std::char_traits<char>> & in) Line 298  C++
    gscored_v143.dll!gs::ScanContext::loadContent(std::basic_istream<char,std::char_traits<char>> & is, const std::string & loadFolder) Line 172    C++
    gscored_v143.dll!gs::ScanContext::loadContent(std::basic_istream<char,std::char_traits<char>> & is) Line 63 C++
    gscored_v143.dll!gs::ScanContext::Load(const std::shared_ptr<gs::Scan> & scan, const std::string & name) Line 884   C++
    gscored_v143.dll!gs::LoadScanContext(const std::shared_ptr<gs::Scan> & scan, const std::string & name) Line 310 C++
    [Managed to Native Transition]
    MyCompany.Sdk_v143.dll!MyCompany::Sdk::ScanContext::TryLoad(MyCompany::Sdk::Scan^ scan, System::String^ name, MyCompany::Sdk::ScanContext^% ctx) Line 660   C++
    MyCompany.Services.dll!MyCompany.Services.ScanService.GetScanContext(MyCompany.Sdk.Scan scan, string name) Line 1725    C#

Is this all just a false warning?

Body:
Interesting.

It's not at all obvious from the documentation exactly what's going on here, but there's an interesting article over at Code Project which explains how (unmanaged) C++ exceptions are handled by the Microsoft compiler.  Basically, when you call throw an SEH exception is generated (via RaiseException) which is then caught and mapped to a C++ exception by the runtime library.

The question now is how that is mapped to a managed C++ exception so that you can catch it in managed code, and the mechanics behind that is not at all clear, but SEHException obviously fits into it somehow.

Perhaps the .NET framework catches your unmanaged throw via its own try ... catch block and calls RaiseException again with a different exception code (one that corresponds to / results in an SEHException), and that's what you're trapping in the debugger.  It then catches that (via __try ... __except) and uses some sort of magic to generate a managed code exception.  Something like that, anyway.

As for whether you need to be concerned about this, the documentation goes on to say:

Note that the SEHException class does not cause unmanaged C++ exception destructors to be called. To ensure that unmanaged C++ exception destructors are called, use the following syntax in the catch block.

C#
catch
{
     // Handle catch here.
}

Now I'm really not sure what they mean by 'C++ exception destructors' (I didn't know there was such a thing) but it may be that yamlmap doesn't get properly destroyed.  I'd be surprised if that were true, but it might be worth checking.  It also doesn't make sense to me to handle the exception in managed code.  Maybe that's just a typo.

Returning to that Code Project article, it cites the fact that the exception code for the SEH exception raised by an unmanaged C++ throw is 0xE06D7363.  If you break on that, you might learn a bit more about all this.  And then again, maybe not.


问:
CSS - why doesn't :hover parent hide child elements
I have a navigation bar with images, like so:

```<code><ul>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
</ul>
</code>```

On hovering over a list item I want to change the background color to cover the span and image like so:

```<code>.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}
</code>```

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

```<code><ul>
  <li>
   <a href="" class="ui-btn">
     <span class="ui-btn-inner"> /* CONTAINS IMAGE AS BACKGROUND */
        <span class="ui-btn-text">text</span>  /* GETS BACKGROUND */
        <span class="ui-icon"></span>
     </span>
   </a>
 </li>
</ul>
</code>```

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

答:
another potential option that should be more cross browser than :after could be:</p>

```<code>.me:hover span { display: hidden; }
</code>```

Body:
I have a navigation bar with images, like so:

On hovering over a list item I want to change the background color to cover the span and image like so:

.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

      /* CONTAINS IMAGE AS BACKGROUND */
        text  /* GETS BACKGROUND */

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

Body:
another potential option that should be more cross browser than :after could be:

.me:hover span { display: hidden; }


问:
Grafana does not see loki (docker-compose setup)
I am trying to log my application into grafana/loki/promtail using the same docker compose ,and I get the following error when connecting to loki :

localhost:3100 -> 404 page not found

and when i try to hook it in grafana :

URL [http://loki:3100 ]-> Loki: Bad Gateway. 502. Bad Gateway

I have seen that you have to put in grafana the name of the container for it to detect it but I get the same error.

Both promtail and loki containers show no errors in their logs.

```<code>version: "3.7"

services:
my-service-to-log:
    image: example:latest
    ports:
      - "8080:8080"
      - "8443:8443"
 loki:
    image: grafana/loki:2.4.1
    ports:
      - "3100:3100"
    volumes:
      - "C:/path/loki-config.yaml:/etc/loki/local-config.yaml"
    command: -config.file=/etc/loki/local-config.yaml

   promtail:
    image: grafana/promtail:2.4.1
    volumes:
      - "C:/path/promtail-config.yaml:/etc/promtail/config.yml"
      - /var/log:/var/log
    command: -config.file=/etc/promtail/config.yml

   grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
</code>```

My loki-config.yaml

```<code>auth_enabled: false

server:
  http_listen_port: 3100
  grpc_listen_port: 9096

common:
  path_prefix: /tmp/loki
  storage:
    filesystem:
      chunks_directory: /tmp/loki/chunks
      rules_directory: /tmp/loki/rules
  replication_factor: 1
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory

schema_config:
  configs:
    - from: 2020-10-24
      store: boltdb-shipper
      object_store: filesystem
      schema: v11
      index:
        prefix: index_
        period: 24h

ruler:
  alertmanager_url: http://localhost:9093

</code>```

And my promtail-config.yaml

```<code>server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki:3100/loki/api/v1/push

scrape_configs:
- job_name: system
  static_configs:
  - targets:
      - localhost
    labels:
      job: varlogs
      __path__: /opt/app/logs/*.log
</code>```

/ # nc -vz localhost 3100
localhost (127.0.0.1:3100) open
```

I have tried to nc from the grafana container to the loki container and it seems to see it .... any ideas ?

答:
Loki needs to listen on all interfaces, not just localhost, when you want to access it from another container:

common:
  path_prefix: /tmp/loki
  storage:
    filesystem:
      chunks_directory: /tmp/loki/chunks
      rules_directory: /tmp/loki/rules
  replication_factor: 1
  ring:
    instance_addr: 0.0.0.0
    kvstore:
      store: inmemory
```

Body:
I am trying to log my application into grafana/loki/promtail using the same docker compose ,and I get the following error when connecting to loki :

localhost:3100 -> 404 page not found

and when i try to hook it in grafana :

URL [http://loki:3100 ]-> Loki: Bad Gateway. 502. Bad Gateway

I have seen that you have to put in grafana the name of the container for it to detect it but I get the same error.

Both promtail and loki containers show no errors in their logs.

version: "3.7"

services:
my-service-to-log:
    image: example:latest
    ports:
      - "8080:8080"
      - "8443:8443"
 loki:
    image: grafana/loki:2.4.1
    ports:
      - "3100:3100"
    volumes:
      - "C:/path/loki-config.yaml:/etc/loki/local-config.yaml"
    command: -config.file=/etc/loki/local-config.yaml

   promtail:
    image: grafana/promtail:2.4.1
    volumes:
      - "C:/path/promtail-config.yaml:/etc/promtail/config.yml"
      - /var/log:/var/log
    command: -config.file=/etc/promtail/config.yml

   grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"

My loki-config.yaml

auth_enabled: false

server:
  http_listen_port: 3100
  grpc_listen_port: 9096

common:
  path_prefix: /tmp/loki
  storage:
    filesystem:
      chunks_directory: /tmp/loki/chunks
      rules_directory: /tmp/loki/rules
  replication_factor: 1
  ring:
    instance_addr: 127.0.0.1
    kvstore:
      store: inmemory

schema_config:
  configs:
    - from: 2020-10-24
      store: boltdb-shipper
      object_store: filesystem
      schema: v11
      index:
        prefix: index_
        period: 24h

ruler:
  alertmanager_url: http://localhost:9093

And my promtail-config.yaml

server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /tmp/positions.yaml

clients:
  - url: http://loki:3100/loki/api/v1/push

scrape_configs:
- job_name: system
  static_configs:
  - targets:
      - localhost
    labels:
      job: varlogs
      __path__: /opt/app/logs/*.log

/ # nc -vz localhost 3100
localhost (127.0.0.1:3100) open

I have tried to nc from the grafana container to the loki container and it seems to see it .... any ideas ?


问:
Spark SQL passing a variable
I have following Spark sql and I want to pass variable to it. How to do that? I tried following way.</p>

```<code> sqlContext.sql("SELECT count from mytable WHERE id=$id")
</code>```

答:
You could use a concatenation, with this the engine understands the query, I leave an example:

First:

In a variable inserts the value to pass in the query (in this case is a date)

```<code>date= spark.range(1).withColumn('date',regexp_replace(date_add(current_date(),-4),"-","")).toPandas().to_string().split()[4]
</code>```

Result = '20220206'

Second:

```<code>query = '''
SELECT
    *
FROM
    table
WHERE
    country = '''+' '+date+'''
'''
df= spark.sql(query)
</code>```

Title: Spark SQL passing a variable

Body:
I have following Spark sql and I want to pass variable to it. How to do that? I tried following way.

 sqlContext.sql("SELECT count from mytable WHERE id=$id")

Body:
You could use a concatenation, with this the engine understands the query, I leave an example:

First:

In a variable inserts the value to pass in the query (in this case is a date)

date= spark.range(1).withColumn('date',regexp_replace(date_add(current_date(),-4),"-","")).toPandas().to_string().split()[4]

Result = '20220206'

Second:

query = '''
SELECT
    *
FROM
    table
WHERE
    country = '''+' '+date+'''
'''
df= spark.sql(query)


问:
How to make an alert dialog fill 90% of screen size?
I can create and display a custom alert dialog just fine but even so I have android:layout_width/height="fill_parent" in the dialog xml it is only as big as the contents.

What I want is dialog that fills the entire screen except maybe a padding of 20 pixel.
Then the image that is part of the dialog would automatically stretch to the full dialog size with fill_parent.

答:
I found very simple and easy to use a workaround</p>
```<code>    fun showDialog(){
    val dialog = Dialog(this@DialogActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.custom_dialog)
    val txtTitle = dialog.findViewById<TextView>(R.id.txtTitle)
    val btn  = dialog.findViewById<Button>(R.id.button)

    btn.setOnClickListener {
        Toast.makeText(this,"test",Toast.LENGTH_SHORT).show()
    }
    txtTitle.setText("ali")
    dialog.show()

    val window = dialog.window
    window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT)
}
</code>```

Body:
I found very simple and easy to use a workaround

    fun showDialog(){
    val dialog = Dialog(this@DialogActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.custom_dialog)
    val txtTitle = dialog.findViewById<TextView>(R.id.txtTitle)
    val btn  = dialog.findViewById<Button>(R.id.button)

    btn.setOnClickListener {
        Toast.makeText(this,"test",Toast.LENGTH_SHORT).show()
    }
    txtTitle.setText("ali")
    dialog.show()

    val window = dialog.window
    window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT)
}


问:
How do you control variables in a python script using a separate python script?
I have a main python code with variables that I wish to control from a separate python script. I get a name error message and I am unsure how to resolve this. Has anyone encountered a similar challenge? How can I control the variable n from a separate python script?

```<code>from main import *
npart = 5

NameError                                 Traceback (most recent call last)
Input In [12], in <module>
----> 1 from main import *
      2 npart = 5

File ~/main.py:91, in <module>
     88 latmin = 45.977778
     89 latmax = 45.931389
---> 91 npart = n  # number of particles to be released
     92 for i in range(n):
     93     lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)

NameError: name 'n' is not defined
</code>```

The main code that I am trying to control looks like this.
main.py. Here I type in 5 so the code will run without error. I would like to call it a variable n here. In the separate code define n = 5 and reproduce the results.

```<code>import random
x = []
y = []

lonmin = -63.226111
lonmax = -63.229722
latmin = 45.977778
latmax = 45.931389

npart = 5  # number of particles to be released
for i in range(5):
    lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
    x.append(lon)
    lat = latmin + random.uniform(0, 1)*(latmax-latmin)
    y.append(lat)

print(x, y)
</code>```

答: It's because you never declared the variable n in your file main.py</p>

Body:
I have a main python code with variables that I wish to control from a separate python script. I get a name error message and I am unsure how to resolve this. Has anyone encountered a similar challenge? How can I control the variable n from a separate python script?

from main import *
npart = 5

NameError                                 Traceback (most recent call last)
Input In [12], in <module>
----> 1 from main import *
      2 npart = 5

File ~/main.py:91, in <module>
     88 latmin = 45.977778
     89 latmax = 45.931389
---> 91 npart = n  # number of particles to be released
     92 for i in range(n):
     93     lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)

NameError: name 'n' is not defined

The main code that I am trying to control looks like this.
main.py. Here I type in 5 so the code will run without error. I would like to call it a variable n here. In the separate code define n = 5 and reproduce the results.

import random
x = []
y = []

lonmin = -63.226111
lonmax = -63.229722
latmin = 45.977778
latmax = 45.931389

npart = 5  # number of particles to be released
for i in range(5):
    lon = lonmin + random.uniform(0, 1)*(lonmax-lonmin)
    x.append(lon)
    lat = latmin + random.uniform(0, 1)*(latmax-latmin)
    y.append(lat)

print(x, y)