C++ pthread_t - How to stop a pthread_t for a period of time

Question: How is it possible to stop a pthread_t for a period of time? And I mean no using of the sleep function ;)
Comment: I need any possibility. It doesnt care what kind of possibility but just no sleep.
Comment: @TobiWeißhaar: Why not sleep?
Comment: possible duplicate of [How to sleep or pause a PThread in c on Linux](http://stackoverflow.com/questions/1606400/how-to-sleep-or-pause-a-pthread-in-c-on-linux)
Comment: please be more specific with the task you are trying to solve
Answer: If your threads implementation library supports it, you can use pthread_suspend and pthread_continue from main thread or another one using any kind of "sleeping time counting".
See man pages about normal uses.
Answer: Use pthread_cond_wait (or pthread_cond_timedwait, but probably not) to block the thread. You'll need a predicate -- a variable that holds a value that indicates whether the thread should go or stop. And you'll need a mutex to protect the predicate and condition variable. Another thread can then unblock the thread by taking the mutex, changing the predicate, signalling the condition variable, and releasing the mutex.
However, generally, you just shouldn't do this. If there's something to do, you should let the thread do it. If there's nothing to do, the thread should be coded to either terminate or wait for work. If you have to force this with specific code, it's likely that you're doing something wrong in the first place.
The thread should be coded to do all, and only, what you want it to do. You shouldn't need to "push it around" from the outside except in truly unusual situations.
Answer: you could wait on the thread handle itself with a timeout ... A thread handle is signalled once the thread terminates, so it will time out while running.
Answer: your question is rather unspecific. There are some possible approaches, but that depends on what you want to achieve.
Do you want to interrupt the thread? do you want to have a point where the thread 'blocks' execution until a certain criterion is met?
Who should be able to stop your thread? who should be able to restart its operation?
Some possibilities include:

thread suspensions: pthread_suspend
synchronisation: mutexes, semaphores, spinlock, pause/alarm
...
Answer: Hoi,
how exact does it need to be? You could consider starting another thread as soon as the first thread is stopped. This "new" thread runs for a specific time and then restarts thread number one.
If the stop is just needed once, you can add a counter.
If you need this all repeatedly, you could also consider a periodic time triggered pthread.
Regards,
G.


Mapbox center and set appropriate zoom level for a country

Question: I'm trying to find a way to center and zoom to a country using Mapbox. I am able to get a   country its coordinates using the geocoder, however, the zoom levels differ per country. (E.g. the zoom level for Spain is not the same level for the U.S.A.)

function showMap(err, data) {

        console.log(data);
        console.log(err);

        if (err == true) {
            console.log("Couldn't find this place!");
        } else {
            map.fitBounds(data.lbounds);
        }

}

var geocoder = L.mapbox.geocoder('x',map);

geocoder.query("Spain", showMap);

Would I need an additional layer with fusion tables to achieve this?
Thanks for any help!
Comment: How did you solve it?
Answer: Can you be much more specific with this question, and provide an example, preferably something you can link to, with full code?

I am able to get a country its coordinates using the geocoder, however, the zoom levels differ per country.

The usage of 'however' is confusing: large countries will have different zoom levels than small. Is this what you see happening? Or not? Is this something you desire, or not?


Is it safe to remove the bottom chords of a series of garage roof trusses?

Question: See attached picture. Looks like an 8x10 cut-out. He wants to lift cars up so he can walk under them.
Is this safe? Doesn't removing the joists affect structural integrity?
Comment: He just created this future situation for himself: https://diy.stackexchange.com/q/94143/42053
Comment: Will you be expecting snow?
Comment: @Jack - or wind. (Not as bad, but still not good).
Comment: @jpa The car lift ground posts are clearly visible in the photo.
Comment: The next problem is probably the lift connection to the concrete. People assume their concrete floor is structural and hammer drill anchors into it, but it's a floating slab just waiting to break... Possibly without any rebar reinforcement.
Comment: Did you notice how the roof angles out on the right side? Rafters attached to rafters. Shouldn't there be a load-bearing wall on the right where the "inner" rafters come down, like you can see on the left? Even with the horizontal joists still in place, that's a huge span for the bottom joist of a truss to support. I have a feeling our DIY specialist here not only cut the trusses but also did some haphazard removal of load-bearing walls before that to create the workshop he wanted. Time to call in a structural engineer!
Comment: Where are the bearing walls? It looks like the remaining ceiling joists could stabilize the roof structure, provided the bearing walls are far enough from the opening.
Comment: Not pictured? Flying buttresses on the outside of the building.... or perhaps there are extremely fine cables (that don't show up well in the photo) are tying the sides of the roof rafters in place?
Comment: With this done to the roof supports, I think his planned car lift might be even more scary. I hope it at least stands on the floor instead of being hung from the now even weaker roof beams.
Answer: Absolutely not safe.
Those trusses were engineered with a heavy (critical) dependency on the bottom chords, which are in tension. Removal has left them extremely vulnerable to collapse due to spreading, especially under snow loads, but also under just the load of the roof itself. The roof system is basically a hinge now.
To get a good mental image, picture yourself standing on an ice rink and sliding your feet outward. How far do you get before your groin starts to scream at you?
Best case scenario, that ridge slowly sags over the opening and looks ridiculous. It will push walls around with it, cracking drywall and binding windows. Worst case, full collapse. Death. Destruction. Worst of all, humiliation.
Repair will require new lumber installed with a suitably fastening system, such as construction adhesive and through-bolts. It may be necessary to winch the walls back into alignment first if sagging has already begun.
Comment: Yes, but that probably goes beyond the DIY capabilities of anyone who would do this to their roof system. Also, any replacement for lumber must be laterally stabilized as those bottom chords were by the "rat run".
Comment: There are a number of ways the damage could be repaired without lumber - but repaired it must be.
Comment: To put the first sentence a different way: ***If those trusses were not necessary, the builder would not have put them there in the first place.*** Why spend more time and use more material, making something that has no purpose?
Comment: It might be cheaper (and safer) to remove the roof, trusses and ceiling and install new trusses (vaulted type?) and new roof.
Comment: @alephzero Because the builder wanted a ceiling.
Comment: Agree, having done a decent bit of construction my thought was "just lift the entire roof system" instead.
Answer: With no bracing above, you might want to check the out side walls - they are probably already spreading. Once they start moving the stabilization and repair can cost many thousands if the roof stays in place, tens of thousands if it comes down.
There are ways to mitigate the damage done, but it needs to be done now before the walls spread, the rafters move and the roof leaks if not collapses. Yes I have seen bonehead DIY hacks like this.
Steel plates in the outside walls with cables to pull the walls back together, repair the damage to the rafters, new bracing with some engineered cables added.
I would suggest getting the bracing and cable system installed now or it will cost much more than the lift and the loss of use if the roof comes down.
Comment: One thought, is that it *may* be possible to replace the joists with much beefier joists higher up.  That would allow some of the additional headroom the owner wants, without compromising the structural integrity of the building.
Comment: It may, but we have no way of knowing what the loads on those truss members are, and 2x4 top chords probably aren't adequate. You'd need to sister heavier boards on the complete A-frame.
Comment: That's the bracing I am talking about but depending on how high the car protrudes into the space will dictate if engineered cable supports are needed. (If the car sticks more than a foot or possibly 2 it will probably require an engineers stamp for whatever is done. Wish I could say I haven't seen this kind of hack before.
Answer: The triangle is an extremely stable form of architecture precisely because it has three sides. You remove one side, and you have one of the least stable forms of architecture on account that two members connected at a point can be affected by torque, which is by definition a force multiplier. If you want to play around with it to get a sense, try gluing two Popsicle sticks and three Popsicle sticks like the design in the picture above.
Any force directed downward will because of the elasticity of the wood create force outwards. If the members were steel, there would be substantially less deformation resulting in less outward force, but lumber is relatively flexible.
Now, it should be noted that some of the horizontal members are still in place, as many as half, and those runs will make it unlikely the structure will collapse under normal conditions, however, heavy winds or heavy snowfall, as mentioned in other comments, likely to create outward stresses in the middle section of the structure. The exact details of what will happen will largely be a matter of detail. To some extent, existing construction code generally overengineers a solution to ensure that minor failure will not result in human harm.
It is possible to create both the space needed to elevate the car, and have a structurally sound garage given the picture. For instance, additional chords can be installed low enough to recreate trusses, but high enough to accommodate a raised vehicle. There are a number of truss styles that do not use a horizontal bottom chord, the scissor truss for instance. And using steel as a construction material can help to redirect the tensions through materials more capable of absorbing the load. Lastly, the walls themselves can be modified. It was typical of cathedrals to buttress on the exterior, the wall to handle high-arching ceilings, for instance.
Construction is often a question of engineering as much as it is design, and if safety is a concern, such as it might be in this photo, consulting a structural engineer would be the right thing to do. Structural design is their expertise, which would be my recommendation.
Comment: @supercat If you want a roof with a hole, you design a roof with a hole. You don't first design a roof without a hole, then cut a hole in it, and then try to fix up the resulting mess.
Comment: Some good information in this answer, and some bad. It is absolutely nothing to do with timber vs steel; it is to do with *connections*, and also member size.
Comment: My intuition (by no means a calculation), would say that in this picture, several strategies would strengthen the roof. Running some sistered members across the cut joists would obviously create rectangles that would reinforce the wall from deforming. Purlins along the rafters would also work, or tying together those inside chords from the front to back parallel to the wall would also help. It's really a question of how sure one wants to be. Horizontal members higher up are a must. https://en.wikipedia.org/wiki/Timber_roof_truss#/media/File:Kehlbalkendach_mit_liegendem_Stuhl_1200px.png
Comment: @supercat This is the sort of timber roof design still standing after more than 600 years after it was built: https://www.greenoakcarpentry.co.uk/wp-content/uploads/Presentations/pageturners/AH%20Timber%20Joints%20Traditional%20and%20Contemporary/index.html#/9/zoomed
Comment: @alephzero: Obviously one should design, engineer, and install reinforcement structures before removing cutting or otherwise removing structural members, rather than hoping that nothing collapses between the removal of old structure and the installation of reinforcement.  The question would remain, though, whether there would be any commonly-approved methods to build a roof with a large hole whose edges don't have supports immediately under them.
Comment: Yes, it's foolish to speculate at repairs that meet the intent of the destructor without doing the math on the remaining truss members. No repair can succeed unless the components the repair is applied to are up to the task. Knowing what I do about modern engineered trusses, there's little room for experimentation.
Comment: Repairs can succeed despite having mathematical certainty. Most repairs do not have mathematical certainty, but follow rules of thumb. To say it doesn't matter if a structure is made of timber with fasteners or welded steel isn't a true statement.
Comment: I agree with your definition of torque.  I don't see how that means torque is "force multiplier".  I think I know what you are trying to say, but i think you are failing to express it clearly.
Comment: Even more than the lumber being flexible, the way *joints* are constructed in a wood truss are absolutely designed to NOT rotate. I think those would start to fail first.
Comment: For situations where one would need a large hole, would there be any approved ways of using horizontally-mounted beams or trusses to convey horizontal forces from the middle of the hole to the ends, or would every such design need to be independently professionally engineered?  Given the roof pitch and amount of ceiling on either side of the hole, it would look like it should be easy to fit horizontal trusses that would be strong enough to handle such loading,
Comment: I think in the design above, my personal choice would be to add to the sawed faces of the joists two sistered 2x6s, and then lay another 2x6 over the length to gusset those joints. I'd go with a purloin on the rafters tied to horizontal chords half way down, and then if I wanted to really strengthen the walls, lay a pratt truss horizontally on top of the joists near the top plates.
Comment: As far as there are any commonly-approved methods for designing ceilings with holes in them, the answer to that is certainly yes. In architecture, the design pattern is called a vaulted ceiling. https://www.architecturelab.net/what-are-vaulted-ceilings/
Comment: There is nothing about the definition of torque which means it is a force multiplier.  I don't think this answer adds anything to either of the earlier answers.
Comment: @MartinBonner The definition of torque is T = F * r * sin(theta) which means that the further away the force is applied, the greater the torque since the force, by definition is literally multiplied in part by the distance.
Comment: A force multiplier is anything which affects the magnitude of the force in an operation. For instance, when torquing a lag bolt into a joist, once might use a breaker bar of different lengths with the longer bar multiplying force by a greater amount. Hence, one can increase torque by using a longer length. The phrase force multiplier, besides its military sense, is used in physics when discussing machines. https://www.primaryconnections.org.au/sites/all/modules/primaryconnections/includes/SBR/data/Phy/sub/mechsys/mechsys.htm
Answer: As pictured - very bad idea.
It may work IF the roof is re-engineered to carry a lot more of the stress across the top and bottom of the cutout.  That means a much beefier horizontal beam on all four sides of his hole AND a rework of the roof by re-trussing the entire structure.
Some examples:
  This one is a Scissor Truss, and also wears the more general name "church truss" or "nave truss"   Note some of these have thinner tie rods across the middle exactly where the bottom chord would be - those aren't suitable.

A little ornate for a workshop, but you can see how the load is being brought down to the walls with inner buttressing.
  This one is called a Coffer Truss and as pictured would work perfectly.  However the thickness of the rafters (top cords)  would have to be increased several-fold to cope with the extra stresses.  As pictured, this one would expect to have supporting walls/posts straight under the lower "corners" so would require a vertical post straight down beside the car lift's posts.  That could be workable, if these new posts were properly footed into/onto the existing concrete floor.
  This would work too - depending on how much height there is at the top of the wall.
  Last option is to completely reframe the roof with steel trusses, and do away with the wooden ones.  Properly enginerded steel will have more strength than the wooden ones while allowing the open space required.
Any way - whatever creative handyman did this has made a difficult job into an utter nightmare of a job.  It would have been less work to remove the roof and then re-truss leaving the bottom chords in place to support the walls until the new roof framing is on.
Frankly, it would probably have been cheaper to build a new garage rather than monster the existing one and now have to repair it.
Also consider any insurance claim will be harder to win, based on the level of care exhibited here.  I'd bet any insurance claim for snow damage or storm damage would be rejected out of hand.  If this is used for a business, any claim for a customer car damaged by this collapse would be rejected as "failure to use due care"
You need to speak with a structural engineer immediately in person and ideally on-site.  I am not a structural engineer.
Comment: The coffer truss as depicted is not suitable in this situation. The image indicates that there are four load-bearing points: The two outside walls but also two more points further in where the outer triangles end. Without those two additional load-bearing points, little would change in the shearing force of the roof against the outside walls. Only difference would be that the roof collapses in three pieces.
Answer: I think it's safe, if...
Now that everyone has upvoted this as unsafe, I've got to take the other side of the argument for several reasons: 1) it's not a truss, 2) it's "stick-built", 3) either side could be removed and the remainder would be stable, 4) horizontal structural support is elsewhere other than in the center horizontal span,
1) Look close and you'll see that it's not a truss. The structure does not create a truss spanning the room...or it would have collapsed immediately...especially with that much removed.
2) The members are stick built. The roof member spans from ridge to next support...diagonal brace. The roof member is in both tension and compression. A truss member is in EITHER tension or compression. (That's why "double bending" in truss design is so dangerous.) The loads are transferred down the diagonal members to the walls or cantilevered beams over walls. In truss construction, loads are transferred to the END of the truss.
3) If you look at the right side you'll see that it could be removed and the left side would remain structurally sound. That's an indication that it's not a truss structure , but a stick built structure. (One half of the roof structure looks like a picnic shelter.)
4) The horizontal stability is in the end walls, NOT the center ceiling support. That's why you don't see large cracks in the ceiling gypsum board.
Now, I said "if" at the beginning. The "if" is in reference to the need that each side must be horizontally stable and has at least 2 bearing points on each side of the opening.....and obviously it is so far.
Comment: They sure look like engineered trusses to me. The photo is lousy, but I believe I see at least one steel gusset at the peak. What superficially appears to be a ridge board is more likely a gap in the sheathing for ridge venting. Also, hand-framed roofs almost always had 2x6 or larger rafters for spans that long. If you have more concrete information, please share that.
Comment: As to the immediate collapse... no. The sheathing is acting as a significant shear brace right now, and the bearing walls may have buttressing from intersecting walls or roof structures.
Comment: @isherwood Nope, it's not a truss and there is no gusset plate. Look at the diagonal member where it intersects the horizontal member...it laps the horizontal member and there's no gusset plate.
Comment: @isherwood It hasn't collapsed immediately because it's not a truss. The loads are transferred "down" the walls, not "out" to the outside walls...that's why it hasn't collapsed.
Comment: I think you may be right. I missed that clue. There's merit in your answer in that case, though the layperson is probably not wise to do what this guy did with so many variables at play.
Comment: @isherwood I wish the original OP would give us an update.
Comment: @leesam The intersection of the horizontal member and diagonal member is not visible in the picture. That "lap" is the horizontal running in front of the diagonal of the next truss back. If this were a cut and stack roof, that diagonal would be supported by a structural member like a load bearing wall or beam. I vote truss.
Comment: @Valkor The support does not need to be directly under the supporting load. I'm not saying it was designed this way, but often we'll design a cantilever to support loads. In this case, they were lucky that they cut the horizontal member in a location where a cantilever would support the load. So, the horizontal member is now a cantilever that happens to support the roof load. Can the horizontal member structurally support the roof load??? We won't know until we know the sizes of the members and their spans, but it's not (nor has it ever been) a truss.


Handle empty result with read_sql chunked

Question: I am still learning Python, I need to handle a case when a sql query doesn't provide any rows, with a pandas read_sql function with chunksize param.
Here is the current line :
df = pd.concat([x for x in pd.read_sql(SQL_request,self.connection, chunksize=50000)], ignore_index=True)

When the query returns zero rows I get this error :
  File "[....]\lib\site-packages\pandas\core\reshape\concat.py", line 239, in __init__
    raise ValueError('No objects to concatenate')
ValueError: No objects to concatenate

What is the best way to handle this ? I need to return an empty dataframe even if there is no rows (the columns must be there). I need to keep the chunking, it really helps not using too much memory.
I thought about running a first query without chunking and check if there is any rows, and then run a second chunked query. But I feel it is a very bad and inefficient idea.
Answer: Since you are trying to concatenate all chunks into a whole dataframe, it seems like you are using chunk only to avoid using too much memory. May be you can try our tool ConnectorX (pip install -U connectorx), which aims to improve the performance of pandas.read_sql in terms of both time and memory usage, and provides similar API. To switch to it, you only need to:
import connectorx as cx

# currently ConnectorX support postgres, mysql, oracle, mssql and sqlite
# conn_url example on mysql: mysql://username:password@server:port/database

df = cx.read_sql(conn_url, SQL_request)

The reason pandas.read_sql uses a lot of memory during running is because of its large intermediate python objects, in ConnectorX we use Rust and streaming process internally to tackle this problem.
Here is some benchmark result on memory usage:
PostgreSQL:

MySQL:
Answer: Try this:
df = pd.concat([x for x in pd.read_sql(SQL_request,self.connection, chunksize=50000) if not x.empty] , ignore_index=True)

EDIT:
Ah got it. Can you try the following code then? I'll update the answer if it works.
try:
    df = pd.concat([x for x in pd.read_sql(SQL_request,self.connection, chunksize=50000)] , ignore_index=True)
except:
    df = pd.read_sql(SQL_request,self.connection)

Comment: try the edit in the answer above (I couldn't format the code in the comments).
Comment: When you use chunksize it returns a generator instead of a Dataframe. And there's no trivial way to test if the generator is empty or not: [link](https://stackoverflow.com/questions/661603/how-do-i-know-if-a-generator-is-empty-from-the-start) .

So the solution I provide is to try and if it fails go get the empty dataframe.


Add abline to legend

Question: First, sorry for posting without reproducible data. Hope you guys understand my question. This is my code. At the end of the code, I am trying to add abline. With the code, I am trying to add the name of abline to the legend but it does not work.
ggplot(aes(x = week_id2, y = Index, color = Chain2, linetype = Chain2, group = Chain2),
       data = data00 +
  geom_point(aes(shape=Chain2), size = 3) +
  geom_line() +
  scale_linetype_manual(values=c("twodash", "dashed", "dotted", "dotdash", "longdash")) +
  scale_shape_manual(values=c(1:5)) +
  xlab("Week") +
  ylab("Index") +
  geom_hline(aes(yintercept=1))

As shown, I just simply add a name of the abline (let's say the name is "add") in the legend.  How should I do it with my current code?
Answer: You can add either color or linetype to aes then use scale_color_xxx or scale_linetype_xxx to fine tune the legend. Here is an example using economics dataset
library(tidyverse)

df <- economics %>%
  select(date, psavert, uempmed) %>%
  gather(key = "variable", value = "value", -date)

ggplot(df, aes(x = date, y = value)) +
  geom_line(aes(color = variable), size = 1) +
  geom_hline(aes(yintercept = 10, color = "My line")) +
  scale_color_brewer(palette = "Dark2",
                     breaks = c("psavert", "uempmed", "My line")) +
  theme_minimal()

ggplot(df, aes(x = date, y = value)) +
  geom_line(aes(color = variable, linetype = variable), size = 1) +
  geom_hline(aes(yintercept = 10, color = "My line", linetype = "My line")) +
  scale_color_brewer(palette = "Dark2",
                     breaks = c("psavert", "uempmed", "My line")) +
  scale_linetype_manual(values = c("twodash", "dashed", "dotted"),
                     breaks = c("psavert", "uempmed", "My line")) +
  theme_minimal()

Edit: per OP's request, we separate linetype & color/shape legends
ggplot(df, aes(x = date, y = value)) +
  geom_line(aes(color = variable), size = 0.75) +
  geom_point(aes(color = variable, shape = variable)) +
  geom_hline(aes(yintercept = 10, linetype = "My line")) +
  scale_color_brewer(palette = "Dark2",
                     breaks = c("psavert", "uempmed")) +
  scale_linetype_manual("", values = c("twodash"),
                        breaks = c("My line")) +
  scale_shape_manual(values = c(17, 19)) +
  # Set legend order
  guides(colour = guide_legend(order = 1),
         shape = guide_legend(order = 1),
         linetype = guide_legend(order = 2)) +
  theme_classic() +
  # Move legends closer to each other
  theme(legend.title = element_blank(),
        legend.justification = "center",
        legend.spacing = unit(0.1, "cm"),
        legend.spacing.y = unit(0.05, "cm"),
        legend.margin = margin(0, 0, 0, 0),
        legend.box.margin = margin(0, 0, 0, 0))

Created on 2018-05-08 by the reprex package (v0.2.0).
Comment: Each line is distinguished by not only line type but also point-type. And I only need to add a line to the legend for the abline (for the ""ADD" in the legend, there is no point type). Does your recommendation still work?

Add abline to legend


Errata for Semigroups and Combinatorial Applications by G. Lallement?

Question: I am asking this question after years of frustration with the typos
in the subject book I have read. It has been cited and referenced by many literatures and books in math and computer science. However, there are many typos, at least in the
copy I own -1979 edition 1st printing.
The fact that it has been used by many researchers lead me to believe
that there might be an Errata either published or circulated. But, I
cannot find it anywhere on Internet. My question is

Does anybody know an errata for the subject book exists? If so,
  where and how can I get it?

Thank you.
Comment: Scaaahu, please don't bump your posts without adding to them or correcting them. Other people also have their questions waiting for answers. I know how unpleasant it is when no one even comments on your question -- it's happened to me more than once. But if nobody has any idea about the answer or wants to answer, what can be done about it?
Comment: @ymar, I apologize. My explanation is the time zone. I live in Asia(Taiwan). I was afraid the time I posted this question was not rigtht for the readers in other areas.
Answer: Th proof of The Prime Decomposition Theorem (Krohn-Rhodes Theorem) in Lallement's book is slightly flawed, but a correction was published shortly afterwards [I should give credit to John Rhodes and Ben Steinberg for pointing out this reference in their book]:
G. Lallement, Augmentations and wreath products of monoids, Semigroup Forum, 21 (1980) 89-90. DOI 10.1007/BF02572539
I don't think a list of typos of Lallement's book has been ever published.


Is there any way to get the Name, Email and phone numbers from the Business card through computer vision API in xamarin.forms

Question: I am able to get the text in the image through the Microsoft's Computer vision API but can I directly get the Name, Email and Phone Numbers classified directly from the API?
If possible how can I do that?
I tried validating the email and phone number using regex but I don't know how to get the Name from the business card.
Answer: Used Text Analytics API from Microsoft to get the name as it recognizes a word as person, number and other.
Email and phone numbers were extracted by using regex.


Using switched outlet to power a wall controller

Question: I have a Lutron RadioRA2 keypad that needs power and I want to put it where I currently have a switch for an outlet. I swapped it in and it works if I have a load attached to the outlet. In my case a fan not turned on.
I want to de-hack this. Outlet is 1/2 switched, 1/2 always on. In picture below, top is not switched: black/white. Bottom switched: red/white.
Can I achieve what I want? I can get new outlet, keep tabs.
Would I:

Connect black/white to new outlet
Pigtial whites (neutral) together
Pigtail red solo

???
Comment: That is correct. (with unbroken tabs) Write it up (the bit after "would I:") as an answer (yes you can do that here...)
Comment: Other than this outlet, is there any other light in this room?  Will it be controlled with a switch? (Doesn't need to be this switch).
Comment: There is an 3/1 circuit for ceiling fan I converted to 2 zone lighting via 2 dimmers. That is working well.
Answer: So my real issue was I had my Lutron keypad wired wrong. It needs hot+neutral and I had hot1 (unswitched)/hot2(switched) from switched outlet to keypad. Changing to hot1(unswitched) and neutral in my wallbox has me up and running.♂
Comment: Be happy that 2 hots didn't fry it!
Comment: I know! Lutron stuff is so good.


How to get NuGet options in Visual Studio 2017 Community?

Question: I am struggling with creating NuGet packages.  I am using Visual Studio 2017 Community edition.
I have seen a couple of videos that show a "Pack" option on the menu when right-clicking the project in Solution Explorer. However, I do not have that option.  Is this one of the features in the other (non-Community) versions of Visual Studio?  I believe I have also seen a "create NuGet package on build" option mentioned somewhere.  I cannot find that either.
I have tried various ways of using nuget, dotnet, and msbuild from the command line(s), but haven't had much success.  Very frustrating.
Any help is appreciated.
Comment: Are you using a .NET Standard class library, or a .NET Framework one?
Answer: If you really want to use Visual Studio, I would recommend installing an extension that helps you with that problem. For example, this one. The options people have in videos depend on the extensions they have installed. For you, it is the same.
Alternatively, just use the command-line tooling for this as explained here or for .NET Core here or here.
Answer: dotnet/msbuild pack is only available for SDK-style projects, but I believe works for all versions of Visual Studio, as well as on the command line. .NET Core introduced these SDK-style projects, which can be identified by <Project Sdk="Microsoft.NET.Sdk">. If your project (.csproj if it's a C# project) doesn't have the Sdk property or import Microsoft.NET.Sdk in either of the two other ways, then it's not an SDK style project and doesn't support packing in this way. Another obvious difference between the two styles of projects is that SDK projects are only a few lines long from the new project template and don't list files in the project, whereas old style projects are typically a full screen long, even from a new project template with only a single class file, and it does list individual files in the project. If you want to continue with this project type, you'll need to use nuget.exe pack and you'll probably want to create a .nuspec file to define some of the package metadata.
However, using SDK style projects is the future, it just takes time for all of Microsoft's existing project types to migrate. It's much simpler to use, so personally I would avoid old style projects unless you're using a project type (like ASP.NET, not ASP.NET Core) that doesn't support it.
All of this is confusing for anyone new to the .NET ecosystem. My recommendation is 1. when you install Visual Studio, when making your workload selections, make sure in the component list that .NET Core is selected, whatever the newest version of .NET Core that is available at the time of installation. When creating a new project in Visual Studio, always select the .NET Core version, or .NET Standard version of any new project template, even if you want to target the (Windows) .NET Framework, in which case you edit the .csproj and change <TargetFramework>netstandard2.0</TargetFramework> to <TargetFramework>net45</TargetFramework>, although I would recommend multi-targeting possible by adding a s to the element name and using a semi-colon separated list: <TargetFrameworks>net45;netstandard2.0</TargetFrameworks>. So, avoid the "Class Library (.NET Framework)" template, instead use "Class Library (.NET Standard)" and then change the target if you have to.
Answer: @zivkan led me down the right path.  Changing my project types to .Net Core from .Net Framework made all the options I mentioned in my original post available.  No extensions were needed.
My .Net Core class library project now has the Pack and Publish options available on the project's context menu.  In addition, there is a another tab (Package) on the project properties page.  On that page there is a "Generate NuGet package on build" option along with version, name, tags and other properties.
I have done much .Net framework development, but have been ignoring .Net Core and the newer options.  I guess I need to dig in and learn about them.


Rendering Hypercentric Perspective

Question: I came across some Non-Euclidean Games which involve Hyperbolic Spaces, Spherical Spaces, Portals, etc. And, I noticed that they give quite deep feel of what Non-Euclidean Spaces feel like. So, I was thinking whether space rendering was possible for other unconventional perspectives, for example, Hypercentric Perspective (Objects that are farther away from the lens produce larger images than objects that are closer to the lens, contrary to the human eye where farther-away objects always appear smaller.) Due to physical restrictions, only a handful of images for Hypercentric Perspective exists on the internet, but these should give some idea:

Now, my question is how to render Hypercentric Perspective in preferably 3 Dimensional Space?
I tried doing this in Unity by varying the physical parameters of the virtual physical camera, but  it was no success. What can be the other way of approaching the problem? Preferably, the optimal approach? I'm very new to Computer Graphics so please pardon me if I missed something obvious here.
Please help me here.
Thank you.
Answer: You can approximate the view of a hypercentric camera with an ordinary 3D perspective camera if you are able to manipulate the projection matrix, and/or reverse the direction of the depth test.
In a hypercentric perspective the camera rays converge at a point in front of the camera. This is just the same as a regular perspective camera but with the direction of rays reversed. You can get the same collection of rays by placing an ordinary 3D camera at the hypercentric focal point, aimed backward toward the hypercentric camera lens. Then, you have to render the scene with the depth test reversed (or equivalently, swap the near and far planes in the projection matrix) so that surfaces farthest from the camera (closest to the hypercentric lens) will occlude others. You may also need to flip the direction of the backface culling test.
This should produce a hypercentric perspective. The caveat to this is that it won't render anything farther away than the hypercentric focal point (contrary to a real hypercentric camera). That's because those points are behind the perspective camera, so will get clipped during rasterization. This could however be addressed by rendering the scene in two passes: first draw everything beyond the hypercentric focal point with a camera facing forward (and turned upside down), and then clear the depth buffer and draw everything in front of the hypercentric focal point with the camera facing backward as described above.
It's unlikely that any of this can be accomplished in Unity with the default camera model as it's not designed for these unusual situations. You'll have to get deeper in, to a point where you can manipulate render passes, the depth buffer, and the projection matrix.
Answer: The answer is yes.
You need 2 things:

View space coordinates of the object
Projection function for the hypercentric perspective camera.

The second one can be found in here.
The overview of the model

Here is a small discription in case the link goes away.

You project the point using this $\begin{aligned} \left( \begin{array}{@{}c@{}} x_\mathrm {u} \\ y_\mathrm {u} \end{array} \right) = \frac{c}{z_k} \left( \begin{array}{@{}c@{}} x_k \\ y_k \end{array} \right) , \end{aligned}$ where components with $k$ represents the coordiantes of the point in camera space.

You then model the lens distortion with $\begin{aligned} \left( \begin{array}{@{}c@{}} x_\mathrm {d} \\ y_\mathrm {d} \end{array} \right) = \frac{2}{1+\sqrt{1-4\kappa r_\mathrm {u}^2}} \left( \begin{array}{@{}c@{}} x_\mathrm {u} \\ y_\mathrm {u} \end{array} \right) , \end{aligned}$ where $r_\mathrm {u}^2=x_\mathrm {u}^2 + y_\mathrm {u}^2$

Then you transform the distorted points to image space with $\begin{aligned} \left( \begin{array}{@{}c@{}} x_\mathrm {i} \\ y_\mathrm {i} \end{array} \right) = \left( \begin{array}{@{}c@{}} x_\mathrm {d}/s_x+c_x \\ y_\mathrm {d}/s_y+c_y \end{array} \right) , \end{aligned}$ where where $s_x$ and $s_y$ are the pixel pitch on the sensor and $(_,_)^⊤$ denotes the principal point.

The description here is very brief, the paper in the link explains various transformations for arriving to the camera space as well; plus other topics such as camera calibration and stereo matching with hypercentric perspective cameras.

Rendering Hypercentric Perspective


ASP.NET Core + Docker not accessible on specified port

Question: It is impossible for me to access container with ASP.NET Core 3.1 application running inside.
Goal is to run application in container on port 5000. When I'm running it locally using standard VS profile I navigate to http://localhost:5000/swagger/index.html in order to load swaggerUI. I would like to achieve same thing using docker.
Steps to reproduce my issue:

Add dockerfile with exposed 5000 port and ENV ASPNETCORE_URLS  variable:
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
ENV ASPNETCORE_URLS=http://+:5000
EXPOSE 5000

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["myapp/myapp.csproj", "myapp/"]
RUN dotnet restore "myapp/myapp.csproj"
COPY . .
WORKDIR "/src/myapp/"
RUN dotnet build "myapp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "myapp.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "myapp.dll"]

Build image
 docker build -t myapp .

Run docker image:
 docker run myapp -p 5000:5000

Running commands above with specific docker file results in this:
    [21:28:42 INF] Starting host.
    [21:28:42 INF] Now listening on: http://[::]:5000
    [21:28:42 INF] Application started. Press Ctrl+C to shut down.
    [21:28:42 INF] Hosting environment: Production
    [21:28:42 INF] Content root path: /app

However, I can't access container using http://localhost:5000/swagger/index.html because of ERR_CONNECTION_REFUSED -> This site can't be reached.
I did get into container to check if host is running for sure, using:
docker exec -it containerId /bin/bash
cd /app
dotnet myapp.dll

what resulted in following error:
Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http://[::]:5000: address already in use.

Conclusion is that port inside the container is used, application is alive, it's just not accessible from outside.I don't know how to get inside of it.
Please point me into right direction.
UPDATE
Issue is solved, answer is posted below. However explanation why it was needed and how it works would be nice!
Answer: To solve the issue I had to manually add "--server.urls" to entrypoint like shown below:
ENTRYPOINT ["dotnet", "myapp.dll", "--server.urls", "https://+:5000"]

Answer: I solved the same issue in the following way:

Added the following in appsettings.json to force Kestrel to listen to port  80.

"Kestrel": {
  "EndPoints": {
    "Http": {
      "Url": "http://+:80"
    }
  }
}

Exposed the port in dockerfile

ENV ASPNETCORE_URLS=http://+:80

EXPOSE 80

ENTRYPOINT ["dotnet", "EntryPoint.dll"]

Ran the container using the below command.

docker run -p 8080:80 <image-name>:<tag>

The app exposed on http://localhost:8080/
Answer: Just two other hints, ENV variables are scoped in build-stages and will not be preserved. (It is not in your case).
Also the publish command in VS is set by default to Release and the initial program.cs has an
if ( app.Environment.IsDevelopment() )
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

clause. So swagger will not be available.


How to access highest role based on role priority

Question: Hi I have a synerio in that user mapped to two roles and roles have priority set like 1 and 2 ...my question is how to access highest code and role only ...
For exp
Code       Name          Role   RolePriority
1          Rehman        Abc    2
2          Rehman        Def    3
3          Neha          Des    1

So  i want Rehman with Def role and Neha with Des role
Comment: Possible duplicate of [SQL select only rows with max value on a column](https://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column)
Answer: You can use ROW_NUMBER() OVER() to select highest priority
DECLARE @test AS TABLE(Code INT,Name VARCHAR(100),Role VARCHAR(100),RolePriority int)

INSERT INTO @test VALUES(1,'Rehman','Abc',2),(2,'Rehman','Def',3),(3,'Neha','Des',1)

SELECT * FROM(
SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY RolePriority desc) AS
rw FROM @test)res
WHERE rw = 1


Is $a^4 + b^4 + c^4$ a spherical harmonic?

Question: I am trying to construct Harmonic polynomials on the sphere.  What about the examples:

$f = x^2 + y^2 + z^2$
$g = x^4 + y^4 + z^4$

We have that $\nabla^2 f \neq 0$ by compuing the second derivative of each coordinate separately:
$$
\left(
\frac{\partial^2}{\partial x^2} +
\frac{\partial^2}{\partial y^2} +
\frac{\partial^2}{\partial z^2}
\right) (x^4 + y^4 + z^4) = 12(x^2 + y^2 + z^2) \neq 0
$$
We have a decomposition $L^2(S^2) = \bigoplus H_d $ with $H_d = \{ \text{harmonic polynomials in }x,y,z \text{ of degree }d \}$.  I am pretty sure the two functions I have constructed are in $L^2$.
$$ \int_{S^2} |f|^2  < 9 \int_{S^2} 1\,  dS  = 9 \times (4\pi) $$
and a similar story for $g$.  How can I get an expansion of $f$ and $g$ in terms of harmonic polynomials?  Are there terms of lower degree missing?
Answer: You can decompose a function on $\mathbb{S}^2$ into spherical harmonics, not into harmonic polynomials. They are related, but they are not the same. Spherical harmonics satisfy the equation
$$ \Delta_{\mathbb{S}^2} Y^m_l(\theta, \phi) = -l(l+1) Y^m_l (\theta, \phi)$$
which means that functions $f(x,y,z) = r^l Y^m_l(\theta,\phi)$ are harmonic functions. Such functions also happen to be polynomials, so they are called harmonic polynomials. However, if you multiply a spherical harmonic with wrong power of $r$, you don't get a harmonic polynomial.
If you want to write your functions into spherical harmonic, you need to separate their radial and spherical part. In case of $f$ it's simple
$$ f(x,y,z) = r^2 = \sqrt{4\pi}\, r^2  Y^0_0(\theta, \phi)$$
You can see that it involves a spherical harmonic with $l=0$ multiplied by $r^2$. The power of $r$ doesn't match, so no wonder you don't get a harmonic polynomial, $\Delta f \neq 0$.
With $g$ you have
\begin{align} g(x,y,z) &= r^4 (\sin^4\theta \cos^4\phi + \sin^4\theta\sin^4\phi + \cos^4\theta) = \\
&= r^4 \left(\sin^4\theta \Big(\frac18 e^{4i\phi} + \frac34 + \frac18 e^{-4i\phi}\Big) + \cos^4\theta\right) = \\
&= r^4 \left(\sqrt{\frac{8\pi}{315}}Y^4_4(\theta,\phi) + \sqrt{\frac{8\pi}{315}}Y^{-4}_4(\theta,\phi)+ \frac34 \sin^4\theta  + \cos^4\theta\right) = \\
&= r^4 \left(\sqrt{\frac{8\pi}{315}}Y^4_4(\theta,\phi) + \sqrt{\frac{8\pi}{315}}Y^{-4}_4(\theta,\phi)+ \frac74 \cos^4\theta - \frac32 \cos^2\theta +\frac34\right) = \\
&= r^4 \left(\sqrt{\frac{8\pi}{315}}Y^4_4(\theta,\phi) + \sqrt{\frac{8\pi}{315}}Y^{-4}_4(\theta,\phi)+ \frac{4\sqrt\pi}{15} Y^0_4(\theta,\phi) +\frac{6\sqrt\pi}{5}Y^0_0(\theta,\phi)\right)\end{align}
Again, you have spherical harmonic with index $l=0$ not matching the power of $r$, so you don't get a harmonic polynomial, and $\Delta g \neq 0$.