Should I Add More Static Vents On My Roof

Question: I want to add insulation to an old ranch house. However, the insulation contractor wants to add static vents (2 turtles and 2 pipes). He says I don't have enough ventilation in my attic.
The roof already has a ridge vent. It also has a gable vents but no soffit . The attic seems fine to me. The attic temperature is always within +/- 10 of the outside temperature.
The house is in MA; so we have extreme weather. Even in the coldest winter, there has never been ice damns. There is no known mold issue. The shingles have aged well, the roof is almost 25 years old. I think it's time to start thinking about a new roof.
Should I think about changing the roof or keep it as is? I'm a big believer in "If it's not broken." Was the insulation guy misinformed?
Comment: Perhaps the existing vents were sufficient when you had no insulation - if you add insulation then the vents may need improving. Did you consider that the insulation guy took that into account?
Comment: I'd go with the soffit vents and avoid any new holes in the roof. Ridge and gable to be truly affective need soffit vents. Just be sure that they are not obstructed with new or old insulation.
Answer: I would not anything more to the roof.  You probably have enough flow through the ridge and gable vents.
If you're really concerned, soffit vents should be next.  But a lot of them I've seen do not have enough free space area, or net free area to be effective.
Comment: Free space area, or net free area is the effective, or useful open area of the holes in a soffit vent.  Because the hole or slots tend to be small, the effective area for air flow is less than the measured aea of the opening.
Comment: What is free space in reference to soffit vents?  Do you mean people block them with junk in the attic?  Thanks for taking time to answer my question.
Answer: Adding openings below ridge vents short-circuits venting function. There are several physical principles at play (convection and scavenging, put simply), and you degrade them by adding openings between the soffit and the ridge. Even gable vents are often ill-advised with soffit and ridge vents. They can hamper air movement at the outer edges of the attic.
Unless you have a hip roof with very little ridge, leave it alone. There are plenty of calculation tables to be found indicating the amount of venting you need for a given attic space. They assume adequate soffit venting, but they're a good guide.
Comment: The roof is a dormer (that is the term I think).  It has gables at the two ends and on the protruding section.  It has a ridge vent down the middle but no soffit vents.  The roof protrudes; I believe soffit vents can be added.
Comment: A [dormer](https://www.thespruce.com/what-is-a-dormer-photo-glossary-4084343) is a small roof in the plane of a larger roof. It's not a roof type itself. Your contractor is probably correct that you could use more venting (for the outer edges of the attic), but the plan you describe is not great. Soffit vents are the ticket.
Comment: Yes, you are correct.  The dormer hangs over the front door vestibule.  It has a gable.  The larger roof has the ridge vent with gable vents on the ends.
Answer: The code requires a certain amount of attic ventilation.
Attic Ventilation shall be "cross ventilation " and shall be 1/150th the area that is to be vented. (See ICC R806 Vents.)
However, there is one exception: The attic ventilation can be reduced to 1/300th the area to be vented provided one of the following items are met:
1) a Class I or II vapor retarder is installed on the "warm-in-winter" side of the ceiling, or
2) not less than 40% and not more than 50% of the ventilation is located in the upper portion of the attic. The upper portion is defined as: "Upper ventilation shall not be lower than 3' below the ridge or highest point of the roof. "  (See ICC R806.1.2.)
Also, the Code says you shall maintain a 1" clearance between attic insulation and framing.
So, you can see there is clearly a benefit to having ridge vents, gable vents, etc. , but in a proportion that allows COMPLETE CROSS-VENTILATION to the attic.
Soffit vents with ridge vents obviously meet that requirement best, but gable vents and "turtle vents" (as you call them) are also effective.
So, if you have a 2,000 square foot house, you'll need 13.33 square feet of vents if about half is NOT located in the upper portion of your attic,
Or
You'll need 6.66 square feet of vents if between 40% and 50% of the vents are in the upper portion of your attic.
You can easily calculate the amount of ventilation on your roof, if you use about 2" wide per foot for ridge vents (about 0.15 square feet per linear foot) and about 1/3 square foot for each roof vent. (The free area of vents are reduced due to insect screen, which is required in every vent. However, this rule of thumb will give you a good idea of how much ventilation you have.)


Number called using empty string, null, or undefined

Question: The following calls returns value of 0:
var n1 = Number()         // n1 === 0 is true
var n2 = Number("")       // n2 === 0 is true
var n3 = Number(null)     // n3 === 0 is true

I tried above in Google Chrome Version 64.0.3282.119
But, is this behavior well-defined?  I'm not sure if it behaves the same way in other browsers.
Comment: Look at the spec https://www.ecma-international.org/ecma-262/8.0/index.html#sec-numbers-and-dates
Comment: It's defined in the `ToNumber()` internal operation description in the language spec.
Answer: From the ECMAScript specification

For string-to-number conversion, there is added information in the next section: https://www.ecma-international.org/ecma-262/8.0/index.html#sec-tonumber-applied-to-the-string-type
Answer: Yes this is an expected behavior on all the browsers.
Any non executable value passed to constructor of Number will return 0.
var num1 = Number();
var num2 = Number("");
var num3 = Number(false);
var num4 = Number(null);
// here num1, num2, num3 and num4 will be 0 as undefined, empty string, false and null are non-executable values.

If you pass executable non-number value to constructor of Number, it will return NaN
var num5 = Number("abc");
var num6 = Number({});
var num7 = Number([]);
// num5, num6 and num7 will be NaN as non-empty string, any object and any array are executable but Not a number values.

Answer: When no argument is provided Number() will always return 0 and if the argument is illegale so Number() will return NaN


How can i show user's current country when user denies location access in Google map?

Question: Is there any way to show the user's current country instead user location when user denies location access of the user?
Answer: You can extract location from ip address. You'll get the country and region easily from ip address but you can't get the exact location.
Answer: You can also get it from the Locale:
let code = Locale.current.identifier
let reg = Locale.current.regionCode
let desc = Locale.current.localizedString(forIdentifier: Locale.current.identifier)

produces:
"en_US"
"US"
"English (United States)"


unable to load shared object quantreg.so

Question: > R.version
               _
platform       x86_64-pc-linux-gnu
arch           x86_64
os             linux-gnu
system         x86_64, linux-gnu
status
major          3
minor          2.3
year           2015
month          12
day            10
svn rev        69752
language       R
version.string R version 3.2.3 (2015-12-10)
nickname       Wooden Christmas-Tree

I am trying to use RStudio for data mining. The last time I was using R only, I didn't have this problem. Then I rebuilt the R packages in my machine to use RStudio
and installed  the package FactoMineR to perform PCA. When I run
library('FactoMineR') or library(FactoMineR), I get this error:
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/home/ci/R/x86_64-pc-linux-gnu-library/3.2/quantreg/libs/quantreg.so':
  libRlapack.so: cannot open shared object file: No such file or directory
Error: package or namespace load failed for 'FactoMineR'

When I tried to reinstall this package, I got the same error, so it is not just the mistake of library().
Comment: This sentence makes no sense: _Then I rebuilt the R packages in my machine to use RStudio_.
Comment: Are you able to load this package in vanilla R?
Comment: @RomanLuštrik, thanks for your reply, and what is the vanilla R? An IDE or somewhat? sorrry I'm a newbie.
Comment: Outside Rstudio. If you run R from the console.
Comment: Have you tried to reinstall the package `quantreg`?
Answer: Thanks to @Stibu, I tried to reinstall the Quantreg packages, and it worked, but there are some other problems.
I will reopen a question.
Thank you all
Comment: This is actually not an answer, is it? Why not editing it to describe what finally worked for you, even though it's three years later?


Java 6 applications are prevented from being deployed to Google App Engine from any version of the SDK

Question: When i tried to deploy the Java 6 application in App engine. I got error like
Java 6 applications are prevented from being deployed to Google App Engine from any
version of the SDK, including older ones. If you need to continue to deploy Java 6
applications for compatibility reasons, you can request that your application be
whitelisted for Java 6 deployment by visiting link.

Then i changed java version 1.7 in project settings. Even after, app engine deployment throw same error.
How to fix this issue.
Comment: Have you change to Java JDK7 (not JRE) in both "Java Build Path" and "Java Compiler" of project properties?
Comment: Yes, I changed the both Build Path and Java Compiler.
Comment: As a tip, I faced alike but re-deployment problem; But today I succeeded to deploy on gae by using eclipse kepler 4.3 which has jdk compliance settings as 1.7 and appengine-api-sdk-1.8.5 which comes as default one with the eclipse kepler 4.3 gwt 2.5 plugin; I hope that helps a bit...
Answer: I finally fix this issue by installing Eclipse 4.3 Kepler and App Engine SDK 1.9.2.
Install Latest Eclipse 4.3
https://www.eclipse.org/downloads/
Install Latest Google Eclipse Plugin
https://developers.google.com/eclipse/docs/getting_started
Answer: Create a new small Java 7 project that deploys and runs successfully.  Copy your existing application content into the new project.  Rename the old project to use it as an archive.  Rename the new project to use the original project name and application id.
Comment: Sorry. This does not hep.
Comment: Are you unable to deploy any AppEngine projects at all, or is the problem only with the formerly Java 6 based project?  How about trying the guestbook tutorial?
Comment: I create new application in the App Engine and try to upload sample `guestbook` application with new application id, it `DOES NOT WORK`. I uses App Engine SDK 1.7.3 version. Will that be problem?
Comment: You've probably just identified the cause of the problem.  SDK 1.7.3 is too old for the AppEngine software in Google's cloud.  It's now on 1.9.2.  In Eclipse, try selecting Help -> Check for Updates. or if that does not work try a fresh SDK install by following [Google Plugin for Eclipse Quick Start](https://developers.google.com/eclipse/docs/getting_started)
Comment: Thanks, i will try and let you know. Moreover i have Google Eclipse Plugin 4.2, NOT 4.3. Do i need to update eclipse plugin too?
Comment: Yes you should update your Eclipse plugin.  For example Debian Stable users get Eclipse 3.8, which is almost identical to Eclipse 4.2, and all these Eclipse versions currently require AppEngine SDK 1.9.2.
Comment: Thank you very much. Installing Latest Eclipse 4.3 `Kepler` and App Engine SDK 1.9.2 solves the issue.
Answer: If you use Eclipse, check at Preferences>Java>Compiler. The JDK Compliance is (on my laptop) not updated to the version 1.7


Cannot read property 'overview' of undefined

Question: I got the following error

Cannot read property 'overview' of undefined

I cannot figure out what this is.
<template>

    {{ fold + 2 }}
    {{ row.correct }}
    {{ row.incorrect }}
    {{ row.accuracy.toFixed(2) }}%

</template>

Then in the browser, I get the following error

TypeError Cannot read property 'overview' of undefined

When I comment this line
perFold.push(fold[fold.overview.bestAttr])

I then do not have any error, but the results expected in my browser are empty.
Comment: Formatted to make it readable to a minimal degree.
Comment: `fold` is in some cases falsy (null, undefined), hence why you cannot access `overview` here.
Comment: I'm not really sure about the actual thing you're trying to achieve here, it could be nice to have an explanation of what is attended an probably also a [repro] if you want to have this one improved.
Answer:         perFold.push(fold[fold[i].overview.bestAttr])

fold is a array. Because of that you need to specify loop index.
Comment: i got an error like this Cannot read property '1' of undefined, what should i do next? do you have any suggestion?
Comment: maybe if you write 'if(fold[i] != undefined)' at the beginning of your code the problem will be solved


Booting problem in Ubuntu 15.10 , 14.04

Question: I want to use Ubuntu 15.10, but every time the computer boots it shows something like:
"SYSLINUX Peter Anvin at el"
I want to fix this error to use Ubuntu.
BIOS -> Pendrive is 1st Boot Disk.
I'm using UNetBootin and it records data in the pendrive.
I downloaded 32bit version.
Comment: Welcome to Ask Ubuntu!  **;-)** Have you tried [checking your hashes](https://help.ubuntu.com/community/UbuntuHashes)?
Comment: Why 32 bit? Very, very old system with 2GB of RAM or less? Or new lightweight system. If so you proably need Lubuntu.  I might try one of the other flash drive creator programs. Some just seem to cause issue, or some flash drives. Or even perhaps some combination of installer & brand flash drive. And a change helps.
Comment: My computer has 2GB of RAM,i tried to install the iso with YUMI[by .wine],but the error keeps appearing.
Comment: Ok,it shows:
51b53fa15c0b89948bbaba311d64a962 *ubuntu-14.04.4-desktop-i386.iso
And the md5sum in terminal correct,but still not booting.
Answer: This seems to be a random issue with 'Unetbootin' and 'startup disk creator'. I used a Kingston 16gb 2.0 usb drive to boot Ubuntu 15.10 installation image (ubuntu-15.10-desktop-i386.iso). All that appeared at boot was:
"SYSLINUX Peter Anvin  etc."

BOOT ERROR

After searching all the articles with no luck, observed at the command line that the drive itself was marked rw only and although Ubuntu showed it as bootable, the drive itself was not executable. Used chmod +x on /dev/sdc and drive worked perfectly installing the existing iso image of 15.10 that Unetbootin and Startup disk creator both configured it with. No other changes needed to be made to the drive or the software image.
Problem is that after installation the usb drive becomes rw only again as follows:
$ls -la /dev/sdc

brw-rw---- 1 root disk 8, 32 Mar 19 11:34 /dev/sdc

$sudo chmod +x /dev/sdc

$ls -la /dev/sdc

brwxrwx--x 1 root disk 8, 32 Mar 19 11:34 /dev/sdc

I tried the install process 3 times with the same results. Each time I received the error was able to make the drive executable from the command line and it worked on reboot. There seems to be an intermittent issue with making the executable setting persistent on the usb drive as the condition and its resulting error can be made consistently repeatable.

Booting problem in Ubuntu 15.10 , 14.04


Is there a CSS parent selector?

Question: How do I select the
 element that is a direct parent of the anchor element?
As an example, my CSS would be something like this:
li < a.active {
    property: value;
}

Obviously there are ways of doing this with JavaScript, but I'm hoping that there is some sort of workaround that exists native to CSS Level 2.
The menu that I am trying to style is being spewed out by a CMS, so I can't move the active element to the
 element... (unless I theme the menu creation module which I'd rather not do).
Answer: The W3C's Selectors Level 4 Working Draft includes a :has() pseudo-class that provides this capability, among others:
li:has(> a.active) { /* styles to apply to the li tag */ }

All major browsers support this selector. Refer to https://caniuse.com/css-has to check if your target browser or browser versions have support for it.

You may need to resort to using JavaScript if your target browser does not fully support this feature.
Comment: As of December 2023, all in-support browsers support this pseudo-class.
Comment: It's so nice to see this be available in all browsers. Previously it was quite painful to do this.
Answer: You can use the :has() CSS pseudo-class.
See browser support at Caniuse.com.
Comment: @TamusJRoyce ... and what does SASS compile the resultant CSS too? It has to use CSS at the end of the day.
Comment: Actually, I think there is [experimental syntax](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) equivalent to Andrew's statement: `@supports selector(:has(a))`
Comment: As @Rodolfo Jorge Nemer Nogueira pointed out, it is possible with sass (scss) by using the & sign. That then gets compiled to the desired css. It would be nice if the next css version supported &
Comment: I had success with `@supports not selector(:has(a, b)) { ... }` to be able to check if a non compatible browser is used, i.e. Firefox at the time of writing. Cfr. https://developer.mozilla.org/en-US/docs/Web/CSS/@supports#testing_for_the_support_of_a_selector
Answer: I don't think you can select the parent in CSS only.
But as you already seem to have an .active class, it would be easier to move that class to the li (instead of the a). That way you can access both the li and the a via CSS only.
Comment: @Dominic Aquilina Take a look at the question, the OP is using a class, not a pseudo selector.
Comment: You can't shift the pseudo selector to the list item, as it is not a focusable element. He's using the :active selector, so when the anchor is active he wants the list item to be affected. List items will never be in the active state. As an aside, it's unfortunate that such a selector doesn't exist. Getting a pure CSS menu to be fully keyboard accessible seems to be impossible without it (using sibling selectors you can make submenus created using nested lists to appear, but once the list gains focus it becomes hidden again). If there are any CSS-only solutions to this particular conun
Answer: You can use this script:
*! > input[type=text] { background: #000; }

This will select any parent of a text input. But wait, there's still much more. If you want, you can select a specified parent:
.input-wrap! > input[type=text] { background: #000; }

Or select it when it's active:
.input-wrap! > input[type=text]:focus { background: #000; }

Check out this HTML:

    <input type="text" class="Name"/>
    Your name sir

You can select that span.help when the input is active and show it:
.input-wrap! .help > input[type=text]:focus { display: block; }

There are many more capabilities; just check out the documentation of the plugin.
BTW, it works in Internet Explorer.
Comment: suppose using jquery `patent()` would be faster. This need testing, however
Comment: @HerrSerker I think #a! is an invalid selector,  what should it select?
Comment: Per my comment on the accepted answer, it looks like the polyfill may be required even in the near future after all, because the subject indicator may never be implemented by browsers in CSS.
Comment: @Idered It fails when you have CSS declaration of a Selector Subject with no child selector (`#a!` alone throws an error, `#a! p` works), and so the others will not works either because of `Uncaught TypeError: Cannot call method 'split' of undefined`: see http://jsfiddle.net/HerrSerker/VkVPs/
Comment: @Idered I don't know. The spec doesn't say it is illegal. #a! should select itself. At least their should be no error in the JavaScript
Comment: Please add the contents of the script here, otherwise this is useless when GitHub is down.
Comment: Why deprecated?
Comment: How would you then stick an `:after` on that parent?
Comment: good approach, but sadly it's [DEPRECATED]
Comment: Could this be used on pseudo selectors [ parent , div and parent::after ], if div is hovered change the parent:after style?

@Idered
Answer: As mentioned by a couple of others, there isn't a way to style an element's parent/s using just CSS but the following works with jQuery:
$("a.active").parents('li').css("property", "value");

Comment: The `<` selector does not exist (verified using jQuery 1.7.1).
Comment: And rather than using `.css("property", "value")` to style the selected elements, you should usually `.addClass("someClass")` and have in your CSS `.someClass { property: value }` ([via](http://stackoverflow.com/a/6279001/578288)). That way, you can notate the style with the full power of CSS and any preprocessors you are using.
Comment: Perhaps that `<`-syntax worked in 2009 but I've updated it (for 2013).
Comment: Even better, use jQuery's built-in [`:has()` selector](http://api.jquery.com/has-selector/): `$("li:has(a.active)").css("property", "value");`. It reads similarly to CSS 4's proposed `!` selector. See also: [`:parent` selector](http://api.jquery.com/parent-selector/), [`.parents()` method](http://api.jquery.com/parents/), [`.parent()` method](http://api.jquery.com/parent/).
Answer: There is no parent selector; just the way there is no previous sibling selector. One good reason for not having these selectors is because the browser has to traverse through all children of an element to determine whether or not a class should be applied. For example, if you wrote:
body:contains-selector(a.active) { background: red; }

Then the browser will have to wait until it has loaded and parsed everything until the  to determine if the page should be red or not.
The article Why we don't have a parent selector explains it in detail.
Comment: actually, the selector would make a very fast browser look slow.
Comment: I trust that browser developers would come up with an implementation which is (at least) as fast as the javascript version, which is the one people end up using anyway.
Comment: @Marc.2377 If you try the above example in JS on your website, I'm never going to visit it. On the other side, I'd say that most of the time, you only care about immediate children, so if it was only limited to the immediate children, it'd be a good addition without too much impact.
Answer: The pseudo element :focus-within allows a parent to be selected if a descendent has focus.
An element can be focused if it has a tabindex attribute.
Browser support for focus-within
Tabindex
Example

.parent:focus-within {
  background: hsl(199deg, 65%, 73%);
}

/* demo styles */
body {
  margin: 0;
}
.parent {
  background: hsl(0, 0%, 80%);
  min-height: 100vh;
  display: grid;
  place-content: center;
}
.child {
  background: hsl(0, 0%, 0%);
  color: white;
  padding: 3rem;
  outline: 0;
  cursor: pointer;
  font: 18px/1.25 sans-serif;
  width: 20ch;
}

    Click or Focus on me, my parent will change.

Comment: This works fine in my case, thanks! Just a not, the example would be more ilustrative if you change the color to the parent, not to the sibling, this is replace `.color:focus-within .change` with `.color:focus-within`. In my case i'm using bootstrap nav-bar that add the class to the children when active and I want to add a class to the parent .nav-bar. I think this is a pretty common scenario where I own the markup but the component css+js is bootstrap (or other) so I cannot change the behavior. Although I can add tabindex and use this css. Thanks!
Comment: Productive answer! I do want to add a caveat for the copy-pasters among us - __it's generally considered an antipattern to add non-zero tabindexes__ when adding focus to non interactive elements... Just use 0 or it will always tab to that element first regardless of document flow.

I updated the answer to have a tabindex of zero.
Answer: There isn't a way to do this in CSS 2. You could add the class to the li and reference the a:
li.active > a {
    property: value;
}

Comment: by making the a element display:block you can style it to fit the whole of the li area. if you can explain what style you are looking for perhaps I could help with a solution.
Answer: Try to switch a to block display, and then use any style you want. The a element will fill the li element, and you will be able to modify its look as you want. Don't forget to set li padding to 0.
li {
  padding: 0;
  overflow: hidden;
}
a {
  display: block;
  width: 100%;
  color: ..., background: ..., border-radius: ..., etc...
}
a.active {
  color: ..., background: ...
}

Answer: The CSS selector "General Sibling Combinator" could maybe used for what you want:
E ~ F {
    property: value;
}

This matches any F element that is preceded by an E element.
Comment: @F-Natic I am not surprised that does not work. It is not valid CSS (there is no `:visible` pseudo-class in CSS). `body` is also a direct and *only* descendant of `html`.
Comment: `.component-one:visible ~ body{ background-color: red; }` does not work.
Answer: In the CSS Selectors 4 specification, CSS introduces a new selector called :has(), which finally lets us select parents. That means is we'll be able to target a CSS element that has specific children within it. This is already supported in Safari and is also in Chrome 105. The full support table is shown
here.
Parent Selectors workings
In CSS, if we want to select something, we use selectors that descend the DOM.
For example, selecting a p tag within a div tag looks like this:
 div p {
   color: red;
}

Until now, couldn't really select the div tags which had p tags within them, though, and this meant we had to resort to Javascript. The main reason this wasn't implemented in CSS is that it's quite an expensive operation to do. CSS is relatively fast to parse, but selecting parent tags requires a relatively significantly larger amount of processing.
Using the :has selector, we can now select div elements which have a p children, or any normal combination of selectors.
For example, selecting a div with a child p now looks like this:
div:has(p) {
  color: red;
}

This will make any div with a child p red.
Combining parent selection with other selectors
Just like any other CSS selector, we can combine this for specific circumstances.
For example, if you want to select only div tags which have direct span children:
div:has(> span) {
  color: red;
}

As the vocabulary of :has suggested, it is not just limited to parent selection.
For example, below we can select a span which :has a sibling div:
span:has(+ div) {
color: red;
}

Or even, selecting an element which does not have a child, by using the :not() selector.
For example, the following will select any div which does not have a p child:
div:not(:has(p)) {
 color: red;
}

Selecting elements that only contain text in CSS
One very common problem in CSS is that the :empty tag does not select elements that contain any text - so sometimes an element can contain one space, and :empty will not apply. The :has selector gives us the power to select elements that only contain text nodes and no other child elements.
Although this is not the perfect solution for simply :empty elements with spaces (as this will select any element with just text and no additional HTML DOM elements) - it does give us the ability to select DOM elements with only text nodes, which was not previously possible. We can achieve this with the following code:
div:not(:has(*)) {
  background: green;
}

Answer: Not in CSS 2 as far as I'm aware.  CSS 3 has more robust selectors but is not consistently implemented across all browsers.  Even with the improved selectors, I don't believe it will accomplish exactly what you've specified in your example.
Answer: You might try to use hyperlink as the parent, and then change the inner elements on hover. Like this:
a.active h1 {color:red;}

a.active:hover h1 {color:green;}

a.active h2 {color:blue;}

a.active:hover h1 {color:yellow;}

This way you can change the style in multiple inner tags, based on the rollover of the parent element.
Comment: In HTML5 it is perfectly fine to put block elements inside links.
Comment: That is correct, but limits the markup code within the `a` tag to certain elements only, if you want to conform to XHTML standards. For instance, you cannot use a `div` within `a`, without getting a warning of violating the schema.
Answer: This is the most discussed aspect of the Selectors Level 4 specification.
With this, a selector will be able to style an element according to its child by using an exclamation mark after the given selector (!).
For example:
body! a:hover{
   background: red;
}

will set a red background-color if the user hovers over any anchor.
But we have to wait for browsers' implementation :(
Comment: The ("!") feature has been replaced with ':has()' https://drafts.csswg.org/selectors/#changes-2013
Answer: I know the OP was looking for a CSS solution but it is simple to achieve using jQuery. In my case I needed to find the
 parent tag for a  tag contained in the child
. jQuery has the :has selector so it's possible to identify a parent by the children it contains:
$("ul:has(#someId)")

will select the ul element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):
$("li:has(.active)")

Comment: Or use `$yourSpan.closest("ul")` and you'll get the parent UL of your span element. Nevertheless your answer is completely offtopic imho. We can answer all of the CSS-taged questions with a jQuery solution.
Answer: Here's a hack using pointer-events with hover:

<!doctype html>

        <title></title>

Answer: Currently there is no parent selector & it is not even being discussed in any of the talks of W3C. You need to understand how CSS is evaluated by the browser to actually understand if we need it or not.
There is a lot of technical explanation here.
Jonathan Snook explains how CSS is evaluated.
Chris Coyier on the talks of Parent selector.
Harry Roberts again on writing efficient CSS selectors.
But Nicole Sullivan has some interesting facts on positive trends.
These people are all top class in the field of front end development.
Comment: The `need` is defined by web developers' requirements, whether to have it in the spec is decided by other factors.
Answer: There's a plugin that extends CSS to include some non-standard features that can really help when designing websites. It's called EQCSS.
One of the things EQCSS adds is a parent selector. It works in all browsers, Internet Explorer 8 and up. Here's the format:
@element 'a.active' {
  $parent {
    background: red;
  }
}

So here we've opened an element query on every element a.active, and for the styles inside that query, things like $parent make sense, because there's a reference point. The browser can find the parent, because it's very similar to parentNode in JavaScript.
Here's a demo of $parent and another $parent demo that works in Internet Explorer 8, as well as a screenshot in case you don't have Internet Explorer 8 around to test with.
EQCSS also includes meta-selectors: $prev for the element before a selected element and $this for only those elements that match an element query, and more.
Answer: Just an idea for horizontal menu...
Part of HTML

    Link

Part of CSS
/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

Updated demo and the rest of code
Another example how to use it with text-inputs - select parent fieldset
Comment: It's not at all clear to me how you mean to generalize this to some/many/most of the parent selector use cases, or even exactly which parts of this CSS are doing what. Can you add a thorough explanation?
Comment: I did not try to apply this to real world scenarios, that is why I say "Not for production". But I think It can be applied to 2-level menu only with fixed item width. "which parts of this CSS are doing what" - .test-sibling here is actually background of parent item (the last line of CSS).
Comment: Added explanation (css section of jsfiddle, starting from "MAIN PART")... And I was mistaken - there may be any number of sublevels.
Answer: The CSS parent selector (also know as the :has() selector) has finally landed in Safari TP 137. The feature is currently being implementated in Chrome as well. (MDN Documentation)
Parent selection is done via the pseudo-class :has().  For example, div:has(> .child) will select all
 elements with a child having a child class.
Other examples:
Selecting direct parent of an element

Child Element

div:has(> p)

Selecting all the parents of an element

The following selector will select both grandparent and parent
div:has(.child)

You can also use it for nested selectors and even with other pseudo classes:
div:has(> :nth-child(10))

Other valid CSS operators can be used to customize the query.
Keep an eye on caniuse.com/css-has for browser compatibility.
Comment: @CodeForGood `document.querySelector('section:has(h1.heading1)').style.padding = 0` but it may not work in all browser yet
Comment: could you please help convert $('section:has(h1.heading1)').css('padding', 0); into pure JavaScript?
Comment: your code throws `Uncaught DOMException: Document.querySelector: 'section:has(h1.heading1)' is not a valid selector` error
Comment: Minor edit: The selector for selecting both grandparent and parent should be `div:has(#child)` instead of `div:has(.child)`
Answer: It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing @nest at-rules.

3.2. The Nesting At-Rule: @nest
While direct nesting looks nice, it is somewhat fragile. Some valid nesting selectors, like .foo &, are disallowed, and editing the selector in certain ways can make the rule invalid unexpectedly. As well, some people find the nesting challenging to distinguish visually from the surrounding declarations.
To aid in all these issues, this specification defines the @nest rule, which imposes fewer restrictions on how to validly nest style rules. Its syntax is:
@nest = @nest <selector> { <declaration-list> }
The @nest rule functions identically to a style rule: it starts with a selector, and contains declarations that apply to the elements the selector matches. The only difference is that the selector used in a @nest rule must be nest-containing, which means it contains a nesting selector in it somewhere. A list of selectors is nest-containing if all of its individual complex selectors are nest-containing.

(Copy and pasted from the URL above).
Example of valid selectors under this specification:
.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .foo > .bar { color: blue; }
 */

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .parent .foo { color: blue; }
 */

.foo {
  color: red;
  @nest :not(&) {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   :not(.foo) { color: blue; }
 */

Answer: The W3C excluded such a selector because of the huge performance impact it would have on a browser.
Comment: false. because the DOM is a tree, they have to go to the parent before getting to the child, so the simply just go back one node. o.o
Comment: CSS selectors are a [queue](http://www.snook.ca/archives/html_and_css/css-parent-selectors) so [selector order](http://www.stevesouders.com/blog/2009/06/18/simplifying-css-selectors/) is evaluated rather than the document XPath or DOM hierarchy.
Comment: @rgb At least that's what they told us.
Answer: Technically there is no direct way to do this. However, you can sort that out with either jQuery or JavaScript.
However, you can do something like this as well.
a.active h1 {color: blue;}
a.active p {color: green;}

jQuery
$("a.active").parents('li').css("property", "value");

If you want to achieve this using jQuery here is the reference for the jQuery parent selector.
Comment: could you please help convert `$('section:has(h1.heading1)').css('padding', 0);` into pure JavaScript?
Answer: Although there is no parent selector in standard CSS at present, I am working on a (personal) project called axe (ie. Augmented CSS Selector Syntax / ACSSSS) which, among its 7 new selectors, includes both:

an immediate parent selector < (which enables the opposite selection to >)
an any ancestor selector ^ (which enables the opposite selection to [SPACE])

axe is presently in a relatively early BETA stage of development.
See a demo here:

.parent {
  float: left;
  width: 180px;
  height: 180px;
  margin-right: 12px;
  background-color: rgb(191, 191, 191);
}

.child {
  width: 90px;
  height: 90px;
  margin: 45px;
  padding-top: 12px;
  font-family: sans-serif;
  text-align: center;
  font-size: 12px;
  background-color: rgb(255, 255, 0);
}

.child.using-axe < .parent {
  background-color: rgb(255, 0, 0);
}

Here, the axe parent selector turns the outer square red.

In the example above < is the immediate parent selector, so

.child.using-axe < .parent

means:

any immediate parent of .child.using-axe which is .parent

You could alternatively use:

.child.using-axe < div

which would mean:

any immediate parent of .child.using-axe which is a div
Comment: The project is in an early Beta stage at present. You can (at least currently) activate axe selectors in your CSS styles by including `` at the very end of your html document, just before ``.
Answer: The short answer is NO; we don't have a parent selector at this stage in CSS, but if you don't have to swap the elements or classes anyway, the second option is using JavaScript. Something like this:
var activeATag = Array.prototype.slice.call(document.querySelectorAll('a.active'));

activeATag.map(function(x) {
  if(x.parentNode.tagName === 'LI') {
    x.parentNode.style.color = 'red'; // Your property: value;
  }
});

Or a shorter way if you use jQuery in your application:
$('a.active').parents('li').css('color', 'red'); // Your property: value;

Comment: or `parentElement`, sameshing - just `document.getElementById().parentElement` etc.
Answer:
Any ideas?

CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use checkbox and/or radio inputs to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...

/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
  display: none;
  visibility: hidden;
  opacity: 0;
  filter: alpha(opacity=0); /* Old Microsoft opacity */
}

/* Base style for content and style menu */
.main__content {
  background-color: lightgray;
  color: black;
}

.menu__hidden {
  background-color: black;
  color: lightgray;
  /* Make list look not so _listy_ */
  list-style: none;
  padding-left: 5px;
}

.menu__option {
  box-sizing: content-box;
  display: block;
  position: static;
  z-index: auto;
}

/* ▼ - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
  content: '\2630';
  display: inline-block;
}
*/

/* ▼ - Down Arrow */
.menu__trigger__selection::after {
  content: "\25BC";
  display: inline-block;
  transform: rotate(90deg);
}

/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
  cursor: pointer;
  background-color: darkgray;
  color: white;
}

/**
 * Things to do when checkboxes/radios are checked
 */

.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
  transform: rotate(0deg);
}

/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
  display: block;
  visibility: visible;
  opacity: 1;
  filter: alpha(opacity=100); /* Microsoft!? */
}

/**
 * Hacky CSS only changes based off non-inline checkboxes
 * ... AKA the stuff you cannot unsee after this...
 */
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
  background-color: lightgray;
  color: black;
}

.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
  background-color: black;
  color: lightgray;
}

.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
  color: darkorange;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
  background-color: darkgreen;
  color: red;
}

.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
  color: darkorange;
}

<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-default">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-one">
<input type="radio"
       name="colorize"
       class="menu__checkbox__style"
       id="style-two">

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

  <input type="checkbox"
         class="menu__checkbox__selection"
         id="trigger-style-menu">
   Theme

      Default Style

      First Alternative Style

      Second Alternative Style

    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the body and :root from just about anywhere by linking the id and for properties of radio/checkbox inputs and label triggers; likely someone'll show how to re-touch those at some point.
One additional caveat is that only one input of a specific id maybe used, first checkbox/radio wins a toggled state in other words... But multiple labels can all point to the same input, though that would make both the HTML and CSS look even grosser.

... I'm hoping that there is some sort of workaround that exists native to CSS Level 2...

I am not sure about the other pseudo classes, but I :checked for pre-CSS 3. If I remember correctly, it was something like [checked] which is why you may find it in the above code, for example,
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
 /* rules: and-stuff; */
}

... but for things like ::after and :hover, I'm not at all certain in which CSS version those first appeared.
That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.
Comment: There has never been a "CSS4" planned, and even CSS3 had been merged into just "CSS" well before 2019.
Comment: It's an opinion piece by a contributing member of the CSSWG extrapolating on her "no" response in the GitHub request, which has languages inactive for over a year. It's safe to say it is not being moved forward with. Module versions *would* conflict massively with spec versioning, as several comments in the thread highlight. Listen, as badly as you want it to be a thing, it's not. It's important to accept that and not confuse readers by mentioning things that don't exist.
Comment: Tyler CSS4 is being considered by those that maintain the spec.  Announcement link → https://www.w3.org/community/css4/ Discussion link → https://github.com/w3c/csswg-drafts/issues/4770
Comment: That's just the name of a discussion group. There will be no technology called CSS4. CSS Modules are versioned independently and have been for many years now. As the actual CSSWG contributors in that random user's GitHub request have already replied [*and wrote a response about*](https://www.smashingmagazine.com/2020/03/css4-pros-cons-discussion/), it's not a good idea. Plus that request has been dead for over a year (you can see the GH w3c account has been deleting recent advocacy comments trying to necro it).
Comment: That article is an opinion peace, and overall is a distraction from the spec discussion thread. A handful of off-topic marked comments and one deleted comment does not make intent to _necro_, and I'd expect the Issue to be marked as Closed if the working group where committed to killing CSS4 discussion. It's okay, and a good thing in large projects, that modules are versioned independently; module versions do not conflict with spec versioning.
Answer: No, you cannot select the parent in CSS only.
But as you already seem to have an .active class, it would be easier to move that class to the li (instead of the a). That way you can access both the li and the a via CSS only.
Answer: At least up to and including CSS 3 you cannot select like that.
But it can be done pretty easily nowadays in JavaScript, you just need to add a bit of vanilla JavaScript, notice that the code is pretty short.

cells = document.querySelectorAll('div');
[].forEach.call(cells, function (el) {
    //console.log(el.nodeName)
    if (el.hasChildNodes() && el.firstChild.nodeName=="A") {
        console.log(el)
    };
});

Peter

Jackson link

Philip

Pullman link

Comment: Eduard Florinescu, could you please help convert $('section:has(h1.heading1)').css('padding', 0); into pure JavaScript?
Answer: Try this...
This solution uses plain CSS2 rules with no Javascript and works in all browsers, old and new. When clicked, the child anchor tag activates its active pseudo-class event. It then simply hides itself, allowing the active event to bubble up to the parent li tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.
Using your example:

        This is a Link

Now apply these styles with the active pseudo-class on a to restyle the parent li tag when the link is clicked:
a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

You should see the link with a green background now change to the list item's blue background on click.

turns to

on click.
Answer: Changing parent element based on child element can currently only happen when we have an <input> element inside the parent element. When an input gets focus, its corresponding parent element can get affected using CSS.
Following example will help you understand using :focus-within in CSS.

.outer-div {
  width: 400px;
  height: 400px;
  padding: 50px;
  float: left
}

.outer-div:focus-within {
  background: red;
}

.inner-div {
  width: 200px;
  height: 200px;
  float: left;
  background: yellow;
  padding: 50px;
}

    I want to change outer-div(Background color) class based on inner-div. Is it possible?
    <input type="text" placeholder="Name" />

Comment: `The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused.` It [works](https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within) with every element, not just `input`
Answer: There no css (and therefore in css preprocessors) parent selector due to "The major reasons for the CSS Working Group previously rejecting proposals for parent selectors are related to browser performance and incremental rendering issues."
Answer: I'd hire some JavaScript code to do that. For example, in React when you iterate over an array, add another class to the parent component, which indicates it contains your children:
<div className={`parent ${hasKiddos ? 'has-kiddos' : ''}`}>
    {kiddos.map(kid =>
)}

And then simply:
.parent {
    color: #000;
}

.parent.has-kiddos {
    color: red;
}

Answer: This is an answer to a similar (but not I feel exactly the same) question which has been closed in favor of this question so I put an answer to How to change the border color when input is checked here.
As it is not possible to style a parent depending on its child's status using pure CSS, this snippet alters the HTML so that there is an empty span element immediately following the input elements. This span element does nothing until the input is hovered at which point it displays itself and expands to fit the same size as the ancestor which has position set. This is the label itself, not the input. Hence the border (shadow) shows as if it is on the label.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.OuterField {
  display: flex;
}

.listLabel {
  padding: 8px 5px;
  border: 2px solid black;
  width: 32%;
  margin: 1%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-flow: row;
  position: relative;
}

input[type="radio"]~span {
  display: none;
}

input[type="radio"]:checked~span {
  display: inline-block;
  width: 100%;
  height: 100%;
  border: 2px solid red;
  box-shadow: 0 0 0 3px orange;
  position: absolute;
  top: 0;
  left: 0;
}

  List 1
        <input type="radio" id="List1" name="list" value="List1">

  List 2
         <input type="radio" id="List2" name="list" value="List2">

Comment: Glad you have something that works. Yes, it is hard to get an absolute placed element exacty at the same spot as another element to get something like a thin border exactly aligned - even if the line-up is exact CSS-wise the underlying screen pixels may show (as there can be several screen pixels to one CSS pixel) so your solution is a practical one.
Comment: Thanks a lot (+1) but what if there is only `border` without `box-shadow` . How to center than , tried to change `top: -2px` `left: -2px` `width: 102%` `height: 112%` on `span` tag . It worked but on some screen sizes only and don't overlap over black border in all screen sizes . Do I have to give absolute values or there are work around this too . Again thanks for help really appreciate .
Comment: Found a work around a that could be using `width: calc(100% + 4px);` `height: calc(100% + 4px);` with `top: -2px` `left: -2px`

Is there a CSS parent selector?


ceph cluster got created, OSDs got initialized, but total cluster space shows 0 bytes available

Question: I am trying to create a ceph cluster.
I've installed ceph on 3 computers and added their names to hosts files.
Created passwordless ssh login.
Installed and configured ntp server and checked, that all the computers show the same time/time zone.
Installed ceph and created mons on all hosts, that are part of ceph cluster with ceph-deploy.
zapped disks, allocated to ceph on each comp and created osds on them.
Checked, the osds were created on those disks.
ceph status shows health_warn, even after reboots of all of the computers and several days have passed. Also, it shows that I have several osds available, but none of them are up. pgmap shows 0 bytes used/available/total.
rados lspools shows only one pool: rbd.
rados -p rbd ls: freezes the output. The cursor just hangs there forever. I've tried to wait even for a couple of hours. Didn't list anything and didn't exited the command. Reboot didn't help.
Tried to zap and osd create once again. It didn't help, only in ceph status, it now shows twice more osds, then were before.
What did I do wrong. I did everything step-by-step from the book: "Learning Ceph - 2015" (Karan Singh), except, that he uses VMs, but I am using metal and I've changed all the radhat based commands/configs, from his book to debian(Ubuntu 15.10). My ceph version is the standard, that comes from the Ubuntu server repository v0.94.5
My current ceph version is based
Answer: OK, with help on ceph's IRC channel, I've found out that Ubuntu changed it's startup during launch of the system to upstart. For that reason, the old way of launching of services doesn't work anymore, so OSDs didn't launch. There is a troubleshooting page on ceph's website, explaining what to do in an upstart sutuation:
http://docs.ceph.com/docs/master/rados/operations/operating/#running-ceph-with-upstart
I've launched OSDs with help from that page. After that, OSDs changed status to up and the cluster showed that it's not 0 bytes in size anymore, but I stumbled upon another problem.
The cluster doesn't initialize completely, so that I can use it. It shows health warning and some details of that warning. Launching command:
ceph status
shows:
<code> health HEALTH_WARN                                                                                │
        10 pgs degraded                                                                                │
        63 pgs stale                                                                                │
        10 pgs stuck degraded                                                                                │
        1 pgs stuck inactive                                                                                │
        63 pgs stuck stale                                                                                │
        18 pgs stuck unclean                                                                                │
        10 pgs stuck undersized                                                                                │
        10 pgs undersized                                                                                │
</code>


Diagnosing noisy power lines

Question: We have a number of devices in our house that communicate via power lines (such as power line networking devices and some solar/electric metering equipment), and we've had persistent problems getting a good signal.  I've tried the steps outlined in this question, but I haven't had much success in locating the problem.
Are any tools available that would help quantify the nature of the problem...that aren't going to set me back hundreds of dollars?  I would love to have some hard data to work with, rather than the rather vague "it's just not working" that I've got right now.
Answer: For power line communication devices to operate correctly they should be on the same leg of the power lines coming into the house. Your house has two power legs and a neutral leg. Voltage from each leg to neutral is nominally 120 volts AC. Voltage from leg 1 to leg 2 is nominally 220 volts. The power line modules work best when all devices are connected to the same leg. If one device is connected to leg 1 and the other device is connected to leg 2, the signal could have to return to the utility transformer (on the pole and could be blocks away) before reaching the other leg.
The quick fix, if you can, is to swap breakers in your main panel so that all power line modules are on the same leg. If you can not do that,this bridge may help. Although this is designed for the "X10" system, they all work pretty much the same and could work as well for your system.
The breakers alternate from leg 1 to leg 2 as shown.
Comment: You should probably do sub-panels as well with the bridge.
Answer: A high school electronics teacher once showed me a trick for finding outlets with loose connections.  This might help you too.
Take a portable radio and tune it to a good AM station with a strong signal. Slightly detune the radio so that you can still hear the station, but with a bit of noise.  Now walk around with the radio, passing it by outlets, switches, etc.  If you get a lot of noise on the radio, you might have found a bad connection.  Turn off the power and open up the device.  Check all of the terminals, wirenuts, etc. to ensure they are snug.
Comment: That's an interesting thought.  Would a bad switch/outlet/etc really contribute to powerline noise in this fashion?  I guess I need to see if I still have that old radio in the basement...
Comment: I believe that should be an AM radio.
Comment: With your suggestion and a little searching I found [this article](http://tdworld.com/mag/power_smarter_approach_resolving/), which is a pretty thorough treatment of the problem.
Answer: The thing on getting a good signal with a power line carrier is getting and keeping a perfectly good 360 degree sine wave.  With today's modern toys, appliances, TV's baby monitors, cordless chargers for razors and what ever else you can think of dumping noise back onto your power lines, good signals are hard to get.  On the link you checked out, Niall C. could not have answered it better.  Without spending a fortune on test equipment, do some research and find a good quality surge suppressor strip that will give you good power quality.  One of the best is a good UPS.
But the problem is all the noise in your house, and keeping whatever you do to correct the noise and keeping it from treating your PLC signal as noise.  It's been years since I've had to do this kind of trouble shooting but it all goes back to what Niall C. pointed out.  Unplug electronics, turn off breakers, try surge strips and or a small UPS system.  Remember just because you have noise at one time today does not mean you will have noise the time everyday, so try at different times of day.
The cheap way is trial and error.  I'm sure you are not the only one with this problem today so keep googling and checking chat rooms dealing with this kind of technology.  If you want a quick fix, you'll have to pay for a professional and with noise on power lines, even it might take them a few trips.

Diagnosing noisy power lines


OWIN - signing and encrypting requests

Question: In our asp.net MVC5 web site we're authenticating against multiple ADFS servers. One of these requests that we sign (and preferably encrypt) our request.
We're using OWIN and the UseWsFederationAuthentication extension method to set up the options for each ADFS server (see below).
var adfsLoginProviderOptions = new WsFederationAuthenticationOptions
            {
                MetadataAddress = adfsLoginProvider.MetadataUrl,
                Wtrealm = AppSettings.FirstAgendaWtRealm,
                AuthenticationMode = AuthenticationMode.Passive,
                AuthenticationType = adfsLoginProvider.Name,
                CallbackPath = new PathString("/adfs/callback"),
                UseTokenLifetime = true
            };
app.UseWsFederationAuthentication(adfsLoginProviderOptions);

My problem is, I don't see a obvious option to set up request signing and encryption and I can't seem to find anyone else who has done this.
Comment: I did actually. Will add a answer
Comment: Hi. I am facing the same problem. Have you found a solution? Thanks.
Comment: Cool. Looking forward to that.
Answer: I did some research and found the following.
I needed to register to SecurityTokenHandlers:

One for decrypting the encrypted token
One for validating the signed token

They are registered as follows:
    var adfsLoginProviderOptions = new WsFederationAuthenticationOptions
            {
                MetadataAddress = adfsLoginProvider.MetadataUrl,
                Wtrealm = "http://[your-realm]",
                AuthenticationMode = AuthenticationMode.Passive,
                AuthenticationType = adfsLoginProvider.Name,
                UseTokenLifetime = false,
                CallbackPath = new PathString("/adfs/callback/" + adfsLoginProvider.ID.ToString()),
                TokenValidationParameters = new TokenValidationParameters
                {
                    AuthenticationType = adfsLoginProvider.Name
                },
                SecurityTokenHandlers = new SecurityTokenHandlerCollection
                {
                    new EncryptedSecurityTokenHandler(new X509CertificateStoreTokenResolver(StoreName.My,StoreLocation.LocalMachine)),
                    new SamlSecurityTokenHandler
                    {
                        CertificateValidator = X509CertificateValidator.None,
                        Configuration = new SecurityTokenHandlerConfiguration()
                        {
                            AudienceRestriction = audienceRestriction,
                            IssuerNameRegistry = issuerRegistry
                        }
                    }
                },

            };

The EncryptedSecurityTokenHandler is implemented as follows:
        public class EncryptedSecurityTokenHandler : System.IdentityModel.Tokens.EncryptedSecurityTokenHandler, ISecurityTokenValidator
        {
            public EncryptedSecurityTokenHandler(SecurityTokenResolver securityTokenResolver)
            {
                Configuration = new SecurityTokenHandlerConfiguration
                {
                    ServiceTokenResolver = securityTokenResolver
                };
            }

            public override bool CanReadToken(string securityToken)
            {
                return base.CanReadToken(new XmlTextReader(new StringReader(securityToken)));
            }

            public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
            {
                // Read token will decrypt it and look for another SecurityTokenHandler in the same collection to do the actual validation
                validatedToken = ReadToken(new XmlTextReader(new StringReader(securityToken)), Configuration.ServiceTokenResolver);
                if (ContainingCollection != null)
                {
                    var identities = ContainingCollection.ValidateToken(validatedToken);
                    var principal = new ClaimsPrincipal(identities.First());
                    return principal;
                }
                return new ClaimsPrincipal(base.ValidateToken(validatedToken));
            }

            public int MaximumTokenSizeInBytes { get; set; }
        }

And the SamlSecurityTokenHandler:
public class SamlSecurityTokenHandler : System.IdentityModel.Tokens.SamlSecurityTokenHandler, ISecurityTokenValidator
{
    public override bool CanReadToken(string securityToken)
    {
        return base.CanReadToken(XmlReader.Create(new StringReader(securityToken)));
    }

    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters,
        out SecurityToken validatedToken)
    {
        validatedToken = ReadToken(new XmlTextReader(new StringReader(securityToken)), Configuration.ServiceTokenResolver);
        var identities = ValidateToken(validatedToken);
        var newIdentities = identities.Select(d => new ClaimsIdentity(d.Claims, "ExternalCookie"));
        var claimsPrincipal = new ClaimsPrincipal(newIdentities);
        return claimsPrincipal; ;
    }

    public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
    {
        var identities = base.ValidateToken(token);
        return identities
    }

    public int MaximumTokenSizeInBytes { get; set; }
}

Audience restriction is the realm of the application:
var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);
audienceRestriction.AllowedAudienceUris.Add(new Uri(http://[your-realm]));

IssuerRegistry is the registry of the issuer signing certificates:
var issuerRegistry = new ConfigurationBasedIssuerNameRegistry();
issuerRegistry.AddTrustedIssuer(adfsLoginProvider.SigningCertThumbprint, adfsLoginProvider.Issuer);

OWIN - signing and encrypting requests


Division by zero error

Question: I have this code throwing up the error:
<?php

    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7

    echo "Success: ";
    echo $res;
    echo "%";

?>

I have tried adding this line:
if ($res === 0)
{
   echo "not eligible";
}

but it still gives the error. any ideas?
Comment: can you indent your code!
Comment: sorry, its the way its written in the script!
Answer: You'd want to check $val2 before the division occurs:
<?php
$val1 = $totalsum;
$val2 = count($allcontent);
if($val2 != 0)
{
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ".$res."%";
}
else
{
    echo "Count of allcount was 0";
}
?>

Answer: You have the following in your code:
$val2 = count($allcontent);

If the $allcontent array is empty, then the value of $val2 will be 0, and you will essentially be doing:
$res = ( $val1 / 0) * 100;

As expected, this will cause PHP to return the 'Division by zero' error.
To make sure this doesn't happen, simply use an if statement:
if ($val2 != 0) {
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ";
    echo $res;
    echo "%";
}

This can be rewritten using sprintf():
if ($val2 > 0) {
    $res = round( ($val1 / $val2) * 100 , 1); // 66.7
    echo sprintf('Success: %d%%', $res); // % is used for escaping the %
}

It does the same thing, but looks a bit more cleaner, in my opinion.
Answer: if($val2!=0){
  //Do it
}else{
  //Don't
}

Answer: Make sure $val2 is NOT zero before trying to divide $val1 with it. Try this:
<?php
    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);

    if( $val2 != 0 ){
        $res = ( $val1 / $val2) * 100;
        // 1 digit after the decimal point
        $res = round($res, 1); // 66.7
        echo "Success: ";
        echo $res;
        echo "%";
    }
?>

Comment: Welcome to Stack Overflow! Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context  would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply.
Answer: I'm guessing $val2 is coming out to 0. Make sure $allcontent is being initialized and filled.

Division by zero error


Poisson Processes - What is the distribution of the number of arrivals $Z$ happening in the random interval of time $[0,T]$?

Question: Let $\{N(t) : t \geq 0\}$ be a Poisson process with rate $λ$, and $Z$ represent the number of arrivals in the interval of time $[0,t]$.
Let $T$ be a random variable, exponentially distributed with parameter $µ > 0$,
independent of $N(t)$. Determine the distribution of the number of arrivals $Z$, happening in the random interval of time $[0,T]$.
Any hints?
Answer: The distribution is also Poisson. Since this process is a Compound Poisson process. It's mean is $\lambda$TE[T] and it's variance is  $\lambda$TE[$T^2$].
Here's a good reference:
http://www.columbia.edu/~ww2040/3106F14/lec1023.pdf


How to frame basement window

Question: Good morning,
I'm working on finishing my basement and need some ideas on how to frame out around the windows to facilitate either a drywall or pine return. I'm using 1 inch xps on the walls and then studs flush against that.
How do I frame to give the drywall or pine returns something to attach to? There's a metal frame that creates the window opening and I don't think I can screw or nail into that.
I can put a stud flush against the edge of the opening and attach to it, but I'm worried the return won't be very stable where it extends to the window frame because I can't think of a way to support it closer to the window.
I'd appreciate any ideas.
Jay [
Answer: Put your studs up to the edges of the window frame. Then attach your pine trim with finish nails into the studs and some dabs of adhesive caulk on the metal window frame.
Caulk the perimeter of the trim to the window.  That should make everything stable enough for normal use.
I prefer to use pvc trim in areas where condensation could be an issue. That is up to you.

How to frame basement window


Emacs org mode is exporting a blank pdf on OSX (possibly due to missing fonts)

Question: I have the org-mode installed and I am trying to export the .org file to pdf. I have the Basic Tex installed and have set the PATH env variable correctly.

When I give this command C-c C-e p, I get the message "Exporting to pdf done", however, the generated pdf is blank.
So it seems, there is something going wrong when I am trying from emacs. There is also a missfont.log file.
Googling for answers is not getting me anywhere. Please help as I am stuck on this problem for quite a while. I initially gave on it, but using org mode for generating pdfs is so productive that I simply cannot live without it. I have this in my office RHEL box working fine. Only at home on my Mac, it is giving me issues
Comment: Are those fonts present in your Basic Tex installation?  If so, then the issue is probably the $PATH even though you are certain it's not.  If the fonts are not present, then install them.
Comment: If storage space is not an issue, perhaps consider installing TeXLive:  https://tug.org/mactex/  Alternatively, a little Googling revealed methods of installing your missing fonts -- e.g., using curl.
Comment: Emacs on OSX doesn't automatically pick-up the regular $PATH that would be seen in the Terminal.app.  On Snow Leopard 10.6.8, I use this line in my `.emacs` file -- just adjust the path accordingly to wherever you have installed your `*.tex` stuff:  `(setenv "PATH" (concat (getenv "PATH") ":/usr/texbin"))`  If you want to see what Emacs thinks your $PATH is before you add this line of code, you can type `M-x eval-expression RET (getenv "PATH") RET`; and, you can do the same thing again after you add the line of code and restart Emacs to make sure it is correct.
Comment: I have passed all that stage and got over these hurdles, actually i think the problem is missingfonts. I can see the missingfont.log containing mktextfm ecrm1095
mktextfm ectt1000
mktextfm ecrm1728
Answer: Installing fonts did the trick, I needed to install ec and wasy2


Modify Sequence with snp position and output in same file

Question: i have two files one with positions information and another is sequence information. Now i need to read the positions and take the snps at the positions and replace that position base with the snp information in the sequence and write it in the snp information file.. for example
Snp file contains
10 A C A/C

Sequence file contains
ATCGAACTCTACATTAC

Here 10th element is T so i will replace T with [A/C] so the final output should be
10 A C A/C ATCGAACTC[A/C]ACATTAC

Example files are
Snp file
SNP Ref Alt
10  A   C
19  G   C
30  C   T
42  A   G

Sequence :

sequence1
  CTAGAATCAAAGCAAGAATACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT

Final output :
SNP Ref Alt Output
10  A   C   CTAGAATCA[A/C]AGCAAGAANACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
19  G   C   CTAGAATCANAGCAAGAA[C/G]ACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
30  C   T   CTAGAATCAAAGCAAGAATACACTCTTTT[T/C]TTTGGAAAAGAATATCTCATGTTTGCTCTT
42  A   G   CTAGAATCAAAGCAAGAATACACTCTTTTTTTTGGAAAAGA[A/G]TATCTCATGTTTGCTCTT

While replacing the snps here from Ref and Alt column, we need to consider the order of {A,T,C,G} like the [Ref/Alt] always the first base should be either A or T or C and followed by that order.
Another thing is if we take the snp position, and if there are any snps in 10 bases difference, we need to replace that snp position with "N".  In the above example in first two positions as the difference is 9 we are replacing the other element with 'N'.
I have written code where it prints the positions in order and also replaces the sequence with that snp position but unable to read nearby positions and replace with N.
My approach might be completely wrong as i am beginner in coding.. I think by using hashes, we might achieve this easily but i am not so familiar with hashes..help with some suggestions please.. i dont have to stick with only perl,
my $input_file = $ARGV[0];
my $snp_file = $ARGV[1];
my $output_file = $ARGV[2];

%sequence_hash = ();

open SNP, $snp_file || die $!;
$indel_count = 0;
$snp_count = 0;
$total_count = 0;

#### hashes and array
@id_array = ();

while ($line = <SNP>) {

    next if $line =~ /^No/;
    $line =~ s/\r|\n//g;

   # if ($line =~ /\tINDEL/) {

    #    $indel_count++;
     #   $snp_type = "INDEL";

    #} else {
     #   $snp_count++;
      #  $snp_type = "SNP";
    #}

    @parts = split(/\t/,$line);

    $id = $parts[0];
    $pos = $parts[1];
    #$ref_base = $parts[3];
    @temp_ref = split(",",$parts[2]);
    $ref_base = $temp_ref[0];
    @alt = split(",",$parts[3]);
    $alt_base = $alt[0];
    $snpformat = '';

    if ($ref_base eq "A" || $alt_base eq "A")
    {

        if ($ref_base eq "A"){
            $snpformat = "[".join("/",$ref_base,$alt_base)."]";}
            #$snpformat = $ref_base/$alt_base;}
            #print "refbase is A $ref_base \t $alt_base \t $snpformat \n"; }

            else
            {$snpformat = "[".join("/",$alt_base,$ref_base)."]";}
            #print "Altbase is A $ref_base \t $alt_base \t $snpformat \n";}
    }

    elsif ($ref_base eq "T" || $alt_base eq "T")
    {

        if ($ref_base eq "T"){
            $snpformat = "[".join("/",$ref_base,$alt_base)."]";}
            #$snpformat = $ref_base/$alt_base;}
            #print "refbase is A $ref_base \t $alt_base \t $snpformat \n"; }

            else
            {$snpformat = "[".join("/",$alt_base,$ref_base)."]";}
            #print "Altbase is A $ref_base \t $alt_base \t $snpformat \n";}
    }

    elsif ($ref_base eq "C" || $alt_base eq "C")
    {

        if ($ref_base eq "C"){
            $snpformat = "[".join("/",$ref_base,$alt_base)."]";}
            #$snpformat = $ref_base/$alt_base;}
            #print "refbase is A $ref_base \t $alt_base \t $snpformat \n"; }

            else
            {$snpformat = "[".join("/",$alt_base,$ref_base)."]";}
            #print "Altbase is A $ref_base \t $alt_base \t $snpformat \n";}
    }

    else
    {$snpformat = "-/-" ;}
    print " $id \t $pos \t $ref_base \t $alt_base \t $snpformat \n  ";
}

open SEQ, $input_file ||die $!;

$header = '';
$sequence = '';
$num_sequences = 0;

while ($line = <SEQ>) {

    $line =~ s/\r|\n//g;
    next if $line =~ //;

    if ($line =~ /^>(.+)/) {
        if ($header eq '') {

            $header = $1;
            $sequence = '';
            next;
        } else {

            $sequence_len = length($sequence);

            $sequence_hash{$header} = $sequence;
            push (@headers,$header);
            #print $header."\t".$sequence_len."\n";
            #print $sequence."\n";
            $num_sequences++;

            $header = $1;
            $sequence = '';

        }

    } else {

        $sequence .= $line;

    }

}
$sequence_len = length($sequence);
$sequence_hash{$header} = $sequence;
push (@headers,$header);
#print $header."\t".$sequence_len."\n";

$num_sequences++;

close (SEQ);

$pos = '4';
substr($sequence,$pos,1) = "[A/G]";
print $sequence."\n";
print "$pos \n";

Comment: Ok. While I like your detailed explanation of the problem, it's always a good idea to add these things also in the snippets you post, so people know you are using them. There are undeclared variables in your code. We don't know if you declared them in your program in a part that you did not show. It's best if you post a [short, self-contained, correct example](http://sscce.org/). That way, it is easier to understand your problem and to help you.
Comment: Please add `use strict` and `use warnings` to your program to help you track down mistakes. Also, please go through your old questions and accept answers that you found helpful. See the [faq#hotoask] for more info on that.
Comment: I did add the strict and warnings but while copying it got cut... i only post it for suggestions but not to get complete solution..
Comment: I think it's safe to say this is too big a job for sed. (Not that you *can't* do it with sed, you just *shouldn't*.)
Answer: This awk script can probably help you get desired result.
awk '
BEGIN {
print "SNP\tRef\tAlt\tOutput"
}
NR==FNR {
    a[++i]=$0
    next
}
FNR>1 {
    x=substr(a[i],1,($1-1))
    z=substr(a[i],($1+1))
    if ($2=="A") {
        y="["$2"/"$3"]"
    }
    else if ($2=="T" && $3=="A") {
        y="["$3"/"$2"]"
    }
    else if ($2=="C" && ($2=="A" || $2=="T")) {
        y="["$3"/"$2"]"
    }
    else if ($2=="G" && ($2=="A" || $2=="T" || $2=="C")) {
        y="["$3"/"$2"]"
    }
    else
        y="["$3"/"$2"]"
    print $1"\t"$2"\t"$3"\t"x""y""z
}' sequence snp

Test:
[jaypal:~/temp] cat sequence
CTAGAATCAAAGCAAGAATACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT

[jaypal:~/temp] cat snp
SNP Ref Alt
10  A   C
19  G   C
30  C   T
42  A   G

[jaypal:~/temp] awk '
BEGIN {
print "SNP\tRef\tAlt\tOutput"
}
NR==FNR {
    a[++i]=$0
    next
}
FNR>1 {
    x=substr(a[i],1,($1-1))
    z=substr(a[i],($1+1))
    if ($2=="A") {
        y="["$2"/"$3"]"
    }
    else if ($2=="T" && $3=="A") {
        y="["$3"/"$2"]"
    }
    else if ($2=="C" && ($2=="A" || $2=="T")) {
        y="["$3"/"$2"]"
    }
    else if ($2=="G" && ($2=="A" || $2=="T" || $2=="C")) {
        y="["$3"/"$2"]"
    }
    else
        y="["$3"/"$2"]"
        print $1"\t"$2"\t"$3"\t"x""y""z
}' sequence snp
SNP Ref Alt Output
10  A   C   CTAGAATCA[A/C]AGCAAGAATACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
19  G   C   CTAGAATCAAAGCAAGAA[C/G]ACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
30  C   T   CTAGAATCAAAGCAAGAATACACTCTTTT[T/C]TTTGGAAAAGAATATCTCATGTTTGCTCTT
42  A   G   CTAGAATCAAAGCAAGAATACACTCTTTTTTTTGGAAAAGA[A/G]TATCTCATGTTTGCTCTT

Answer: I am not a perl expert, but I think this will do it:
#!/usr/bin/perl

open(SEQ, "seq");
my $seq = <SEQ>;
$seq =~ s/.* //;

print "SNP Ref Alt Output\n";
open(SNP, "snp");
<SNP>;# header line
while(<SNP>)
{
    my($line) = $_;
    chomp($line);
    my ($loc, $ref, $alt) = split(/ +/, $line);
    my $outString = $seq;
    substr($outString, $loc-1, 1, "[$ref/$alt]");
    print $loc."  ".$ref."   ".$alt."   ".$outString."\n";
}

Answer: A=1;T=2;C=3;G=4
echo "SNP Ref Alt Output"
while read l1 l2 l3; do
    lp=$(($l1 - 1))
    eval ol2=\$$l2 && eval ol3=\$$l3
    if [[ $ol2 > $ol3 ]]; then
        ol2=$l3 && ol3=$l2;
    else
        ol2=$l2 && ol3=$l3;
    fi
    sed "s@[^ ]* \(.\{$lp\}\).\(.*\)@$l1  $l2   $l3   \1[$ol2\/$ol3]\2@" sequence
done < snp

Output
SNP Ref Alt Output
10  A   C   CTAGAATCA[A/C]AGCAAGAATACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
19  G   C   CTAGAATCAAAGCAAGAA[C/G]ACACTCTTTTTTTTGGAAAAGAATATCTCATGTTTGCTCTT
30  C   T   CTAGAATCAAAGCAAGAATACACTCTTTT[T/C]TTTGGAAAAGAATATCTCATGTTTGCTCTT
42  A   G   CTAGAATCAAAGCAAGAATACACTCTTTTTTTTGGAAAAGA[A/G]TATCTCATGTTTGCTCTT

Comment: OP has a constraint that substitution needs to follow certain order. `While replacing the snps here from Ref and Alt column, we need to consider the order of {A,T,C,G} like the [Ref/Alt] always the first base should be either A or T or C and followed by that order.`


How did -1/√2 and 1/√2 turn into 0 and 1? and how to find the ker f?

Question: I am trying to find the matrix representation Aββ of f with respect to β = {b1,b2}. The values of b1 and b2 are given to me.
b1 =  \begin{bmatrix}1/√2\\1/√2\end{bmatrix}
and b2 = \begin{bmatrix}-1/√2\\1/√2\end{bmatrix}
and here's what I got:
I have f(b1) =
\begin{bmatrix}0\\0\end{bmatrix}
and f(b2) =
\begin{bmatrix}-1/√2\\1/√2\end{bmatrix}
This means that my Aββ should be
\begin{bmatrix}0&-1/√2\\0&1/√2\end{bmatrix}
right?
but the solution says that Aββ should be
\begin{bmatrix}0&0\\0&1\end{bmatrix}
Why is that? How did -1/√2 and 1/√2 turn into 0 and 1? is it because of rref? and how do I find the kernel of f?
Comment: Is your $f(b_2)$ expressed in the $\beta$ basis?
Comment: So, that's why. $f(b_1)=0b_1+0b_2$ while $f(b_2)=0b_1+1b_2$, right? These coefficients go in the matrix columns.
Comment: Your response to me and your response to Berci seem contradictory.
Comment: Btw, what you obtained first is $A_{\beta,\gamma}$ with $\gamma$ the standard basis.
Comment: @Arthur, oh, I understand what you mean now. Sorry, actually it wasn't expressed in the  basis earlier.
Comment: Your matrix is similar to the given matrix, so the given matrix is the matrix of the same function but in a different basis.
Comment: @Arthur Yes, it is.
Comment: Let me guess: $b_2=\pmatrix{-1/\sqrt2\\ 1/\sqrt2}$?
Comment: @Berci yes, that's right.
Comment: Oh yes @Berci, that makes sense. Thanks.
Comment: @Berci and others, is the kernel of f the zero vector? and is the image of f: α(1     -1)^T? if the question asks find the kernel of f, should I find the kernel of , with  the standard basis or  with the  basis? Thanks.
Comment: To answer this question, you need to know what $b_1$ and $b_2$ are. From the intended answer, it is possible to deduce that $b_2$ equals $\begin{pmatrix}-1/\sqrt{2}\\ 1/\sqrt{2}\end{pmatrix}$, but that should really be part of the question. The OP knows them ('The values of b1 and b2 are given to me'), but is not giving them in this question.
Comment: @Magdiragdag   b1 = Transpose of (1/√2, 1/√2)
Comment: That information should be added to the question.
Comment: @Magdiragdag I have made the necessary edit now :)
Answer: The $i$th column of the matrix $A_{\beta,\gamma}$ of a linear map $A:V\to W$ w.r.t bases $\beta=(b_1,b_2,\dots)$ in $V$ and $\gamma\in W$ consists of the coefficients of $A(b_i)$ when written as a linear combination of elements of $\gamma$, i.e. the $\gamma$-coordinates of $A(b_i)$.
In your case what you obtained is $A_{\beta,\gamma}$ with $\gamma$=standard basis instead of $A_{\beta,\beta}$ which was asked.
The kernel of $A$ consists of all vectors $v\in V$ for which $A(v)=0$.
In this example $\ker A$ is generated by $b_1$.
Comment: Yes, exactly. This coincides with the subspace generated by $b_1$.
Comment: Yes the image is correct. And the assumption you wrote is exactly the property of being *linear*. If a map is not linear, it makes no (or much less) sense to write up 'its matrix'. The theorem is that: after having fixed any bases in the domain and codomain, every linear map can be written of the form $x\mapsto Ax$ for a unique *matrix* $A$ (where we coordinatize the vectors w.r.t the given bases).
Comment: Btw, this particular $f$, geometrically, is an orthogonal projection (to its image, which is a line in the plane), and $b_1,b_2$ is an orthonormal eigenbasis.
Comment: I have edited the question to include the value of b1 and b2 given. Could you please elaborate on how in this case Ker A is generated by b1?
Comment: Do you know the rank-nullity theorem? Probably that's the fastest approach. Nevertheless, $b_1$ is clearly in the kernel as $f(b_1)=0$. Now, $f(\alpha_1b_1+\alpha_2b_2)=\alpha_2b_2$ it's zero iff $\alpha_2=0$...
Comment: can we just say that the kernel is  *$$\begin{pmatrix}1 \\1 \\\end{pmatrix}$$
Comment: I'd be interested to know how we could find the image of f in this case. How to go about it? Thanks.
Comment: Since $b_1,b_2$ is a basis, any vector can be written as $\alpha b_1+\alpha b_2$, right? Some comments ago I just summarized what $f$ does to $\alpha b_1+\alpha b_2$. Can you find the image ( = range) of $f$ based on that information?
Comment: You wrote (11+22)=22 . I suppose that would mean that the image is  *
$$
    \begin{pmatrix}
    -1 \\
    1  \\
    \end{pmatrix}
$$

but I don't understand how you got (11+22)=22.
Comment: Omg... :) How did I get? You calculated $f(b_1)=0$ and $f(b_2)=b_2$. And we know $f$ is linear. So....
Comment: Ah, I see your point. But doesn't it rely on the assumption that f(1b1 + 2b2) = 1f(b1) + 2f(b2)? How do we assume that? And is the image value I wrote in my above comment correct? Thanks :)


Test for convergence of the series $\sum_{n=2}^\infty\frac{1}{(\ln n)^{\ln n}}$

Question: Could I have a hint for testing the convergence of the following series please?
$$\sum_{n=2}^\infty\frac{1}{(\ln n)^{\ln n}}$$
Edit
The integral test does not work because $\int_1^n\frac{1}{(\ln x)^{\ln x}}dx$ has not an elementary primitive.
Thank You.
Comment: did you try the integral test?
Comment: http://en.wikipedia.org/wiki/Sophomore's_dream
Comment: @Alex I'm trying with the integral test, but this integral is really tough for me... I'll check your link now! Thank you for your help man; I really appreciate it.
Comment: @Alex Am I on the right way? Can this integral be reduced to a simple one?
Comment: Related: https://math.stackexchange.com/questions/408824/determine-if-sum-frac1-lnn-lnn-converges
Answer: Alternate hint:
$$
(\ln n)^{\ln n} = n^{\ln \ln n}.
$$
Comment: @KitKat, take $\ln$ of $(\ln n)^{\ln n}$ to get $(\ln n)\ln\ln n$, rewrite this as $\ln(n^{\ln\ln n})$, then exponentiate this to get $n^{\ln \ln n}$.
Comment: I have never seen this before, how do you get to that equation?
Comment: Thank you. I did it with the comparison test.
Comment: You're welcome :)
Comment: @AntonioVargas Nice, thanks.
Answer: Hint:
Consider
$$
2^k \frac{1}{(k\ln e)^{k\ln 2}}>\sum_{2^k\le n< 2^{k+1}} \frac{1}{(\ln n)^{\ln n}}> 2^k\frac{1}{((k+1)\ln e)^{(k+1)\ln 2}},
$$


Changing ylim (axis limits) drops data falling outside range. How can this be prevented?

Question: df <- data.frame(age=c(10,10,20,20,25,25,25),veg=c(0,1,0,1,1,0,1))
g=ggplot(data=df,aes(x=age,y=veg))
g=g+stat_summary(fun.y=mean,geom="point")

Points reflect mean of veg at each age, which is what I expected and want to preserve after changing axis limits with the command below.
g=g+ylim(0.2,1)

Changing axis limits with the above command unfortunately causes veg==0 subset to be dropped from the data, yielding

"Warning message: Removed 4 rows containing missing values (stat_summary)"

This is bad because now the data plot (stat_summary mean) omits the veg==0 points. How can this be prevented? I simply want to avoid showing the empty part of the plot- the ordinate from 0 to .2, but not drop the associated data from the stat_summary calculation.
Answer: you can do that by specifying the coord system:
df <- data.frame(age=c(10,10,20,20,25,25,25),veg=c(0,1,0,1,1,0,1))
g=ggplot(data=df,aes(x=age,y=veg))
g=g+stat_summary(fun.y=mean,geom="point")
g+coord_cartesian(ylim=c(0.2,1)) #do not use +ylim() here

Comment: Does someone know why you have to specify coordinate system in order not to drop values? Why not to have this as a default setting? The example here is probably not the best one, but if you have large error bars for a couple of values, and want to limit the range of y-axis to a show general pattern, this solution works perfectly. If I use ylim() or scale_y_continuous() the error bars going over the range are not drawn at all.
Comment: This gets everything presented on the same scale, which is good, and avoids dropping the out-of-range values, which is good, but now the y-axis labels only show the range that actually contain values, which I find undesirable.  Not sure how to make the axis reflect the full range of the plot.


FormTextField is hidden behind keyboard despite SingleChildScrollView and no scaffold on page

Question: I have seen similar questions asked but their situation was diiferent.
I have a Form, with several TextFormFields. The page scrolls just fine but with keyboard up, it won't show the lower fields. Other solutions here suggested adding a new tag to style.css. I have tried that. Did not work. Some suggested adding "resizeToAvoidBottomInset: true," to Scaffold, did that although this page does not have any Scaffold.
Widget build(BuildContext context) {
    return Scrollbar(
      isAlwaysShown: true,
      controller: _scrollController,
      child: SingleChildScrollView(
        controller: _scrollController,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                _buildSummary(),
                _buildDescription(),
                _buildHourRate(),
                _buildBudget(),
                _buildBudget(),
                ButtonCreate(
                  color: Color(0xFF18D191),
                  textForButton: "SUBMIT",
                  onPressShit: () {
                    if (!_formKey.currentState.validate()) {
                      return;
                    } else {
                      _formKey.currentState.save();

                      print(_summary);
                      print(_description);
                      print(_hourRate);
                      print(_totalBudget);

                      //Send to API
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

The fields are built like this;
Widget _buildSummary() {
    return TextFormField(
      decoration: InputDecoration(
          labelText: 'Summary',
          labelStyle: TextStyle(color: Colors.purpleAccent.shade400),
          filled: true,
          fillColor: formFieldbackground.withOpacity(0.3)),
      maxLength: 45,
      validator: (String value) {
        if (value.isEmpty) {
          return 'Summary is required';
        }

        return null;
      },
      onSaved: (String value) {
        _summary = value;
      },
    );
  }

This form is a ModalBottomSheet.
See screenshots
Comment: Try remove scrollbar and controller from the code only specify SingleChildScrollView@Firaun
Comment: @Assassin Tried that too. Didn't work :(
Answer: I tried everything you guys suggested but didn't work. However I learned that the problem isn't on form but the place (container) where form is being called.
So this form isn't actually a full screen but a bottomsheet. So it needs to have some height to pull out as tray. So once where I reduced the height of the container where this form is called then it started to work!!
It freaking doesn't make sense but somehow it works.
This is where the form is called;
Widget build(BuildContext context) {
return Center(
child: Container(
height: MediaQuery.of(context).size.height / 1.8, //previous height was 600;


Change form radio button options after each answer

Question: There are forms where you have multiple choice answers where the question and the answer options changes after each answer.
Example:
A question with four different radio buttons (styled like buttons) as different options for answers and when you press one of the buttons the question changes and the text on the answers change so you get four new options for answers.
I cant find anything about this, how do you make one of these forms?
Comment: Sorry, but your question is too broad. See [ask]. This is just a matter of creating event listeners and taking action as appropriate. It has nothing to do with form types, though you might call them "data-driven" or "reactive".
Comment: @isherwood The question is how to make the form questions change after a choice is picked.
Comment: I didn't say unclear. I said broad. Asking how to build a large portion of a React app isn't appropriate here. Did you read that page? Asking for off-site resources is also off topic.
Comment: @random1234, I think you want to clear the selected radio and , update the questions with options ?
Comment: Can you provide an example of something you've seen?
Comment: I think you need a multiple step form. If you want to do it just on the FE you can for instance add multiple fieldset, each with a question and answers. Then with css you add display: none to all of the fieldsets. With JS you create `activeStep` variable, which will correspond to the visible question + answers (fieldset). When the user enters an answer you can update the variable and show / hide the fieldsets so only the currently active is visible. If you google "multistep form" i think you will find some good information, for instance https://www.w3schools.com/howto/howto_js_form_steps.asp
Answer: You will have to do something called as conditional rendering. You can check more about it on google, there are enough articles and tutorials based on conditional rendering a form.


Process pool in Bash

Question: I am trying to get a for loop that will only execute a threaded volatility yara scan module based off a list of rules. One scan per rule per core. Basically it should take the current number of vol.py processes running and check against the core count and maximize the processes running.
However, when I run this it will spawn a volatility process for every rule and not just the max of 4 (based off my core count). Any help with the syntax here would be great.
Currently I have this:
count=$(ps aux | grep vol.py | wc -l)
cores=$(cat /proc/cpuinfo | grep processor | wc -l)
for x in $(cat $rules_path/rules.txt)
do
  if [ $count -lt $cores ]; then # we are under the limit
     echo $x
     vol.py -f /home/cuckoo/.cuckoo/storage/analyses/12/memory.dmp --profile=Win7SP1x64 yarascan --yara-file=$rules_path/allrules/$x --output=text --output-file=$out_dir/$x.log &>/home/$name/Desktop/error.txt &
  else
     wait
  fi
done

Comment: I think you want `count` to be a current indication of the number of `vol.py` processes. But you only measure this once at the start. You'll want to do it again inside the loop.
Comment: Ah, okay. Do I place the variable inside the for statement or the if statement?
Answer: You can do this easily with sem from GNU parallel:
for x in $(cat "$rules_path/rules.txt")
do
  sem -j +0 vol.py -f /home/cuckoo/.cuckoo/storage/analyses/12/memory.dmp \
      --profile=Win7SP1x64 yarascan --yara-file="$rules_path/allrules/$x" \
      --output=text --output-file="$out_dir/$x.log" \
         &> "/home/$name/Desktop/error.txt"
done

You don't have to count cores or manage processes. sem handles everything, and runs one process per core.
Answer: Your approach could work, with something like:
cores=$(cat /proc/cpuinfo | grep processor | wc -l)
count=$(ps aux | grep vol.py | wc -l)
for x in $(cat $rules_path/rules.txt)
do
  if [ $count -lt $cores ]; then # we are under the limit
     echo $x
     vol.py -f /home/cuckoo/.cuckoo/storage/analyses/12/memory.dmp --profile=Win7SP1x64 yarascan --yara-file=$rules_path/allrules/$x --output=text --output-file=$out_dir/$x.log &>/home/$name/Desktop/error.txt &
     count=$(ps aux | grep vol.py | wc -l)
  else
     wait -n
  fi
done

All I've changed is:

recalculate count each time we add a process
wait -n -- to just wait for one job to end

However there are simpler ways to achieve this. One is with xargs --max-procs:
cat $rules_path/rules.txt | xargs --max-procs="$cores" -n1 call_volatility

... where call_volatility is a script like this:
#!/bin/bash
x=$1
vol.py -f /home/cuckoo/.cuckoo/storage/analyses/12/memory.dmp \
     --profile=Win7SP1x64 yarascan \
     --yara-file=$rules_path/allrules/$x \
     --output=text \
     --output-file=$out_dir/$x.log \
     &>/home/$name/Desktop/error.txt

There is no guarantee with either approach that the processes will be evenly distributed between your cores.
Comment: Is there a way to pipe the stdout and stderr to a file? Not too sure how to use mkfifo with this loop...
Comment: I don't understand what you're asking, specifically. Perhaps it needs to go in a separate question. There's nothing in here that would prevent you from working with fifos.
Comment: I'll work with it a bit and see what I can come up with, thanks!

Process pool in Bash


Modify 3-way switch to add circuit

Question: I am a DIYer with electrical wiring experience.  I would like to add an existing secondary light to the 3-way circuit.  The current box has two switches.  The one on the left controls the main light and is part of the 3-way circuit.  The one on the right controls a secondary light.  I would like to remove the switch for the secondary light and have it controlled with the 3-way switch.  The existing wiring is a little confusing.  I have diagrammed it below as best as I can figure it out.  (Ground wires are ignored.)

I would appreciate any advice you could provide.  Thanks!
Comment: Wow! Colors are usually a hot mess in boxes like this, but by sheer luck, all of your colors are color-coded by function, except the travelers.   I like to mark those yellow (both of them, no need to distinguish one from the other).
Comment: Hello, and welcome to Home Improvement. Good question, with good diagram/picture: thanks. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Answer: Color coding time
Cables have certain default colors of wires.  We're married to that, so usually trying to "color code wires by function" is a big mess.  But in this case, it works out to be very close. Let's get there.
I want you to mark both traveler wires with yellow tape (or another color, just not black, red or white).  No need to distinguish  one from the other. We wont be doing anything with them; I just don't want to confuse them with the wires we will be working with.
Now, remove the switch that is going away.  When you do, you will free up a "pigtail wire".  Remove it from the black bundle (always-hot).   Tape or paint it red.
With the travelers marked, there is one red wire on the 3-way switch.  Remove it and replace it with the red pigtail.
I believe at this point you have three red wires, all loose.  These are switched-hot.   Join them.
And we're done.
Comment: Thanks so much!  This makes sense. I will try it out in the next couple days.

Modify 3-way switch to add circuit