Algorithm for best suiting people's choices from a definite list of items where there is only one of each available?

Question: Ladies and Gents,
My best friends and I do a "Secret Santa" type gift exchange every year, this year I've been trying to think of a couple of ways to make it interesting. There are six of us involved and I want to design a small program that allows the six of us to rank their preferred gift-recipients from 1 to 5 as well as their preferred gift-givers.
So, let's say we're called A, B, C, D, E and F.
A submits two lists:

List 1 - People I would most like to give a present to: B, D, C, F, E
List 2 - People I would most like to recieve a present from: F, D, E, B, C

All six of us will submit both these lists, so I'll have 12 lists all together. I suppose my question is what is the best algorithm to now go ahead and assign each person a gift recipient?
I thought of something like this:
If two people have both selected each other in their opposing lists (i.e. A most wants to give to B, B most wants to get from A) then I immediately assign A to B. So now A is removed from our list of gift-recipients and B is removed from our pool of gift-givers.
Once I've assigned the "perfect matches" I'm kind of lost though, is there an establish algorithm for situations like this? Obviously it's only for entertainment value but surely there must be a "real" application of something similar? Perhaps timetabling or something?
My Google-fu has failed me but I have a feeling it might just be due my own lack of precision in search terms.
Cheers,
(and Happy Holidays I guess),
Rob

Update / Part 2
Okay, Ying Xiao came to the rescue by recommending the Gale Shapley Algorithm for the Stable Marriage Problem and I've implemented that in Python and it works a treat. However, this is just a thought that occurred to me. I guess within our group of six best friends there are three pairings of "extra-best" friends so I have a feeling we'll just end up with three pairs of AB, CD, EF and BA, DC, FE in terms of gift giving and recieving.
Is there an algorithm we could design that did take peoples rankings into account but also restricted two people forming a "closed group"? That is, if A is assigned to buy a gift for B, B can not be assigned to buy a gift for A? Perhaps I need to solve the Stable roommates problem?
Related questions:

Secret santa algorithm.
What is the best low-tech protocol to simulate drawing names out of a hat and ensure secrecy?
Comment: This is a lot of work for Secret Santa.  I thought the point of Secret Santa was for it to be secret and random.(?)  Pick names out of a hat!  It's more fun that way.
Comment: Lisa, chances are we'll do exactly that. Although traditionally we've all put our phones into a bag and pulled them out, noted whose phone we got and then returned them. We've been doing it for years though so wanted some way to spice things up!
Answer: The Gale-Shapley algorithm (for the Stable Marriage problem) applies only when each person has a ranked list of all other participants -- you may or may not be able to convert your problem to that form (make everyone rank everyone).
Also, note that the thing it is optimizing for is something different: it tries to find a set of stable marriages, where no pair of people will "elope" because they prefer each other to their current partners. This is not something you care about in your Secret Santa application.
What you want (depending on your definition of "best") is a maximum-weight bipartite matching, which fixes both the above objections: put the "givers" on one side, the "receivers" on the other (so two copies of each person, in this case), give each edge a weight corresponding to how highly that giver ranks that receiver, and it is now the assignment problem. You can use the Hungarian algorithm for this, or simpler (slower) ones. You can also vary how you assign the weights to optimize for different things (e.g. maximize the number of people who get their first choice, or minimize the worst choice that anyone gets, etc.)
If you do use the Gale-Shapley stable marriage algorithm, note that it is optimal for the "proposers" (male-optimal and female-pessimal), so be sure to put the "givers" as the "proposers", and not vice versa.
Comment: @canary_in_the_data_mine Thanks for the note! Anyway I'm still torn on whether the "no eloping" goal of the stable-marriage problem is the same as the goal of the OP here.
Comment: Gale Shapley provides a matching that is pairwise Pareto (locally) optimal. The maximum weight matching scheme implicitly assumes that preferences are additive...this is a very strong (unfounded) assumption. I agree with your comment on male optimal/female pessimal though...
Comment: Yes, the Gale Shapley algorithm is better in game-theoretic settings, with a notion of "Pareto optimal" or "best response" or the possibility of "eloping", but this is not such a setting... all you want here is an assignment that is "good" by itself, not in terms of its local neighborhood.
Comment: Plus the weighted matching scheme extends to situations where the gift-givers assign weights to the receivers, not just ranks. :-)
Comment: Great answer, @ShreevatsaR, but I want to note that it is *not* strictly required to make everyone rank all other participants. Incomplete rank-ordered lists are acceptable but may leave unfilled positions (which is perhaps why you suggested they must be complete). For example, http://www.nrmp.org/wp-content/uploads/2014/05/Run-A-Match.pdf.
Answer: For each person, create two virtual people, a "giver" and a "receiver". Now match the set of givers against the set of receivers using the Gale Shapley Algorithm. Runs in O(n^2) time.
http://en.wikipedia.org/wiki/Stable_marriage_problem


(Project Tango) Rotation and translation of point clouds with area learning

Question: I have a java application that, when I press a button, records point clouds xyz coordinates together with the right pose.
What I want is to pick an object, record a pointCloud in the front and one in the back, then merge the 2 clouds.
Obviously to get a reasonable result I need to translate and rotate one or both the clouds I recorded. But I'm new to Tango Project and there are some things I should be missing.
I have read about this in this post.
There, @Jason Guo talks about those matrix:

start_service_T_device, imu_T_device , imu_T_depth

How could I get them?
Should i use getMatrixTransformAtTime()?

The first matrix is from start of service to device, but I'm using area learning, so my BaseFrame is TangoPoseData.COORDINATE_FRAME_AREA_DESCRIPTION.

Is it possible to use same strategy also in my case?
Just replacing start_service_T_device with something like area_description_T_device?

Side question
I want to extend this approach for the 3D reconstruction of objects.
I want to get several pointClouds of different view of the same object, rotate and translate them wrf some fixed axes. Then i'll assume that 2 points (x,y,z) and (x',y',z') are the same point if x~=x' && y~=y' && z~=z'.
This way i'll should be able to get a point cloud of the entire object, am I right?

Is this approach suitable?
Is there better alternatives?
Answer: The original post is a little bit out of date. Previously, we don't have getMatrixTransformAtTime(). So you have to use Tango.getPoseAtTime to query each of the transformation, and then chain them up using matrix.
But now, with getMatrixTransformAtTime, you can directly query area_description_T_depth, even in opengl frame. In order to transform a point cloud to the ADF frame in opengl, you can use following code (pseudo code):
TangoSupport.TangoMatrixTransformData transform =
  TangoSupport.getMatrixTransformAtTime(pointCloud.timestamp,
          TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
          TangoPoseData.COORDINATE_FRAME_CAMERA_DEPTH,
          TangoSupport.TANGO_SUPPORT_ENGINE_OPENGL,
          TangoSupport.TANGO_SUPPORT_ENGINE_TANGO);

// Convert it into the matrix format you use in render.
// This is a pure data structure conversion, transform is
// in opengl world frame already.
Matrix4x4 model_matrix = ConvertMatrix(transform);

foreach (Point p in pointCloud) {
  p = model_matrix * p;
}

// Now p is in opengl world frame.

But note that, you have to have a valid area description frame to query the pose based on area description, that is after relocalized with an ADF or in learning mode.
Comment: Thanks a lot.
Just one more thing:
I'm assuming your  `pointCloud` to be a `TangoXyzIjData` (am i right?). Points inside `pointCloud.xyz` are packed 3 by 3 so a point can be represented in a Vector3 or similar data structure.

So `myMatrix4x4 * myVector3` is gonna be an illegal expression.
Is `Point` something different than what I think?
Comment: Yes, the point cloud is TangoXyzIj. In order to let the matrix transform, you need to convert it to vector4 by adding 1.0 to the forth value. usually it's something like 'vec4 v = vec4(p.x, p.y, p.z, 1.0f);'
Comment: Thanks.
I tried and retried, but i always get TangoInvalidException when trying to calculate the transform matrix.
i get this error:
`E/tango: support_jni.cc:865 TangoSupport: problem calculating Matrix Transform`
` E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.xxx.yyy, PID: 14455 com.google.atap.tangoservice.TangoInvalidException`
Comment: I've only used the C Tango Support API, so the Java one might be different, but there is an initialization function you have to call before using the getMatrixTransformAtTime function.  I think for Java it is TangoSupport.initialize().


getting exception at expect interact command

Question: [Linux Dev:as ~]$ cat expectsh1.sh
echo "hi"
echo "world"
echo "hello"

[Linux Dev:as ~]$ cat expectshmain.sh
#!/usr/bin/expect

spawn "./expectsh1.sh"

expect "hello" { send "12\r" }
expect "hi" { send "23\r" }

interact

Getting Exception as below for interact statement :
[Linux Dev:as ~]$ ./expectshmain.sh
spawn ./expectsh1.sh
hi
world
hello
12
spawn_id: spawn id exp6 not open
while executing
"interact"
    (file "./expectshmain.sh" line 8)

Could any one please let me know whats the issue caused and solution for problem. What is the purpose of using interact command in shell..?
Comment: `interact` *is not* a shell command; it's an expect command, and expect is not a shell language (it's TCL). `expect` should only be used when you have a command which is otherwise impossible to control without human interaction, and you do not have one of those use cases.
Comment: Also, as they are not shell scripts, expect scripts should not be given names ending in `.sh`. (Neither should shell scripts -- see https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful -- but that's a longer discussion).
Answer: The purpose is to give control of the spawned program to the human at the keyboard. In this case, after you expect "hello", the spawned program is finished running.
If you don't actually want to interact with the spawned program, if you just want the expect script to exit cleanly, use expect eof
Answer: If your goal is to demonstrate use of expect, consider rewriting your scripts as such:
cat >expectsh1 <<'EOF'
#!/bin/sh
echo "hi"
read -r first_num
echo "world"
read -r second_num
echo "You entered $first_num and then $second_num"

# ...and do something with further human interaction
while read -r; do
  echo "You entered: $REPLY"
done
EOF

cat >expect-test <<'EOF'
#!/usr/bin/expect

spawn "./expectsh1"

expect "hello" { send "12\r" }
expect "hi" { send "23\r" }

interact
EOF


How to upgrade old sewer drain?

Question: I have a 4" cast iron sewer pipe in a concrete floor basement dating to 1910.
I can't figure out how it is configured. Here is what is visible:

The connection to the house drains is cast iron pipe about 5' long that slopes down into the concrete of the basement. It connects up to a vertical cleanout which might be part of a U or P-shaped trap, but if so it is buried in concrete below and not visible. Then nearby in the well is sloping cleanout. I cannot figure out how these might be connected because they are are at different angles.
The cast iron is 100 years old and probably should be replaced with new pipe, but I am not sure how to configure the new pipe. Should I just start jack hammering the concrete away to expose all the existing pipe so I can see where it goes?
Comment: Check out [this YouTube video](https://www.youtube.com/watch?v=qGN5y_-QMZc). It shows how to use a fish tape and a rented locator, to find the pipe.
Answer: Before resorting to demo you might hire a plumber to use a drain camera to scope upstream and downstream of the vertical cleanout, it might cost $60 - $100 but would be money well spent if it saves you some jack hammering and digging.
There are some pretty effective and long lasting methods of rehabilitating old sewer pipe by "shooting" a new internal pipe lining, the liners will even bridge cracks and small breaks. It involves high-pressure hydroblasting to clean the I.D., and opening up the line for access, but maybe that could be done from the exposed portion above the floor and 16" deep well. It may be a good alternative to extensive concrete demo and excavation.
Answer: I suspect that you and an electric jack hammer are going to become well acquainted in the next couple of weeks.  However as Jimmy says above, I would pay an experienced plumber to come down and look at your basement first.  His input would be well worth the price of a service call.

How to upgrade old sewer drain?


Is the following an Initial Value Problem or not?

Question: I'm trying to solve an Initial Value Problem, but I'm not sure now if the problem I have in hand is even an Initial Value Problem. Notes from Paul Dawkins' Course states IVP has the definition below - those are the initial values we have:
$$
\frac{dy}{dt} = f(t,y), \quad y(t_0) = y_0
$$
The problem I'm trying to solve on the other hand, is as follows:
$$
\frac{dy}{dt} = f(y), \quad y(t_0) = y_0
$$
In my problem $\frac{dy}{dt}$ is only a function of $y$, not $t,y$.
Does my problem qualify as an Initial Value Problem and can it be solved by Euler's method? The confusion arises, because I have an initial value and an initial direction. But the rate of change does not depend on time $t$ .
Thanks!
Comment: It's just a special case...
Comment: So it can be solved by Euler's method? Or is there a modification needed?
Answer: To post a clear answer to your query, kindly note that
$$
y' = f(y), \ \ y(t_0) = y_0 \tag{1}
$$
is an Initial Value Problem (with an autonomous ODE and an initial condition at $t_0$) and this is a special case of
$$
y' = f(t, y), \ \ y(t_0) = y_0 \tag{2}
$$
(general case - when $f$ involves $t$ and $y$, the IVP (2) involves a non-autonomous ODE and an initial condition at $t_0$).
Euler's method or any finite-difference method used for finding estimates for the solution to the IVP (2) can be also applied for
finding estimates for the solution to the IVP (1).
Comment: Hi @Dr.Sundar, this is unrelated to your answer, hence I would be deleting this comment soonest. Please could you help out with this question https://math.stackexchange.com/q/4435979/585488


Google App Function - Recalculate/Refresh values

Question: I have tried to find a solution to this problem already for a while.
This is the code
function CHECK(INPUT) {
  var url = "GOOGLE SHEET URL" + INPUT;
  var response = UrlFetchApp.fetch(url);
  var json = response.getContentText("UTF-8");
  var data = JSON.parse(json);
  var price = data;
  SpreadsheetApp.flush();
  return price;
}

This function pulls values from google sheet and, as a result, display it in another google sheet. The problem is that when the source changed the destination value do not change.
All that I need is something which will force to recalculate values in google sheet, or refresh function or something else but will keep values up-to-date.
P.S. =CHECK(INPUT, **DATE**) is not a solution
Answer:
You want to forcibly recalculate the custom function using Google Apps Script.

If my understanding is correct, how about this sample script? I think that there are several answers for your situation. So please think of this as just one of several answers.
In this sample script, in order to recalculate the function, the function is replaced by the same function.
Sample script 1:
In this sample script, when =CHECK(INPUT) is the cell "A1" of "Sheet1", the function is replaced by the same function.
var sheetName = "Sheet1"; // Please modify this for your situation.
var cell "A1"; // Please modify this for your situation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getSheetByName(sheetName).getRange(cell);
var formula = range.getFormula();
range.clearContent();
SpreadsheetApp.flush();
range.setFormula(formula);

Sample script 2:
In this sample script, all functions in "Sheet1" are replaced by the same function.
var sheetName = "Sheet1"; // Please modify this for your situation.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getSheetByName(sheetName).getDataRange();
var values = range.getValues();
var formulas = range.getFormulas();
var replacedValues = values.map(function(e, i) {return e.map(function(f, j) {return formulas[i][j] || f})});
range.clearContent();
SpreadsheetApp.flush();
range.setValues(replacedValues);

Note:

When the above sample scripts are run, the function is recalculated. For example, one of sample scripts is installed as the time-driven trigger, the function you want to recalculate is forcibly updated by the time-driven trigger.

References:

getFormula()
getFormulas()
setFormula(formula)
setFormulas(formulas)
Time-driven triggers

If I misunderstood your question and this was not the direction you want, I apologize.
Comment: @Oksana Ok Thank you for replying. I'm glad your issue was resolved.
Comment: Thank you, have modified a bit second script and now it does work, THANK YOU !!


Is it possible to simplify $ \sin\left(\frac{1}{2}\arctan x\right)$?

Question: Is it possible to simplify the expressions
$$
\sin\left(\frac{1}{2}\arctan x\right)
$$
and
$$
\cos\left(\frac{1}{2}\arctan x\right)?
$$
My idea was to make use of the double angle formulae to reexpress the above expressions as e.g.
$$
\frac{1}{\sqrt{x^2+1}}=\sin\left(\arctan x\right)=2\sin\left(\frac{1}{2}\arctan x\right)
\cos\left(\frac{1}{2}\arctan x\right),
$$
and similarly for $\cos\left(\arctan x\right)$, but I haven't been able to solve for $
\sin\left(\frac{1}{2}\arctan x\right)$ or $
\cos\left(\frac{1}{2}\arctan x\right)$.
Comment: As a practical note, $\sin(\frac 12\arctan(x))$ is not much different from $\alpha\arctan(x)$ with some $\alpha$ slightly less than $\frac 12$ (approx 0.46). This may be of interest if you call for approximation instead of exact value.
Answer: Try $$\sin^2\Bigl({x\over 2}\Bigr) = {1-\cos(x)\over 2}$$ to get rid of the one-half.
Answer: $$\sin^2\Bigl({\theta\over 2}\Bigr) = {1-\cos(\theta)\over 2}$$
$$\sin^2\Bigl({\arctan(x)\over 2}\Bigr) = {1-\cos(\arctan(x))\over 2}={1-{1\over \sqrt{1+x^2}}\over 2}$$
By the way, $\sin(\arctan(x))={x\over \sqrt{1+x^2}}$, not ${1\over \sqrt{1+x^2}}$


Create a tree using get / set functions that accept an arbitrary number of parameters

Question: I'm trying to create two functions: get & set, that both accept an arbitrary # of parameters (let's say 4). The set function accepts an array and sets it in memcached, the get function gets an array from memcached and returns it.
<code>function get($a, $b, $c, $d) {
    ...
    return $array;
}

function set($a, $b, $c, $d, $array) {
    ...
}
</code>
Let there be 5 possibilities for $a, 10 possibilities for $b, 100 possibilities for $c, and 1000 possibilities for $d.
The twist: only $a is guaranteed, but there should always be a response to get (based on whatever data is passed it). It should also be able to handle a case where for a given $a, $b, & $c, if there's nothing set that matches all three of those params, it goes "up" (in a tree sense) and finds the closest match based on the priority of the param).
Right now I'm thinking of building some form of weighted tree, with the params being prioritized and assigned weights (e.g. $a has priority 100, $b has priority 10, $c has priority 90, $d has priority 50)...
Code is language agnostic, looking more for ideas on how to approach this (most effectively / efficiently). Thanks in advance!
Answer: I would approach this as a nearest neighbor search problem (the wikipedia link is a fairly good summary). If you can find a suitable distance metric perhaps you can be best off with a off-the-shelf algorithm/data structure, say the R-Tree.


Flair Framework with PyTorch - OverflowError: int too big to convert

Question: I'm trying to train a named entity recognition model with Flair Framework (https://github.com/flairNLP/flair), with this embedding: TransformerWordEmbeddings('emilyalsentzer/Bio_ClinicalBERT'). However, it always failed with OverflowError: int too big to convert. This is also happening in some other transformer word embedding such as XLNet. However, BERT and RoBERTa works fine.
Here is the full traceback of the error:
2021-04-15 09:34:48,106 ----------------------------------------------------------------------------------------------------
2021-04-15 09:34:48,106 Corpus: "Corpus: 778 train + 259 dev + 260 test sentences"
2021-04-15 09:34:48,106 ----------------------------------------------------------------------------------------------------
2021-04-15 09:34:48,106 Parameters:
2021-04-15 09:34:48,106  - learning_rate: "0.1"
2021-04-15 09:34:48,106  - mini_batch_size: "32"
2021-04-15 09:34:48,106  - patience: "3"
2021-04-15 09:34:48,106  - anneal_factor: "0.5"
2021-04-15 09:34:48,106  - max_epochs: "200"
2021-04-15 09:34:48,106  - shuffle: "True"
2021-04-15 09:34:48,106  - train_with_dev: "False"
2021-04-15 09:34:48,106  - batch_growth_annealing: "False"
2021-04-15 09:34:48,107 ----------------------------------------------------------------------------------------------------
2021-04-15 09:34:48,107 Model training base path: "/home/xxx/data/xxx-clinical-bert"
2021-04-15 09:34:48,107 ----------------------------------------------------------------------------------------------------
2021-04-15 09:34:48,107 Device: cuda:0
2021-04-15 09:34:48,107 ----------------------------------------------------------------------------------------------------
2021-04-15 09:34:48,107 Embeddings storage mode: gpu
2021-04-15 09:34:48,116 ----------------------------------------------------------------------------------------------------
Traceback (most recent call last):
  File "train_medical_2.py", line 144, in <module>
    train_ner(d + '-base-ent',corpus_base)
  File "train_medical_2.py", line 136, in train_ner
    max_epochs=200)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/trainers/trainer.py", line 381, in train
    loss = self.model.forward_loss(batch_step)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/models/sequence_tagger_model.py", line 637, in forward_loss
    features = self.forward(data_points)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/models/sequence_tagger_model.py", line 642, in forward
    self.embeddings.embed(sentences)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/embeddings/token.py", line 81, in embed
    embedding.embed(sentences)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/embeddings/base.py", line 60, in embed
    self._add_embeddings_internal(sentences)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/embeddings/token.py", line 923, in _add_embeddings_internal
    self._add_embeddings_to_sentence(sentence)
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/flair/embeddings/token.py", line 999, in _add_embeddings_to_sentence
    truncation=True,
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/transformers/tokenization_utils_base.py", line 2438, in encode_plus
    **kwargs,
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/transformers/tokenization_utils_fast.py", line 472, in _encode_plus
    **kwargs,
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/transformers/tokenization_utils_fast.py", line 379, in _batch_encode_plus
    pad_to_multiple_of=pad_to_multiple_of,
  File "/home/d111199102201607101/flair/lib/python3.6/site-packages/transformers/tokenization_utils_fast.py", line 330, in set_truncation_and_padding
    self._tokenizer.enable_truncation(max_length, stride=stride, strategy=truncation_strategy.value)
OverflowError: int too big to convert

I have tried to change the embedding_storage_mode, hidden_size, and mini_batch_size. None of these gave me the fix to the issue.
Does anyone have the same issue?
Is there any way to resolve this?
Thanks
Comment: I have the same issue. Have you managed to solve this?
Answer: you can use the below parameters to limit the length of tokens
embedding = TransformerWordEmbeddings('emilyalsentzer/Bio_ClinicalBERT')
embedding.max_subtokens_sequence_length = 512
embedding.stride = 512//2


Current Page URL in a hyperlink

Question: In the code below, I am hard coding the url.

Instead I want something like this:

Edit: For the record I used
$(location).attr('href');

However nothing gets returned.
Is there any  cross-browser Javascript to return the current url of the page?
Answer: To get the path, you can use:
  var pathname = window.location.pathname; // Returns path only
  var url      = window.location.href;     // Returns full URL

You can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if you're interested in rather links starting with a   certain URL, use the attribute-starts-with selector:
var allLinks = $('a[href^="http://google.com"]');

Answer: If you are looking for a browser compatibility solution use
window.location.href

where document.URL is having issues with Firefox with reference to this
Current URL

This is simple to use as below with no complexity ,the thing what I found is you are not assigning any value to the href attribute and by default in jquery it assigns back

https://somewebsite.com/submit/?url=returnpageurl()

Now the below one should work for your case,
 $("#current_url").attr("href",window.location.href );

Answer: This is easy to achieve by using the window.location.href JavaScript window property.
Html Example:
my link

Javascript
var a = document.getElementById('link1');
a.href = a.href + '?returnUrl=' + encodeURIComponent(window.location.href);

With jQuery:
$('#link1').attr('href', $('#link1').attr('href') + '?returnUrl=' + encodeURIComponent(window.location.href));

Note the use of the built in function encodeURIComponent(str) reference.

The encodeURIComponent() function encodes a Uniform Resource
  Identifier (URI) component by replacing each instance of certain
  characters by one, two, three, or four escape sequences representing
  the UTF-8 encoding of the character (will only be four escape
  sequences for characters composed of two "surrogate" characters).

Current Page URL in a hyperlink


Use of frames with vertical scrolling for product area - Good or Bad?

Question: I wonder if using frames with vertical scrolling for product display and selection is a no-no from the usability standpoint or is it OK? Here is a wireframe where our designer suggests this solution http://wordofbuzz.com/wyf/SunTouch_Mats.html

Although in the above example the frames seem to make sense - I personally get a bit nervous when I work with sites that have product descriptions or other info implemented like that - you want to scroll the page and it scrolls inside the frame or vice versa you want to scroll the frame and it scrolls the entire page.
Comment: Are you talking about literal frames (HTML elements)? Or just scrollable areas of content? The former is typically never a great idea. The latter can work, but your big hurdle there is usability on touch screens.
Comment: It seems all-in-one-page site pushes you to frames. Actually it could be better to re-design the site.
Comment: Thanks Alex! - it's not a site but a landing page for PPC - so everything needs to happen on one page ideally. There is a traditional ecommerce site behind that landing page with a conventional display for products/categories but it doesn't make it clear how to select/buy the right product (the nature of the product requires that you know a few specific things about your project before you can buy the right one that would fit - right now people are just calling for help or bailing)
Comment: What is the *maximum* number of items that'll appear in the scrollable table?
Comment: Jon, the total number of items for the 1st tab is 30 - i think those tabs in the wireframe have the exact products that will be showing live. There won't be any more
Comment: thanks and yes i'm talking about the latter - scrallable content. Overall when you open this wireframe - does it strike you as user-friendly or you feel like something wrong is going on with those scroll areas or some other things.
Comment: the page will be used for PPC and will target desktop computers for now
Answer: Users spend 80% of their time looking at information above a page fold (see "Scrolling and Attention").  But somehow they need to pick the right product.  So instead of thinking of this pattern as generally "good" or "bad" ask instead, "How can I get the customer to pick the right product the fastest?"
A pattern based on questions
If you were in a brick and mortar store and they wanted to purchase a mat, you could start out by asking "what size area do you need to heat?"  In the UI this could translate to a dropdown list with the different sizes.  After that they would need to pick the wattage.  And so on.  This pattern is called "Cascading Lists".  This helps eliminate the noise of products for which they're not interested.
A pattern based on browsing
However, customers might want to browse and see what they can get based on the price instead of specifying a heating area.  Another pattern is "Active Filtering".  This pattern supplements the list you provide while minimizing how often users should spend scrolling.
To summarize
To answer your question, this could be confusing but not a deal breaker.  I think the more important issue is figuring out a pattern to get them to the right item without relying on them to scroll and find it in a list.
Comment: Thank you so much Jonathan - this is awesome info! Very educational and makes absolute sense.
Comment: Our earlier wireframe for a similar product included some of the items you re talking about but we had limitations in the way we could implement it and had to go that other route. http://wordofbuzz.com/wyf/Kits_4.html Thanks a lot again for the great info!
Comment: @Mark Glad to hear - your new wireframe looks much improved.


Will high wattage LED bulb work with this light fixture?

Question: I am looking to replace the LED light bulbs in my ceiling downlights with some stronger ones.
Specification of existing lightbulb: LED, GU10, 5W, 240V
Specification of light fixture: KR (KangRong), 250V, 100W, K512GU, 2/250
The attached pictures show the existing light bulb and fixture.
I would like to replace the light bulb with a GU10 LED bulb with around 10W and 950 lumen. Was wondering if switching to such a higher wattage light bulb will be safe. My main worry is risk of fire due to overheating.
Thanks for your advice.
Answer: The part number you supply is just for the socket, it is rated for the heat of a 100w GU10 bulb, the socket can definitely handle 10 watts of heat put out by a 10w bulb.
But nobody can tell from the socket rating what heat limit the trim is or what voltage the supporting wiring is designed to withstand.
Common design of that style of fixture is to be able to handle 35, 50, or 75w incandescent bulb, so it is likely able to handle 10 watts, but more info is needed to be certain. It is possible (but unlikely) that the fixture was designed to operate with a maximum of 5w, but that really seems unimaginable.
Comment: Halogen, not incandescent bulbs, though the general point is still sound.
Comment: @user3757614 Don't halogens emit electromagnetic radiation, making halogens a type of incandescent?
Comment: All lights emit electromagnetic radiation by definition; visible light is on the electromagnetic spectrum. Halogen bulbs are a type of incandescent light that can operate at a higher temperature in a smaller package, thus making them more suitable for small fixtures like this. However, this is Home Improvement, where Halogen and Incandescent mean different things.
Comment: Great, thanks NoSparksPlease and user3757614 for your replies!


How to find blank within Category in Pandas

Question: I am trying to find "Order Number" of the Customer that has been designated a Driver but not for that Order Number. if you see in the screen shot attached

You can See "Ray" that has no Designated Driver as well,but since none of his Orders has been designated a Driver ,I am not looking to get him ,in the following case only trying to get "James" with Order "15"
Please help
Thank you
Comment: what have you tried so far? Can you share your code
Comment: Since you are trying, please share what did you try so far. Not as an image, please. Will be impossible to copy-paste your code for us to test any possible solution.
Comment: read through this and see if you can get some help doing it yourself. https://datatofish.com/if-condition-in-pandas-dataframe/.  Also search Stack Overflow for similar questions. There are many questions that answer this
Answer: Given csv as per screenshot (data.csv):
name,address,order_num,driver
james,ny,12,rod
james,ny,13,rod
ray,ny,14,
james,ny,15,
cody,ny,16,rod
ray,ny,,

You can groupby customer (name) and then apply filter where
1 -  at least one order has empty driver
2 - not all driver is empty
import pandas as pd

df = pd.read_csv("data.csv")
g = df.groupby("name").filter(
    lambda s: s["driver"].isna().values.any() and not all(s["driver"].isna())
)
print(g[g["driver"].isna()])

and get the following:
    name address  order_num driver
3  james      ny       15.0    NaN


Invertibility of a matrix.

Question: Indicate why if a is a square matrix such that in each row and in each column one and only one element is non-zero then a is an invertible matrix.
I tried to encompass the problem by determinants, taking it to a form in which the main diagonal is zeros and the rest we all numbers are different from zero, but I can not find how to explain that the determinant of that matrix is different from zero.
Comment: What happens if you put it in row-echelon form?
Comment: The columns are linearly independent (to wit, a reordering of the standard basis of $\Bbb R^n$).
Comment: I can't see what happen when i put in the row-echelon form because i think there we already suppose some stuffs that we have to proof
Comment: Of all the terms in the determinant, exactly one is nonzero.
Comment: Reorder the rows (or columns if you prefer) so that your matrix is diagonal.
Comment: First paragraph says exactly one nonzero entry in each row/column. Example considered in 2nd paragraph is the opposite – exactly one zero in each row/column.
Answer: This should give you some intuition on why your square matrix is invertible (it is also what the people in the comments are saying/hinting at).
Say your matrix looks like  $\begin{pmatrix}
0 & a & 0 \\
b & 0 & 0 \\
0 & 0& c
\end{pmatrix}$. Then, you can simply rearrange the columns so that it looks like $\begin{pmatrix}
a& 0 & 0 \\
0 & b & 0 \\
0 & 0& c
\end{pmatrix}$. Once it is in this form, you should be able to tell that all of the columns are linearly independent. Thus, the matrix is invertible. (Note: It is important to assume that the matrix is square.)
Answer: We need to show that any column vector is not in the span of the others (i.e. they're linearly independent). Take one such column vector and suppose its nonzero element is in the $i$th row. Then in this row the other vectors have all $0$ entries by the condition, so their span contains of vectors with $0$ entries in the $i$th row too. Clearly, this column vector, having a nonzero element in that row, is not in the subspace.

Invertibility of a matrix.


Messaging an unbound service from Broadcast Receiver

Question: I currently have two services in my android application, which for simplicity I'll call DataService, and CommunicationService. DataService retrieves data from a content provider, which it then serializes and passes on to CommunicationService. CommunicationService then takes the serialized data and divides it into packets, which it sends to a third-party device one packet at a time. The way that CommunicationService knows to send the next packet is through a BroadcastReceiver.
CommunicationService is started by DataService but is unbound and has a longer lifetime than DataService (which ends as soon as it has started CommunicationService). What is the best way for the BroadcastReceiver to call a method on CommunicationService to let it know that it's time to send the next packet? Two of the ideas that I've seen are:

Bind the service in the BroadcastReceiver, call the method, and unbind it. This seems to be best case incredibly bad practice and worst case not feasible.
peekService, although it appears this only works with a service that has been bound at least once, which rules it out.

I know that this architecture might seem a little confusing, but the goal for CommunicationService is to be able to reuse it across multiple apps that communicate with a third-party device; as a result, it can't be too tightly bound to a specific implementation.
Comment: You cannot call `context.bindService()` from a `BroadcastReceiver`. Can you explain why you can't just call `startService()` from your receiver? Even if the service is already running, it will receive a call to `onStartCommand()`
Comment: I was under the impression that `startService()` would start a new instance of a service - didn't realize it just signaled an existing one. This seems like the easiest solution so I might end up going with it! Thanks!
Answer: Your BroadcastReceiver may timeout, so better to have it call an IntentService
Since your goal is to have this service provide updates for more than one app, each app should register with the service (which notifies it of potential updates) and then the service should provide a callback to each registered app.
The callback can be specified by the CommunicationService and perform whatever functions you like, following the standard serialization restrictions for cross process communication, which you seem to be aware of.
So the basic "flow" would be something like:
Register -> respond with callback
BroadcastReceiver -> IntentService' -> execute callback ->CommunicationService'
The main issue with calling anything directly from the BroadcastReceiver is that your CommunicationService may have died, possibly leading to either a timeout or NPE. With the callback, it can check to see if the service is alive and if not, create it. The IntentReceiver should be wakeful. And providing a callback object allows you more control over thread-safe code for situations where there are multiple, simultaneous calls and/or data queuing.
Comment: Just to make sure I understand this correctly:

`CommunicationService` should extend `IntentService`. It provides the definition for a callback (either through an interface or an inner class that the clients of the service must implement). It provides a mechanism for registering a callback (perhaps a static public function that starts the service if it doesn't exist already) and a mechanism for triggering the next packet to be sent (likely by an Intent?).

(I can't find anything on `IntentReceiver` besides a post that suggests it's deprecated)
Comment: Yes - I meant `IntentService` - I edited my post where I made that mistake. You should be careful with having it define a callback through an interface because not all clients will properly implement serialization, which is required. However, you may be able to define flexible callback object API's that are properly serialized, depending on your use-case.
Comment: Awesome, I think that makes sense then! Thanks for the help.


What is the "array of intensity values" return value of CGColorGetComponents()?

Question: const CGFloat * CGColorGetComponents ( CGColorRef color );
The Apple documentation says  CGColorGetComponents() returns an array of "intensity values". What does it mean by intensity value? Why is its return type not an array but a pointer to CGFloat instead?
Answer: The reason it says "an array of intensity values" is that it doesn't know what the numbers in the array mean. Their meaning depends upon the color's color space. For example, if it's a greyscale color space, there are two numbers, the amount of whiteness and the amount of transparency. But if it's an RGB color space, there are four numbers, the red, green, blue, and transparency components. And there are many other possibilities.
The reason it's a pointer to CGFloat is that this is a C API, and in C, a pointer to a CGFloat is the same as an array of CGFloat.
Comment: If you don't know C, you can't know Objective-C. You might want to read my book, which teaches you enough C to use Objective-C. Here's the section on arrays: http://www.apeth.com/iOSBook/ch01.html#_arrays


How to save a data frame as CSV to a user selected location using tcltk

Question: I have a data frame called, Fail.
I would like to save Fail as a CSV in a location that the user selects.  Below is some example code that I found, but I don't know how to incorporate Fail into it.
require(tcltk)
fileName <- tclvalue(tkgetSaveFile())
if (!nchar(fileName)) {
    tkmessageBox(message = "No file was selected!")
} else {
    tkmessageBox(message = paste("The file selected was", fileName))
}

Answer: Take a look at the write.csv or the write.table functions. You just have to supply the file name the user selects to the file parameter, and the dataframe to the x parameter:
write.csv(x=df, file="myFileName")

Comment: I didn't see it mentioned, so I thought it would be useful to mention the
    `row.names = F`
parameter that will remove the rownames from taking up an output column
Answer: You need not to use even the package "tcltk". You can simply do as shown below:
write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".
Answer: write.csv([enter name of dataframe here],file = file.choose(new = T))

After running above script this window will open :

Type the new file name with extension in the File name field and click Open, it'll ask you to create a new file to which you should select Yes and the file will be created and saved in the desired location.


Why does HttpWorkerRequest fail during HttpRuntime.ProcessRequest after a .NET 2.0 to .NET 4.0 upgrade?

Question: I am upgrading our application, which has an internal webserver, from .NET 2.0 to .NET 4.0.
I am handling a request with an object HttpListenerWorkerRequest, that extends the HttpWorkerRequest class, and creates a request which GetRawUrl() returns a Url in the format of http://localhost:82/Default.aspx.
In .NET 2.0, sending this to HttpRuntime.ProcessRequest(httpListenerWorkerRequest) works without issue, however in .NET 4.0, I get a web page with the nothing but the text "Bad Request" on it.
Cracking open HttpRuntime, I can see that Bad Requests are thrown from ProcessRequestInternal(HttpWorkerRequest wr), a private method that tries to build an HttpContext.
I tried this myself:
try
{
    //what's going on?
    hcontext = new HttpContext(workerRequest);
}
catch(Exception e)
{
    //Debugging break point here
}

Pre-update (.NET 2.0), it builds fine, post-update (.NET 4.0), I get a System.ArgumentException stating that
The relative virtual path 'http:/localhost:82/Default.aspx' is not allowed here,  thrown at
at System.Web.VirtualPath.Create(String virtualPath, VirtualPathOptions options)
   at System.Web.HttpRequest.get_ClientFilePath()
   at System.Web.Security.CookielessHelperClass.RemoveCookielessValuesFromPath()
   at System.Web.HttpContext.Init(HttpRequest request, HttpResponse response)
   at System.Web.HttpContext..ctor(HttpWorkerRequest wr)
   at Talcasoft.Web.Hosting.HttpWorkerThread.Run(Object request) in
   C:\[OurLibrary].Web\Hosting\HttpWorkerThread.cs:line 51

What has changed in .NET to cause this, and what can I do to get around it?
EDIT I have just noticed that the disallowed http: is followed by a single slash, not a double, although the GetRawUrl() in the request certainly returns a double.
Comment: http://www.asp.net/whitepapers/aspnet4/breaking-changes I think you hit the XSS change
Comment: @Lex Li, thanks for that, it certainly looks possible. I'll have to test that tomorrow, but let you know how it goes.
Comment: @Lex Li, not the case, unfortunately, thanks for the suggestion though
Comment: Can you show the entire exception? Set your debugger the break on all exceptions and disable "my code only" so that the debugger pauses on the first exception (the one that is being caught in ProcessRequestInternal).
Comment: That doesn't look like a relative virtual path at all.
Comment: @usr Amended the question to include it's a System.ArgumentException at VirtualPath.Create (I can see this is getting called within ProcessRequestInternal). Is that the information you were requesting?
Comment: @Andreas I agree. I didn't write the server code, but the person who did has left. It works in 2.0, so I am loathe to touch it until I understand how it broke. Stepping through it in 2.0 shows that nothing appears to have changed in the WorkerRequest
Comment: Did you make any progress yet? I'm interested in whether my suggestions works for you.
Comment: @usr We had to take our kid to the doctor today, do my mind has been on other things. I'll let you know tomorrow. Thanks for the input
Comment: usr and @NSGaga You are both worthy of receiving the bounty points, however, unless you know of some way to split the points, I have to choose. I thank you both enormously, but have decided, as NSGaga supplied the actual line of code I used to fix the problem (and he/she could use the additional rep more than usr) I will mark NSGaga as the accepted answer IF you work your last two comments into the post
Comment: @usr Please see comment above. Thanks again for your help.
Answer: I'm not a 100% certain that this is the 'exact answer' but looks pretty close to me - and there is some more to write...
There seems to be a breaking change of a sort inside the VirtualPath class - and it's substantiated with how they are checking for illegal characters. (btw. you can google the 'VirtualPath source' for what seems a .NET 4 version of it).
Inside VirtualPath.Create a check is invoked for 'illegal virtual path characters'.
It first goes into registry ("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET", "VerificationCompatibility") - to see if the compatibility mode 'illegal chars' should be used.

Based on that - I'm guessing (I don't have a way of checking this
  right now) - that if you set the above registry value (int) to 1 -
  you should get your methods working the old way and w/o any
  additional effort. Note: a IIS (or host process) restart may be required as suggested in one of the links

And then based on that registry flag it used either of these two...
':', '?', '*', '\0' // .NET 4.0 - the default
'\0' // the 'compatibility' mode

That seems to actually describe your story quite well as your path with the 'port' designation is actually illegal per the new default.

FINAL EDIT / EXPLANATION:
(update based on comments and the solution that solved it)
This is my understanding of what's going on inside:
1) Solution for prior to .NET 4.0 was the VerificationCompatibility key (see above).
2) With .NET 4.0 internal handling and fixing of url paths is made more robust. And works fine in most cases. In short, all paths are fixed and normalized before entering the VirtualPath.Create - and your http://... becomes an expected absolute path /Default.aspx.
However when you supply the HttpWorkerRequest (instead of Request/Response etc.) - the raw Url is taken directly from the worker - and the responsibility for supplying the correct and normalized paths is down to your worker request. (this is still a bit iffy, and looks like a bug or bad handling internally).
To reproduce the issue:
internal class MyRequest : SimpleWorkerRequest
{
    public MyRequest() : base("", "", String.Empty, String.Empty, null) { }
    public override String GetRawUrl() { return "http://localhost:82/Default.aspx"; }
}
// ...
var wr = new MyRequest();
var context1 = new HttpContext(wr);

Gives the error The relative virtual path 'http:/localhost:82/Default.aspx' is not allowed here.
The FIX:
public override String GetRawUrl()
{ return new Uri(url, UriKind.RelativeOrAbsolute).AbsolutePath; }

And some of the research on the subject based on that VerificationCompatibility keyword in the registry which seems to be the key to it.
Ampersand in URL filename = bad request
Configure IIS to accept URL with Special Characters...
For 32 vs 64 difference in Registry
And here is a similar thing from Microsoft - but what seems to be a 'hotfix' for '2.0', i.e. doesn't apply to you - but just attaching it as something official in this line.
FIX: "HTTP 400 - Bad request" error message in the .NET Framework 1.1
FIX: Error message when you try to visit an ASP.NET 2.0-based Web page: "HttpException (0x80004005): '/HandlerTest/WebForm1.aspx/a:b' is not a valid virtual path"
ASP.NET 2.0 x64 – You may get HTTP 400 Bad Request or Error as mentioned in KB 932552 or 826437

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET
DWord Value Name: VerificationCompatibility  Value Data: 1
Comment: It looks like the right answer, but still doesn't work. I'm going to drill down a bit further on this idea before I give up on it though. BTW, I'm using dotPeek to reflect on the code. Thanks for the pointers!
Comment: I tried fast and it's not easy to reproduce (context, request). But if you use a custom `HttpWorkerRequest` and just override `GetRawUrl()` to return your url - it fails (and this being the culprit `VirtualPath.Create("...", VirtualPathOptions.AllowAbsolutePath)` - called internally and you have no 'say' there). The registry setting indeed doesn't seem to have any effect on that so I confirmed that. **I think it's down to your `HttpListenerWorkerRequest.GetRawUrl()` which needs to return the proper absolute path (w/o host:port)**.
Comment: i.e. something like... `public override String GetRawUrl() { return new Uri(url, UriKind.RelativeOrAbsolute).AbsolutePath; }` in your `HttpListenerWorkerRequest` - should `fix` the problem.
Comment: thanks for your help on this. I had to take the day off, so I'll have a look at your work tomorrow.
Comment: the line public override String GetRawUrl() { return new Uri(url, UriKind.RelativeOrAbsolute).AbsolutePath; } worked perfectly! Thank you so much for your time on this!
Comment: you're welcome John - glad it helped. I just made a final edit to incorporate what's in the comments here. I think that's pretty much the whole story. I don't want to make your life more complicated, just to wrap this up into a proper answer. Whatever you do is fine, Cheers.
Answer: Here is my take on it. It still contains some guesswork but I'll include a test that you can make to prove or disprove this hypothesis.
The stack trace shows ClientFilePath.get as the origin of the exception. It looks like this:
    if (this._clientFilePath == null)
    {
        string rawUrl = this.RawUrl;
        int index = rawUrl.IndexOf('?');
        if (index > -1)
        {
            rawUrl = rawUrl.Substring(0, index);
        }
        this._clientFilePath
     = VirtualPath.Create(rawUrl, VirtualPathOptions.AllowAbsolutePath); //here!
    }
    return this._clientFilePath;

It creates a VirtualPath and allows only absolute values. http://localhost:82/Default.aspx is a relative path because it does not start with a slash. It is not a URL in this context because it is not being interpreted as such.
So VirtualPath.Create understandably denies this path. I don't know why .NET 2.0 allowed this, but .NET 4.0 requires an absolute path and according to the code this is non-configurable.
Actually, I have never seen HttpRequest.RawUrl return a URL before. In my experience it should return an absolute path like /Default.aspx. If you want to set the host and port you have to find other means to do that.
So the fix is to not use http://localhost:82/Default.aspx but /Default.aspx. Would that work for you?
Comment: Thanks, I'll have a look at that tomorrow, I was off today
Comment: That was exactly the problem. Thanks so much for your time and help on this. Unfortunately as there are 2 of you supplying this answer, I'm a bit stumped as to who to accept as the bounty winner.
Comment: I think you should accept the answer which explains the problem most clearly and which will be most useful for future visitors who have this exact problem. I'll leave that for you to judge.


How do you mark components and what effect does it have?

Question: Inspired by a statement in the question "How can I get more adhesive?":

I keep adhesive marked as a needed component all the time, and grab every piece of marked junk I see.

How do you mark crafting components? And I'm assuming it just "alerts" you when an item has that material, but how/when will I know exactly?
I play on PS4, in case it matters in terms of buttons.
Answer: You're also able to do this from within your inventory on the junk tab by selecting the "Component View" option. This also allows you to remove items from the search list:

Additionally, when you're in Workshop mode and building, if you do not have all of the required component parts to build an item the "Tag for search" option will enable on the bottom menu bar:

This will add the missing items from the item list to the search list and when you hover over an item that scraps into components including the parts on your search list the item name has a magnifying glass next to it.
Comment: Also worth noting: when you look at items in your inventory, and it shows the components it breaks down into, the ones you have marked have a magnifying glass next to them. This is useful in stores. I scroll to the item, then glance at the middle to see exactly which components it has that I need, and how many.
Comment: Ah! The fact that you can do it individually in the pip boy makes it so much better.
Answer: If you have the "Scrapper" perk at level 2, items that contain tagged components will be highlighted in the world, not just in item lists (e.g. inventory and shops). If such an item is inside a container, the whole container will be highlighted.
However, this only applies to junk, not scrappable items such as weapons and armor.
Answer: There are a few ways to tag items for search, but the easiest is to go into your junk inventory and enter component view, you can mark anything you have for search here. If you want to find something you don't have, say for a weapon mod, you can hit the button (it will tell you on-screen) and it will tag all items required for building for search. To do this you have to be at a workbench and highlighting a mod you want to build, items you don't have will be greyed out.
Now once you've tagged an item, you will see a magnifying glass icon next to the name of any junk items that can be broken down into that item. If you were to tag adhesive, junk items like wonderglue and duct tape would have the magnifying glass next to their name. It will appear at all times, whether it's sitting out in the open or in the inventory of something like a toolbox or enemy.


Excel formula in sorting delimited numbers in a single cell

Question: Im new in excel formulas. I need an excel formula that can sort delimited numbers in a single cell.
Note: I have different lengths of values per cell.
I.g.
349|2|4|11|1|2
Outcome:
1|2|2|4|11|349
Im thinking of reverse concatenating it first then sort it then concatenate it again. But i can't figure it out how to make a working formula for that. Hope someone can help me. Thanks.
Comment: Here is a [UDF Solution](https://superuser.com/questions/705131/sorting-values-within-a-cell-in-excel) that you can use. Just change the split to be on `|` instead of `,`
Comment: I believe you will ultimately need a VBA solution (in the form of a User Defined Function - UDF) to solve this because each number is separated by a delimiter. If you only had numbers in the cell, see [this site](https://www.extendoffice.com/documents/excel/1870-excel-sort-numbers-within-cell.html) for some ideas.
Comment: See if [this link](https://stackoverflow.com/a/60797214/9808063) helps .. I tried it on the given sample, no issues. It works on alphanumeric as well.
Answer: This formula solution worked in cell contains numeric value only.
The formula using Textjoin and Filterxml function of which Textjoin available in Office 365 and Excel 2019, and Filterxml available in Excel 2013 and later Excel version
Assume your data housed in A1
In B1, enter array formula (Confirm by pressing Shift + Ctrl + Enter) :
=TEXTJOIN("|",1,IFERROR(1/(1/SMALL(FILTERXML(""&SUBSTITUTE(A1,"|","")&"","//b"),ROW($1:$99))),""))


trying to make a schema

Question: I have a schema of a (course) which is this:
  targetNamespace="http://www.nova.edu/course"
  xmlns="http://www.nova.edu/course"
  xmlns:ins="http://www.nova.edu/instructor"
  xmlns:mat="http://www.nova.edu/materials"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
  <xs:import schemaLocation="InstructorSchema.xsd" namespace="http://www.nova.edu/instructor" />
  <xs:import schemaLocation="MaterialsSchema.xsd" namespace="http://www.nova.edu/materials" />

  <xs:element name="course">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="title"/>
        <xs:element type="xs:string" name="program"/>
        <xs:element type="xs:short" name="number"/>
        <xs:element name="term">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:int" name="crn"/>
              <xs:element type="xs:int" name="code"/>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:short" name="year"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="schedule">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="dates">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:date" name="startdate"/>
                    <xs:element type="xs:date" name="enddate"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element type="xs:string" name="day"/>
              <xs:element name="time">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:string" name="starttime"/>
                    <xs:element type="xs:string" name="endtime"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="location">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="building"/>
              <xs:element type="xs:short" name="room"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element ref="ins:instructor" />
        <xs:element ref="mat:materials" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

now am trying to Create a new schema that defines a Courses element that is a collection of zero or more (course) elements.
targetNamespace="http://www.nova.edu/allcourses"
  xmlns="http://www.nova.edu/allcourses"
  xmlns:cor="http://www.nova.edu/course"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
    <xs:import schemaLocation="CourseSchema.xsd" namespace="http://www.nova.edu/course" />

     <xs:element name="courses">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="course" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                    <xs:sequence>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

am not sure if I should add more elements in my new schema in order for it to work well. The idea is just to be able have multiple courses and each course is based on the (course)schema above.
Comment: Consider alternatives.
Answer: In your courses element, use
<xs:element ref="course" minOccurs="0" maxOccurs="unbounded"/>

to refer to the existing declaration of element course, rather than redefining it locally.

trying to make a schema


Hot water heater running out at 50%

Question: I have a 120 gallon indirect water heater. I notice that when I take a shower with a 3 gpm shower head, the water starts to cool after about 20 minutes, which would be 60 gallons or only 50% of the tank. I assume this is because any hot water removed from the tank is being immediately replaced with cold water which then starts to cool the tank down. Is this correct?
If so, is there anything I can do to increase the duration of hot water, such as somehow only having it start to refill the tank when it is 20% full or something like that?
The system is heated by hot water coming from a boiler. The pressurization is by city water supply at 80 PSI. The temperature set point is 130F.
Comment: There does seem to be a problem, but just to get the facts, what is the temperature set-point for the water in the tank?  What is the indirect heat source for the tank?
Comment: You should describe the hot water system in more detail to get the best advice. Is the tank pressurized or does it deliver by gravity? city water or a well?, etc. Usually cold water is fed into the tank at the bottom and hot withdrawn at the top and stratification keeps the output hot as water is used. But if you have a 120 gal tank maybe stratification is harder to maintain as water is drawn out.
Comment: When you have not used hot water for a while (say first thing in the morning) does the boiler come on immediately when a high flow rate demand is made on the hot water? This is a "combination" boiler, right? That is it also heats water for space heating of the house. Since it does double duty maybe the "recovery rate" for water heating is compromised.
Comment: The 3 GPM is assuming a specific water PSI so you maybe be getting more or less depending on your actual PSI. Answering the questions the other people asked will help figure out the issue. And no, you can't use X % of water from the tank and then start to refill it because of the reason you gave. Even though cold water starts to refill the tank, it won't mess up the hot water significantly unless there is something wrong on the inside.
Comment: @JimStewart I have updated the question with answers to your questions.
Comment: @HazardousGlitch The 3 GPM is a measured GPM, not a calculated GPM.
Comment: Does the feed into the tank come from the boiler or is there a loop from the boiler that heats a coil in the tank? In the latter case there would be a separate cold feed into the tank.
Comment: @JimStewart As I said it is an indirect fired water heater, which means there is a coil and water from the boil flows through that coil to heat the water.
Comment: @JimStewart I tested your question by turning on the shower and watching the boiler. The circulator for the water heater came on in exactly 9 minutes and boiler came on about 15 seconds after the circulator came on. The boiler is used to heat the house as well. What do you mean by the "recovery rate"?
Comment: Recovery rate is the time rate for the water heater to bring a volume of cold feed up to the set point temperature. https://georgebrazilplumbingelectrical.com/blog/what-is-water-heater-recovery-time
Answer: You absolutely cannot delay delivering cold water into the tank to replace the hot water output. You have a pressurized tank which must remain full of water to deliver water. If you had an unpressurized water tank which delivered hot water by gravity, you could do this, but you don't have that.
I assume that the cold feed is very cold in Cambridge MA. You may not be starting with a full tank of 130 F water. It could be that the controls on the boiler are set to reduce the number of heating cycles per unit time. Where is the temperature sensor located vertically in the tank?
Some recommendations on the temperature set point of tank water heaters are that it be set at 140 F (60 C) to prevent the growth of legionella bacteria. Other recommendations give 130 F. Does your shower valve have an anti-scald  temperature control?
Comment: The temperature sensor for the tank is about mid-way up the tank. There are no controls on the shower heads.
Comment: AFIK there are no shower heads with controls on the shower head itself (except for electric resistance heads used in less developed countries), but does the shower valve have a thermostatic anti-scald feature? If you were going to raise the set-point the temperature of the water in the tank to 140 F, you'd probably need that.
Comment: There is no anti-scald feature that I know of.

Hot water heater running out at 50%


Distance matrix between ALL features in ArcGIS

Question: I have 20 000 polygons in a dataset. I need to have the Euclidean Distance between all polygons, so a 20 000 x 20 000 distance matrix where for each of the polygons, the distance to all other polygons is stored.
I have read in some other threads the recommendation to use the "Near" tool in Arcmap. However, this tool only calculates the distance to the NEAREST polygon, while I need the distance from ALL polygons to ALL polygons.
Is there any solution for this?

Near tool: Calculates distance and additional proximity information between the
input features and the closest feature in another layer or feature
class.
Answer: In order to calculate the distance between the centroids of each of your polygons make sure your map is in a projected coordinate system.
Then, make sure the centroid points are calculated (detailed step-by-step here: https://support.esri.com/en/technical-article/000009381 )
Export your centroid point attribute table as a DBF (Click on Options > Export.)
Add the table to your map. Right click on the new table, Display XY Data, select Longitude for the X and Latitude for Y, and select the map's coordinate system to create an events layer.
Then, use the Point Distance tool (Details here: https://desktop.arcgis.com/en/arcmap/10.3/tools/analysis-toolbox/point-distance.htm ). The event points are both the input and near features. The output will be a table displaying distance between all polygon centroids on the map.


How can we run matlab function code in my android application?

Question: I have a function of Matlab, which is performing a specific task. The parameter which is passed to this function is extracted in the android application. Now I want to run this function inside my android application by passing the extracted parameters. Can you please suggest how to do this or if any workaround is available or not?
Answer: The only way to do this I can think of would be to use the Matlab CodeGen toolbox to create C++ code for your function.
You could then use this code within your android project.
If you've got Simulink, potentially you could do some stuff with the Android Support Package
Personally, I think you're better off using NumPy and Python if you're targeting an Android Environment.


A reducibility of a polynomial $x^2+ax-a+2a^2$

Question:
Element $a$ generates a multiplicative group of a field F of $343$ elements. Is the polynomial $x^2+ax-a+2a^2$ irreducible in the polynomial ring $F[x]$?

As I understand, $F[x]$ is the ring of all polynomials, which can be generated by the coefficient from $F$. How then can I check a reducibility of a polynomial $p(x)$ in $F[x]$? Should I try to decompose it into the $p(x)=g(x)*h(x)$, where "=" means equality modulo 343?
Comment: Note that the field with $7^3=343$ elements is *not* the ring of integers mod $343$.
Answer: Since it has degree $2$, $x^2+ax-a+2a^2$ is reducible in $F[x]$ iff $x^2+ax-a+2a^2$ has a root in $F$ iff its discriminant is a square in $F$.
The discriminant is $4 a - 7 a^2 = 4a$, since $F$ has characteristic $7$ because $343=7^3$.
Therefore, $x^2+ax-a+2a^2$ reducible in $F[x]$ iff $a$ is a square in $F$.
But $a$ is not a square in $F$ because $a$ is a generator of $F^\times$, which is a cyclic group of even order.
Answer: We can verify that
$$
{\bf f }(x)=(x^2+ax+2a^2)-a=2\, \left( a+2\,x \right) ^{2}-a
$$
Assume that there is an $x \in\operatorname{GF}(7^3)$ such that ${\bf f}(x)=0$, which result in
$$
2\, \left( a+2\,x \right) ^{2}=a \Rightarrow  \left( a+2\,x \right) ^{2}=4\, a
$$
The rest of proof is the same as the nice proof that is given by @lhf.


Merging two dataframes, trying to match a cell value to a column name - Pandas

Question: I have two dataframes with country data, small examples as follows. As you can see one is a "vertical" table and the second is a "horizontal" table.
df1
Code Year
ALB  2000
ALB  2001
ALB  2002
ARG  2000
ARG  2001
ARG  2002

df2 values - I believe the column headers are strings hence the quotes
Code '2000' '2001' '2002'
ALB    1m     2m     3m
ARG    2m     4m     6m

The resulting dataframe I want is to "add" df2 values to df1
Code Year Value
ALB  2000  1m
ALB  2001  2m
ALB  2002  3m
ARG  2000  2m
ARG  2001  4m
ARG  2002  6m

I tried a merge. This is obviously not going to work as df2 doesn't have a year column.
df_new = df1.merge(df2, on=['Code', 'Year'], how='left')

I tried a concat. Didn't work either, just resulted in NaN in the columns.
df_new = pd.concat([df1, df2])

Answer: You can use stack with merge.
Try this :
out = (
        df1.merge(df2.set_index("Code")
                     .stack()
                     .reset_index()
                     .rename(columns= {"level_1": "Year", 0: "Value"})
                     .assign(Year= lambda x: x["Year"].astype(int)),
                  on=["Code", "Year"], how="left")
      )

# Output :
print(out)

  Code  Year Value
0  ALB  2000    1m
1  ALB  2001    2m
2  ALB  2002    3m
3  ARG  2000    2m
4  ARG  2001    4m
5  ARG  2002    6m


Can I convert a Minecraft: Education Edition world to Bedrock Edition?

Question: I made a world in Education Edition and would like to continue playing in Bedrock. I exported the world, but when I try and open it in Bedrock it says:

This level was saved from Minecraft: Education Edition. It cannot be loaded.
Is there a way to load it?
Answer: If you're willing to use an NBT editor, this is most certainly possible, if you know where to look.
Prerequisites

You have access to Minecraft: Bedrock Edition and Minecraft: Education Edition.
You have an NBT editor that can edit MCBE and MCEE world files.

Step One: Get the world file.
There are two methods you may take to access the world file. You can either find the folder for yourself, or you may use the Export World button in MCEE.

Method A: Direct folder access
Windows 10 devices can use the following file path to find their files. Users on a different OS, sorry, I am unable to provide a file path for you yet. If you have one, please comment below.
C:\Users\ExpertCoder14\AppData\Roaming\Minecraft Education Edition\games\com.mojang\minecraftWorlds

Obviously replace ExpertCoder14 above with your actual Windows username.

(ignore that this one has _UMCbackup, that's just from past experimentation.)
Unfortunately the names of the folders do not provide any indication of which world is which. The only way to find out is to enter it and open the levelname.txt file there.

Once you have found the folder that contains the world you wish to use, copy its entire world folder (not just levelname.txt) to somewhere you can easily access. I just put it on my Documents folder. Up to you.

Method B: Export button
You'll be able to save a .mcworld file to your computer by clicking the highlighted button in the image below.

You should be able to open this file directly with UMCE. If your NBT editor does not support .mcworld editing, you'll need to convert it to an actual folder by changing the filename extension from .mcworld to .zip and extract the files into another folder.

Whew! You've successfully retrieved the world file. Now for step 2...
Step Two: Edit level NBT
Open your NBT editor. Go to the level.dat file of the world, and look for the Integer tag named eduOffer. Change it from 1 to 0. The following image shows where to find the correct NBT tag in UMCE:

Ensure that you save the file and then close it! Otherwise your changes won't take effect.
Importantly, if you chose method B from step 1, ensure you've converted the world back to .mcworld format before continuing. This will involve creating a compressed folder and then renaming the extension to .mcworld.
Step Three: Import the world
You'll need to follow a different step depending on which method you used in step 1.

If you chose method A
Move the edited world folder to the following Windows file path:
C:\Users\ExpertCoder14\AppData\Local\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang\minecraftWorlds

If you chose method B
Use the import button in Bedrock Edition to select your edited .mcworld file.
Answer: ExpertCoder14 answer works with a few tweaks!
First: converting to .zip via renaming seems to break the files (the UMCE didn't want to open them anyway)
Instead what you can do is use 7zip, which can extract .mcworld directly
From there follow the instruction to change the tag, save.
You also cannot rezip it and convert it the other way, it also didn't work (my win10 minecraft wouldn't load it)
Instead you have to copy the folder into the win10 savegame folder on your computer (the instructions for this are also in the answer, just follow those)
Anyway, thanks a lot for this, it's going to be very cool for school kids that have normal minecraft at home!
Edit: for those who don't want to bother with 7zip, there is a minecraft editor that can open the EDU .mcworld directly, and then save them back, so you're just left with tag editing to do:
MCC Tool Chest PE
Comment: I thought UMCE *does* work to open `.mcworld` though, you just need to push "Open File" instead of "Open Folder."
Comment: Might have been my world, but it didn't work when I tried either options *shrug*
Answer: Sadly not. Education Edition is functionally different from the rest of the game; objects such as specialty blocks, the Code Builder function, and NPCs are unique to EE and thus mean it cannot be ported to any other version.
Comment: Thanks for that one; I just wondered though, as the world contains no Education Edition-specific items?
Answer: EE is 1.12.6, and BE is a different version. So you can't export it.


SDL Image Split screen

Question: Trying to display two images on screen each take up one half of the screen.  Here is the code I am using:
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* pScreen = SDL_SetVideoMode(1280,720,16, SDL_FULLSCREEN );
SDL_ShowCursor(SDL_DISABLE);
//load two images
SDL_Surface* pImage1 = IMG_Load("/media/x01.JPG");
SDL_Surface* pImage2 = IMG_Load("/media/x02.JPG");

//create two rectangles for left and right of screen
SDL_Rect leftR;
SDL_Rect rightR;
leftR.x = 600;
leftR.y = 0;
leftR.w = 640;
leftR.h = 720;
rightR.x = 640;
rightR.y = 0;
rightR.w = 640;
rightR.h = 720;

//display
SDL_BlitSurface(pImage1,&leftR,pScreen,&leftR);
SDL_BlitSurface(pImage2,&rightR,pScreen,&rightR);
SDL_Flip(pScreen);

//free image surfaces
SDL_FreeSurface(pImage1);
SDL_FreeSurface(pImage2);

//wait to see what's on screen...
sleep(5);

//close SDL
SDL_Quit();

I'm hoping to achieve a split screen effect with two static images.  However all that happens is the first image is being displayed on one half of the screen, the other is blank.
I have tried messing around with the Rect x & y and it seems the position of the image doesn't change but instead the size of the viewing rectangle does.  Any ideas?
Answer: SDL_BlitSurface takes two rectangles, one for the source, and one for the destination.
The source rectangle, which is the second parameter, is what part of the source surface (in this case, your image) to draw.
The destination rectangle, which is the fourth parameter, is where to draw on the destination surface.
You're passing the same rectangle for both, which probably isn't what you want. If you just want to display the whole image, pass NULL for the source rectangle.

SDL Image Split screen


How to parse text into json in express sever using bodyParser?

Question: I have an express server which is acting as an API, main.ts (this has the code to up the server) looks somewhat like this
const app = express();

app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.text({ type: "text/plain" }));
app.use('/', routes);

app.listen(8080, () => {});

and the routes object has a GET definition as :-
routes.get('/myObject', (request: Request, response: Response) => {
    console.log(request.body); // Output : {}
});

I have another server from where I send a request but the request body is not getting parsed as it should
The XHR I'm sending from the second server is :-
    const request: XMLHttpRequest = new XMLHttpRequest();
    request.open("GET", "http://localhost:8080/myObject");
    request.setRequestHeader('Accept', 'application/json');
    request.setRequestHeader("Content-Type", "text/plain");
    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.onload = () => {
        console.log(request.status);
    };
    request.onerror = (err) => {
        console.log(request.status);
    }
    request.send(JSON.stringify({ "key": "value" }));

But on my express server, { "key": "value" } is not appearing only {} is coming?
Any idea what is wrong here?
Also if I do get "{\"key\":\"value\"}" in the express server can I implicitly convert it to a JSON object which can be sent as request.body?
Answer: Change the method to POST  instead of GET and give it a try.
Responses for GET´s have their body set to null.
Comment: Hi, Thanks for the answer. Using POST works. But I'm curious as of why it doesn't work with get when I send an XHR and does via Postman?
When I sent a request with postman, it recognized the request body.


Need an alternate way to install hand-spray bidet on my toilet - can I Tee off the 3/8th input valve?

Question: I bought some hand-spray bidet kits to add to some toilets.  I've done this before on standard toilets, and the installation went smoothly - just remove the input pipe from the port on the underside of the toilet tank, insert the provided T-valve, and connect the hand-spray pipe to the T-valve.

But in my new house, I have some toilets that are non-standard (Porcelanosa NK One) and which do not give access to the input port on the back of the tank.  The toilets are fixed to the ground and flush with the wall, and so there is no good access to where the input pipe connects.  I can squeeze my hand back there and kind of feel it, but certainly could not unscrew anything and install new plumbing there.

As a result, I am stuck with trying to Tee off the other end of the input pipe - the part that comes out of the wall.  The pipe size is different than that on the bottom of the toilet port - the wall valve seems to be a 3/8" compression valve, compared to the 7/8" valve at the input port of the toilet tank.  So I cannot use the T-valve that came with the bidet kit.

My question is this - can I just buy an off-the-shelf 3/8" T-valve, insert it between the existing shut-off valve and the input pipe that runs up to the toilet, and connect the hand-sprayer to that T-valve?

Is there any reason such a T-valve will be unhappy having a hand-spray attachment on it?  Will the pressure be significantly different at the end of the hand-spray attachment?  It won't have the on-off valve that the provided T-valve does, but I never use that anyways (and if I did need to turn off pressure to the hand-spray - say, to remove the end and de-scale it - I could just turn off pressure to the entire toilet).
Answer: You should be able to do what you propose because the adapter/valve that came with the unit does not appear to have any sort of pressure regulator built into it, meaning it appears to be designed for normal household pressure (btw this is not the case with all hand-held sprayer units).
Because the consequences of failure could be catastrophic (e.g. flooded house) I would hook it up but closely monitor it for a while to confirm no leakage, hose swelling, etc.
Oh, and turn it off when you go on vacation...
Answer: Keep in mind that you will need to do something about the output side of the bidet valve, and that's not as simple as it seems.  You can use a 3/8" tee connected to a standard toilet supply line that then connects to the bidet valve, but the, you will also need a plug for the female side of the valve.
Another option would be to not use a 3/8" compression tee and just run a standard toilet supply line to the bidet valve, then connect a second toilet supply line to the female side of the bidet and have that go up to the toilet.
The problem for both of these cases is finding the proper fitting for the female side of the bidet valve.  This is a pipe size that is really only used for toilet valves so fittings in that size are not common.
If you go the first route, you will need to find a 7/8" pipe male plug.  I've honestly never seen one of those.  If you choose the second option, you can use a "toilet supply line extension hose".  Those are rare, but I found at least one example online (it is only 6" long, however).
Also, if you're idea was to not use the bidet valve and connect the sprayer directly to the 3/8" compression tee, that won't work either.  Sprayers use another rare thread pattern that you won't find fittings for.
Comment: Ah - that sounds like a great idea (the extension).  Let me try that and see how it goes...


Will this be considered a bad React Context Practise

Question: I am just starting out with react and trying as much as possible to prevent rerenders, thereby using less useState. Would updating my context this way opposed to using a reducer be termed bad practise? What are the pit falls of structuring it this way?

import React from "react";

export const DataContext  = React.createContext();

initialData = {
    sGross: 0,
    sExpenses: 0,
    sPension: 0,

  };

export const DataProvider= ({children}) =>{
    const updateData = (newData, name) => {
       initialData[name] = newData

        }

    return (
    <DataContext.Provider  value={{initialData, updateData}}>
        {children}
    </DataContext.Provider>
)}

Comment: Context provides a way to pass data **through the component tree** without having to pass props down manually at every level check doc : https://react.dev/reference/react/createContext
Comment: to prevent rerenders and infinite loop you can use hooks like useeffect, usecallback, usememo check doc https://www.datainfinities.com/20/too-many-re-renders-react-limits-the-number-of-renders-to-prevent-an-infinite-loop
Comment: https://www.joshwcomeau.com/react/usememo-and-usecallback/
Comment: The main problem with this approach is that components and hooks using initialData won't be able to react to changes to it. The data will only change when something else triggers a re-render. I would just use a useState in this situation.
Comment: i send answer with a full example to how to use createContext and useState to show and update a context data... note i use typescript  but you can delete all typescript and keep javascript code
Answer: The method you describe will not trigger a re-render even if the data changes... For best performance, you can use memo and callback hooks to create  your context.
and for more performance and preventing unnecessary re-rendering you can use context splitting just like so :
// we suppose that a component A need only sGross and a component B need sExpenses & sPension
context = {
    sGross: 0,
    sExpenses: 0,
    sPension: 0,
};

// then you can split the context into 2 context
contextA = {
    sGross: 0,
};

contextB = {
    sExpenses: 0,
    sPension: 0,
};

You can check this example to how to use createcontext to share an auto increment counter between 3 components using memo and callback hooks :
import React, { createContext, useCallback } from "react";
import { useEffect } from "react";

type TDataContext = {
  contextData: TData;
  setContextData: (data: TData) => void;
};

type TData = {
  counter: number;
};

const initialData: TData = {
  counter: 0
};

const DataContext = createContext<TDataContext | null>(null);

const DataProvider: React.FC<React.ReactNode> = ({ children }) => {
  const [data, setData] = React.useState<TData>(initialData);
  const setContextData = React.useCallback(
    (newState: TData) => {
      setData((prevData) => ({ ...prevData, ...newState }));
    },
    [setData]
  );
  const getContextValue = React.useMemo(
    () => ({ contextData: data, setContextData }),
    [data, setContextData]
  );

  return (
    <DataContext.Provider value={getContextValue}>
      {children}
    </DataContext.Provider>
  );
};
const ShowTimerOne: React.FC<{ counter: number }> = ({ counter }) => {
  return (
    <>

Component One : Show Counter From props

{counter}

    </>
  );
};
const ShowTimerFour: React.FC = () => {
  React.useEffect(() => {
    console.log("Component Four rendred");
  });
  return (
    <>

Component Four

    </>
  );
};
const ShowTimerTwo: React.FC<React.ReactNode> = ({ children }) => {
  const { contextData, setContextData } = React.useContext(
    DataContext
  ) as TDataContext;
  return (
    <>

Component Two : Show Counter From context

{contextData.counter}

{children}

    </>
  );
};
const ShowTimerThree: React.FC = () => {
  const { contextData, setContextData } = React.useContext(
    DataContext
  ) as TDataContext;
  return (
    <>

        Component Three : Show Counter From context and it is child of component
        Two

{contextData.counter}

    </>
  );
};

const SetTimer: React.FC<React.ReactNode> = ({ children }) => {
  const { contextData, setContextData } = React.useContext(
    DataContext
  ) as TDataContext;
  const Ref = React.useRef<NodeJS.Timeout | string | number | undefined>(
    undefined
  );

  const incrementCounter = useCallback(() => {
    const counter = contextData.counter + 1;
    setContextData({ counter: counter });
  }, [contextData, setContextData]);

  useEffect(() => {
    if (Ref.current === undefined) {
      Ref.current = setInterval(incrementCounter, 1000);
    }
    return () => {
      clearInterval(Ref.current);
      Ref.current = undefined;
    };
  }, [incrementCounter]);

  return <ShowTimerOne counter={contextData.counter} />;
};

const App = () => (
  <DataProvider>
    <ShowTimerFour />
    <SetTimer />
    <ShowTimerTwo>
      <ShowTimerThree />
    </ShowTimerTwo>
  </DataProvider>
);

export default App;

you can see it in action at :
https://codesandbox.io/s/react-18-playground-forked-hlhhm9?file=/src/App.tsx
Comment: The components that utilises the context have a form that rerenders and calls the Provider onSubmit, thereby able to get the present value and use that for further calculations.  My app work has expected, but i needed clarifications on if the use of objects assignement with context and without a reducer is bad?    A code that works doesnt necessarily translates to good code, if you get me.   I have never seen context used in the way i have, i had my reasons for using them this way - abstraction, but wanted another eye.


CSS: Input checkbox and radio button appearance

Question: I am trying to fix checkbox with tickmarks and radio with periods.

toggling content:"" on unchecked state and content:"\2714" checked state I am getting a flicker. So I made color transparent. Is that correct?
The tick mark doesn't fit exactly to the box. How can alter only that tickmark?
If the sentence is split into lines, the square and text fall on the same margin. What should I do if both should be in seperate blocks?
The period (.) on the radio button, is tiny enough to be visible. If I increase the font-size it misaligns with the text.

I have copied bootstrap CSS and HTML format too.
Here is my jsfiddle link.
https://jsfiddle.net/488s5e70/2/

input[type="radio"],
input[type="checkbox"] {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  outline: none;
}
input[type="checkbox"]+span:before {
  width: 16px;
  height: 16px;
  border: 1px solid #000;
  content: "\2714";
  color: transparent;
  display: inline-block;
  font-size: 13px;
  margin-right: 5px;
  text-align: center;
}
input[type="checkbox"]:disabled+span {
  color: #ddd;
}
input[type="checkbox"]:checked+span:before {
  content: "\2714";
  color: #000;
}
input[type="checkbox"]:disabled:checked+span:before {
  content: "\2714";
  color: #ddd;
}
input[type="checkbox"]:disabled+span:before {
  border: 1px solid #ddd;
}
input[type="radio"]+span:before {
  width: 16px;
  height: 16px;
  border: 1px solid #000;
  content: ".";
  color: transparent;
  display: inline-block;
  font-size: 13px;
  font-weight: bold;
  margin-right: 5px;
  border-radius: 8px;
  text-align: center;
}
input[type="radio"]:disabled+span {
  color: #ddd;
}
input[type="radio"]:checked+span:before {
  content: "\00b7";
  color: #000;
}
input[type="radio"]:disabled:checked+span:before {
  content: "\00b7";
  color: #ddd;
}
input[type="radio"]:disabled+span:before {
  border: 1px solid #ddd;
}

      <input type="checkbox" value="" checked>
      Option one is this and that—be sure to include why it's greatOption one is this and that—be sure to include why it's greatOption one is this and that—be sure to include why it's great

      <input type="checkbox" value="">
      Option one is this and that—be sure to include why it's great

      <input type="checkbox" value="" disabled>
      Option one is this and that—be sure to include why it's great

      <input type="checkbox" value="" disabled checked>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios2" id="optionsRadios1" value="option1" disabled>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios2" id="optionsRadios1" value="option1" checked disabled>
      Option one is this and that—be sure to include why it's great

Comment: Take a look at Font Awesome. It may have what you want for the graphics http://fontawesome.io/icons/
Comment: I dont want to use font awesome. Thats my issue. I should get it done by css and html only
Answer:
Transparency instead content ""

its right way! its even better. every thing is OK

fitting the tick mark

when its about a font, there is no warranty about a same and true display in all browsers, i just prefer a background image for check box, a png image
if you have mobile side users, note that all contents inside your elements (tick and ball) probably got change
plain text replaced with android emoticons

seperate blocks

A table with only 2 column could be fastest solution.

Radio

use another character, my offering is "●" or "•"
however the best way is background-image
input[type="radio"]:checked+span:before{
  content:"\25CF"; /* or any better character */
  color:#000;
}

Comment: Point 3. If you can see my example, the first checkbox contains multiple line test. For example it can be terms and conditions aggrement statement. In that case, the checkbox should be seperate.
Answer: Right, some things I would change to fix this.

Flexbox, Flexbox everywhere.
Why use a period, when we can use a BLACK CIRCLE

You can find different shapes here if you type "(Hex value)" as the content in you before it will appear.
Here's what I've done.

input[type="radio"],
input[type="checkbox"] {
  position: relative;
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  outline: none;
}
input[type="checkbox"]+span:before {
  width: 16px;
  height: 16px;
  border: 1px solid #000;
  content: "\2714";
  color: transparent;
  display: inline-block;
  font-size: 13px;
  margin-right: 5px;
  text-align: center;
  /* new code notice me! */
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
input[type="checkbox"]:disabled+span {
  color: #ddd;
}
input[type="checkbox"]:checked+span:before {
  content: "\2714";
  color: #000;
}
input[type="checkbox"]:disabled:checked+span:before {
  content: "\2714";
  color: #ddd;
}
input[type="checkbox"]:disabled+span:before {
  border: 1px solid #ddd;
}
input[type="radio"]+span:before {
  width: 16px;
  height: 16px;
  border: 1px solid #000;
  content: ".";
  color: transparent;
  display: inline-block;
  font-size: 13px;
  font-weight: bold;
  margin-right: 5px;
  border-radius: 8px;
  text-align: center;
  /* new code notice me! */
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
input[type="radio"]:disabled+span {
  color: #ddd;
}
/* \25cf is the code for BLACK CIRCLE */
input[type="radio"]:checked+span:before {
  content: "\25cf";
  color: #000;
}
input[type="radio"]:disabled:checked+span:before {
  content: "\25cf";
  color: #ddd;
}
input[type="radio"]:disabled+span:before {
  border: 1px solid #ddd;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>

      <input type="checkbox" value="" checked>
      Option one is this and that—be sure to include why it's greatOption one is this and that—be sure to include why it's greatOption one is this and that—be sure to include why it's great

      <input type="checkbox" value="">
      Option one is this and that—be sure to include why it's great

      <input type="checkbox" value="" disabled>
      Option one is this and that—be sure to include why it's great

      <input type="checkbox" value="" disabled checked>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1">
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios2" id="optionsRadios1" value="option1" disabled>
      Option one is this and that—be sure to include why it's great

      <input type="radio" name="optionsRadios2" id="optionsRadios1" value="option1" checked disabled>
      Option one is this and that—be sure to include why it's great

The flexbox lines are;

display: inline-flex;
align-items: center;
justify-content: center;

They mean;
 - things inside me should use flexbox,
 - they should be centered vertically,
 - they should be centered horizontally.
I hope you find this helpful :-)