text:
Q: How to detect if polygons overlap in leaflet I am using leaflet draw to create polygons.
My requirement is when a user draws a polygon ,it should not intersect/overlap with existing polygons.
I have used point in polygon leaflet to detect if point falls within the polygon and it is working,
but the problem is i am not able to detect if a line crosses another polygons.In this case points lie outside the existing polygons but overlapping exists.
Below attached image can give a better picture!

A: You can also probably use Turf.js. Turf is a new js GIS engine developed by the guys at Mapbox.
Here are few examples that may do the job:

*

*Turf Intersects

*Turf Overlaps

A: In leaflet.draw, you can pass options to individual draw handlers. One of them allowIntersection is a boolean type that "Determines if line segments can cross."
Your options would look something like this (excerpted from the leaflet.draw example config):
var options = {
    position: 'topright',
    draw: {
        polygon: {
            allowIntersection: false, // Restricts shapes to simple polygons
            drawError: {
                color: '#e1e100', // Color the shape will turn when intersects
                message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
            },
            shapeOptions: {
                color: '#bada55'
            }
        },
    },
    edit: {
        featureGroup: editableLayers, //REQUIRED!!
        remove: false
    }
};

var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);

A: You can probably also use Terraformer Core, which is an open-source project done by the folks at ESRI. You would probably do something like this:

var polygon = new Terraformer.Primitive({
  "type": "Polygon",
  "coordinates": [ [ [ -101.46972656250001, 34.125447565116126 ],
                     [ -100.85449218750001, 33.760882000869195 ],
                     [ -101.09619140625, 33.19273094190692 ],
                     [ -102.12890625000001, 33.137551192346145],
                     [ -102.19482421875, 33.63291573870479 ],
                     [ -101.46972656250001, 34.125447565116126 ] ] ] });
var intersects = polygon.intersects({
  "type": "Polygon",
  "coordinates": [ [ [ -103.32539, 30.58608 ], [ -102.32083, 29.87894 ], [ -103.32539, 30.58608 ] ] ] });
// intersects is a bool.


text:
Q: hive ngram stopword list? While listed as one of the example use cases ... I haven't found an example of filtering out junk words (and, or, etc) from a Hive n-gram.
SELECT explode(context_ngrams(sentences(lower(description)), array("criminal", null), 10)) AS x FROM mapped_discussions;

{"ngram":["justice"],"estfrequency":274.0}
{"ngram":["behavior"],"estfrequency":121.0}
{"ngram":["law"],"estfrequency":92.0}
{"ngram":["activity"],"estfrequency":69.0}
{"ngram":["acts"],"estfrequency":41.0}
{"ngram":["procedure"],"estfrequency":35.0}
{"ngram":["and"],"estfrequency":29.0}
{"ngram":["or"],"estfrequency":27.0}
{"ngram":["case"],"estfrequency":26.0}
{"ngram":["cases"],"estfrequency":25.0}

Any ideas?  Thanks!

A: There is an excellent post on this topic here. http://bigdatabloggin.blogspot.com/2012/08/trending-topics-in-hive-ngrams.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disqus: get thread ID or URL to show comments on a separate page Instead of showing comments right on the page I want to put a link to the corresponding thread page on disqus.com. Two questions:

*

*How to get the Disqus thread ID (or thread URL) for a page?**

*Is it possible to create such a page if no comments were previously posted into the thread?**

Explanational info:
Disqus has a separate page for each website where you can see all commented pages:
https://disqus.com/home/forum/%SITENAME%/, where %SITENAME% is a forum name used by Disqus for you website.
Each commented(!) page there has it's own URL like this: https://disqus.com/home/forum/%SITENAME%/__1234/ where __1234 is an example of an internal ID (thread ID?) Disqus uses. Note, that this is NOT a page ID set via JS variable this.page.identifier.

A: This is the solution I ended up with.
1. How to get the Disqus thread ID (or thread URL) for a page?
They call it a thread slug. It could be taken form threads/detail endpoint. See the docs here: https://disqus.com/api/docs/threads/details/
Here is the jQuery ajax code example:
$.ajax({
    type: 'GET',
    url: "https://disqus.com/api/3.0/threads/details.json", // API endpoint
    data: {
        api_key: '%YOUR_API_KEY%',
        forum : '%YOUR_FORUM_NAME%',
        thread: 'ident:%PAGE_IDENTIFIER%', // get thread by identifier
        thread: 'link:' + %PAGE_URL%,        // OR get thread by page url
    },
    cache: false,
    dataType: 'jsonp', // for cross-domain requests
    success: function (result) {
        var slug = result.response.slug; //this will contain the thread slug

        // let's update the link somewhere on the page
        $('.disqus-comments-link')
             .attr('href','https://disqus.com/home/discussion/%YOUR_FORUM_NAME%/' + slug + '/');
    }
});

2. Is it possible to create a thread if no comments were previously posted?
It is more complicated. If you will use the code above for the page where Disqus scripts were never run, the thread slug will be empty since it needs to be created first.
Thread page could be created in two ways:

*

*By running Disqus initialisation scripts on a page at least once.

*Manually via threads/create API endpoint. It requires authentication and currently is in beta. See docs here: https://disqus.com/api/docs/threads/create/
Result: Instead of creating the thread manually, I just run the Disqus initialisation script and then get the thread slug via API. That's it.


text:
Q: Avoid loop in computing running average/statistics over a column I would like to speed up the following (PostgreSQL) code, and I speculate it would help by getting rid of (some of) the loops, but I do not see a way to do that. Any suggestion on speed-up is welcomed. Thanks in advance!
The code computes some statistics (mean, slope) for each columns at different portions. The portion is determined by a sliding time window (say of 60mins). So the code below

*

*loops through different columns which I am interested in computing their statistics

*for each column, I sequentially move my time window and compute the statistics of the values in that window.

for col_name in ..... a list of column names
truncate small_table;           -- where statistics are temporarily stored
for cur in select time from big_table loop
    execute 'select regr_slope('|| col_name ||', time) as slope,'
        || ' avg(' || col_name || ') as mean'
        || ' from big_table where'
        || ' time <=' || cur.time
        || ' and time >=' || cur.time-60
        into result;

    execute 'insert into small_table values($1,$2,$3)'
        using cur.time, result.slope, result.mean;
end loop;

execute 'update big_table set '
    || col_name || '_slope = small_table.slope, '
    || col_name || '_mean = small_table.mean '
    || ' where big_table.time=small_table.time';
end loop;

small_table, where results are temporarily stored, is introduced to avoid multiple updates on the big_table.
small_table and big_table have the same structure, but the small table has much less rows.
Columns of the two tables are
time | field_1 | field_2 | field_1_slope | field_1_mean | field_2_slope | field_2_mean
There are actually quite a few columns (~50), which maybe another factor of slowdown?

A: If you generate the following pattern of SQL dynamically, you can at least perform all this in one query. I'm not sure whether it will perform any better, though (obviously you need to loop through all the columns and add those in). I'd test the performance before I worry about building the SQL in code.
Update
    big_table b
Set
    field1_slope = x.field1_slope,
    field1_mean = x.field1_mean,
    field2_slope = x.field2_slope,
    field2_mean = x.field2_mean
From (
    Select
        b1.time,
        regr_slope(b2.field1, b2.time) field1_slope,
        avg(b2.field1) field1_mean,
        regr_slope(b2.field2, b2.time) field2_slope,
        avg(b2.field2) field2_mean
    From
        big_table b1
            Inner Join
        big_table b2
            On b2.time >= b1.time and b2.time < b1.time + 60
    Group By
        b1.time
    ) x
Where
    b.time = x.time;

I'm not overly familiar with PostgreSQL, there may be a way to eliminate one of the references to big table.
Example SQL Fiddle
Another way with cursors


text:
Q: Writing ISO8859 data to MySQL in R (error:"could not run statement: Invalid utf8 character string") I need to import an SAS Transfer File (.xpt) to MySQL.
Because I don't own SAS, I tried
a) first importing the .xpt in R
b) then using dbWriteTable from the library RMySQL to create a table from the data frame.
The problem is that the data frame contains ISO8859 characters and MySQL (or dbWriteTable?) expects UTF-8.
(Detail: Precisely a degree character, which is B0 in ISO8859 and C2B0 in UTF8)
I receive the following output:
dbWriteTable(con,"new_table",mydata,overwrite=T)
Fehler in .local(conn, statement, ...) :
  could not run statement: Invalid utf8 character string: 'Hallo'>
So I tried converting the data with iconv like iconv(mydata,"ISO8859-1","UTF8"), but it only seems to work vice-versa (it correctly converts UTF8 to ISO8859, but not the other way round).
Then I was trying a lot with
SET character_set_client = latin1;
SET character_set_results = latin1;
SET character_set_connection = latin1;

but without any luck.
Any help would be so appreciated

A: I found a workaround I want to share:
As iconv only works UTF8->ISO8859, this is no use, but you can:

*

*write the data frame to a temp file using fileEncoding="utf8"

*read it back

*then use dbWriteTable

write.table(mydata,file="tmp.txt", fileEncoding ="utf8")
  mydata_utf8 <- read.table(file="tmp.txt",encoding="utf8")
  dbWriteTable(con,"new_table",mydata_utf8,overwrite=T)


text:
Q: How to create a shell script which can create a .java file on executing? The requirement is to create a shell script that can create a FileName.java file where FileName would be the parameter passed to the script while running the script.
Example:
$ ./shellscript.sh Sample

On executing the above command, a file Sample.java should get created with content:
class Sample{
   public static void main(String[] args){
      for(int i=0;i<10;i++){
      System.out.println("Hello World !!!");
   }
}

If sources for learning bash scripting is added in the answer it would be very helpful.

A: You just need to make a "template", something like:
classTemplate.txt
class #ClassName{
   public static void main(String[] args){
      for(int i=0;i<10;i++){
      System.out.println("Hello World !!!");
   }
}

After that, you just need to replace #ClassName with your parameter
#create .java file
cp classTemplate.txt classTemplate.java
#set class name
sed -i 's/#ClassName/MyClass/g' classTemplate.java

A: Here-docs will expand variables, so
NAME=$1
cat << EOF > $NAME.java
class $NAME{
   public static void main(String[] args){
      for(int i=0;i<10;i++){
      System.out.println("Hello World !!!");
   }
}
EOF

A: The following book is a good reference:
https://www.amazon.com/Bash-Pocket-Reference-Power-Admins/dp/1491941596
I would just continue to use stackoverflow and google. This is what has helped me most, since I can search for specific solutions to what I am trying to do. In stackoverflow, you can also run your code and proposed solution by other people and find improved solutions. This is extremely valuable.


text:
Q: R Shiny: Use input in inline commands I just started to use shiny and I am currently trying to embed widgets in R markdown. I already have a working markdown, and I'm trying to adapt it to a selection box. I followed some tutorials but I think I missed something.
My dataset contains species observations within sites. Here's my code:
```{r echo=FALSE}
selectInput("region", "Reserve :",
                    choices=colnames(DF)) #Here i select my site in my dataset DF

shinyServer(function(input, output) {
  v <- reactive({
           as.character(unique(input$region))})
  })
```

Then I have a sentence where I want my site name to apear  inline reactively with the site selection box:
Site name: ``r v`
However, I get "v not found". Seems like I can't access it directly to input$region either.
How can I access to my site name and return it as a character string?
Thanks for your help!


text:
Q: Android onCreateOptionsMenu is not displaying In my android activity, i removed the Action Bar by using this Theme
 <style name="Theme.NoTitle" parent="@android:style/Theme.NoTitleBar"></style>

but my problem is "onCreateOptionsMenu" is not display, I tried this method to create
that pls see
 private void getOverflowMenu()
    {

        try
            {
                ViewConfiguration config = ViewConfiguration.get(Home.this);
                Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
                if (menuKeyField != null)
                    {
                        menuKeyField.setAccessible(true);
                        menuKeyField.setBoolean(config , false);
                    }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
    }

in this  "onCreateOptionsMenu" is not displaying. please help me
but it displaying in Samsung
Because: in Samsung mobile has its own hardware menu button, but not in nexus etc
please see the image

A: finally i got the answer
in my AndroidManifest.xml i just removed this line
   android:targetSdkVersion="18"

A: If you don't have action bar and neither a menu button (on most devices) where do you want to display your menu??
The easiest way is to use PopupMenu. Add a button somewhere in your layout and on the click even add the PopupMenu (Dropdown menu). If you want to use it for devices starting Android 2.1 use a Support Library.
You have HERE the android documentation about PopupMenu.
From SDK Manager you can download and see the support library v7 sample which includes PopupMenuHelper.
Hope it helps. Good Luck!


text:
Q: Autocomplete = "off" cross browser functionality I have a website where I have some functionality needed:

*

*No autocompletion, suggestions or saving on my site:

*

*No form Fields should ever be auto-completed or have drop Down suggestions based on earlier input

*No form data (entries) should be saved/cached in the browser

*Prevent "spilling" to other sites:

*

*When visiting other websites, data from my site should not appear as suggestions in the forms (ref 1b).

Up until now I have accomplished this by using autocomplete = "off" on all forms. Based on  this link from Mozilla  this should originally have the effect of solving all the issues above, but some browsers are now starting to ignore the autocomplete attribute. The article referred to above states that the trick is to assign an invalid value to the attribute, such as autcomplete = "nope"
My questions are:

Q1: Will the solution of using autocomplete = "nope" also prevent caching/saving the data?
Q2: Are there better solutions to accomplish my criteria for best cross-browser compatibility? (I have searched, but not found anything that gives me Clear answers).

A: The best solution is as you mentioned to put an invalid value as shown here.

In some cases, the browser will continue suggesting autocompletion
  values even if the autocomplete attribute is set to off. This
  unexpected behavior can be quite puzzling for developers. The trick to
  really enforcing non-autocompletion is to assign an invalid value to
  the attribute, for example:

autocomplete="nope"

Since this value is not a valid one for the autocomplete attribute,
  the browser has no way to match it, and stops trying to autocomplete
  the field.

Your data or cache wouldn't be affected by this and depending on what your form is built in, the data would only be saved via the form action or function handlers on the inputs.
Alternatively, I have found autocomplete= 'new-password' on the input to be reliable, however the above example on the form wrapper requires much less work than adding to every input


text:
Q: Visual Studio Code - Azure Functions - New Project button disappeared So I have been messing around trying to create an Azure Function using Visual Studio code.  Frustrated enough to start all over and now according to Microsoft, to create a new project, I have to click the Azure icon on the left hand side and click New Project:

That being said, I don't have it anymore somehow:

Somebody please advise.  I'm going crazy here trying to make it reappear.

A: For me, this option was buried in the sidebar menu in vscode as pictured below. I was not able to get the icons to reappear (I'm on an Apple Silicon machine).

A: 1.Try to uninstall Azure Function Extension.
2.Restart Visual Studio Code.
3.Install the extension again.

A: The documentation on how to create New Azure Function Project in Visual Studio Code appears to be out of date. I found the solution in the store page of the extension. Open the 'Azure' extension, go to Workspace, click the plus, create function. Proceed as normal as per the MS Docs. Uninstalling did not work for me as @bala suggested.

A: Yeah, I did not had the button to create a new local Azure function.
I uninstalled Azure function plugin and after the refresh the button appeared. When I clicked the button, it informed me that I need to have Functions plugin installed.Then I reinstalled the plug-in and the button disappeared.
Restarting and Updating VSC fixed the issue.


text:
Q: Installing wine in debian i'm totally new to debian and i've been trying to install wine.This is what i did...
root@sutta:/home/sutta# sudo add-apt-repository ppa:ubuntu-wine/ppa
You are about to add the following PPA to your system:
Welcome to the Wine Team PPA.  Here you can get the latest available Wine   betas for every supported version of Ubuntu.  This PPA is managed by Scott  Ritchie and Maarten Lankhorst.
More info: https://launchpad.net/~ubuntu-wine/+archive/ubuntu/ppa
Press [ENTER] to continue or ctrl-c to cancel adding it

Executing: gpg --ignore-time-conflict --no-options --no-default-keyring   --secret-keyring /tmp/tmp.je9yp6CIpu --trustdb-name /etc/apt//trustdb.gpg --keyring /etc/apt/trusted.gpg --primary-keyring /etc/apt/trusted.gpg --keyring /etc/apt/trusted.gpg.d//debian-archive-squeeze-automatic.gpg --keyring /etc/apt/trusted.gpg.d//debian-archive-squeeze-stable.gpg --keyring /etc/apt/trusted.gpg.d//debian-archive-wheezy-automatic.gpg --keyring /etc/apt/trusted.gpg.d//debian-archive-wheezy-stable.gpg --keyserver hkp://keyserver.ubuntu.com:80/ --recv 883E8688397576B6C509DF495A9A06AEF9CB8DB0
gpg: requesting key F9CB8DB0 from hkp server keyserver.ubuntu.com
gpg: key F9CB8DB0: "Launchpad PPA for Ubuntu Wine Team" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1
root@sutta:/home/sutta# sudo apt-get update
Err http://ppa.launchpad.net wheezy Release.gpg
Could not resolve 'proxy.falcot.com'
Err http://ftp.cn.debian.org wheezy Release.gpg
Could not resolve 'proxy.falcot.com'
Reading package lists... Done
W: Failed to fetch http://ftp.cn.debian.org/debian/dists/wheezy/Release.gpg  Could not resolve 'proxy.falcot.com'

W: Failed to fetch http://ppa.launchpad.net/ubuntu-wine/ppa/ubuntu/dists/wheezy/Release.gpg  Could not resolve 'proxy.falcot.com'

W: Some index files failed to download. They have been ignored, or old ones used instead.
root@sutta:/home/sutta# sudo apt-get install -y wine1.7
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package wine1.7
E: Couldn't find any package by regex 'wine1.7'

My steps would probably be wrong.
Can some one tell me the right steps to download wine in debian ?
Please help me out..!

A: You need to add a 32-bit architecture in your repository:
dpkg --add-architecture i386 | sudo apt-get update

Now:
sudo apt-get install wine.

The sintax of wine is:
wine <runnable.exe>
I home my answer is enough

A: try install from the GUI software manager. i.e. gnome-software


text:
Q: VueJS 2 properties not being passed down in production build I'm struggling with getting properties to work in the production build of my Vue app. Everything appears to work fine in development, but when the app is compiled it doesn't. Take this navigation component I'm using for example:
navigation.js:
import Vue from 'vue';
import template from './navigation.html';

export default Vue.extend({
  props: ['activePage'],
  template,
  methods: {
    setActivePage: function() {
      // Set activeEl to ref (see template) that corresponds to activePage parameter
      var activeEl = this.$refs[this.activePage];
      if (activeEl) {
        activeEl.className += ' active';
      }
    }
  },
  mounted: function() {
    this.setActivePage();
  }
});

navigation.html:

            <router-link to="/"></router-link>

<router-link to="/">a</router-link>

<router-link to="/b">b</router-link>

<router-link to="/c">c</router-link>

This is how I use this component:
<navigation activePage="a"></navigation>
So, this component takes an activePage property, checks the template if there is a ref that corresponds to the activePage value, and if that is true, it adds the active class to the ref element. It works with the development build, but in production it results in this:

Am I doing something wrong here? My project is based on this template, if that matters: https://github.com/villeristi/vue.js-starter-template

A: Have a look at https://v2.vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case
You have to use kebab case when binding camelCased props. You will need to use
<navigation active-page="a"></navigation>


text:
Q: How can I get the count of total distinct rows before paging? SELECT

    someColumnA,
    someColumnB,

FROM someTable

[A COUPLE JOINS HERE]

[A NICE WHERE STATEMENT]

ORDER BY someColumnA DESC

Let's say this query returns 1000 results. When I apply a DISTINCT it will condense down to let's say 300.
What I want to do is only return 10 results using paging to act a preivew to my users and I want to include a total count of the number of DISTINCT ROWS. If I add paging with a count over in the select it will return the number of rows BEFORE THE DISTINCT.
Here is the final query I have so far
SELECT DISTINCT

    count(*) OVER() as total,
    someColumnA,
    someColumnB,

FROM someTable

[A COUPLE JOINS HERE]

[A NICE WHERE STATEMENT]

ORDER BY someColumnA DESC

OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

total = 1000 and not the 300 I want. Is there a simple way to accomplish this or will I have to resort to using a sub select to fetch all 300 distinct rows to then count that and fetch the first 10?

A: You can try using group by instead of distinct
SELECT
    count(*) OVER() as total,
    someColumnA,
    someColumnB,

FROM someTable

[A COUPLE JOINS HERE]

[A NICE WHERE STATEMENT]

GROUP BY someColumnA, someColumnB
ORDER BY someColumnA DESC

OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

A: You can use CTE
;WITH CTE_Distinct
AS
(
   SELECT DISTINCT
      someColumnA,
      someColumnB
  FROM someTable
  [A COUPLE JOINS HERE]
  [A NICE WHERE STATEMENT]
)

SELECT
    count(*) OVER() as total,
    someColumnA,
    someColumnB
FROM CTE_Distinct
ORDER BY someColumnA DESC
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY


text:
Q: Using command line arguments in imported module I have script download.py with:
import argparse
import models

parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)

args = parser.parse_args()

models.py:
import peewee

database = peewee.SqliteDatabase("wee.db")

class Artist(peewee.Model):
    name = peewee.CharField()

    class Meta:
        database = database

class Album(peewee.Model):
    artist = peewee.ForeignKeyField(Artist)
    title = peewee.CharField()
    release_date = peewee.DateTimeField()
    publisher = peewee.CharField()
    media_type = peewee.CharField()

    class Meta:
        database = database

Instead of wee.db I'd like to use database path from args.db_path in download.py file. How can I do this?

A: All you have to do is pass your arg to the SqliteDatabase constructor.
It seems like you're using Django. If that's the case, you could (and should) specify your database in settings.py, as indicated on the docs.
EDIT
Here is a code example of how to do it with your existing code the way you suggested (I still think there are betters way of doing this):
models.py:
database_name = "wee_db"

def set_database_name(name):
    database_name = name

database = peewee.SqliteDatabase(database_name)

download.py:
models.set_database_name(args.db_path)

A: Here's a possible solution:
# download.py
import argparse
from models import DBManager

parser = argparse.ArgumentParser()
parser.add_argument("--db_path", required=True)

args = parser.parse_args()
DBManager(args.db_path)

# models.py
import peewee

class Artist(peewee.Model):
    name = peewee.CharField()

class Album(peewee.Model):
    artist = peewee.ForeignKeyField(Artist)
    title = peewee.CharField()
    release_date = peewee.DateTimeField()
    publisher = peewee.CharField()
    media_type = peewee.CharField()

class DBManager(object):

    def __init__(self, db_path):
        self.database = peewee.SqliteDatabase(db_path)

        Artist._meta.database = self.database
        Album._meta.database = self.database

        self.database.connect()
        self.database.create_tables([Artist, Album])


text:
Q: My SQL: Sum each row After Specific Row I have a table which collects the results of football games played every week.
Based on the results of each game I input 3, 1 or 0 points for a player by ID, depending one whether they have won, drawn, or lost.
id  Name    A1  B1  C1  A2  B2  C2

1   C       0   3   1   3   0   0

2   G       3   0   1   3   0   0

3   k       3   0   1   0   3   3

4   S       3   0   1   N   N   N

5   G       N   N   N   3   0   0

6   D       N   N   N   N   N   N

I'd like to be able to sum these columns, and I can do it manually by using SELECT SUM(A1+B1+C1+A2+B2+C2) FROM Results WHERE id ='1'
My issue is that each week I add an additional 2 or 3 game results - so I'd need to manually add the new games into SUM().
I thought that I would be able to use something like SUM(...) AFTER Name WHERE id = 'id'
I'm hoping I can concatenate the names of all Columns after Name and then add that into SUM(concatenatedcolumns).
But I haven't found a good example to work from yet.

A: You can have two tables if you do not care about 'games' metadata, I assume not as you were ready to have games listed as columns.
table:players (rows unique by id)
id name
1  A
2  B

table:scores (rows unique by combination of game_id and player_id)
game_id, player_id, score
A1       1          3
A1       2          1
B1       1          0

You can then join these two tables to get sum of scores for each players across all games
select players.id, players.name, sum(scores.score) from players inner join score
on players.id = scores.player_id group by players.id, players.name

There will not be any rows for players who did not appear in a game in 'scores' table and you do not have to deal with any null values thereby.


text:
Q: Extracting multiple tables from webpage containing hyperlinks with R This is my first attempt at web scraping. I am trying to extract a list of tables (Column name: Oil & Gas Tables) from this webpage. Oil and Gas Data. It was easy to extract the data for one state by using the link for that state Alabama Data. However, I want a program that can extract data for all states, keeping them year wise as shown in the HTML data. I have loaded up packages RCurl, XML, rlist and purrr based on previous similar posts I came across.
How can I use R (Rcurl/XML packages ?!) to scrape this webpage? This solution looks complete, however, the problem webpage has probably changed since it was posted (I tried to emulate, but couldn't)
R: XPath expression returns links outside of selected element. How Can I use Xpath to extract my needed tables since they all contain "stateinitials_table.html" as in for Alabama "al_table.html" view source
theurl <- getURL("https://www.eia.gov/naturalgas/archive/petrosystem/al_table.html",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
berilium<-tables[seq(3,length(tables),2)]

This is the output for "al_table.html" a list of 15 data frames for 15 years.

So I need to,
make a function (Xpath vs readHTMLTable, preferable Xpath) to extract all tables from the main web link. And I need it 'marked' by state and year as shown in the web pages. (Currently not concerned about clean up of useless columns and rows)

A: This is more of a blog post or tutorial than an SO answer but I can also appreciate the desire to learn and am also working on a book for this very topic and this seems like a gd example.
library(rvest)
library(tidyverse)

We'll start with the top-level page:
pg <- read_html("https://www.eia.gov/naturalgas/archive/petrosystem/petrosysog.html")

Now, we'll use an XPath that only gets us table rows that have state data in them. Compare the XPath expressions to the tags in the HTML and this should make sense. Find all
s without colspan attributes and only choose remaining
s that have both the right class and a link to a state:
states <- html_nodes(pg, xpath=".//tr[td[not(@colspan) and
                     contains(@class, 'links_normal') and a[@name]]]")

data_frame(
  state = html_text(html_nodes(states, xpath=".//td[1]")),
  link = html_attr(html_nodes(states, xpath=".//td[2]/a"), "href")
) -> state_tab

It's in a data frame to keep it tidy and handy.
You'll need to put the next bit below the function that comes after it, but I need to explain the iteration before showing the function.
We need to iterate over each link. In each iteration, we:

*

*pause since your needs aren't more important than EIA's server load

*find all "branch"
s since they hold two pieces of information we need (the state+year and the data table for said state+year).

*wrap it all up in a nice data frame

Rather than clutter up the anonymous function, we'll put that functionality in another function (again, which needs to be defined before this iterator will work):
pb <- progress_estimated(nrow(state_tab))
map_df(state_tab$link, ~{

  pb$tick()$print()

  pg <- read_html(sprintf("https://www.eia.gov/naturalgas/archive/petrosystem/%s", .x))

  Sys.sleep(5) # scrape responsibly

  html_nodes(pg, xpath=".//div[@class='branch']") %>%
    map_df(extract_table)

}) -> og_df

This is the hard worker of the bunch. We need to find all the State + Year labels on the page (each are in a
) then we need to find the tables with data in them. I take the liberty of removing the explanatory blurb at the bottom of each and also turn each into a tibble (but that's just my class preference):
extract_table <- function(pg) {

  t1 <- html_nodes(pg, xpath=".//../tr[td[contains(@class, 'SystemTitle')]][1]")
  t2 <- html_nodes(pg, xpath=".//table[contains(@summary, 'Report')]")

  state_year <- (html_text(t1, trim=TRUE) %>% strsplit(" "))[[1]]

  xml_find_first(t2, "td[@colspan]") %>% xml_remove()

  html_table(t2, header=FALSE)[[1]] %>%
    mutate(state=state_year[1], year=state_year[2]) %>%
    tbl_df()

}

Re-pasting the aforeposted code just to ensure you grok it has to come after the function:
pb <- progress_estimated(nrow(state_tab))
map_df(state_tab$link, ~{

  pb$tick()$print()

  pg <- read_html(sprintf("https://www.eia.gov/naturalgas/archive/petrosystem/%s", .x))

  Sys.sleep(5) # scrape responsibly

  html_nodes(pg, xpath=".//div[@class='branch']") %>%
    map_df(extract_table)

}) -> og_df

And, it works (you said you'd do the final cleanup separately):
glimpse(og_df)
## Observations: 14,028
## Variables: 19
## $ X1    <chr> "", "Prod.RateBracket(BOE/Day)", "0 - 1", "1 - 2", "2 - 4", "4 - 6", "...
## $ X2    <chr> "", "||||", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|"...
## $ X3    <chr> "Oil Wells", "# ofOilWells", "26", "19", "61", "61", "47", "36", "250"...
## $ X4    <chr> "Oil Wells", "% ofOilWells", "5.2", "3.8", "12.1", "12.1", "9.3", "7.1...
## $ X5    <chr> "Oil Wells", "AnnualOilProd.(Mbbl)", "4.1", "7.8", "61.6", "104.9", "1...
## $ X6    <chr> "Oil Wells", "% ofOilProd.", "0.1", "0.2", "1.2", "2.1", "2.2", "2.3",...
## $ X7    <chr> "Oil Wells", "OilRateper Well(bbl/Day)", "0.5", "1.4", "3.0", "4.9", "...
## $ X8    <chr> "Oil Wells", "AnnualGasProd.(MMcf)", "1.5", "3.5", "16.5", "19.9", "9....
## $ X9    <chr> "Oil Wells", "GasRateper Well(Mcf/Day)", "0.2", "0.6", "0.8", "0.9", "...
## $ X10   <chr> "", "||||", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|", "|"...
## $ X11   <chr> "Gas Wells", "# ofGasWells", "365", "331", "988", "948", "867", "674",...
## $ X12   <chr> "Gas Wells", "% ofGasWells", "5.9", "5.4", "16.0", "15.4", "14.1", "10...
## $ X13   <chr> "Gas Wells", "AnnualGasProd.(MMcf)", "257.6", "1,044.3", "6,360.6", "1...
## $ X14   <chr> "Gas Wells", "% ofGasProd.", "0.1", "0.4", "2.6", "4.2", "5.3", "5.4",...
## $ X15   <chr> "Gas Wells", "GasRateper Well(Mcf/Day)", "2.2", "9.2", "18.1", "30.0",...
## $ X16   <chr> "Gas Wells", "AnnualOilProd.(Mbbl)", "0.2", "0.6", "1.6", "2.0", "2.4"...
## $ X17   <chr> "Gas Wells", "OilRateper Well(bbl/Day)", "0.0", "0.0", "0.0", "0.0", "...
## $ state <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Ala...
## $ year  <chr> "2009", "2009", "2009", "2009", "2009", "2009", "2009", "2009", "2009"...

A: Hope this helps!
library(rvest)
library(dplyr)

main_page <- read_html("https://www.eia.gov/naturalgas/archive/petrosystem/petrosysog.html")
state <- main_page %>%
  html_nodes(xpath='//td[contains(@width, "110")]') %>%
  html_children() %>%
  html_text()
state_link <- main_page %>%
  html_nodes(xpath='//td[contains(@width, "160")]') %>%
  html_children() %>%
  html_attr('href')

final_data <- list()
for (i in 1:length(state)){
  child_page <- read_html(paste0("https://www.eia.gov/naturalgas/archive/petrosystem/",state_link[i]))
  Sys.sleep(5)

  child_page_stateAndYear <- child_page %>%
    html_nodes(xpath = '//td[@class="c SystemTitle" and @style=" font-size: 14pt; color: #CC0000;"]') %>%
    html_text
  child_page_table <- lapply(
    (child_page %>%
       html_nodes(xpath = '//table[contains(@class, "Table")]') %>%
       html_table()),
    function(x) x[-nrow(x),])
  final_data[[state[i]]] <- setNames(child_page_table, child_page_stateAndYear)

  print(paste('Scraped data for', state[i], '...'))
  flush.console()
}
print('Congratulation! You have finished scraping the required data!')

names(final_data)
names(final_data[[1]])

final_data has the 34 elements (i.e. states available on the main webpage) and each element is a list of tables (i.e. year wise tabular data of a state). So if you want to have data belonging to 'Alabama 2009' then just type
final_data[['Alabama']]['Alabama 2009']

(note: You may need to do little bit of data cleaning)
Edit: added logic to sleep for sometime before scraping another webpage as suggested by @hrbrmstr


text:
Q: Date filtering in Excel Online I might be completely overlooking the feature, but i've been trying to filter a range of dates to only display today and future days in Excel Online (365).
At first sight it appears that there is such a feature:

Data > Filter > Click array on column > Date Filters > ...

However, there is no default filter to display only today and future dates. There is one to do the exact opposite (Year To Day). So I guess it would be either custom filter.
In the next screen I can't seem to add a TODAY() function or anything at all. So definitely no TODAY()-1 or something.
Any suggestions anyone or is this just a feature that hasn't made it to Excel online..
Example sheet: https://protimeeu-my.sharepoint.com/:x:/g/personal/donald_valkaert_protime_eu/EVCQvYZ-4i9HvMHGHS-cwJcBKun_D6NzHuEWSgbNxbLiMg?e=m3Ams1

A: You can filter your dates in a table in Excel Online in same way as normal via Date Filters.
Apply a custom filter that uses the condition 'Is after or equal to' then the value of 'Today'

A: You're right, it turns out it isn't obvious, and doesn't work quite the way we were all guessing.  Here's how you can set the filter to "today and future dates".
Use the Filter pull-down (the little icon already showing in the "Date" column heading), and select After.

Thanks, Lee, for the image.
That will open a little dialog window prefilled with is greater than and an entry box.
Type yesterday's date in that box, and click OK.

Unfortunately, you can't insert functions like TODAY() or cell references, you can't use multiple selections from the initial list, like After and Yesterday, and picking one of the date offerings from the list automatically assigns = as the comparison.


text:
Q: Azure Help: Your sign-in was blocked When I try to sign in to the Azure Portal, I get the following error:
Your sign-in was blocked We've detected something unusual about this sign-in. For example, you might be signing in from a new location, device, or app. Before you can continue, we need to verify your identity. Please contact your admin.
The problem is I am the admin. How do I get back into my account??

A: According to the documentation:

To unlock your account, follow the instructions on the sign-in screen
  and select where we can send you a security code. After you've
  received the code, enter it to access your account.

There should be the possibility for you to login based on Microsoft sending a code as an SMS to your phone.


text:
Q: C++ - binding function I have some (library API, so I can't change the function prototype) function which is written the following way:
void FreeContext(Context c);

Now, at some moment of my execution I have Context* local_context; variable and this is also not a subject to change.
I wish to use boost::bind with FreeContext function, but I need to retrieve Context from local variable Context*.
If I write my code the following way, the compiler says it's "illegal indirection":
boost::bind(::FreeContext, *_1);

I managed to solve this problem the following way:
template <typename T> T retranslate_parameter(T* t) {
   return *t;
}

boost::bind(::FreeContext,
            boost::bind(retranslate_parameter<Context>, _1));

But this solution doesn't seem really good to me. Any ideas on how to solve this using something like *_1. Maybe writing a small lambda function?

A: You could use Boost.Lambda which have overloaded the * operator for _n.
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <algorithm>
#include <cstdio>

typedef int Context;

void FreeContext(Context c) {
    printf("%d\n", c);
}

int main() {
    using boost::lambda::bind;
    using boost::lambda::_1;

    Context x = 5;
    Context y = 6;
    Context* p[] = {&x, &y};

    std::for_each(p, p+2, bind(FreeContext, *_1));

    return 0;
}

A: Use either Boost.Lambda or Boost.Phoenix to have a working operator* on a placeholder.

A: You can also place the Context pointer in a shared_ptr with a custom deleter:
#include <memory> // shared_ptr

typedef int Context;

void FreeContext(Context c)
{
   printf("%d\n", c);
}

int main()
{
   Context x = 5;
   Context* local_context = &x;

   std::shared_ptr<Context> context(local_context,
                                    [](Context* c) { FreeContext(*c); });
}

Not sure this is relevant though. Good luck!


text:
Q: Hololens 2 emulator not recognizing inputs I am trying to build and deploy a basic unity project to a hololens2 emulator, however I am running into many issues:

*

*There is no Unity C# use checkbox in the build settings for UWP (I see this as an option in many tutorials however no one has explained how to set up for a hololens2 emulator with the newest unity versions)

*** Main issue: The emulator itself does not recognize any inputs from the mouse/keyboard and is frozen on the start screen. Also when I try and change the setting for the inputs it is wither grayed out or the changes do not go through**
If anyone has any help they can offer that would be great.

A:
There is no Unity C# use checkbox in the build settings for UWP (I see this as an option in many tutorials however no one has explained how to set up for a hololens2 emulator with the newest unity versions)

The Unity C# Project checkbox has been deprecated in the latest version of Unity. It used to be available when the Scripting Backend as .Net. But now il2cpp is the only available backend for the UWP platform in Unity, so this checkbox is no longer necessary.
For Unity version, we recommend the Unity LTS (Long Term Support) stream as the best version to use when starting new projects, and the current recommendation is to use Unity 2019.4.9f1: https://unity3d.com/unity/qa/lts-releases

The emulator itself does not recognize any inputs from the mouse/keyboard and is frozen on the start screen. Also when I try and change the setting for the inputs it is wither grayed out or the changes do not go through

For Hololens-2 Emulator issue you got, I found a similar topic from the Unity forum: https://forum.unity.com/threads/hololens-2-emulator-input-controls-not-working.711713/#post-4758179 You can try the suggestions under this topic.

A: i assume that you used the official guide, is this correct?
Does the second point of the known issue section regarding AMD / Intel graphics apply to you? Also see the last point under Troubleshooting.
Let me know if that helps.


text:
Q: My C code is not working I'm so confused here. Why this code of mine doesn't work as it SHOULD be..
Here's the code:
void print(int x) {

    x = 140;
    int i,total, length, value;

    if (x < 10){
        value = 0;
    }
    else {
        int sum = 1;
        for (i = 0 ; i < 10 ; i++){
            total = 10 * sum;
            sum = total;
            length = x / total;
            if (length < 10 && 1 <= length){
                value = i+1;
                break;
            }
        }
    }
    value = pow(10,value);
    printf("%d\n",value);
}

Let me explain how the code should works first:
It takes an integer x and print out the highest power of 10 value it can be divided by.
So if X = 80, it should print 10 and if x = 12435, it should print 10000.
But this doesn't work with my code perfectly... if x = 140, it prints 99 but. if x = 1400, it prints 1000 then again, if x = 14000 it prints 9999 and if x = 140000 it prints 100000 and the sequence continues...
I've already tried exactly the same code in Java and it works perfectly!!
Why does it not works in C??

A: pow() is returning an double value, which you are casting to an integer. So instead of rounding it will be truncated.
You should try
value = round(pow(10,value));


text:
Q: Python - Array goes out of bounds Good day everyone,
today I struggled with my code for more than an hour, just to find out that Python did not give an out of bound error.
This is my summarised code:
array = []
n = 0
while n < 5:
    array.append(1)
    n = n + 1
print array
for i in range(0,1):
    print i-2
    print array[i-2]

Clearly array[i-2] is out of bound, but the code still runs. This is the output:
[1, 1, 1, 1, 1]
-2
1

Am I missing something, is it my PC or is it something more in depth on how arrays in Python work?
Greetings

A: You can access Python lists from the end using negative numbers. In the same way some_list[0] gives you the first item in the list, and some_list[1] the second, some_list[-1] will give you the last element on the list, some_list[-2] the second to last, etc.
example = [1, 2, 3, 4]
example[-1] = 4
example[-2] = 3

A: A note to begin: take care of how you call python lists, because python arrays also exist but they are different objects.
Then you have indeed discovered a property of python list: for your convinience using negative indexes will loop from the end of the list meaning that some_list[-1] is equivalent to some_list[len(some_list)-1].


text: Q: Открытие полноразмерного изображения по нажатию в Ionic-приложении Пишу приложение на ionic. Нужно добавить возможность просмотреть изображение в полном размере при нажатии на него. Раньше на сайтах для таких целей всегда подключал jquery fancybox, но в этот раз при всём желании так и не смог подключить данную библиотеку к angularJs. Возможно в angular или ionic есть собственные библиотеки для данных целей? Кто может подсказать?


text:
Q: Why should I build my own error/exception handling into a Webflux application? When there is some internal exception in a Webflux application, why do I want/need to write code to handle these exceptions? I understand handling issues and returning appropriate ServerResponse bodies when the service client incorrectly invokes a service, or when a non-error-condition (i.e., query returns empty cursor, etc.) occurs.
But, other than generating debug information into a logfile, is there anything to be gained by rolling-your-own exception handling components? This approach makes "more sense" to me in a monolithic application, where one is trying to avoid a scenario where the app "just dies".
But, for a service implementation, especially if there's some incentive not to expose too much about the internal implementation to a client, why wouldn't Spring's default error/exception handling (and "500 Internal Server Error" response/message) be sufficient.

A: So, after some time and thought (and little, but still helpful-and-appreciated feedback), I guess it boils down to:
(a) - It provides a localized context to "do things", like logging information about the exception/error condition, or categorizing the severity of the exception within-the-context of a server-client interaction.
(b) - It provides a localized context to hide/expose information from a client, based on the nature of the exception/error condition and whether the server is deployed in a production or test environment.
(c) - Being localized, it makes maintenance/modification a bit easier, as the handling of exceptions/errors is not scattered throughout the code.
(a) and (c) are enough to make me believe it's worth the effort.


text:
Q: How to use Oracle DBMS_ALERT within Oracle APEX? Using Oracle APEX 4.2, I have a page process that uses DBMS_ALERT for a running process that may take up to a minute to complete or fail.
While this is running, through the use of a trigger, there is a DBMS_ALERT.signal posting notifications of progress.
My question is, within Oracle APEX 4.2, how can I display to the user, a running progress of these notifications from DBMS_ALERT, within a region or modal on the page?
I need to provide the user all these alerts as the job is running until it finally completes.
For example:
Started Job...
Waiting on resources...
Processing job...
Job completed successfully.

Obviously through each of these DBMS_ALERTS, there may be a few seconds before each line is presented to the user.
I am unsure how to grab these alerts and show the user, within Oracle APEX.

A: I'd set up a demo on apex.oracle.com, but since you need an execute grant on dbms_alert, it'll have to be textual-only.
You can go quite far with the entire set-up, so I'd consider this as basics to build on.
For example, I have only worked with one alert. In your sample you may want to use multiple events to catch the different progress alerts. This is for the simple reason that in order to return something to the client (the ajax response) the ajax callback has to 'closed'. So when catching an alert and wanting to return that, you need to write to the buffer and it needs to be returned. This means that you will also stop listening to the event (read: in apex, you should!).
Consider the flow like this: you will make an ajax call, and have an ajax callback process which registers interest in an event. Then you wait for an alert to occur. You catch it and return it by writing it in the http buffer (htp.p). That's the end of the code and apex will flush the buffer, the ajax call will then pick up the response and you'll be able to manage that return.
Don't forget though: apex uses connection pooling, and database sessions are not linked directly but rather reused all the time. You don't want to 'leave' a database session 'dirtied'. You'll have to unregister your alert-interest too. This also makes a case for using unique IDs for alerts - alerts can be registered to in different (database) sessions, so if this would be a page which multiple users can use to follow the progress of their process' progress, you don't want them to interfere with other users' alerts.
However, this fleeting nature of interest also means there will be "interruptions" between different ajax calls made. When you want to listen for multiple alerts, and these alerts may be packed very very closely together, the chance exists you may miss one. Say 2 alerts are spaced 1ms apart: the first will be caught, reported to the ajax call, which would have to start a new call right away in order to listen for more alerts. But since there was no active listener during that short time, that next alert may have been missed. Now - this is likely only to be an issue where you fire off multiple alerts under the same handler. If you'd use multiple handlers and start ajax calls for all those at the same time, they'll all be handled in time. There are solutions for both, of course. I imagine that when using one handler only you could catch all alerts in a collection and check against that if you've already sent a response for a certain alert or not and whether to continue checking in or not. With multiple handlers you could use a unique id and suffix it with different statusses.
So here is some actual code which I've used in my local POC.
Overview: I have 3 buttons: 1 to generate an alert id, for which I used a sequence. Another button to start listening for an event, and yet another button to send an alert.
JS code for NEW_ALERT_ID button:
apex.server.process("NEW_ALERT").done(function(pdata){
$s("P1_ALERT_ID",pdata.alertId);
})

JS code for START_LISTEN button:
apex.server.process("LISTEN_ALERT",{x01:$v("P1_ALERT_ID")},{timeout:(31*1000)})
.done(function(pdata){
  if (pdata.success ){
      alert('Caught alert: ' + pdata.message);
  } else {
      alert("No alerts caught during wait on database. You may want to continue listening in...")
  }
})
.fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {
        alert('Call should have returned by now...');
        //do something. Try again perhaps?
    }
});

JS code for SEND_ALERT button:
apex.server.process("SEND_ALERT",{x01:$v("P1_ALERT_ID")},{dataType:"text"});

AJAX Callback processes:
NEW_ALERT:
htp.p('{"alertId":'||alert_seq.nextval()||'}');

LISTEN_ALERT:
declare
  alert_id number := apex_application.g_x01;
  msg varchar2(2000);
  stat pls_integer;
  keep_looping boolean := true;
  insurance binary_integer := 0; -- prevent an infinite loop

  onecycle binary_integer := 3; -- one cycle of waiting, in seconds
  maxcycles binary_integer := 10; -- in this session, the max amount of cycles to wait
begin
  dbms_alert.register(alert_id);

  while keep_looping
  loop
    insurance := insurance + 1;

    dbms_alert.waitone(alert_id, msg, stat, onecycle);
    if stat = 1 then
      apex_debug.message('timeout occured, going again');
    else
      apex_debug.message('alert: '||msg);
      keep_looping := false;
    end if;

    exit when insurance = maxcycles;
  end loop;

  if keep_looping then
    -- we waited a really long time now. It may be a good idea to return this info to the client and let it start a new call
    htp.p('{"success":false,"message":"No alert during wait on database"}');
  else
    htp.p('{"success":true,"message":"'||msg||'"}');
  end if;
end;

SEND_ALERT:
declare
  alert_id number := apex_application.g_x01;
begin
  dbms_alert.signal(alert_id, 'alert sent at '||to_char(systimestamp, 'HH24:MI:SS FF6'));
end;

So, I'd first get an alert ID, then I'd start to listen, and then at some point I'd send an alert (or not). It's a skeleton though and will need further refinement in your actual setup.


text:
Q: How do I make async_read_some of asio to call a callback? I'm trying to use serial_port of asio(standlone) to get data from a device. But I can't read even a byte.
I post a screenshoot of the example usage found from documentation website as below :
enter image description here
enter image description here
https://think-async.com/Asio/asio-1.24.0/doc/asio/reference/basic_serial_port/async_read_some.html
There are 3 question I have:

*

*What is the specific type of the first parameter of async_read_some? std::vector<uint8_t>, for example?

*How to bind a class member function as the callback/handler?

*Is it right that we just make sure io_context.run() run on a background thread and call async_read_some just once?

I'll appreciate it if you guys could help me check out my code or give some advice.
class NmeaSource {
public:
    explicit NmeaSource(std::shared_ptr<asio::io_context> io, const nlohmann::json& settings);
    void parse();
    void handle(const asio::error_code& error, // Result of operation.
        std::size_t bytes_transferred           // Number of bytes read.
    );

private:
    void open();

    std::string m_port;
    int m_baudrate;
    std::shared_ptr<asio::io_context> m_io;
    std::shared_ptr<asio::serial_port> m_serial;
    unsigned char m_readBuffer[1024];
};

NmeaSource::NmeaSource(std::shared_ptr<asio::io_context> io, const nlohmann::json& settings)
    :m_io(io)
{
    try {
        setPort(settings.at("port"));
        setBaudrate(settings.at("baudrate"));
        //LOG("");
        std::cout << "port: " << m_port << ", baudrate: " << m_baudrate << std::endl;
    }
    catch (nlohmann::json::basic_json::type_error& e1) {
        std::cout << "type is wrong " << e1.what() << std::endl;
        throw e1;
    }
    catch (nlohmann::json::basic_json::out_of_range& e2) {
        std::cout << "key is not found " << e2.what() << std::endl;
        throw e2;
    }
    catch (...)
    {
        std::cout << "unknown error"<< std::endl;
        exit(-1);
    }

    open();

}

void NmeaSource::open()
{
    m_serial = std::make_shared<asio::serial_port>(*m_io);

    asio::error_code ec;
    m_serial->open(m_port, ec);
    if (!ec) {
        asio::serial_port_base::baud_rate baudrate(m_baudrate);
        m_serial->set_option(baudrate);
        std::cout << "successfully" << std::endl;
    }
    else {
        std::cout << "failed " << ec.message() <<std::endl;
    }
}

void NmeaSource::handle(const asio::error_code& error, // Result of operation.
    std::size_t bytes_transferred           // Number of bytes read.
)
{
    if (!error) {
        std::cout << bytes_transferred << " bytes read!" << std::endl;
    }
    else {
        std::cout << error.message() << std::endl;
    }
}

void NmeaSource::parse()
{
    m_serial->async_read_some(
        asio::buffer(m_readBuffer, 1024),
        std::bind(&NmeaSource::handle, this,
            std::placeholders::_1,
            std::placeholders::_2)
    );

}

int main()
{
    auto io = std::make_shared<asio::io_context>();
    //std::thread t(std::bind(static_cast<size_t(asio::io_service::*)()>(&asio::io_service::run), io.get()));
    std::thread t([&io]() {io->run(); });
    NmeaSource rtk(io, nlohmann::json{ {"port", "COM3"}, {"baudrate", 115200} });
    rtk.parse();
    for (;;)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
}

The output


text:
Q: Could someone help me understand how this component class works import React, { Component, ComponentClass, ComponentType } from "react";

interface State {
  hasError: boolean;
}

const withErrorBoundary = <T extends Record<string, never>>(
  WrappedComponent: ComponentType<T>
): ComponentClass<T, State> =>
  class ErrorBoundary extends Component<T, State> {
    state: { hasError: boolean };

    constructor(props: T) {
      super(props);
      this.state = { hasError: false };
    }

    static getDerivedStateFromError(error: Error) {
      console.error(error);
      return { hasError: true };
    }

    render() {
      if (this.state.hasError) {
        return
Something went wrong
;
      }
      return <WrappedComponent {...this.props} />;
    }
  };

export default withErrorBoundary;

So I know what this class component does. What I'm trying to understand is <T extends Record<string, never>>(WrappedComponent: ComponentType<T>). I get it's a wrapper class but I can't wrap my head around it. Why is <T extends> defined before the class component? Any resources that can solidify my understanding would be appricted.

A: T is a generic type parameter. Think of it like a variable for a type.
And it represents the props of the wrapped component so that the wrapper component can have the exact same props and pass them through.
So with this code:
const withErrorBoundary = <T extends Record<string, never>>(
  WrappedComponent: ComponentType<T>
): ComponentClass<T, State> =>
  class ErrorBoundary extends Component<T, State> {}

Let's go line by line.

const withErrorBoundary = <T extends Record<string, never>>(

This is a function named withErrorBoundary which declares the generic parameter T. T is constrained by Record<string, never>. This means that T must be a subtype of the constraint. In other words, whatever T is must be assignable to the constraint.

  WrappedComponent: ComponentType<T>

ComponentType is any react component, and it accepts a generic type for its' props. For example ComponentType<{ a: number }> would be used like <MyComponent a={123} />
So this function accepts a single argument of type ComponentType<T>. This is where T infers its type. Whatever the type of the props of the component passed as WrappedComponent is assigned to the type T, because T appears in the spot where ComponentType expect the props type to be declared.

): ComponentClass<T, State> =>

The function returns a class based react component with props T (the props that WrappedComponent would accept) and a state type of State (which is an interface you've declared elsewhere)

  class ErrorBoundary extends Component<T, State> {}

This line creates a class component that extends a react component that has props of type T and state of type State. This matches the return value of the function, and will be returned by the function.

Lastly, this type:
T extends Record<string, never>

is a little strange. A Record typed like that means an empty object (like {}). So this function may only take components that have no props. Which doesn't make much sense:
const MyComp = () => <>test</>
const TestComp = withErrorBoundary(MyComp) // fine

const MyCompA = ({a}: { a: number }) => <>{a}</>
const TestCompA = withErrorBoundary(MyCompA) // type error

See playground
Instead, I'm guessing this type was intended:
T extends Record<string, unknown>

This means that T is constrained by the type of an object with string keys and unknown typed values. This means the wrapped component can have any props.
See playground


text:
Q: CSS/(PHP/HTML?) Background For my site I've been trying to get the background to WORK and to REPEAT, but there's something wrong I guess?
This is my code:
    body
{
    background-image:url('../images/backkground.png');
}

and then it's included in the index like this:
<?php include 'style.css'; ?>

Yeah I know, those php tags but that's placed before all the rest.
Does anyone have tips on what I'm doing wrong? (If I AM doing something wrong)

A: You don't use PHP to include a CSS file, you reference it in HTML:
 <link rel="stylesheet" href="/path/to/style.css" type="text/css">

Ideally you place this in the <head></head> tags at the top of the HTML page.

A: You're using PHP's include wrong. What you're doing is including the contents of the file server side.
You want to include the stylesheet in the HTML output:
<link rel="stylesheet" type="text/css" href="style.css">

In PHP this would look like:
<?php
   echo '<link rel="stylesheet" type="text/css" href="style.css">';
?>

It could also be a problem with where the file is. It should be in the same directory as the calling page so if you're on site.com/index.php you should be able the see the css file at site.com/style.css.

A: As the others already told you, you are using the include in the server side, you should use something like
<?php
   echo '<link rel="stylesheet" type="text/css" href="style.css">';
?>

But if for any reason you need to use the server side include, you could try the following:
<style>
  <?php include 'style.css'; ?>
</style>


text:
Q: Design Pattern for .Net data reader What do you think the "ideal" design pattern for reading a certain file type into my application.
I want to be able to reuse the code in various places, so clearly I want to have this in a separate dll, however although I have no problem passing a filename or stream into the code, what's the recommended design pattern for handling the read data.
Reading all the data into an array and passing this out is obviously not ideal from a memory management point of view, but the only other way I can think of doing it is by raising events when a record is read, however this doesn't feel "right" in that I would be worried that some of the events could go astray.
I'm sure there's a really slick way of doing this, but I can't for the life of me think of it.
Thanks

A: What is the format? If it is text, passing in a TextReader would be ideal; and for xml, an XmlReader. If it is arbitrary binary, pass in a Stream.
For large data, the ideal approach where possible is to read the data in a non-buffered way - i.e. don't load it all into memory. Iterator blocks can be useful here, for example here's a silly example that shows reading lines (but it could just as easily yield return objects built from data in a stream):
    public IEnumerable<string> ReadLines(TextReader source)
    {
        string s;
        while ((s = source.ReadLine()) != null)
            yield return s;
    }

obviously in the general case a lot more processing may be necessary per item!
The caller now has a lazily-spooling, non-buffered source of your data, for example:
using(var file = File.OpenRead(path))
{
    foreach(var customer in YourSpiffyParser(file))
        DoSomethingFun(customer);
}

And handling stream/textreader etc allows them to use it in a decorator chain with things other than files; network streams, in-memory streams, compression/crypto streams, etc.

A: It's difficult to define something so general. You would have to specify more what you really need, or the file type. Then you can have a look at the .NET Framework itself, there are a lot of "XXXReader" classes, for example:

*

*BinaryReader

*TextReader

*StreamReader

*StringReader

*XmlReader

*XmlTextReader

*IDataReader

*EventLogReader

*XamlReader

*EntityDataReader

And each one is really different from the others... Some are abstract, some aren't, etc...


text:
Q: Propagate new DNS records faster Does setting the refresh time in an SOA record make newly created DNS records "propagate" faster? (I understand the term propagate is technically inaccurate)
I'm making many new DNS records (A records to assign subdomains to each new user on the site), and I'd like for that subdomain to be available ASAP after a user signs up. So I'm looking for ways to speed up the rate at which DNS servers check for new DNS records.
Is this possible with the refresh time in the SOA? Or somewhere else?

A: New A records shouldn't have any propagation delay at all, since they aren't cached anywhere. Any DNS client that can't find your new record in a cache should be going direct to your authoritative servers. It's only changes to existing records that can suffer from a delay.


text:
Q: Maximizing sum of logarithms (Z-channel capacity) In the context of information theory, I am trying to maximize the following function (mutual information of the Z-channel's input and output) with respect to $p$ in order to derive Z-channel's capacity:
$$I(X;Y)=\mathit{H}(ap)-\mathit{H}(1-a)p$$
where $\mathit{H}(x)=-xlog_2(x)-(1-x)log_2(1-x)$, $0<x<1$ is known as the binary entropy function.
So the function is:
$$I(X;Y)=-aplog_2(ap)-(1-ap)log_2(1-ap)-\mathit{H}(1-a)p$$
Differentiating with respect to $p$ I get:
\begin{eqnarray*}
\frac{\partial I(X;Y)}{\partial p}&=&-alog_2(ap)-ap\frac{1}{pln2}+alog_2(1-ap)-(1-ap)\frac{a}{ln2(ap-1)}-\mathit{H}(1-a)\\
&=&log_2((ap)^{-a}e^{-a}(1-ap)^{-a}e^aa^a(1-a)^{1-a})\\
&=&log_2((ap)^{-a}(1-ap)^{-a}a^a(1-a)^{1-a})
\end{eqnarray*}
Then:
\begin{eqnarray*}
\frac{\partial I(X;Y)}{\partial p}=0&\Rightarrow &log_2((ap)^{-a}(1-ap)^{-a}a^a(1-a)^{1-a})=0\\
&\Rightarrow &(ap)^{-a}(1-ap)^{-a}a^a(1-a)^{1-a}=1\\
\end{eqnarray*}
I can't solve this. Eventually, I am trying to prove that the value of $p$ that maximizes the function is:
$$p=\frac{1}{a(1+2^{\mathit{H}(1-a)/a})}$$
More information on the Z-channel can be found here, but I am using different notation regarding the probabilities.

A: It is easier to separate the process using the chain rule instead of using the full equation for I:
$$I=H(ap)-H(1-a)p$$
$$\frac{dI}{dp}=\frac{dH(ap)}{d(ap)}\frac{d(ap)}{dp}-H(1-a)=\frac{dH(ap)}{d(ap)}a-H(1-a)$$
Now we need to find $H'$
$$\frac{dH}{dx}=-log_2(x)-x\frac{1}{x  ln2}+log_2(1-x)+(1-x)\frac{1}{(1-x)ln2}=\frac{-ln(x)-1+ln(1-x)+1}{ln2}=log_2(1-x)-log_2(x)$$
Substituting in the previous equation with $x=ap$:
$$\frac{dI}{dp}=a(log_2(1-ap)-log_2(ap))-H(1-a)$$
Setting $dI/dp=0$
$$\frac{H(1-a)}{a}=log_2(1-ap)-log_2(ap)$$
$$2^{\frac{H(1-a)}{a}}=2^{log_2(1-ap)-log_2(ap)}=\frac{2^{log_2(1-ap)}}{2^{log_2(ap)}}=\frac{1-ap}{ap}$$
$$ap2^{\frac{H(1-a)}{a}}+ap=1$$
$$ap(2^{\frac{H(1-a)}{a}}+1)=1$$
$$p=\frac{1}{a(2^{\frac{H(1-a)}{a}}+1)}$$


text:
Q: How To Retrieve a csv file pointing to Git-lfs? I am trying to download this CSV file: https://graphmining.ai/datasets/facebook_large.zip
The CSV file shows a pointer to a git lfs file:
CSV File Output
Any idea how to retrieve the original CSV file?
I tried installing git-lfs and redownloading the file. The problem is, it is not my repo, and the original owner did not store the data in a repo in the first place.


text:
Q: How to create a new context per every async operation and use it in a thread-safe manner for storing some data I'm working on something like a context-bound caching and a little bit stuck on thread-safety...
Let's say I have the following code:
public class AsynLocalContextualCacheAccessor : IContextualCacheAccessor
{
    private static readonly AsyncLocal<CacheScopesManager> _rCacheContextManager = new AsyncLocal<CacheScopesManager>();

    public AsynLocalContextualCacheAccessor()
    {
    }

    public CacheScope Current
    {
        get
        {
            if (_rCacheContextManager.Value == null)
                _rCacheContextManager.Value = new CacheScopesManager();

            return _rCacheContextManager.Value.Current;
        }
    }
}

public class CacheScopesManager
{
    private static readonly AsyncLocal<ImmutableStack<CacheScope>> _scopesStack = new AsyncLocal<ImmutableStack<CacheScope>>(OnValueChanged);

    public CacheScopesManager()
    {
        CacheScope contextualCache = _NewScope();

        _scopesStack.Value = ImmutableStack.Create<CacheScope>();
        _scopesStack.Value = _scopesStack.Value.Push(contextualCache);
    }

    public CacheScope Current
    {
        get
        {
            if (_scopesStack.Value.IsEmpty)
                return null;

            CacheScope current = _scopesStack.Value.Peek();
            if (current.IsDisposed)
            {
                _scopesStack.Value = _scopesStack.Value.Pop();
                return Current;
            }

            // Create a new scope if we entered the new physical thread in the same logical thread
            // in order to update async local stack and automatically have a new scope per every logically new operation
            int currentThreadId = Thread.CurrentThread.ManagedThreadId;
            if (currentThreadId != current.AcquiredByThread)
            {
                current = _NewScope();
                _scopesStack.Value = _scopesStack.Value.Push(current);
            }

            return current;
        }
    }

    private static void OnValueChanged(AsyncLocalValueChangedArgs<ImmutableStack<CacheScope>> args)
    {
        // Manual is not interesting to us.
        if (!args.ThreadContextChanged)
            return;

        ImmutableStack<CacheScope> currentStack = args.CurrentValue;
        ImmutableStack<CacheScope> previousStack = args.PreviousValue;

        int threadId = Thread.CurrentThread.ManagedThreadId;

        int threadIdCurrent = args.CurrentValue?.Peek().AcquiredByThread ?? -1;
        int threadIdPrevious = args.PreviousValue?.Peek().AcquiredByThread ?? -1;

        // Be sure in disposing of the scope
        // This situation means a comeback of the previous execution context, in case if in the previous scope Current was used.
        if (currentStack != null && previousStack != null
            && currentStack.Count() > previousStack.Count())
            currentStack.Peek().Dispose();
    }
}

And I'm trying to satisfy the next test:
    [TestMethod]
    [TestCategory(TestCategoryCatalogs.UnitTest)]
    public async Task AsyncLocalCacheManagerAccessor_request_that_processed_by_more_than_by_one_thread_is_threadsafe()
    {
        IContextualCacheAccessor asyncLocalAccessor = new AsynLocalContextualCacheAccessor();
        Task requestAsyncFlow = Task.Run(async () =>
        {
            string key1 = "key1";
            string value1 = "value1";

            string key2 = "key2";
            string value2 = "value2";

            CacheScope scope1 = asyncLocalAccessor.Current;

            string initialKey = "k";
            object initialVal = new object();

            scope1.Put(initialKey, initialVal);
            scope1.TryGet(initialKey, out object result1).Should().BeTrue();
            result1.Should().Be(initialVal);

            var parallel1 = Task.Run(async () =>
            {
                await Task.Delay(5);
                var cache = asyncLocalAccessor.Current;
                cache.TryGet(initialKey, out object result2).Should().BeTrue();
                result2.Should().Be(initialVal);

                cache.Put(key1, value1);
                await Task.Delay(10);

                cache.Items.Count.Should().Be(1);
                cache.TryGet(key1, out string result11).Should().BeTrue();
                result11.Should().Be(value1);
            });

            var parallel2 = Task.Run(async () =>
            {
                await Task.Delay(2);
                var cache = asyncLocalAccessor.Current;

                cache.StartScope();

                cache.TryGet(initialKey, out object result3).Should().BeTrue();
                result3.Should().Be(initialVal);

                cache.Put(key2, value2);
                await Task.Delay(15);

                cache.Items.Count.Should().Be(1);
                cache.TryGet(key2, out string result21).Should().BeTrue();
                result21.Should().Be(value2);
            });

            await Task.WhenAll(parallel1, parallel2);

            // Here is an implicit dependency from Synchronization Context, and in most cases
            // the next code will be handled by a new thread, that will cause a creation of a new scope,
            // as well as for any other await inside any async operation,  which is quite bad:(

            asyncLocalAccessor.Current.Items.Count.Should().Be(1);
            asyncLocalAccessor.Current.TryGet(initialKey, out object result4).Should().BeTrue();
            result4.Should().Be(initialVal);
        });

        await requestAsyncFlow;

        asyncLocalAccessor.Current.Items.Count.Should().Be(0);
    }

And actually this test is green, but there is one (or more) problem. So, what I'm trying to achieve, is to create a stack of scopes per every new async operation (if the current scope was accessed) and when this operation is finished I need to successfully come back to the previous stack. I have done this based on a current thread ID (because I didn't find any other way how to do that automatically, but I don't like my solution in any way), but if continuation of async operation was executed not in the initial thread (implicit dependency from current SynchronizationContext), but in any other, then this causes the creation of a new scope, which is very bad, as for me.
I would be glad if someone could suggest how to do that correctly, big thanks! :)
UPD 1. Code updated in order to add static for every AsyncLocal field since the value of every AsyncLocal is acquired from ExecutionContext.GetLocalValue() which is static, so non-static AsyncLocal just a redundant memory pressure.
UPD 2. Thanks, @weichch for the answer, since comment could be big, I just added additional info directly to the question. So, in my case logic with AsyncLocal stuff encapsulated, and what client of my code can do - it only invokes Current on IContextualCacheAccessor, which will get the instance of an object under AsyncLocal<CacheScopesManager>, AsyncLocal is used here just to have one instance of CacheScopesManager per logical request and share it across this request, similar to IoC-Container scoped lifecycle, but the lifecycle of such object is defined from the creation of the object until the end of the async flow where this object was created. Or let's think about ASP NET Core where we have IHttpContext, IHttpContext does not seem to be immutable, but is still used as AsyncLocal through IHttpContextAccessor, isn't it? Similar to this way CacheScopesManager was designed.
So, if client code, to get current CacheScope, can only invoke Current on IContextualCacheAccessor, then in case of AsyncLocal implementation of IContextualCacheAccessor call stack will fall into next code:
public CacheScope Current
{
    get
    {
        if (_scopesStack.Value.IsEmpty)
            return null;

        CacheScope current = _scopesStack.Value.Peek();
        if (current.IsDisposed)
        {
            _scopesStack.Value = _scopesStack.Value.Pop();
            return Current;
        }

        // Create a new scope if we entered the new physical thread in the same logical thread
        // in order to update async local stack and automatically have a new scope per every logically new operation
        int currentThreadId = Thread.CurrentThread.ManagedThreadId;
        if (currentThreadId != current.AcquiredByThread)
        {
            current = _NewScope();
            _scopesStack.Value = _scopesStack.Value.Push(current);
        }

        return current;
    }
}

and if another thread decided to use Current, this will cause the creation of new scope, and since ImmutableStack<CacheScope> is 'AsyncLocal', we are saving the stack of the previous async flow from any changes, which means that when we return to it, the stack will be fine without any corruptions (for sure, if hacks were not used). All this was done to make the stack of scopes threadsafe, rather than a real 'AsyncLocal'. So, your code
async Task Method1()
{
    Cache.Push(new CacheScope { Value = "Method1" });

    await Task.WhenAll(Method2(), Method3());

    Cache.Pop();
}

async Task Method2()
{
    await Task.Delay(10);

    var scope = Cache.CurrentStack.Peek();
    scope.Value = "Method2";

    Console.WriteLine($"Method2 - {scope.Value}");
}

async Task Method3()
{
    await Task.Delay(10);

    var scope = Cache.CurrentStack.Peek();

    Console.WriteLine($"Method3 - {scope.Value}");
}

in case if my accessor is used, will not cause mutation in the async flow which will be reflected in another one (and adding data to the scope of the previous async flow, before thread switching - is fine for me). But there is one problem, actually, the purpose of this CacheScope is to have some storage that goes across the logical request and caches some data, and this data is scoped to CacheScope and will be popped up from the referencable memory, as soon as the scope will end. And I want to minimize the creation of such scopes, which means that if code was executed sequentially, there should not be any reasons to create a new scope, even if continuation of some async operation has happened on another thread because logically code is still 'sequential' and it's ok to share the same scope per such 'sequential' code. Please, correct me if I wrong somewhere.
But your answer and explanation are really useful and for sure will protect others from making mistakes. Also, it helped me to understand what Stephen meant under:

If you do go down this route, I recommend writing lots and lots of
  unit tests.

my English is poor and I thought that 'route' means 'link to the article', now understand that it's is rather 'way' in that context.
UPD 3. Added some code of CacheScope for a better picture.
public class CacheScope : IDisposableExtended
{
    private ICacheScopesManager _scopeManager;
    private CacheScope _parentScope;

    private Dictionary<string, object> _storage = new Dictionary<string, object>();

    internal CacheScope(Guid id, int boundThreadId, ICacheScopesManager scopeManager,
        CacheScope parentScope)
    {
        _scopeManager = scopeManager.ThrowIfArgumentIsNull(nameof(scopeManager));

        Id = id;
        AcquiredByThread = boundThreadId;

        _parentScope = parentScope;
    }

    public Guid Id { get; }

    public int AcquiredByThread { get; }

    public IReadOnlyCollection<object> Items => _storage?.Values;

    public bool IsDisposed { get; private set; } = false;

    public bool TryExpire<TItem>(string key, out TItem expiredItem)
    {
        _AssertInstanceIsDisposed();

        key.ThrowIfArgumentIsNull(nameof(key));

        expiredItem = default(TItem);

        try
        {
            expiredItem = (TItem)_storage[key];
        }
        catch (KeyNotFoundException)
        {
            // Even if item is present in parent scope it cannot be expired from inner scope.
            return false;
        }

        _storage.Remove(key);

        return true;
    }

    public TItem GetOrPut<TItem>(string key, Func<string, TItem> putFactory)
    {
        _AssertInstanceIsDisposed();

        key.ThrowIfArgumentIsNull(nameof(key));
        putFactory.ThrowIfArgumentIsNull(nameof(putFactory));

        TItem result;

        try
        {
            result = (TItem)_storage[key];
        }
        catch (KeyNotFoundException)
        {
            if (_parentScope != null && _parentScope.TryGet(key, out result))
                return result;

            result = putFactory(key);

            _storage.Add(key, result);
        }

        return result;
    }

    public void Put<TItem>(string key, TItem item)
    {
        _AssertInstanceIsDisposed();

        key.ThrowIfArgumentIsNull(nameof(key));

        _storage[key] = item;

        // We are not even thinking about to change the parent scope here,
        // because parent scope should be considered by current as immutable.
    }

    public bool TryGet<TItem>(string key, out TItem item)
    {
        _AssertInstanceIsDisposed();

        key.ThrowIfArgumentIsNull(nameof(key));

        item = default(TItem);

        try
        {
            item = (TItem)_storage[key];
        }
        catch (KeyNotFoundException)
        {
            return _parentScope != null && _parentScope.TryGet(key, out item);
        }

        return true;
    }

    public void Dispose()
    {
        if (IsDisposed)
            return;

        Dictionary<string, object> localStorage = Interlocked.Exchange(ref _storage, null);
        if (localStorage == null)
        {
            // that should never happen but Dispose in general is expected to be safe to call so... let's obey the rules
            return;
        }

        foreach (var item in localStorage.Values)
            if (item is IDisposable disposable)
                disposable.Dispose();

        _parentScope = null;
        _scopeManager = null;

        IsDisposed = true;
    }

    public CacheScope StartScope() => _scopeManager.CreateScope(this);
}

A: Your code is really fighting the way AsyncLocal<T> works. Setting in a getter, trying to manage the scopes manually, having an async local manager for an async local type, and the code using the change handler are all problematic.
I believe all this is really to try to deal with the fact that CacheScope isn't immutable. The best way to solve this is to make CacheScope a proper immutable object. Then everything else will fall into place more or less naturally.
I find it's often easier to write a separate static API for immutable objects which is more "async local-friendly". E.g.:
public class ImplicitCache
{
  private static readonly AsyncLocal<ImmutableStack<(string, object)>> _asyncLocal = new AsyncLocal<ImmutableStack<(string, object)>>();

  private static ImmutableStack<(string, object)> CurrentStack
  {
    get => _asyncLocal.Current ?? ImmutableStack.Create<ImmutableDictionary<string, object>>();
    set => _asyncLocal.Current = value.IsEmpty ? null : value;
  }

  // Separate API:

  public static IDisposable Put(string key, object value)
  {
    if (key == null)
      throw new InvalidOperationException();
    CurrentStack = CurrentStack.Push((key, value));
    return new Disposable(() => CurrentStack = CurrentStack.Pop());
  }

  public static bool TryGet(string key, out object value)
  {
    var result = CurrentStack.Reverse().FirstOrDefault(x => x.Item1 == key);
    value = result.Item2;
    return result.Item1 != null;
  }
}

Usage:
public async Task AsyncLocalCacheManagerAccessor_request_that_processed_by_more_than_by_one_thread_is_threadsafe()
{
  Task requestAsyncFlow = Task.Run(async () =>
  {
    string key1 = "key1";
    string value1 = "value1";

    string key2 = "key2";
    string value2 = "value2";

    string initialKey = "k";
    object initialVal = new object();

    using var dispose1 = ImplicitCache.Put(initialKey, initialVal);
    ImplicitCache.TryGet(initialKey, out object result1).Should().BeTrue();
    result1.Should().Be(initialVal);

    var parallel1 = Task.Run(async () =>
    {
      await Task.Delay(5);
      ImplicitCache.TryGet(initialKey, out object result2).Should().BeTrue();
      result2.Should().Be(initialVal);

      using var dispose2 = ImplicitCache.Put(key1, value1);
      await Task.Delay(10);

      ImplicitCache.TryGet(key1, out string result11).Should().BeTrue();
      result11.Should().Be(value1);
    });

    var parallel2 = Task.Run(async () =>
    {
      await Task.Delay(2);

      ImplicitCache.TryGet(initialKey, out object result3).Should().BeTrue();
      result3.Should().Be(initialVal);

      using var disose3 = ImplicitCache.Put(key2, value2);
      await Task.Delay(15);

      ImplicitCache.TryGet(key2, out string result21).Should().BeTrue();
      result21.Should().Be(value2);
    });

    await Task.WhenAll(parallel1, parallel2);

    ImplicitCache.TryGet(initialKey, out object result4).Should().BeTrue();
    result4.Should().Be(initialVal);
  });

  await requestAsyncFlow;

  ImplicitCache.TryGet(initialKey, out _).Should().BeFalse();
}

A: I think @StephenCleary is not saying mutable CacheScope is incorrect, but semantically incorrect, meaning using mutable CacheScope may violate the purpose of AsyncLocal<T> being used in your cache.
AsyncLocal<T> is designed for providing access to ambient data which is local to an async control flow. Using mutable data type in AsyncLocal<T> could make such local data escape its scope.
For example, consider this
static class Cache
{
    private static AsyncLocal<ImmutableStack<CacheScope>> StackValue
        = new AsyncLocal<ImmutableStack<CacheScope>>();

    public static ImmutableStack<CacheScope> CurrentStack
    {
        get => StackValue.Value;
        set => StackValue.Value = value;
    }

    public static void Push(CacheScope scope)
    {
        CurrentStack = CurrentStack.Push(scope);
    }

    public static CacheScope Peek()
    {
        return CurrentStack.Peek();
    }

    public static void Pop()
    {
        CurrentStack = CurrentStack.Pop();
    }
}

Assuming there are two methods:
async Task Method1()
{
    // Push scope where Value = Method1
    Cache.Push(new CacheScope { Value = "Method1" });

    // Call method2
    await Method2();

    // Unexpected: value = Method2
    var value = Cache.CurrentStack.Peek().Value;

    Cache.Pop();
}

async Task Method2()
{
    await Task.Delay(10);

    var scope = Cache.CurrentStack.Peek();
    scope.Value = "Method2";
}

Method2 is a new async flow which has its own logical call context copied from Method1. However, because the copy is a shallow copy, the two contexts will share the same CacheScope instances in the ImmutableStack. Mutations made in Method2 could be unexpectedly reflected into Method1.
And remember, we could also do fork/join:
async Task Method1()
{
    Cache.Push(new CacheScope { Value = "Method1" });

    await Task.WhenAll(Method2(), Method3());

    Cache.Pop();
}

async Task Method2()
{
    await Task.Delay(10);

    var scope = Cache.CurrentStack.Peek();
    scope.Value = "Method2";

    Console.WriteLine($"Method2 - {scope.Value}");
}

async Task Method3()
{
    await Task.Delay(10);

    var scope = Cache.CurrentStack.Peek();

    Console.WriteLine($"Method3 - {scope.Value}");
}

You could see two sets of results:
Method3 - Method1
Method2 - Method2

and
Method3 - Method2
Method2 - Method2

The mutation made in Method2 unexpectedly flows into Method3.
This kind of unexpected behavior could be problematic to your cache. It would be really hard to locate bugs related to the implicit context when the call stack is fairly big, which is why Stephen suggested:

If you do go down this route, I recommend writing lots and lots of unit tests.


text:
Q: Style for chat top bar is broken Where to find: the main chat domain. For example https://chat.stackoverflow.com/ or https://chat.meta.stackexchange.com/ both have the same problem:
SE chat:

SO chat:

On the top, the user information and search is all the way to the left. Seems either some styling is missing or it is broken.


text:
Q: Change physics based on group - visjs I would like to make some groups of nodes in my Graph behave differently than the other nodes.
For example I have a group called "properties" that I dynamicly add to the graph. I need to change the gravity constants or weights for this group so they are closer to the parent then the rest of the nodes.

I hope this example helps visualize the problem. (Had to black out the labels because of sensitive info)
How would I accomplish this in vis.js?

A: //
Hi Json.
see the attached code snippet.
hope it helps you.

// create an array with nodes
  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1', group: 1},
    {id: 2, label: 'Node 2', group: 2},
    {id: 3, label: 'Node 3', group: 1},
    {id: 4, label: 'Node 4', group: 2},
    {id: 5, label: 'Node 5', group: 2}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  // create a network
  var container = document.getElementById('mynetwork');
  var data = {
    nodes: nodes,
    edges: edges
  };
  var options = {
    groups: {
      1: { color: 'red', mass: 500 },// try to change this value
      2: { color: 'blue', mass: 5 }
    },
    physics: true
  };
  var network = new vis.Network(container, data, options);

#mynetwork {
      width: 600px;
      height: 400px;
      border: 1px solid lightgray;
    }

    p {
      max-width: 600px;
    }
<!doctype html>

  <title>Network | Basic usage</title>

  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.css" rel="stylesheet" type="text/css"/>


text:
Q: Programa de python compilado con pyinstaller no se ejecuta en ALGUNOS pc Estoy intentando convertir un programa de python a exe con pyinstaller. El exe generado me funciona bien en 3 ordenadores y una máquina virtual pero al ejecutarlo en el ordenador de la empresa se queda la pantalla así:

Esta pantalla negra se queda para siempre.
Alguna idea de porqué no está compilando el código? Debería imprimir una frase diciendo: Idioma / Lenguage ? (esp/eng)
Esta es la primera parte del código:
import mkdir
from os import path

if path.isfile('utils/specs.py'):
    from utils.specs import lang
else:
    print('Idioma / Lenguage ? (esp/eng) ')
    lang = input()
    mkdir('utils')
    f = open("utils/specs.py", "w")
    f.write("lang = '" + lang + "'")
    f.close()

Como no existe ni la carpeta utils ni el fichero specs al ser la primera ejecución debería imprimir lo dicho anteriormente.
Alguna idea de lo que puede estar passando?
PD: comando utilizado para pyinstaller:
pyinstaller ./iwom_automator.py --onefile --icon=logo_iwom.ico


text:
Q: If $n,k\in\mathbb N$, solve $2^8+2^{11}+2^n=k^2$. If $n,k\in\mathbb N$, solve $$2^8+2^{11}+2^n=k^2$$
It's hard for me to find an idea. Some help would be great. Thanks.

A: HINT:
We have $\displaystyle2^8+2^{11}=2304$
Now, $2^8+2^{11}+2^0=2304+1\ne k^2$
$\displaystyle 2^8+2^{11}+2^1=2304+2\equiv2\pmod8$, but $a^2\equiv0,1,4\pmod8$
So,  $n\ge2$ let $n=m+2$ where $m\ge0$
$\displaystyle 2^8+2^{11}+2^{m+2}=4(576+2^m)\implies 576+2^m$ must be perfect square
Like either method $m\ge2$ let $m=r+2$ where $r\ge0$
$\displaystyle576+2^{r+2}=4(144+2^r)$
Follow this step
One Observation :
$$(2^4)^2+2\cdot2^4\cdot2^6+(2^6)^2=(2^4+2^6)^2$$

A: First assume $n\ge 8$ and write $n=m+8$, we get:
$$(2^4)^2(1+2^3+2^m)=k^2$$
This is possible only if $1+2^3+2^m=9+2^m$ is a perfect square. If it is, then we can write it as $(3+p)^2$ (since it is obviously greater than $3$), and thus:
$$9+6p+p^2=9+2^m$$
$$\Leftrightarrow p(6+p)=2^m$$
In particular, $p=2^r$ and $6+p=2^{m-r}$ for some $1\le r\le m$ (notice that $r=0$ is impossible). From this we get $6+p=6+2^r=2(3+2^{r-1})=2^{m-r}$, and the only solution to this equation is $r=1$, $m=4$. Thus the only solution for $n\ge8$ is $n=12$, which gives us:
$$2^8+2^{11}+2^{12}=80^2$$
Now for $0\le n<8$, we have:
$$2^n(2^{8-n}+2^{11-n}+1)=k^2$$
Since the number in the brackets cannot be a multiple of $2$, we observe that $n$ must be even. This leaves us with the condition that $2^{8-n}+2^{11-n}+1$ is a square. That number is exactly:
$$2^{8-n}3^2+1$$
For $n=6$ we have $2^23^2+1=37$ which is not a square.
For $n=4$ we have $2^43^2+1=145$ which is not a square.
For $n=2$ we have $2^63^2+1=577$ which is again not a square.
Finally for $n=0$ we have $2^83^2+1=1153$ which is not a square either.
Thus the only solution is $n=12$.

A: This is justa a partial solution.
we assume first that $n>8$ and we see $2^8+2^{11}+2^n=k^2$ as
$2^8(1+2^3+2^{n-8})=k^2$ we see $2^8$ is a square...
so the problem reduces to see when would $1+2^3+2^{n-8}$ be a square..
As we have assumed $n>8$ we would have $1+2^3+2^{n-8}$ to be an odd integer.
Now, any odd perfect square is congruent to $1$ modulo $8$
we see that $1+2^3$ is congruent to $1$ modulo $8$
so the problem is to make $2^{n-8}$ as $0$ modulo $8$
i.e., to make $n-8=3k$
least possible case would be $k=1$ i.e., $n=12$
I tried to repeat this and let $k=2$ but then It does not work.
being congruent to $1$ mod $8$ is only necessary condition but not sufficient so I can not say this works for all $k\geq 2$.
trying to solve this completely for a long time with no success. so i thought of posting what i have done and expecting for some suggestions.


text:
Q: Qt DragLeaveEvent not being called when leaving with a drag operation I have a row of buttons, each of which can accept drops. However, when I leave a button with my cursor with another button being dragged, the 'dragLeaveEvent' is not being called.
class Button(QtGui.QPushButton):
    def __init__(self):
        super(Button, self).__init__()
        self.setAcceptDrops(True)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            drag = QtGui.QDrag(self)
            mime = QtCore.QMimeData()
            mime.setText("f")
            drag.setMimeData(mime)
            drag.exec_()

    def dragEnterEvent(self, event):
        print "enter"

    def dragLeaveEvent(self, event):
        print "leave"

class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.mainLayout = QtGui.QVBoxLayout()
        self.setLayout(self.mainLayout)
        for i in range(10):
            btn = Button()
            self.mainLayout.addWidget(btn)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

A: As the documentation about dragEnterEvent() reports (it's from Qt5, but the same was valid for Qt4 also):

If the event is ignored, the widget won't receive any drag move events.

Note: any drag move events.
This also means drop events.
By default, all drag events are ignored for most widgets if the drag enter event is not accepted, so if you want to receive all events (including the leave event) that first event must be accepted.
class Button(QtGui.QPushButton):
    # ...
    def dragEnterEvent(self, event):
        event.accept()
        print "enter"


text:
Q: Hot Reload and Runtime Compilation Blazor Webassembly hosted I am developing a Blazor Webassembly hosted project with VS2019. Each time I change something in the razor pages, I have to recompile it. Which options are there to see changes in a preview or hot reload or what so ever?
I tried some Google solutions but they are not working. Adding the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget to my Server solution and add it in Startup.cs
services.AddControllersWithViews().AddRazorRuntimeCompilation();

has no effect and to the client solution it raised a error. Are there any problems in Blazor?

A: Assuming you are using .NET Core 3.1 or .NET 5 you can use the dotnet watch run command from a cmd line prompt on the folder with your CSPROJ file.


text:
Q: How to set cron in to run PHP file on localhost in Ubuntu? I want to execute a PHP script on my localhost in Ubuntu. I have tried a lots of methods to apply cron but no luck!

A: We can set cron on our localhost through following steps:

*

*Open crontab in your terminal:
EDITOR=gedit crontab -e

*Add your cron settings at the end of your file (we are setting cron to be execute in every 2 minute in our example):
*/2 * * * * /usr/bin/php -q /path/to/phpfile.php > /dev/null

*Save your cron file and run:
sudo service cron restart


text:
Q: why my adhoc profile will expire? I got notice from my Adhoc App at my Development device that, my adhoc profile will expire 2 days later.
But I want to use it as a Demo in next week.
Why that happens?
how to solve the problem?
thanks

A: Go to the developer.apple.com and download the profile again and install. You should see a download link there. If you dont have access to the portal, ask the team admin/agent for the profiles.


text:
Q: Efficient way to request touch focus from WindowManager? I have created two views on a FrameLayout, and requested focus to second. When I start the activity touch events hangs up for a while, then passes to my GL view. This takes random time I think (generally 5-10 seconds). It there a way to flush event queue?
I have a GLSurfaceView and I want draw an overlay SurfaceView above it. SurfaceView must be drawn on top of GLSurfaceView but input events must be delivered to opengl surface.
This is my activity,
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGLView= new SFView(this);
    mCanvas= new SFCanvas(this);

    mLayout=new FrameLayout(this);
    mLayout.addView(mCanvas);
    mLayout.addView(mGLView);

    setContentView(mLayout);

    mGLView.post(new Runnable() {
        public void run() {
        while( mGLView.isFocused() == false )
           {
                mGLView.requestFocus();
           }
        }
    });
}

and my Logcat looks like this.
KeyInputQueue        Enqueueing touch event1
KeyInputQueue        Enqueueing touch event0
KeyInputQueue        Enqueueing touch event1
KeyInputQueue        Enqueueing touch event0
KeyInputQueue        Enqueueing touch event1
KeyInputQueue        Enqueueing touch event0
..
WindowManager        Delivering pointer 1 > Window{com.myapplication/com.myapplication.activity}
WindowManager        Delivering pointer 0 > Window{com.myapplication/com.myapplication.activity}
WindowManager        Delivering pointer 1 > Window{com.myapplication/com.myapplication.activity}
KeyInputQueue        Enqueueing touch event0
WindowManager        Delivering pointer 0 > Window{com.myapplication/com.myapplication.activity}
KeyInputQueue        Enqueueing touch event1
WindowManager        Delivering pointer 1 > Window{com.myapplication/com.myapplication.activity}
..

I've also tried a single requestFocus() , but it gave same effect
Application becomes irresponsible at first seconds activity starts. Where did I wrong?
Thanks for all suggestions.
I am sorry for misexplanation, and for my language. I am a newbie for android platform, and this site.

A: I have found the mistake I did.
I was loading resources in views constructor. It was blocking android to doing stuff.
I've migrated resource loading into a child thread and problem fixed, a little.