File permission to PHP uploaded image

Question: In my PHP site I have a script to upload images, see the script below
<code>$uploaddir = $root_path."images/uploaded_images/category/";
            $small_file_name = trim($_FILES['cat_image1']['name']);
            $small_file_len = strlen($small_file_name);
            $small_file_ext = strtolower(substr($small_file_name,-4)); // select last 4 characters
            $small_uploadfile = $uploaddir. $_FILES['cat_image1']['name'];
            if($small_file_len>4 and ($small_file_ext==".gif" or $small_file_ext==".jpg" or $small_file_ext=="jpeg")){
                if ($small_file_ext=="jpeg")
                    $uniqname = uniqid(rand()).".".$small_file_ext;
                else
                    $uniqname = uniqid(rand()).$small_file_ext;
                $thumb_filename1 = "thumb_".$uniqname;  //  store uniqname into database
                $uploadfile = $uploaddir.$uniqname; //uncomment for local testing
                if (move_uploaded_file($_FILES['cat_image1']['tmp_name'], $uploadfile)) {
                    chmod($uploadfile,0777);
                    list($width, $height, $type, $attr) = getimagesize($uploadfile);
                    $max_width = 276;
                    $max_height = 162;
                    $a = new Thumbnail($uploadfile,$max_width,$max_height,$uploaddir.$thumb_filename1,100,'');
                    $a->create();

                }else{
                        $flag=1;
                        $frm_server_side_error= $frm_server_side_error."Error in uploading image,";
                }
            }
            else{
                $flag=2;
                $frm_server_side_error= $frm_server_side_error."Image not in gif or jpg format,";

            }
</code>
After uploading in to the server its can't be see (I am displaying the thumb image). So I checked the file permission of that image through the FTP and give read permission. Thus image displays. But I give the read and write permission to the category folder and it's parent folders. How can view the image after uploading (default read permission to the uploading files ie thumb image.)
I noticed that the actual image have read permission but the thumb image doesn't have the read permission. I need to display only the thumb image.
Comment: What do the parameters represent of `new Thumbnail();`? And you have already used `chmod($uploadfile,0777);`. Perhaps you can do this too on the new file? (`$uploaddir.$thumb_filename1`)
Comment: What OS is your server running?
Answer: You have used a class Thumbnail to create a thumbnail image. But I guess you have missed to change the file permission in the new thumbnail image. Please check the code in the create() function of the class Thumbnail
Answer: Your code formatted poorly here (half is in code format, half not), but it appears you have a comment before the snippet that would copy the file from the temp location to the final location - if that's the case, the file won't exist, and thus won't be viewable.
But I could be wrong - I'm happy to take a second look if you fix the formatting.

File permission to PHP uploaded image


Perl - Pattern for verbosity levels?

Question: I have a basic function for printing messages of verbosity levels in a perl package:
<code># 0 = no output, 1 = debug output
our $verbosity = 0;
sub msg {
    (my $verbLevel, my $format, my @addArgs) = @_;
    if ($verbLevel <= $verbosity) {
        printf($format, @addArgs);
    }
}
</code>
This is IMO an elegant solution inside the package, because to print a debug message I can simply do:
<code>msg(1, "Some debug message");
</code>
However, in practice this package is being 'used' in a long chain of packages, each of which also uses a verbosity feature.  Let's say the chain of usage is like this: entry.pl > package0.pm > package1.pm > package2.pm.  Each file must set the verbosity flag of the next in order for each to work right.
I now think this is an inelegant solution because of duplicate code and the requirement for each "parent file" to set each of it's children's verbosity level.  What I would like to happen is for each *.pm file to inherit the verbosity level and function from entry.pl.
Is there a design pattern I can follow to share a verbosity functionality across packages?  Is there a module out there that can already do this?
Answer: Perhaps look at Log::Log4Perl - either as a model to work from for your own implementation or as a potential replacement.

Perl - Pattern for verbosity levels?


What is the difference between broadcasting and flooding?

Question: In the Open Shortest Path First routing algorithm, the information about connected links is "flooded" throughout the network.
How is flooding different from broadcasting?
Answer: Broadcasting is a term that is used on a broadcast domain, which is bounded by layer-3 (routers). Broadcasts are sent to a special broadcast address, both for layer-2 and layer-3. A broadcast cannot cross a layer-3 device, and every host in a broadcast domain must be interrupted and inspect a broadcast.
Flooding is used by a switch at layer-2 to send unknown unicast frames to all other interfaces. If a frame is not destined for a host which receives it, the host will ignore it and not be interrupted. This, too, is limited to a broadcast domain.
Flooding in OSPF (layer-3) means that the routes get delivered to every OSPF router in an area. It really has nothing to do with a broadcast. OSPF doesn't use broadcasts to send routes, it uses unicast or multicast to connect with its neighbors. Each OSPF router needs to have a full understanding of all the routers and routes in its area, and it tells all its neighbors about all its local routes, and any routes it hears about from other neighbors. (OSPF routers are unrepentant gossips.)
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/133976/discussion-on-answer-by-ron-maupin-what-is-the-difference-between-broadcasting-a).
Answer: I will explain here in the context of switches (layer 2).
Flooding
When a switch receives a unicast frame (a frame with a specific MAC address intended for a particular device), it looks for the frame's destination MAC in its MAC address table. If there is no entry for the destination MAC in its table, it will simply send the frame out to everyone connected to its ports.
The frame is still a unicast frame, since it has a specific destination MAC address in its header. The switch doesn't change any header data in the frame.
All the devices that receive the frame will compare the destination MAC address in the frame with their own MAC address and drop the frame if it doesn't match.
Broadcasting
A broadcast frame is created by the host itself. A frame becomes a broadcast frame if the destination MAC address is ff:ff:ff:ff:ff:ff. Usually, the host creates this type of frames during the ARP process. When the switch receives a broadcast frame, it sends it out to everyone connected to it.

In flooding the switch sends the frame to all because it doesn't know how to reach the destination.
In broadcasting the host that created the frame itself addressed the frame to everyone.
Comment: ARP process uses flooding not broadcasting.
Comment: @S.M.: According to [Wikipedia](https://en.wikipedia.org/wiki/Address_Resolution_Protocol#Example) and [this](https://youtu.be/gYN2qN11-wE?list=PLIFyRwBY_4bRLmKfP1KnZA6rZbRHtxmXi&t=400) video by Ed Harmoush, ARP does use the MAC broadcast address `ff:ff:ff:ff:ff:ff` for the destination.
Answer: I would like to give a simple summary of these two concepts from what I learned from Siva`s answer.
ALL about the intention of the original frame.
For flooding: the destination of frame is specific! just switch has no idea of where to switch it but simply switch to everyone it connected except the source interface.[frame exactly know its destination MAC]
For broadcasting: the destination of frame is NOT specific but to anyone(SO that is broadcast!). therefore its MAC address is ff-ff-ff-ff-ff-ff ( or FF-FF-FF-FF-FF-FF, as a MAC address's case does not matter. )[frame has no idea of its destination MAC]
Answer:
There is often some confusion about a switch in regards to a Broadcast and a Switch's flooding behavior. The confusion is
understandable because the end result is the same, but it is also
important to understand the distinction.
A Broadcast frame is a frame which is addressed to everyone on the
local network. This is done using the same Ethernet header we've been
discussing, except the Destination MAC address field is populated with
a special address: ffff.ffff.ffff. The "all F's" address is specially
reserved for the purpose of broadcasting.
By definition, if the Switch ever encounters a packet with a
destination MAC of ffff.ffff.ffff, it will always flood the frame
(after learning the Source MAC, of course).
Another way of looking at it is, since the address ffff.ffff.ffff is
reserved, the switch is unable to learn a MAC Address Table mapping
for it. As such, any frame destined to this MAC address will always be
flooded.
In summary, a Broadcast is a frame addressed to everyone on the local network (ffff.ffff.ffff), and Flooding is an action a switch can
take. A broadcast frame, by definition, will always be flooded by a
switch. But a switch will never broadcast a frame (since broadcasting
is not a function of a switch).

Source: https://www.practicalnetworking.net/
https://www.practicalnetworking.net/series/packet-traveling/host-to-host-through-a-switch/#:~:text=Broadcasts-,There,-is%20often%20some
https://youtu.be/G7GyWjJtjNs
Comment: I'd just like some clarification if possible. When you say broadcasting is not a function of a switch, how is that so? A switch is a data link layer device that can broadcast frames if the MAC is addressed as such, is it not?
Answer: A host send a packet to another host through a switch or router or both.  A Broadcast can only happen at layer 3 which is the network layer.  Flooding  happen a Layer 2.   A switch will send out a flood when the mac address is not in it table.
You do have switch that do layer 2 and Layer 3 however it the port is configured for layer 3  then layer 2 is not present at that port.
We sometimes in the industry call a flood a broadcast but it can not be. It seem the some people here have fell into that scenario
Comment: A L3 ethernet port still has L2 processing; it just has no need to maintain a MAC table (the L3 ARP table holds the same data) As Ron answered years ago, flood is a L2 "I don't know where it is" process; NICs that aren't the dest will ignore those frames. Broadcasts are processed by everything in the L2 broadcast domain -- even if it's a different L3 subnet. (they can overlap, btw)
Comment: "A Broadcast can only happen at layer 3 which is the network layer." - no. There are IP broadcasts (limited and directed) as well as Ethernet broadcasts. *OSPF flooding* is also completely different from Ethernet flooding as Ron's pointed out.
Comment: @Zac67 routing protocol runs at application layer? So, source routing protocol communicates with the destination routing protocol in a different host (router) by ip address(layer3) and Mac address(layer2)?


Is there anything I need to worry about when growing the mulberry tree?

Question: I tried to get some sea berries for the yard, but my parents made me send them back due to the suckering/invasive nature. Do I need to worry about anything with the mulberry tree similar to what I had to worry about the sea berry bush?
Answer: I just got rid of a mulberry tree this year, and I'm glad I did.

The fruit is so thick and dense that it covers the ground and not much else grows there.
They grow fast. A branch growing 3ft a year is not unusual.
They grow easily from seed. You will have seedlings every where.
The juice stains cars and clothing.
When it gets hot all those berries squashed on the ground smells like a brewery.
The berries are edible but usually birds peck at them a bit, so you're left with lots of pecked berries.
They are so messy they will likely decrease the value of your yard.
Some cities might consider it a pest due to the huge mess.
Comment: sounds great for the canopy layer of my chicken yard I'm building with grass on the bottom layer along with blackberries, and things.
Comment: If chickens eat mulberries, you should be all set.
Comment: It is possible to get [all-female mulberry trees](https://www.burntridgenursery.com/Mulberry-Trees/products/20/).  These have three advantages:  No pollen to trigger allergies, no seeds in the fruit, and no seedlings.
Answer: Mulberry trees can grow roots that break up sidewalks and such. I wouldn't plant them next to a house, either.
Mulberries with dark fruits may fall on the ground, people may walk on them, and if they step on carpet in the house, it can really stain the carpet (so I've read). White-fruited mulberries are probably non-staining (but I could be wrong). It should be noted that White Mulberry is a species (Morus alba), as is Red Mulberry (Morus rubra) and Black Mulberry (Morus nigra). The color in the name doesn't refer to the fruit color.
Mulberry trees can get very large, unless you get such as dwarf trees or weeping mulberries. I'm not sure if these are safer to have by houses.
Mulberry trees can attract birds, which may eat the fruits and leave droppings all over the place. I don't know if this is a common occurrence, since I've never grown mulberries (but for some people it may be).
Anyway, they are great fruits, though, with a lot of health potential, I think.
I've read that birds may spread the seeds of mulberries. I don't know how often this happens, nor how invasive they are, however.
Comment: How far from the house/driveway do they need to be so they don't damage anything?
Comment: @blackthumb I have no idea, but based on sidewalks I've seen that were torn up by what I think were mulberry tree roots, I'd guess plenty more than 10 feet away. I don't know how much more.
Comment: No sidewalk close by, but we do have a driveway.
Answer: They're short lived (50-80 years), enormous, prone to leaf spot which they will spread all over the area they're in (at least they are here), and should never be planted in a back yard unless your yard is huge and can comfortably accomodate removing the tree when it's close to death - it will fall over one day. They're great for parks but terrible in the yard. I wonder why they're not planted in parking lots, as they grow incredibly quickly and provide wonderful, impenetrable shade. Also tons of very tasty berries. They attract a lot of wildlife, too. You do have to do some climbing if you want berries.
The leaf spot is a very real problem if you intend to do any gardening. My neighbor has one and before I had it pruned back, it was infecting everything in my backyard with this dreadful disease. It doesn't seem to hurt the tree, but spraying such a huge tree with fungicide is not realistic. http://homeguides.sfgate.com/cercospora-leaf-spot-treatments-mulberry-tree-26386.html
Why not consider something more appropriate to a yard, such as blueberries or blackberries or whatever berries you like that grow in your area?
Comment: We have a huge front yard (300-foot + driveway), and a small back yard that we maintain (our side of the creek). I've heard that common fruit trees will provide an increased value in the yard, so by that logic, a rare fruit tree should increase the value that much more. We don't get very rainy weather in MN, unless it's the snow melt, then we only get fog for a week or two.
Comment: Well, there's nothing rare about a mullberry tree, it's a trash tree, and why would "rare" be more valuable? Is the food "rare" because no one likes it (durian), or because the product is too fragile to exist in the food markets?
Comment: I love durian, but can't grow it in MN :'(,  so I will likely like them.


vSphere Enhanced Authentication Plugin for SSO

Question: I have recently configured a vCenter Server to monitor our companies virtual machines, and would like to use the Windows Sessionauthentication.
The vCenter is already joined to the AD Domain, and i can log in with my domain credentials no problem, but in order to use the Windows Session Authentication feature i need to download the "Enhanced Authentication Plugin", whenever i try to do so i get a certificate warning. so i figured i would go to the base URL of the vCenter Virtual appliance and click "Download trusted root CA certificates", when i do so i get taken to the proper URL (https://vcenter.domain.com/certs/download.zip) however no file gets downloaded, all i get is half a screen full of strange symbols.
Has anyone here ever had the same issue, and if so knows how to fix it ?
Answer: I know this iks an old topic but maybe the answer will assist someone else.  instead of clicking on the link, right click and save link as then browse to the save location you want and save it.  open the zip file and save the crt files.  (there will also be crl files) this should resolve the issue.


Why is my Commercial (High Density Only) revenue suddenly dipping?

Question: So I've been running my city for about a couple of months. In the beginning, I had a gain of $50k+ a week. Then, over the course of a few months, it plummeted to over $20k+ loss a week. I checked my "Budgets" panel and it showed that my commercial revenue went from ~$116k to ~$56k. The only thing I did was add more commercial (and a bit of industrial/offices) and changed the policies a bit to compensate for it saying "Not enough goods to sell!" and "Not enough buyers!" I tried turning off the day/night cycle because I saw that commercial buildings don't sell stuff in the night (unless After Dark DLC.) It didn't work. Please help, my money went from $5.5m to $1.6m very very fast.
I'm on PC.
Answer: I just realized I'm on hard mode on accident.


Weight lifting stunts growth?

Question: I just reached out to ask you guys' ideas on weight lifting stunt growth myth. I am 15 years old, and I am 5"7" tall. I've been working out since last month, and I use a pair of dumbbells which is a bit heavy for me. I used to do overhead presses and bench presses, but was forced to stop it. So, I minimized my workout to the basics, and now I'm only doing push ups, dips, hammer curls, and dumbbell bicep curls. However, there still are people warning me and I wanted to make sure if this won't stunt my growth.
My question is
1. Do overhead presses or bench presses stunt growth?
2. Do push up, dips, hammer curl, dumbbell bicep curls stunt growth?
3. Are there any other exercises that stunt growth?
Comment: @MuntasirAlam - A quick google search will also find articles that propagate the myth. If you find a relevant study, post that instead of asking the OP to just trust you and your sources which you keep secret.
Comment: A quick google search will answer this question. The answer is no.
Comment: @Alec, or one could read scientific papers, none of which propagate that claim. But I agree I should post some links, will do when I'm at a desktop thanks.
Answer: There's no evidence to "weightlifting affecting growth" claims. People warn you because of several myth related to exercises. Do they workout? Do they have enough experience, or are they certified or qualified when it comes to weightlifting?. Ask any informed and qualified  gym instructor, or a certified coach, and their answers would vary to what you hear from people. Most of the guys who play football at high school, start lifting at your age. They all grow big and strong. Pro-wrestlers lift early as well. So no, weightlifting is not the culprit,  doing it wrong with improper form is. Improper form affects your posture and leads to injuries. Keep it safe and do it right, you will be fine and above all, eat right and get good amount of rest.
Answer: The "growth plate" is the area of active bone growth, and is more prone to injury than the more hardened areas of bone or the bones after that growth plate has closed.  That's were any claim of stunted growth due to injury is going to come from.
To the degree that a growth plate injury could effect bone growth, sure, weight lifting could effect your growth.  So could walking down the street, playing soccer, or any other activity where the injury occurs.
So the real question to evaluate is whether weight lifting carries an inordinately high risk of causing a growth plate injury vs other physical activities that are not deemed "unsafe."
It does not.  Of course, this assumes that you follow the common sense practice of performing the exercises properly, in technique, amount of weight and spotters.  That's true in general to avoid injuries, though, not exclusive to this type of injury.

Weight lifting stunts growth?


How to create dynamic panel column content?

Question: Hello i am  new to drupal and trying to make a dynamic column content using panels,
so i had created a two columns the right side one is a menu and left side one is about to be dynamic, so when we click a link in the right side menu the content will be rendered in the left side one and we keep the right side menu visible.
Answer: By "dynamic", do you mean "only that panel pane changes and the page doesn't reload"?
If so, check https://www.drupal.org/project/jquery_ajax_load and this tutorial http://www.stevepolitodesign.com/blog/load-content-drupal-ajax-without-coding .
If you don't need that functionality, then enable the panel page that overrides /node/%node and put your fields in the left side and your menu in the right.
Comment: yes i didn't need to load it ajax just need to render the content, it seems to me working fine, but one more problem that not all types of nodes needs to be overrides, can i control what nodes to be overrided?
Comment: Each panel has got variants. In the variant, you go to selection rules and add  "Node: type Node being viewed is type "Your content type". This allows you to have different panel setups per content type.


Why can't I get a hard border when I expand the border?

Question: Why can't I get a hard border when I used modify -> border? This is maddening and I've read about 5 posts so far that do not solve the problem?
Comment: when you say hard, are you referring to the rounded corners or are the lines antialiased/not crisp?
Answer: The Modify > Border command always centers the value and always anti-aliases the selection.
If you input a 4px border, you get 2 pixels inside the document and 2 pixels outside the document. PLUS 2px of anti-aliasing inside the document and 2px of anti-aliasing outside the document. So basically you get the value you input inside the document edges, but half the value is used for anti-aliasing. That's simply how the command works.
If you fill the border selection with a solid color, you see half the value in anti-aliasing. So, in the sample 4px border, you get a 2px selection inside the document, then 2px of anti-aliasing.
Repeatedly filling the selection will eventually result in a hard-edged border by filling those 2px of anti-aliasing space.
Why does this happen? I have no idea. There's certainly no way to alter the behavior of the Border command.


Can you say 日本のたべもの instead of わしょく?

Question: In  the sentence 'わしょく は おいしい です' (Japanese food is delicious), can you instead say '日本 の たべもの は おいしい です' and it will translate the same?
Answer: It depends on what you mean.
Normally, 和食{わしょく} means Japanese traditional dishes, such as nikujaga, sukiyaki etc. A typical washoku set menu may look like this for example.
日本の[食べ物]{たべもの} would technically mean everything you can eat in Japan, and at least include dishes that are originally from other countries. For examples, ramen and curry are originally Chinese/Indian, but they are fairly localized and typical ones are definitely called 日本の食べ物 but not 和食. (Ramen is called 中華{ちゅうか}=Chinese, but Japanese ramen are not usually found in China. Similarly for Japanese curry in India, as far as I know.)
Comment: What about 日本料理?
Comment: @mudri In terms of meaning, they are practically the same, as suggestd by [Wkipedia article](https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E6%96%99%E7%90%86). In terms of usage, 日本料理 is used more often when you are talking about food culture or the Japanese food as provided in a very authentic manner. For example, 朝食はいつも和食です is ok (meaning you eat rice and miso soup for breakfast), but you cannot say 朝食は日本料理です.
Answer: destroyer2009
I am Japanese.
I read your question.
As a Japanese, I think the two expressions are a little bit different each other as @sundowner answered.
Washoku represents Japanese traditional (original?) cuisine, for example, Sushi, Tenpura, Udon and so on.
But the second expression means foods in Japan are delicious.
So, even Pasta and Sandwich are included.

Can you say 日本のたべもの instead of わしょく?


Detect browser language in Rails

Question: How do you detect the users language (in RoR) as set in the browser? I will have a select box the user can use at anytime, but I'd like to default to whatever their browser language is.
Answer: This is an old question, but I came across it as a soul in search of answers and the only available answer was a link without any context. So here's a bit more depth, based on my subsequent digging.
Accessing the Accept-Language header
Query the request object in the relevant controller:
request.env['HTTP_ACCEPT_LANGUAGE'] #returns nil or a string, e.g.:
# => "en-AU,en-US;q=0.7,en;q=0.3"

That's the easy part though. To make good use of it in Rails, you'll need to parse that string (or maybe it's nil?).
Sidebar: A primer on Accept-* headers
So, looking at the example string above, some languages have "q-values" - the relative quality factor, between 0 and 1. Higher q-values mean that language is preferred by the client. Lack of a q-value is really the highest q-value - an implicit 1.0 (as with en-AU in the above string). A slight complication though - the browser may send you languages with q-values that are, say, 0 - and I gather this means you should reject those languages if possible.
Parsing the Accept-Language header
Bearing that in mind, here's a couple of different yet similar approaches I've looked at for parsing such a string into a list of languages, ordered by their q-values. With straightforward Ruby:
# to_s to deal with possible nil value, since nil.to_s => ""
langs = request.env['HTTP_ACCEPT_LANGUAGE'].to_s.split(",").map do |lang|
  l, q = lang.split(";q=")
  [l, (q || '1').to_f]
end
# => [["en-AU", 1.0], ["en-US", 0.7], ["en", 0.3]]

Or if you're proficient at regular expressions, you can achieve the same as above, and probably improve upon my butchered regex at the same time:
rx = /([A-Za-z]{2}(?:-[A-Za-z]{2})?)(?:;q=(1|0?\.[0-9]{1,3}))?/
langs = request.env['HTTP_ACCEPT_LANGUAGE'].to_s.scan(rx).map do |lang, q|
  [lang, (q || '1').to_f]
end

Either way, you can follow up as needed with something like:
# return array of just languages, ordered by q-value
langs.sort_by(&:last).map(&:first).reverse
# => ["en-AU", "en-US", "en"]

I started out my parsing by looking at this gist, but ended up modifying it fairly significantly. The regex especially was throwing away perfectly good secondary locales, e.g. en-AU became en, zh-TW became zh. I've attempted to rectify this with my modifications to that regex.
Comment: Not very readable, I would favor using and adapt the example from the Rails doc
Comment: @StéphaneBruckert Can you be more specific about how I could improve this answer? (P.S. I just looked and yes - the Rails docs section on browser language has really improved a lot since this was first written!)
Comment: Don't worry, it seems correct, just that the code does not look as simple as in the doc. Still a good answer!
Comment: That's fair. The added complexity comes from keeping and sorting all the browser supplied locales, including secondary locale information. Some applications will need that extra info, some won't.
Answer: Here's the solution:

2.6 Setting the Locale from the Client Supplied Information
In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites — see the box about sessions, cookies and RESTful architecture above...
One source of client supplied information would be an Accept-Language HTTP header. People may set this in their browser or other clients (such as curl)...
Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as GeoIP Lite Country...
You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well...
Answer: This is a really old question, but I like to mention that Rails guide has a description of how to detect user browser language.
Below code is based on the solution from Ruby on Rails guide with improvements:

checks are there HTTP_ACCEPT_LANGUAGE - sometimes that header is missing for bots, and you will get errors in your error reporting tool
checks are language supported by your application

code:
  def set_locale_based_on_browser
    locale = extract_locale_from_accept_language_header

    I18n.locale =
      if locale_valid?(locale)
        locale
      else
        I18n.default_locale
      end
  end

  private

  def locale_valid?(locale)
    I18n.available_locales.map(&:to_s).include?(locale)
  end

  def extract_locale_from_accept_language_header
    accept_language = request.env['HTTP_ACCEPT_LANGUAGE']
    return unless accept_language

    accept_language.scan(/^[a-z]{2}/).first
  end
end

More information about locale detection can be found in Ruby on Rails guide:
https://guides.rubyonrails.org/i18n.html#choosing-an-implied-locale
Comment: Nice, thank you. A minor improvement in my opinion: use `I18n.default_locale` instead of `:en`
Comment: @Rorrim Thanks! I updated code. It's good idea to use `I18n.default_locale` instead of hardcoded language.
Answer: Last night I did this tiny gem: accept_language
It can be integrated in a Rails app like that:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :best_locale_from_request!

  def best_locale_from_request!
    I18n.locale = best_locale_from_request
  end

  def best_locale_from_request
    return I18n.default_locale unless request.headers.key?("HTTP_ACCEPT_LANGUAGE")

    string = request.headers.fetch("HTTP_ACCEPT_LANGUAGE")
    locale = AcceptLanguage.parse(string).match(*I18n.available_locales)

    # If the server cannot serve any matching language,
    # it can theoretically send back a 406 (Not Acceptable) error code.
    # But, for a better user experience, this is rarely done and more
    # common way is to ignore the Accept-Language header in this case.
    return I18n.default_locale if locale.nil?

    locale
  end
end

I hope it can help.
Answer: Here is a well tested Ruby gem which does exactly what you want: https://github.com/ioquatix/http-accept
languages = HTTP::Accept::Language.parse("da, en-gb;q=0.8, en;q=0.7")

expect(languages[0].locale).to be == "da"
expect(languages[1].locale).to be == "en-gb"
expect(languages[2].locale).to be == "en"

It has 100% test coverage on a wide range of inputs. It returns the languages in the order specified by the relevant RFCs.
In addition, if you are trying to match user language to content which is available in a specific set of locales, you can do the following:
available_localizations = HTTP::Accept::Languages::Locales.new(["en-nz", "en-us"])

# Given the languages that the user wants, and the localizations available, compute the set of desired localizations.
desired_localizations = available_localizations & languages

The desired_localizations in the example above is a subset of available_localizations, according to user preference, available localisations, and RFC recommendations.

Detect browser language in Rails


Need to add someone to Bank of America savings account

Question: I want to add my partner to my BoA savings account. How do I go about doing this? Do I need to open a new account or what?
Comment: This is a customer service question for your bank, not a personal financ question.
Answer: Short answer - It depends on the bank.
There are 3 primary ways you can "add" someone to an account.

Add someone as an "authorized user."   This person can use the account and get money in or out of the account but doesn't "own" the account.
Add someone as "Joint Tenancy with Rights of Survivorship".   This is what we typically think of as a joint account that a married couple would have.   Both people fully own the account and if one dies, the other owns the entire account.
Add someone as a "Tenant in common".   If two people own an account this way, then each owns 50% of the account.

There should not be any account number changes required to add an authorized user.
If you want a Joint Tenancy with Rights of Survivorship, aka typical joint account - It depends on the bank on whether they can add an owner or have to create a new account.  I've seen both ways.
I believe for a Tenant in Common account you will need a new account.


Program to automatically screenshot or notify if certain numbers, $0.00 is shown on the screen?

Question: I'm testing a website to see if a price is $0.00 and set up an automatic clicker to click through the different options. It will take hours to go through though. Is there a program that reads the displayed number and tracks if and when the numbers are $0.00 or something like that?
Answer: For something this specific my first thought is to write a web scraper yourself. If you have any coding knowledge (and even if you don't), drafting something up in Python would probably be the most time-effective solution compared to searching for an existing tool that could do this.
Basically you'd just need it to make an HTTP request to the site, parse the HTML response for the value in question, and somehow grab a screenshot of the page (or maybe notify you/collect other data, whatever you see fit). This article is a great resource if you're interested.


How does many possible futures not mean many possible pasts?

Question: The following link implies that quantum mechanics only violates the "one future" aspect of information conservation:
https://www.physicsforums.com/threads/is-information-always-conserved-in-quantum-mechanics.458985/

How is it possible that we can know that there can only be one past even though any state of any system isn't known from the previous states?
Comment: @march Trees aren't time symmetric. Given a known state for a quantum system, the same laws that you use to predict its future as a superposition of outcomes will lead to you to say the same thing about its past. The OP's question is not stupid.
Comment: @Rococo. No question! I agree. I retract my snark. I'll blame it on the monumental pile of grading I have.
Comment: How does many possible branches not mean many possible trunks?
Comment: That can get to anyone's head!
Answer: Hopefully someone can come along and give a better answer, but I will put a brief comment as encouragement:
I agree that, naively, one can look at the laws of quantum physics and conclude that there is not one definite past or history that leads to the current universe, for just the same reasons that the current universe's state does not lead to a definite outcome to future experiments. To be precise, it's a straightforward result of the unitarity of time evolution. It's not obvious to me that this is a problem, particularly if you consider the wavefunction to be real, but it is certainly a feature that people don't usually think about.
This is rather similar, although not quite identical, to the Boltzmann brain issue. You can read a lot of arguments about that if you look around (for example, I recommend Sean Carroll's book From Eternity to Here), but a popular one is that we should assume, by some mechanism we don't understand yet, that the universe started with an extremely low entropy. So we have to put a boundary condition on the universe to make any sense of anything, and although it doesn't seem particularly necessary to me one could presumably stipulate that this boundary not be a macroscopic superposition.
Finally, taking an Everettian many-worlds perspective on this question is interesting. The idea in many-worlds is that the total wavefunction of the universe has a sort of fractal shape, with branches that have the same initial state dividing whenever (in some usually undefined way) two parts of some superposition become entangled enough with other things that they could never interfere again. So from this perspective it is actually quite wrong to run quantum evolution backward from your current state, because the state that includes "you" is only part of the total state of the universe. You should actually gather up all the other branches representing different outcomes and apply time evolution to them at the same time. And if you do this, you would actually see all of these branches interfere with each other in such a way that they nicely reduce instead of proliferating and lead back to the one unique past that they all originated from. So this interpretation does appear to naturally have a unique past, something that I don't think I've ever seen discussed...
Comment: Why would many worlds require a unique past? Couldn't branches join together, just as easily as split apart?
Comment: @user66309 Maybe I overstated the claim here. One must specify the initial conditions in either interpretation. But there does seem to me that in the MWI the number of branches is always increasing (this is very nearly a restatement of the second law of thermodynamics), and to reverse this correctly one must start with all the distinct branches and run them backwards. This seems to me to be different than a Copenhagen-style interpretation, in which you start with only one branch at the present time and therefore they can only proliferate in each direction.
Answer: Take a look at Newton's third law:

For every action, there is an equal and opposite reaction

Change the wording a bit and we can say:

For every past, there is an equal and opposite future

What this implies is that there can only exist one past for any given future.
This further implies that although any past can have multiple futures, but since only one of the futures succeed in happening, the number of futures are the same as the number of pasts
Even more interesting is the fact that since actions do not simply vanish after happening (gravity for example), then whatever action started all reactions still exists. i.e. whatever past started all future-pasts, is still out there.


What exactly does it mean that storing "large blobs in the database reduces performance"?

Question: To someone who knows database internals this may be an easy question, but can someone explain in a clear way why storing large blobs (say 400 MB movies) in the database is supposed to decrease SharePoint performance, i.e. file-upload performance, site browsing, displaying lists, document opening etc.? Remote Blob Storage aka moving files out of the database, leaving only a reference, is supposed to solve this, but what exactly - at the bottom level - is the difference? It's obvious that backups would take longer with giant files stored in the database ... but what operations exactly are impacted and what's the underlying mechanism of it (i.e. in what way are files stored on filesystem outside of the database accessed or stored differently)? It's not like the actual binary content columns are indexed.
Answer: I would say that the problem isn't a SharePoint problem (SharePoint is really speaking just a ASP.Net website reading and writing to a SQL database), but more of a SQL Problem.
I found a good article where Microsoft did some research on the topic. Read here: http://research.microsoft.com/pubs/64525/tr-2006-45.pdf


Dual monitor fullscreen with Swift

Question: I'm working with swift 2.0 in Xcode in OSX 10.10. I'm following the example here http://blogs.wcode.org/2015/06/howto-create-a-locked-down-fullscreen-cocoa-application-and-implement-nslayoutconstraints-using-swift/ for creating a fullscreen app. I've been able to get it to work in fullscreen for one monitor, but in my dual monitor setup, I'd like another window that goes fullscreen as well for the second monitor.
One monitor will basically be a control panel, and the other monitor will eventually be a web-cam preview.
I'm unsure if I need to add a second view, or a second window controller, or what?
Answer: Two "Spaces" in Fullscreen means two NSWindow objects, since each window can only be part of one space.
So you need to use two NSWindowsController objects, one for each window.
Edit
You can still do essentially the same for both views to achieve the desired effect. The only thing you have to change is the following:
override func viewDidAppear() {
    *other code*

    self.view.enterFullScreenMode(NSScreen.mainScreen()!, withOptions:optionsDictionary)
}

to the screen you want the second view to be displayed.
Take a look at NSScreens screen class method.
To initialize both views, create the needed view controllers within the App Delegates applicationdidFinishLaunching
Comment: So how would I be able to initialize both at the same time?

Dual monitor fullscreen with Swift


Double parameter with 2 digits after dot in strings.xml?

Question: I want to have a parameter in one string in strings.xml and this parameter should be a double value. So I use %1$f. Here - http://developer.android.com/reference/java/util/Formatter.html there are many examples, but what if I want to have have a few double/float parameters and I want only the second one to have 2 digits after .? I tried to use combinations like %2$.2f or %2.2$f. Nor of them worked. %.1f does not work as well.
So, does anybody know how can I "customize" a float/double value inside a strings.xml? Thanks.
Answer: Just adding to @David Airam's answer here; the "incorrect" solution he gives is actually correct, but with a bit of tweaking. The XML file should contain:
<string name="resource1">Hello string: %1$s, and hello float: %2$.2f.</string>

Now in the Java code:
String svalue = "test";
float sfloat= 3.1415926;
String sresult = getString(R.string.resource1, svalue, sfloat);

The exception that @David Airam reported is from trying to jam a String into a format specifier with %f, which requires a floating point type. Use float and there is no such exception.
Also, you can use Float.valueOf() to convert a String to a float in case your input data was originally a string (say, from a EditText or something). However, you should always try/catch valueOf() operations and handle the NumberFormatException case, since this exception is unchecked.
Answer: %.1f work for me if you like to show only 1 digit after ','
Answer: Define is strings.xml file
  <string name="price_format">$%,.2f</string>

//For using in databinding  where amount is double type
    android:text="@{@string/price_format(model.amount)}"

//For using in java runtime where priceOfModifier is double type
                amountEt.setText(context.getResources().getString(R.string.price_format, priceOfModifier));

Answer: A simpler approach:
<string name="decimalunit">%.2f%n</string>
float sfloat= 3.1475926;
String sresult = getString(R.string.decimalunit, sfloat);
Output: 3.15
Answer: This worked for me.
<string name="market_price">Range ₹%1$.0f - ₹%2$.0f</string>

android:text="@{@string/market_price(viewModel.suggestedPriceRange.max, viewModel.suggestedPriceRange.min)}"

Outputs: Range ₹500 - ₹1000
In ₹%1$.0f, .0f defines how many digits you want after the decimal.
Answer: If it were me I'd store the values in the resources as simple values, and then use formatter methods to control how they're displayed, roughly like this
public String formatFigureTwoPlaces(float value) {
    DecimalFormat myFormatter = new DecimalFormat("##0.00");
    return myFormatter.format(value);
}

public String formatFigureOnePlace(float value) {
    DecimalFormat myFormatter = new DecimalFormat("##0.0");
    return myFormatter.format(value);
}

Comment: The comment here is the real answer! You should put it as another answer to this question. I almost didn't see it.
Comment: the answer by Iomza in the comments is the real solution
Answer: I now that this reply is arriving too late... but I hope to be able to help other people:
Android sucks with multiple parameters substitutions when you want decimal numbers and format this in common style %a.bf
The best solution I have found (and only for these kind of resources) is put the decimal parameters as strings %n$s and in the code apply my conversion with String.format(...)

Example:

INCORRECT WAY:
// In xml file:
<string name="resource1">You has a desviation of %1$s and that is a %2$.2f%% percentage.</string>

// And in java file
  String sresult = getString(R.string.resource1, svalue, spercentage); // <-- exception!

This solution is technically correct but incorrect due to android substitution resources system so the last line will generate an exception.

CORRECT WAY / SOLUTION:
Simply convert the second parameter into a String.
<string name="resource1">You has a desviation of %1$s and that is a %2$s percentage.</string>

And now in the code:
...

  // This is the auxiliar line added to solve the problem
  String spercentage = String.format("%.2f%%",percentage);

  // This is the common code where we use the last variable.
  String sresult = getString(R.string.resource1, svalue, spercentage);

Comment: What is the type of `spercentage` in your "incorrect" example? I'm guessing (as @Nik Reiman points out) that it's a `String` - i.e. no wonder you're getting an exception when trying to pass it as a float (at `%2$.2f`). This "answer" is incomplete and misleading.
Comment: I also can't get formatted floats to work from a string resource, and yes I'm passing a float.  I use "%1$0.6f" in the string resource, and I get an exception: java.util.MissingFormatWidthException: %01$.6f  so it's getting mangled somehow.  This answer is correct.


How to hide previous commands/history in terminal and start like the beginning of the tab?

Question: There should be a command on terminal that hides the history belongs a specific tab and lets you start from the beginning of the tab like it is new, but when you scroll up with a mouse you can see your history. I can't remember and find it online. I hope someone can tell it.
Comment: Ok, I've found it. it is kntrl+L
Answer: If you want to clear your terminal window:

use the command clearto clear whatever is showing
use command+K to clear everything

There are other things you can try too:
https://stackoverflow.com/questions/2198377/how-to-clear-previous-output-in-terminal-in-mac-os-x


Select configurable attributes on an existing product

Question: I have a configurable product setup which has single products as colours, however I now wish to add a new attribute (e.g. size) to the product. I know that when you create a new product and select Configurable Product it lets you choose the attributes to associate, however I can't see an option to add more to an existing product.
Answer: Simple answer: You can't add additional "super" attributes later.
But: You can add it in the database. Have a look at the database table "catalog_product_super_attribute". If you know the product ID and the attribute ID (you can get them from the URLs when editing the specific product / attribute), you can add a new row there directly.
Comment: Ahhh that's disappointing but I can do it from the database I suppose. Thank you very much for responding.


How to switch from user mode to kernel mode?

Question: I'm learning about the Linux kernel but I don't understand how to switch from user mode to kernel mode in Linux. How does it work? Could you give me some advice or give me some link to refer or some book about this?
Comment: What's the context of your question? Are you asking about specific CPU mechanisms on a specific CPU or in general? Is there a problem you're trying to solve?
Answer: The only way an user space application can explicitly initiate a switch to kernel mode during normal operation is by making an system call such as open, read, write etc.
Whenever a user application calls these system call APIs with appropriate parameters, a software interrupt/exception(SWI) is triggered.
As a result of this SWI, the control of the code execution jumps from the user application to a predefined location in the Interrupt Vector Table [IVT] provided by the OS.
This IVT contains an adress for the SWI exception handler routine, which performs all the necessary steps required to switch the user application to kernel mode and start executing kernel instructions on behalf of user process.
Comment: Not quite. On x86 any exception originating in user mode will transfer control to the appropriate exception handler in the OS, in kernel mode.
Comment: True. As soon as I posted my answer I wanted to edit it reflecting that it is the case when user app wants to explicitly switch to kernel mode. However, I struggled to do so due to network issues. Have edited it now to reflect this.
Comment: @AmarnathRevanna How does the OS know it has infact switched to kernel mode when servicing a SWI? Is there a specific hardware register/bit that keeps track of mode to be supervisor(ring 0)/user(ring 3) and is updated on a SWI? Basically what asserts the switch to user to kernel mode at the hardware level.
Answer: To switch from user mode to kernel mode you need to perform a system call.
If you just want to see what the stuff is going on under the hood, go to TLDP is your new friend and see the code (it is well documented, no need of additional knowledge to understand an assembly code).
You are interested in:
<code>  movl    $len,%edx           # third argument: message length
  movl    $msg,%ecx           # second argument: pointer to message to write
  movl    $1,%ebx             # first argument: file handle (stdout)
  movl    $4,%eax             # system call number (sys_write)
  int     $0x80               # call kernel
</code>
As you can see, a system call is just a wrapper around the assembly code, that performs an interruption (0x80) and as a result a handler for this system call will be called.
Let's cheat a bit and use a C preprocessor here to build an executable (foo.S is a file where you put a code from the link below):
<code>gcc -o foo -nostdlib foo.S
</code>
Run it via strace to ensure that we'll get what we write:
<code>$ strace -t ./foo
09:38:28 execve("./foo", ["./foo"], 0x7ffeb5b771d8 /* 57 vars */) = 0
09:38:28 stat(NULL, Hello, world!
 NULL)               = 14
09:38:28 write(0, NULL, 14)
</code>
Answer: I just read through this, and it's a pretty good resource.  It explains user mode and kernel mode, why changes happen, how expensive they are, and gives some interesting related reading.
https://blog.codinghorror.com/understanding-user-and-kernel-mode
Here's a short excerpt:
Kernel Mode
In Kernel mode, the executing code has complete and unrestricted access to the underlying hardware. It can execute any CPU instruction and reference any memory address. Kernel mode is generally reserved for the lowest-level, most trusted functions of the operating system. Crashes in kernel mode are catastrophic; they will halt the entire PC.
User Mode
In User mode, the executing code has no ability to directly access hardware or reference memory. Code running in user mode must delegate to system APIs to access hardware or memory. Due to the protection afforded by this sort of isolation, crashes in user mode are always recoverable. Most of the code running on your computer will execute in user mode.


Truffle console.log is not working

Question: I've installed Truffle by npm, and running testrpc, but console.log is not working in Truffle console. A simple console.log('test'); do nothing. Any idea?
Comment: which truffle version are you using, which testrpc version are you using, what's your operating system, can you provide sample code?
Answer: I don't have a complete answer, but I believe it has to do with the console's automatic resolution of javascript promises. For example,
Contract.deployed().then(instance => instance.contract)

the truffle console will actually wait for the final .then promise to resolve and will then print instance.contract. That said, I would imagine that
new Promise(() => console.log('test'))

would work, or even
new Promise(() => 'test')

but they don't for me. I don't know enough about promises or the truffle console to understand why that doesn't work. Hopefully this gets fixed in the future. For now, you can do
Contract.deployed().then(() => console.log('test'))

or
Contract.deployed().then(() => 'test')

as workarounds.
Answer: in the Testing Your Contracts
Please try it if your file location is /test/contract.js
$ truffle test ./test/contract.js

Truffle console.log is not working


What is the gas cost to read a member of a global struct?

Question: Say I have a global state variable struct MyStruct that has multiple members/attributes/fields, what is the gas cost for reading a specific member? Is it equivalent to the gas cost of reading the entire struct or much less and proportionate to that member. So if a struct has 16 uint members, then is the gas cost for reading/loading just 1 of the 16 members from storage approximately 1/16 the gas cost of reading/SLOADing the entire struct?
Answer: The costs of reading a full struct from storage in a contract heavily depends on your struct.
You pay gas costs for every storage slot that you access. If your struct spans multiple storage slots and you read them all at once (by loading the whole struct) you will pay more gas than only loading a specific member of the struct.
But Solidity can fit multiple parameters into one slot. (see related question and Solidity docs). In this case reading all at once is cheaper since you only access one storage slot one time.
These struct storage optimizations of Solidity become more important when you update a struct (so storage writes) as writing multiple storage slots is significantly more expensive than writing a single storage slot.
Note: Repeatedly writing or reading the same storage slots became a lot cheaper with EIP-2929
Answer: Reading data from Blockchain does not cost any gas.
Comment: It can if you submit a valid transaction to the network, even if you're not modifying state, you have services like Etherscan who run their own archive nodes which allow you to read contract state for free, but technically it's still possible to execute a view call directly on chain, so my question is in this context.
Comment: @MShakeG the op says nothing about sending transactions
Comment: I think it's implied since it's a given that gas is only charged if a transaction is executed on the network.
Comment: Well, the OP should ask that then. If the question is posed what "the gas cost to read" anything from a blockchain is ... the asnwer is simple "nothing". I'm not gonna asssume that OP is talking about txs unless he states that in his question ... otherwise, he might as well be talking about unicorns; so yeah, this is pretty much the first time I get downvoted for answering a question correctly ...


How much gas do 0x00000000... addresses and 0x00000000 methods really save?

Question: I have seen many contract addresses being created using vanity address generators to have many 0s in the begginning and even method sighashes having all 0s in them and have come to the conclusion that they do save gas. If yes, then how much gas do they really save?
Comment: I would think that they have no function at all (and no gas saving). It's only for vanity and looking cool. But I am not sure so I will let someone else answer...
Answer: Following the rules of the yellow paper, it costs 4 gas for every zero bytes of transaction data (msg.data). Compare that to the cost of 68 gas, or 17 times as expensive for a non-zero byte. The hamming weight of msg.sender makes no difference tho. The only bytes we are interested in are in msg.data, which includes the function selector.
For example, if you're using the transfer(_to, _amount) method on an ERC20 token, if the receiver address _to contains a lot of zeroes, it will save you gas executing the transaction.
Using OpenZeppelin's StandardToken as a reference implementation, a standard transfer to an address with non-zero bytes costs 51,486 gas. However, a transfer to an address with eight zero bytes only costs 50,974 gas, a difference of 51486 — 50974 = 512 gas, which can be expressed as 64 * 8 (the number of zero bytes).
I suggest you read this article On Efficient Ethereum Addresses for a detailed explanation.
Answer: One of the projects using such 'short' addresses is the Gas Token. From https://gastoken.io/#GST2 :

The address of our GST2 GasToken, 0x0000000000b3F879cb30FE243b4Dfee438691c04, is hardcoded. Note that this address is very short (only 15 non-zero bytes instead of 20). We generated our GasToken contract at such an address on purpose, so as to save some gas when creating contracts. The above child contract uses 22 bytes of code, and thus costs roughly 32000 + 22 * 200 = 36400 gas to create (the additional overhead of calling mint is only about 150 gas). If we could make use of address 0x0 for GasToken, we could save an extra 3000 gas or so for every created contract!

So there are gas savings. And the cost savings really depend on the usage. In this case, the usage is when new contracts are created which reference to another (short addressed) contract. Basically less bytes need to be stored.
I'm not sure if having zeros in method signature hashes help, but I guess it might. Haven't really encountered such. Anyway, in my opinion, modifying function names to get a desired hash for them is bad idea, since it makes the contract harder for humans to understand.
Comment: Thanks for the answer. My question is "HOW" much gas does it save
Comment: There is no generic answer to that question. It depends on the implementation. I just gave you one example which states how much is saved


Are encrypted databases secure against all attacks?

Question: If I use a database encryption package for oracle like dbms_crypto, would this be vulnerable to any attacks? I know that it uses algorithms like 3DES, AES, etc. These are all thigns that you can use while using this package, and there are attacks against 3DES, and AES but they are relatively secure. Other than a system being compromised, and having keys stored on the system, and a malicious Database Admin, are there any other attacks that a DB that is encrypted using a package would be vulnerable to?
Comment: Encryption protects **Dead Systems** from theft of content. A running system, database or otherwise, is effectively decrypted in order to run. A running system is subject to all the same attacks, regardless of whether the underlying storage was originally encrypted or not. *Homomorphic encryption* is mostly a side entertainment.
Answer: An encrypted database protects the database against attacks on the filesystem or storage. If someone manages to get a shell on the server, or gets the credentials to the SAN storage, they cannot make a copy of the database and run with its data.
On the other hand, the applications need access to the database, so they must have the credentials and the encryption keys for it. If an application can access the data, so can an attacker.
If the application is vulnerable to SQL Injection, an attacker can extract data from the database even if the database itself is encrypted.
Answer: There are many different attacks possible. For instance there are different attacks related to privilege escalation via indexes. Attacks via TNS listener. Attacks via web interface isqlplus. DoS attacks (running complex queries, filling shared tablespaces). Etc.
When you encrypt data, you do only that, encrypt. It protects only in this single case, when somebody gets access to database files. All other possible attacks do not depend on encryption. That's why it is not correct to expect that the database is secure otherwise.
Answer: No, they are not secure against attacks, especially in multi-user case.
For example, the CryptDB of MIT is shown to be attackable in various ways

On the Difficulty of Securing Web Applications using CryptDB

privilege escalation is possible if there is no integrity and authentication
The difference of two-time snapshot of the encrypted database can leak information with the help of frequency attacks.

Inference Attacks on Property-Preserving Encrypted Databases

Inference attacks and Frequency attacks are still applicable to Encrypted DB's if one uses ECB mode of operation. for the equality queries.
The real problem is the protection of the encryption keys. As one said if you encrypt the database and perform queries over the encrypted data then all of the application servers need the key. Therefore, one distributes the protection of one key ( Oracle's raw encryption) into protection of the key in multiple places like having 20-25 application servers that need the key to perform queries.
One solution is using an HSM module for storing the key and executing some encryption with the help of them as en encryption oracle. They may have limited capabilities and can have unnoticed failures.
Conclusion: Encryption is essential, however, one still need consider new sophisticated attacks.

NSA: "Attacks always get better; they never get worse.


Is audio porn haram?

Question: Salam aleykoum,
i have made it so far to stop watching porn and masturbating.So my question is can we listen to porn recordings as they don t include any nudity.And there is also the fake recordings done by professionals,do they stand for the same? Thanks for all the answers(pls i need answers with proves,coran or hadith if possible)
Comment: Audio porn is the Zina of the ears...hence it's haram. Audio porn includes, possibly the woman/man moaning, groaning and breathing heavily. These sexual sound belong to the invidious who is not permissible for you. Hence haram.
Answer: Bismillahir rahman nir rahim
Iam not a scholar.
I trying to speak from me
Word porn itself is haraam in islam.
 If u listen audio porn its zinaah of ears, Which is forbidden in islam by ALLAH
And its sin.

Is audio porn haram?


Mailed 2018 taxes-Not processed so no AGI or pin...how do I efile?

Question: I mailed my 2018 Federal Taxes 4/11/20...they have not been processed yet.  I was told by IRS to go ahead and file my 2019 taxes...I want to use efile, since mailing didn't work well.  There isn't any record of my 2018 AGI and I don't have a pin from last year.
Comment: You would only have a PIN if you e-filed. So if you mailed your previous tax returns, then you would not have a PIN.
Answer: If you did not file a tax return for 2018, you can still file in 2019 by selecting 0 as your prior year AGI.  This of course will only work if the 2018 taxes haven't been processed yet, but the good news is you get fairly quick feedback of that information.
You could also request a transcript of your 2018 taxes, in the case that they have accepted and processed the 2018 return and you just don't know it yet.  6 months is a very long time for them to not have processed it yet, so I'd be concerned, and consider re-sending the 2018 taxes in as well.


Can data clustering algorithms be used to find the borders of an area in 2D space ?

Question: If we have spatial points randomly distributed in 2D space, then we clustered those points according to some parameters, say location x,y. Can we use the same clustering algorithm and apply it on finding a geographical area borders? .
In another words , If  a set of points with the same  characteristics are clustered according to their geographical relationship , can we say that we have found the area borers that contains those points ?
For example this paper
Comment: There doesn't seem to be enough information to answer this question, because you haven't posited any connection whatsoever between the locations of these points and the geographical area in which you might consider them to enclosed.  Could you provide more specifics about your actual problem?
Comment: To map boundaries you would need to be able to evaluate what cluster a hypothetical new data point would belong to, i.e. you would need a [tag:classification] style decision function. As noted [here](http://stats.stackexchange.com/a/252111/127790), clustering can be considered as classification with hidden labels. So your clustering approach may already implicitly give you a classification function. (Or you could just train a classifier on the data w/label=cluster-id.) This will give *an* answer, but how useful/reliable this answer is will depend on the specifics, as noted by @whuber.
Comment: @whuber Here is my idea, I have overlapped shapes , and there are points arrived randomly to this space(some maybe inside the overlapped  areas and some can be out), I want to make use of those points to find the overlapped areas so that in the future I can tell if a new arrived point is inside or outside an overlapped area.
Answer: Yes, people have successfully used clustering algorithms such as DBSCAN for this.
I don't have references for you, but look for image segmentation by clustering.
I don't think it is the best way to do this (in particular on images, you really should exploit the pixel grid for performance) and I really do not recommend k-means for this. But a well built generalized DBSCAN in a special implementation for your data may work well, and give you good control over the desired outcome. Generalized DBSCAN is much superior here, because you can specify both adjacency and similarity thresholds.


Show if group has access to certain forms

Question: I'm trying to understand how to write a query to distinguish if a user has access to certain form or not. I know what I am asking here looks easy but when I tried to implement it, it was whole different thing.
Maybe I am doing it wrong.
Before starting I want to mention the two tables names in start:

sys_forms,
sys_forms_in_groups

Also I am putting a SQL Fiddle link at the end.
Here is what I am trying to do.

If you can see the picture, on top dropdown box (it's a select2 dropdown), user selects the group and it will return GroupID, on the base of which I want to populated the below datatable. (DataTable is just showing groups, it's a dummy, but it will show forms, will fix it if problem is solved)
Now here the problem arise:
I want datatables to show all the forms available in sys_forms table in datatables but in actions columns of datatables only those checkboxes/switches should show granted which are available in the selected group(Group can be selected for select2 dropdown as said before).
GroupID is the column of other table sys_forms_in_groups.
All I want is that all the forms should show in the datatables no matter what group I choose, but Actions column in table should display Granted if the group has access to that particular form.
forms_in_groups is for showing if group has access to that certain form or not. For example:
    FormID  GroupID
------------------------------
    1          1
    2          1
    1          2

FormID 1 is available to both groupID 1 and 2, on other hand FormID 2 is avaialable only to GroupID 1.
Here is my SQL Fiddle.
Edit
The SQL Fiddle is not working, so putting screenshots here.
Table : sys_forms

Table : sys_forms_in_groups

I have tried this query, but it only returns forms for the selected group, where I want that all forms should show but they must show granted in Actions Columns on checkboxes/switchButtons
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 1;

Comment: Not read it all yet — but it looks like a brilliant example of a question. Well done.
Comment: @matrixdevuk
Thankyou sir.
Comment: — The SQLFIDDLE site is being a douche... not loading the fiddle properly.
Comment: @matrixdevuk
Ok, wait sir, i will find another way to display my tables and columns.
Comment: You might have to do `WHERE \`sys_forms_in_groups\`.\`GroupID\``
Comment: Also, you'd have: `SELECT * FROM \`sys_forms\``
Comment: @matrixdevuk
Sorry, i didn't understood. i already have tried where condition for GroupID as you can see in the query in the end of the question.
Answer: What I can see from your database schema, an inner join is the correct choice here based on the data you are looking for. The only issue I can see is in the WHERE clause. Seems that it may try to look for GroupID in the sys_forms table, so try specifying.
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE
`sys_forms_in_groups`.`GroupID` = 1;

Answer: I think you're, incorrectly, trying to offload the issue onto MySQL.
It's not MySQL's job to render the forms and show whether a selected group has access to a specific form. That will fall onto your rendering of the page; using Select2 in this case.
You just want to retrieve all forms, then show whether the selected group has access to a specific form. That comes down to some Javascript that makes that check for you and displays it properly.
If you want to return all forms, the query would be:
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID`;

If you only want the forms that group 1 has access to, the query would be just as you have it:
SELECT * FROM (`sys_forms`) INNER JOIN `sys_forms_in_groups`
ON `sys_forms_in_groups`.`FormID` = `sys_forms`.`FormID` WHERE `GroupID` = 1;

I didn't do a lot of digging into Select2, so I can't really help you in that aspect.
Comment: As i stated in top of my question, i thought it would be easy in start but when i started work on this, i knew its not that easy as i thought.
No, Javascript can only ON and OFF the switch button, but who will tell javascript to which Switch to ON or which switch to OFF?
Answer: Finally Problem Solved and working perfectly fine, but after solving that problem i found out there is an other issue i didnt think of, but thats another matter. xD.
However, It was a little rough way to solve but i got what i wanted.
Here is how i did it,
I first needed to update my select query to,
SELECT f.FormID
     , f.FormName
     , f.FormCIPath
     , MAX(g.IsMenuLink) AS IsMenuLink
     , GROUP_CONCAT(DISTINCT g.GroupID ORDER BY g.GroupID) AS GroupIDs
  FROM `sys_forms` f
  JOIN `sys_forms_in_groups` g
    ON g.FormID = f.FormID
   AND g.GroupID IN (1,2)
 GROUP BY f.formID

Here you can see it will return all the forms which belongs to group 1 and group 2 but in a way that 1 and 2 will be in same column separated by comma.
Here how it shows now.

I am not a very complex query master so i am very much grateful to stackoverflow community to help me with the query. As i wanted to join both results to show in comma separated value.
After the MysQL the jquery work was not much difficult, i only sent the group ID for which i wanted the result to show in table. and there i got this result in return where i separate the GroupIDs with javascript split function and i get my groups.
Thankyou again everyone.


Calculating the work done by friction on a rigid body due to the piston

Question: I have a uniform rod of length 0.5m and mass 0.1kg, and on this rod are two balls of mass 0.03kg both at a distance of 9.997cm away from the center of the rod. There is a pin about the center of the rod upon which it rotates. The angular velocity I have worked out to be 20rad/s and the tangential velocity of the beads are 1.679m/s. The balls are released and move to the end of the rod and I want to find the work done by the pin dur to friction. I know the final kinetic energy is 0.1566J so I thought about using the work kinetic energy theorem but the result is not correct. Maybe I have been calculating the initial energies incorrectly. I took 1/2Iw^2 + 2(1/2)(Mass of ball)(Tangetial Velocity)^2 and used that. Is this the correct method?
Answer:
I know the final kinetic energy is 0.1566J

How did you find the final kinetic energy?
To find the final state of the system you have to assume that there are no external torques acting on the system and that angular momentum is conserved.


What was Natsume hiding in her closet in episode 11?

Question: In episode 11 of Tokyo Ravens, what was Natsume hiding in her closet?
Answer: It was never shown in the whole series, but we can make some intelligent guesses. Here are the list of things Natsume hides:

She is a girl. No one except Harutora knows she is a girl.
She is the controller behind Hokuto.
She is obsessively in love with Harutora.

So based on these things, it could be

Girl clothes, cosmetics, girly things, etc.
Clothes and kit that Hokuto uses.
A whole collection of things related to Harutora, maybe during his time with Hokuto. Pictures, memorabilia etc..
Answer: Actually, Harutora, Touji and even Suzuka know she's a girl. So I don't think she's too worried about that sorta things like cosmetics or clothes being out at this point.
She also traipses around with that ribbon Harutora won and even has a tiger statuette on display, so I don't really think she's shy of the memorabilia all that much and I honestly don't think she's the sorta girl to build a shrine for her crush or something.
So taking an educated guess, I think it's her porn collection, seeing as Harutora's was subtly mentioned before this particular scene to be in his closet.


How do you prevent the readers or viewers from guessing the whole plot when you use foreshadowing?

Question: How do you prevent the readers or viewers from guessing the whole plot when you use foreshadowing? I remember watching Monster.Inc when I was young and I was able to guess the whole plot of the movie half-way through when the little girl laughed and shut down the whole electric grid. I didn't guess every little detail, but I was able to guess what was going to happen in the end and everything in between the end and that scene. How do you prevent that from happening when you foreshadow things, and is it a bad thing?
Comment: Bear in mind that what is too subtle for one set of readers to pick up on (so they think your ending is a deus ex machina) is too ham-handed for another, and in between, one hopes, your target audience lies.
Answer: Just keep your foreshadowing subtle or indirect.
It is subtle when characters use phrases or sayings that are commonly used, for example. "That woman will be the death of me, Richard."
Because it is commonly used, the audience doesn't take such common idioms literally.
The same thing is true for common mistakes that in the shown situation, have no major consequences, but in a future situation does have a major consequence. Just make them a little indirect.

"Richard!STOP!"
Richard screeches to halt. "What?"
You just ran a red light, you idiot! Pay attention to what you are doing!
Richard looks confused, then irritated. "It's two o'clock in the morning, nobody's out here anyway."
He starts up again, looking in the rear view mirror.

This can be indirect foreshadowing for a future critical mistake -- that has nothing to do with a red light, but everything to do with Richard being distracted and not paying attention to what he is doing. Maybe he makes a stupid mistake in the middle of the night, and kills somebody.
Or, in one of my stories, there is a pair of spies, male and female, that literally grew up together. They are couple and the guy is in love with the girl. He gets killed, because he broke protocol to save her -- and did not need to, she was not in real danger. I found two places to foreshadow this in earlier scenes, where he couldn't help himself, acted against training to protect her from harm. In both cases there was no major consequences other than her scolding him, but then forgiving him. His intentions were good!
But the third time he does this, on a critical mission, he gets himself killed.
His over-protectiveness (and failure to trust his partner to be able to take care of herself when surprised) created an unforced error that was a major failure in the plan, and it almost did get her killed, and she lost the love of her life in the bargain, and a months long plan was trashed over what could have been just a hiccup.
It was the "All is Lost" moment in the story, foreshadowed by a seemingly minor weakness in his character. Since when is "backup" not a good thing? When it betrays a larger plot to the enemy so they can mobilize, seek out spies and traitors and nullify any advantage of a surprise surgical attack.
To me, the best foreshadowing grows out of the aspects of our character's personality. Then it is believable -- yeah, she would do that!
And in the payoff, the thing that happens harkens back to the foreshadowed scenes.
Remember that a shadow has no detail. It is just a shape. Your foreshadowing should not be too explicit; it should just be similar in shape to what will become a pivotal moment.
As a discovery writer I do not plot ahead of time; so in order to foreshadow something, I often go back and look for good places to do that by modifying an existing scene; to establish the shape of the personality trait that will eventually lead to a turning a point.
Answer: Misdirection
To run with the Monsters Inc example, there are two things I would do to make the foreshadowing more subtle.

Misdirection on the power grid.

Add extra Distractions.

In Action
I would set scene by making the electric grid unstable even without any children present - make wires spark, lights dim, etc. for no discernible reason. It's just part of the worldbuilding that the power grid here does that.
Then I'd tone down the incident with the laughing child, and do it a couple of times. Have the kid laugh, and then you get a power dip, but it's just like a normal power issue, so it doesn't stand out. Do that often enough to establish a pattern, but not too often.
Then I'd use some distractions to make the pattern less obvious. Have the kid laugh, then the lights dim, then something completely unrelated and very interesting happens.
Readers understand that scenes have purposes. So if nothing happens in a scene except that the baby laughed and the lights dim, they will figure out that the point of that scene was to show that specific interaction. But if the baby laughs, the lights dim, and then some important plot point happens then the reader will assume that the plot point is the purpose of the scene, and that the laughing baby was just fluff.
Unless it's for a children's movie, foreshadowing works best if it's subtle, it's blended into other action, and you do it a couple of times.


Flyback vs. Coupled inductors vs. Transformer?

Question: So I am in the process of making a high voltage power supply and after a failed attempt at using a modified MOT and difficulties finding a flyback transformer, also difficulties understanding how they work, I've come here. I am wondering if I can make my own "flyback" from a ferrite rod, since as far as I know, a flyback is coupled inductors? But then, if you check the image, how are primaries able to be wound on the other side of the transformer and create such high voltage? Is that simply inducing a current in the primary of the flyback which is affecting the secondary, but I suppose that wouldn't make sense? I just don't understand how the ferrite doesn't become saturated from such low windings on the primary, when being used as a transformer. An explanation of this would be very helpful because after hours and hours on the internet I have not gained any concrete knowledge about the workings of these things.
Answer: There are two main differences between the cores in a fly-back transformer and in a traditional power transformer.

The core in a fly-back transformer has a much higher reluctance. This can be achieved in a number of ways. One is to add an air-gap to a core. Another is to use a core with a "distributed air gap", and a third is to use core materials that have naturally high reluctance. A distributed air-gap arises when the core consists, for example, iron powder in a binder. The binder is not air, but it is called an air gap nonetheless.

An increase in reluctance allows a core to store more energy for the same inductance. However, for the same inductance, more turns will be required.
Energy storage is important for a fly-back transformer because energy is stored in the core and air-gap (in fact largely in the air-gap) for part of a cycle, and then released later in the cycle. However, in classical transformer action, the power drawn by the load on the secondary side is transferred immediately from primary side power supply.

The core in a fly-back transformer generally can work efficiently at might higher frequencies than a traditional power transformer. The cores of traditional power transformers are typically made with silicon steel laminations. They work well for mains frequency applications, but become very lossy at higher frequencies. Ferrite cores, on the other hand can be efficient will past beyond 1 MHz.

A word about air-gaps. A ferrite rod is not an ideal core for either a traditional power transformer, or for a fly-back transformer. The air-gap in a rod is, for the most part, too big. The consequence of this is that it will take a great many turns to create the appropriate inductance. An air gap in the millimeter range is much more appropriate.
Comment: that explains why they come in 2 separate pieces. I guess I'll have to find some flyback cores and order them in. thank you for your reply.
Answer: Math Keeps Me Busy's answer covers the magnetizing aspect (self inductance), so that leaves the topic of mutual inductance (leakage).
In general, we can express a nonideal transformer as a "wye" of inductors (and an ideal 1:1 transformer, if we still need to express isolation between the two sides):

simulate this circuit – Schematic created using CircuitLab
Where L1 = Lp - M, L2 = M and L3 = Ls - M.
Or a "delta" configuration, equally well.
See: Coupled Inductors as Transformer |  Analog/RF IntgCkts
Note that, for odd turns ratios, we get negative inductors.  This is merely a representation, of course.  But if we confine ourselves to a 1:1 turns ratio (putting an ideal 1:N transformer afterwards), then L1 + L3 become realistic values.  Particularly when the coupling coefficient (\$k = \frac{M}{\sqrt{L_p L_s}}\$) is large (\$M\$ approaching \$\sqrt{L_p L_s}\$), we call their sum leakage inductance (LL), and L2 the magnetizing inductance (Lm).  This doesn't stop working for small k of course, just that we are less interested in LL, or find it less useful for such cases (which are also less commonly used).
Geometrically, leakage is the flux not coupled between windings.  There is flux surrounding each winding, and not only that, but each part of each wire in each winding as well.  We can overlap a pair of windings to share some of that flux, and thus couple the inductors; to couple them significantly, they must occupy nearly the same space.
This does not change when a core is introduced.  In fact, the core contributes additional flux, but this does not change the intrinsic flux in the space around each winding.  The core makes it "easier" (takes less current) to store a certain total amount of flux; but the introduction of a core does not affect the flux outside of its boundary.  (Well, it does, it's a bit more complicated than this; but typical situations can be decomposed into rough equivalents, and, the above is most true for the most common case.)
When we draw the diagram with windings on opposite sides of a core loop, we're doing just that: a diagram, a cartoon, and nothing else.  Indeed, this is a terrible way to construct a transformer, generally speaking: it maximizes leakage (the space between windings).
Practical transformers put the windings on the same "leg" of the core, with the windings in layers, one on top of the other.  When low leakage is required, they might indeed be interleaved even closer than this -- for example, using a twisted pair, which leaves merely the gap between wires as leakage (which is therefore proportional to the between-wires geometry, and their length; such transmission line transformers are particularly convenient for analysis, and high-bandwidth applications).

Why does leakage matter?  We take a slight diversion.
Consider the flyback converter.  Notice it's a minor transformation of the boost converter:

simulate this circuit
The secondary simply has a different DC reference voltage, but the "start" ends of both windings share a supernode (they connect to either side of an ideal voltage source) so the dynamics are unchanged.
Leakage in the transformer, is equivalent to an inductance between M1 and D1 (LL1 and LL2 as shown).  Any current stored in this loop, represents energy that must be cycled through the converter (because the current is rising and falling), but which cannot be cycled into the output (because there's no diode directly from M1 to Vo, or from GND to D1).  Without explaining how/why (basically, there's always a resistor somewhere), this energy can only be lost.  Thus, we require low LL to achieve high efficiency.

So, in summary: for the flyback converter (and generally similar arguments for other types), we require low LL for high efficiency, good output (cross)regulation, etc.; and we obtain low LL by placing the windings in as close proximity as is feasible.  The core has no effect on LL (indeed you can measure this: dismantle a ferrite-core transformer, short the other windings, and measure LL on the remaining winding; insert core and observe LL increases by some percent, if at all), and is used to increase Lm instead.

Finally, we come to the high voltage driver.  What gives?  Given all the above, they've maximized leakage!  You literally can't put it any farther away, while still being on the same core.  And it's a single-switch circuit, so, it's gotta be something flyback-y, right?
Well, never assume anyone truly knows what they are doing.  (Which is a much deeper, fundamental truth than is needed here, but as a rule, too.)  This is especially true of gimmicky things like high voltage generators.  Newbies just want to throw together a couple parts and make sparks, damn the engineering, who needs theory, it's cool and fun (or until it's deadly, but, yeah).  So you find a lot of circuits like this out there.
These are basically memes in electronic form.  Indeed, they don't even need to function well, if at all; they just need to be passed on, often enough to continue being passed on: the definition of a meme.
Well, anyway, note that the primary windings for these (CRT flyback) transformers are generally within the major winding assembly itself.  They knew what they were doing (or, that is to say: to a much greater degree).
Mainly, the added winding is put there, because, well, it's additional, there's nowhere else to put it.  And, it seems to work well enough, so who cares.
There is some justification for the leakage, in other circuits, actually; when using the two-transistor oscillator ("ZVS", or sometimes "Royer", but technically it's a Baxandall oscillator), leakage allows the primary circuit to resonate, over a range of frequencies depending on load.  This keeps the circuit running even with the output shorted (or, it can, anyway), and limits output current.

On a more practical note, some converter designs tolerate more leakage, and some use it intentionally (even adding some in series as needed).  The two-switch forward converter delivers load current during the forward (on) phase (hence the name), and has clamp diodes to return both magnetizing and leakage inductances to the supply.  Resonant converters work much like the above ZVS description, but comprehensively designed along with a controller to adjust frequency and pulse timing as needed to deliver desired output voltage.
Comment: I must have read this more than 5 times now and I still don't fully understand, but it sounds like what you're saying is that a flyback transformer would work without the core, because it's simply coupled inductors? I mean as you have noticed I am trying to make a gimmicky high voltage power supply to run an even gimmickier tesla coil and I am trying to understand the theory behind these things. As far as I've seen, a regular transformer has a saturation of x volts per turn of the primary and like I said, was confused how flybacks didn't saturate. So if I understand correctly (next comment)
Comment: -the added coil, the one of the other side is not transferring power through the core, but through the coupled inductance between the primary and the secondary? I suppose the ferrite core would boost the magnetic field of the primary allowing it to pass to the secondary. Is that the role of the ferrite core in a regular flyback, as you said, makes it "easier" to store flux. I still don't fully understand but I will get there. And the ferrite core cannot just be a rod because then the "air gap" is too large? I still don't fully understand the energy storage theory.
Comment: You said about the boost converter before, I have made one before which I was pretty proud of at the time, is a flyback, or any coupled inductor system for that matter, pretty similar to that? The primary has a magnetic field that induces a current in the secondary which creates a magnetic field, which is where the energy is stored. When the current through the primary is switched off, the magnetic field of the primary, and more importantly (is it more important?) the secondary collapses, the induced current in more turns of wire creating a high voltage as it collapses?
Comment: That would make sense to me I think, but it still doesn't completely explain why a ferrite rod wouldn't work, it would increase the inductance, no? Alternatively, why does it need  a core at all?

In summary: Trying to make high voltage supply. Does all that mean that flyback converters work without a core? Is my third comment correct lol?
Comment: You're getting there. Flyback can be done with a coreless inductor but it's not going to perform great. Cores are used to increase inductance in relation to winding resistance, while using less wire length --> less leakage inductance. You don't use excessive core either, because air gap is required for energy storage. The rest is practical; rod cores certainly work, but are on the low side of mu_eff, and the external field is large, making it a big EMI issue.
Comment: Ah ok, so the core increases inductance, reducing resistance, hence losses, but having an open core will let fields escape, instead of cutting the other inductor, resulting in losses? I know that's basically repeating what you said but helps me figure it out. Ok why the high frequency then? Is that beneficial to coupled inductors? Or is that just what they tend to resonate at?
Comment: Theory and analysis will benefit greatly; instead of hand-waving and heuristics, these things can all be worked out precisely in terms of the inputs/assumptions. Never be afraid to break out a piece of paper and do the analysis; force yourself to work the equations if you must. These topics can take months (and years) to learn, so take your time!
Comment: External fields aren't a problem between windings (that's already solved by putting the windings close together), but to anything nearby, like stray wiring that isn't supposed to have switching noise induced into it, which upsets radio channels or etc.
Comment: Ohhhhh ok, that makes sense. Well it sounds like I have some experimentation and reading to do. You're explanations have been very helpful to me and I will do my best to avoid the meme flyback converter where the primary inductor is nowhere near the secondary. Part of the reason I love electronics is that there's always more to learn. I think I have a better understanding of them now, the overclocked boost converters they are, and I think I can work with that. Thank you for all your help.


Is it Possible to Determine Radiation Levels Using Satelites?

Question: Given recent events in Japan, this got me wondering. Is it possible to determine radiation levels reliably not having Geiger counters near the possible radiation contaminated zone? According to wikipedia the Chernobyl disaster was first (other than Soviet Union naturally) detected by Swedish via radioactive particles found on clothes of nuclear plant workers. Surely more efficient ways should have been developed by now.
Answer: Short answer: no.
Longer answer: No, excepting neutrinos none of the products of radioactive decay has the penetrating power to pass through the atmosphere, and neutrino detection is not something we can do from satellites.
To elaborate, the immediate products of radioactive decay are (some set of, depending on the decay in question) fission fragments, electrons, positrons, alphas, neutrons, photons (gamma rays) and neutrinos. Plus the remnant nucleus. The only secondary product which might be interesting is Cerenkov light.
The electrons and positrons will travel a number of cm in air (at ground level). The gamma might go a few meters. The heavy stuff has no penetrating power at all.
Even if lofted to the top of the troposphere, there is just too much air in the way.
Cerenkov light will, of course, go through a lot of atmosphere, but you'd be looking for a pale blue glow against the general light background. For dispersed radionucleides (i.e. contamination), the intensity will be awfully low.

N.B. I too have seen various TV show and movie where some character from some agency says "We can track the radiation with satellites!". I believe this to be misinformed babbling of desperate script writers.
Comment: @Georg - yes a lot signal from cosmic rays hitting the upper atmosphere but nothing through our dense opaque atmosphere. It's the same reason the Hubble can't see the bottom of the sea.
Comment: @Joseph Optical properties, such as opacities, are necessarily functions of wavelength. The atmosphere is very opaque in to X-rays and gamma Ray's (which is why telescopes operating in those bands must be spaceborne).
Comment: Would a Gamma observatory "see" something if directed  down to earth?
Comment: Ah I see, Its like being blinded in fog by ones own headlights (backscatter)
Comment: Our apmosphere is not opaque.  How could light get in otherwise?
Answer: I hear that the WC-135 Constant Phoenix has recently been deployed to monitor radiation in the air around Japan.
The Vela satellites which were operational until 1984, and currently the DSP satellites, are intended to give immediate reports of nuclear bomb detonation and ICBM launches.
The Vela satellites included gamma ray detectors, which accidentally discovered astronomical gamma-ray bursts (GRBs).
Since these satellites can detect ICBM launches from the ground and nuclear bomb detonation on the ground, and such detonations produce lots of radiation including gamma rays, and these satellites include gamma ray detectors, it would be easy for people to (incorrectly) jump to the conclusion that these satellites detect gamma rays emitted from the ground.
As dmckee and Martin Beckett pointed out, our atmosphere is far more than thick enough to convert practically all cosmic rays into gamma rays, and practically all gamma rays into visible light and muons.
That's why all gamma-ray telescopes and X-ray telescopes are designed to be placed outside the earth's atmosphere.
The gamma ray detectors on those satellites can't detect gamma rays emitted by things on the ground; apparently those detectors were originally designed to detect gamma rays emitted by nuclear bombs detonated in space.
(Has that ever happened?)
Stuff that happens on the ground is detected by the other sensors on those satellites.
As far as I can tell, satellites pretty useless for measuring radiation levels around nuclear reactors.
Radiation levels high enough for them to see (indirectly -- gamma rays converted to visible light) are also bright enough for humans to see, and only nuclear bomb detonation gives radiations levels that high.
The radiation levels that a damaged nuclear reactor could produce in a worst-case scenario -- lethal but not high enough to indirectly produce enough light for the human eye to see -- that light is also far too dim for these satellites to see.
Comment: There were [17 "high altitude nuclear explosions"](http://en.wikipedia.org/wiki/High-altitude_nuclear_explosion), some of them clearly "outside the atmosphere" for some purposes.
Comment: Airborne surveillance doesn't normally detect radiation as such, it filters radionuclides emitted from weapons tests (or reactor accidents) from the air. From the mix of isotopes it's possible to determine what kind of weapon was detonated, how long ago, and if you are lucky even the source of the fission material.
Comment: Vela was designed to detect the double flash and GRBs from nuclear detonations, not low level radiation emitted from earthly sources (or even leaking reactors). Those levels simply are too low to yield a detectable peak that's higher than background radiation at the altitude the satellite would orbit.
Comment: @mmc: Thank you, that's what I wanted to know. Apparently the last high altitude nuclear explosions occurred in 1962.
Answer: It doesn't make sense that satellites cannot detect radiation on the ground.  They can detect visible light which is far less penetrating than gamma radiation from a decaying radioisotope.  Remember, we are talking about MASSIVE amounts of radioactive isotopes in the atmosphere.  They have fingerprints, I'm confident, which can be detected from space.
Also, a huge portion of this radioactivity is at a high level in the atmosphere, which would logically make it EASIER to detect from space.
We have data ..... somebody does ... all the time.
Comment: The atmosphere is transparent to visible light, it isn't very transparent to gamma rays (fortunately). You can only detect radioisotopes at a distance if they emit something that reaches you. Alpha and Beta radiation don't travel far enough and it would be an unlikely radioisotope that got high enough into the atmosphere for its gamma ray emissions to reach a satellite - in any significant quantities.