How to reverse this algorithm to get back the original text?

Question: Can anyone please explain with the easy coding how to reverse this algorithm so that I get back the original text string?
Public Function CreateIntChecksum(ByVal s As String) As Integer
    Dim r As Integer = 0
    For i As Integer = 0 To (s.Length() - 1)
        Dim bchar As Byte = Convert.ToByte(s(i))
        r = bchar + ((r << 5) - r)
    Next
    Return r
End Function

Comment: @Charles Bailey Two words?
Comment: Two words: im-possible. You need to look up what a hash or checksum function is and it's purpose. In any case, there are more `String` values than `Integer` values so a reverse mapping is not possible.
Comment: @Tush: You already asked a *very* similar question, and you got a *very* similar answer: http://stackoverflow.com/questions/3539013/i-need-crc-reverse-code-for-my-crc64-checksum-coding-closed I'm sorry, but what you're asking for is just NOT possible. It's not because we don't *know* how to do this, or because we wouldn't *want* to tell you. It is because *there is no way to do what you're asking for*. It's like asking "I made orange juice out of an orange, now how do I reverse that?" You can't do that, and nobody else can, either.
Comment: It was a deliberate Goldwynism: http://en.wikipedia.org/wiki/Samuel_Goldwyn
Comment: The title of the following web page **is** two words. Do not settle for inferior two words. http://en.wikipedia.org/wiki/Pigeonhole_principle
Comment: @Piskvor - I love that analogy. Absolutely wonderful. XD.
Comment: It actually might be reversible if the input strings are very short or of a known set.
Answer: Although it is impossible to find the original text, it is possible find a preimage easily. The crucial point is
r = bchar + ((r << 5) - r)

which is equivalent to
r = bchar + r*31

Therefore, the hash encodes the string in base-31. To find a preimage, just rewrite the integer in base 31.
For instance, if the result is 3456, we know 3456 = 3 × 312 + 18 × 31 + 15, so one possible original text is "\x03\x12\x0f". Of course, we could rearrange the numbers to give 110 × 31 + 46 ("n.") or 109 × 31 + 77 ("mM") etc, which shows there is no unique preimage.
Comment: If anyone got a simple reversible algorithm?
Comment: I am totally new to these codes. Please give a coding.
Comment: That really like this answer. +1 for being awesome.
Answer:
how to reverse this algorithm so that I get back the original text string?

You can't, by design.
This is a (simple) checksum or hashing function.
Take a look at the size of the information going in and out: the function transforms a string s of arbitrary length into a 32-bit Integer. For each integer value there will be many input strings that will yield that result.

Edit: Apparently you want a shuffling algorithm. Maybe take a look at ROT13. Be advised this is not a (very) safe form of encryption.
Comment: I also need a formula based shuffling algorithm in c#. I was searching internet when I found this code. If anyone has such formula based shuffling which has reversing function too so that even if I shuffle a single text hundreds of times, it can be reversed.
Answer: You can't. What you have here is a Checksum, which is a basic hashing function. The the whole point of a hashing function is that it is irreversible. Hashing functions map a set of inputs (usually infinite) to a smaller set of outputs - so multiple inputs can end up with the same output, and thus this makes reversing a hash impossible (assuming the hash is correctly done). This is why they are used to store passwords - there is no way to read a hash and go "Oh, that is password XYZ".
One way of trying to find out the original value is to use a Rainbow Table. This is merely a massive table of inputs and their equivalent hashed (or in this case checksummed) values. If you have the hashed value of your unknown string you can search for it in the table and get the set of possible inputs. This is not a way to reverse a hash function, which is impossible; it is merely a brute force guessing method. Note also that in this case (assuming the hashing function is not biased) there are an infinite number of strings that match each checksummed value, as a visual basic string can be of arbitrary length. This would make a rainbow table for this very impractical - you could cover the set of probably inputs for a hashing (as most normal users won't enter more than a 10 character code), but nothing stops the user using a 67 character code, or 109, or...
Read the wikipedia articles for Hash Functions, Checksums and Rainbow Tables.
Comment: @Tush: And you don't seem to get the answers: 64 bits or 128 bits wouldn't solve the irreversibility problem here.
Comment: @Wes & Piskvor: Maybe I should have said "encode lossless". I think it is fairly obvious that you cannot decode an arbitrary length text from a fixed-length number. ;-)
Comment: +1 Note however, that with rainbow tables, it may be possible to read a hash and say "the string XYZ will hash to this, and so will infinitely many other (but probably dissimilar) strings". RT are basically a solution by brute force.
Comment: This is not a hashing function. I picked it up to find out if Reversing is possible. This is a bit-wise encoding function which outputs an integer through this algorithm. It might be reversible?
Comment: @Pisk: but that will only get you a colliding string, OK if you want a (equivalent) password but it is very unlikely a rainbow table will give you the original text.
Comment: @Tush: You have a checksum (= simple hash) function. The answer is No.
Comment: How should it be possible to encode an arbitrary length string into 32 bits?
Comment: @Eiko if you could bye-bye rar bye-bye zip. nearly every file on the computer would be 32 bits.
Comment: @Henk Holterman: That's what I was trying to say - you'll get something which could have been the original string, but there isn't a way to find out. Sorry if it wasn't clear enough. (For many intents and porpoises, this is sufficient; plus it's more likely that the RTs will be made from the [a-zA-Z0-9] space, so the colliding string has some propability of being meaningful)
Comment: 64 Bits? Can anyone code for me?
Comment: @Eiko: Oh, you can *encode* it all right, see the OP's algorithm. The problem lies in the decoding - you'll have many strings (countably infinite, to be precise), of various lengths and content - and *all* fo them will correctly map to the same integer. There's the problem - you can not find out which of the inputs was encoded into the output.
Comment: @Tush - use a [Long](http://msdn.microsoft.com/en-us/library/y595sc15(v=VS.80\).aspx), which is 8 bytes (64 bits) instead of an Int, which is 32 bits?
Comment: What is OP's algorithm, please provide sample in c# if possible. I require a reversible formula based shuffle algorithm which is able to shuffle, then reverse the text string. It would be nice of you to help me now. :-)
Comment: I am learning. Please provide a sample for 64 bits reversible algorithm in c#.
Comment: @Tush - That's both a rude question (questions of the type "Plz I can has code now?" are considered rude - we are here to **help**, not to write your code for you), and a different question from what you asked here. You should mark an answer for this question (choose the best given answer and click on the outline of the tick beside it), and then open a new question to ask about your shuffling and reversing of text strings in C#.
Comment: @Tush: You are the OP (Original Poster) here.
Comment: @Eiko My comment was actually meant to support yours not contradict you.
Comment: It is all right :-) Nothing bad should matter.
Comment: Long String Text may or may not be crushed and compressed into hash kind of ascii "checksum" by using sophisticated mathematical formula/algo. To compress megabytes of asci text into a 128 or so bytes. When we are decompressing it, the last character is extracted first, then we just go on decompression using the formula and the sequential keys. This is the terra compression I was thinking about.
Answer: You simply can't reverse it. It's a checksum which is not reversible.
Answer: You can't. If nothing else, then simply because Integer contains only 32 bits of data and String can have any length.
Comment: @Tush: Hmm, that's quite a different question, IMO. Try asking for that in a new question - something like "I wish to have a reversible encryption algorithm for a fixed string length, which one is good for my situation" and describe your use case (for what you need the encryption, what you need to protect against, etc.). I'd say this should get you some answers.
Comment: @Tush no. Unfortunatly not. What is it you want reversible encryption?
Comment: @Piskvor +1
@Tush consider this an upvote to asking a new question.
Comment: Do you agree that if I use 64 Bit Integer, will I get back any fixed length of string by reversing?
Comment: Yes. I am learning and weak in mathematics. I wish to have fixed string length = fixed reversible encryption algorithm.
Comment: @Wes: The question seems to be already asked, as of 5 hours ago: http://stackoverflow.com/questions/3541378/dont-know-how-to-code-reversible-shuffle-algorhythm-by-using-key-anyone-can-hel
Answer: First of all the code as posted will throw an exception for anything but the shortest of strings.
The following code includes the OP's original code, plus a simple checksum, and a guess at how the checksum might be used.
Private Sub Button2_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button2.Click

    Dim buffer() As Byte

    Dim tstString As String = "Calculate a checksum for a given string"

    Dim chkSumFix As Integer = CreateIntChecksumFixed(tstString) 'get a checksum

    buffer = SendPacket(tstString, chkSumFix) 'create a byte buffer to send
    tstString = decodePacket(buffer)

    'do the same using the OP's original code
    Dim chkSum As Integer = CreateIntChecksum(tstString) 'error

    buffer = SendPacket(tstString, chkSum)
End Sub

'OP
Public Function CreateIntChecksum(ByVal s As String) As Integer
    Dim r As Integer = 0
    For i As Integer = 0 To (s.Length() - 1)
        Dim bchar As Byte = Convert.ToByte(s(i))
        r = bchar + ((r << 5) - r)
    Next
    Return r
End Function

'a very simple checksum
Public Function CreateIntChecksumFixed(ByVal s As String) As Integer
    Dim r As Integer = 0
    For i As Integer = 0 To (s.Length() - 1)
        Dim bchar As Byte = Convert.ToByte(s(i))
        r = (r And &HFFFF) + bchar
    Next
    Return r
End Function

Private Function SendPacket(ByVal aString As String, _
                            ByVal aChecksum As Integer) As Byte()
    'construct a packet to be sent
    'Packet format
    'returns a byte buffer
    'byte(0 -3) = length of original string - use BitConverter.ToInt32 to extract
    'byte(4-n) = original string.  n = (4 + string length) - 1
    'byte(n + 1, n + 2, n + 3, n + 4) = checksum

    Dim length As Integer
    Dim retV As New List(Of Byte)
    retV.AddRange(System.Text.Encoding.ASCII.GetBytes(aString)) 'add string to packet
    length = retV.Count 'get length - use this length in case a different encoding is used
    retV.AddRange(BitConverter.GetBytes(aChecksum)) 'add checksum
    retV.InsertRange(0, BitConverter.GetBytes(length)) 'insert length at start of packet

    Return retV.ToArray
End Function

Private Function decodePacket(ByVal buffer As Byte()) As String
    Dim sLen As Integer = BitConverter.ToInt32(buffer, 0)
    If sLen + 8 <> buffer.Length Then Throw New ArgumentOutOfRangeException

    Dim s As String = System.Text.Encoding.ASCII.GetChars(buffer, 4, sLen)

    Dim chksum As Integer = CreateIntChecksumFixed(s)

    Dim embeddedChecksum As Integer = BitConverter.ToInt32(buffer, sLen + 4)

    If chksum <> embeddedChecksum Then Throw New ArgumentException("Invalid checksum")
    Return s
End Function

Comment: And why exactly does a simple statement of fact deserve a down vote?
Comment: This leads to a new thought.. If the string is sufficient short enough, it actually *might* be reversible. :-)
Not sure why it should throw an exception - do overflows generate exceptions in vb.net?
Comment: As has been pointed out, the code appears to be used to generate a checksum (name of the function, code).  I will edit my post with the code and intended purpose(guess).
Comment: There are bugs in the above coding. Multiple Invalid characters are added in the left and right corners of the reversed string thereby making the reversed string corrupted. The string gets reversed though. Please fix the bugs so that the code becomes useful.
Comment: I guess 64 bit UInt64 integer can hold 8 bytes of integer. So if you can provide the coded function for 64 Bit and not integer.
Comment: @tush - I am lost?  The original string (assumed to be ascii) is not touched.
Comment: Added the code in place to decode the packet and check the checksum.
Comment: Thanks, now the code is working without corruption of output string upon reversing. I must ask if it is possible to encode the input ascii string into only one 64 bit integer, by using a formula/algo and a key/password? That I was asking for in here. Because if that is possible, string would just be crushed into the 64 bit integer. Thanks.


asp.net core 1.1 antiforgery with angular 2/4

Question: I am trying to implement antiforgery token on asp.net core 1.1 with angurl 2/4 cli but everytime when I use "ValidateAntiForgeryToken" system giving me 400 Bad request error.
in asp.net startup.cs I have use
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

app.Use(async (context, next) =>{
 await next();
 string path = context.Request.Path.Value;
 if (path != null && !path.ToLower().Contains("/api"))
 {
      var tokens = antiforgery.GetAndStoreTokens(context);
      context.Response.Cookies.Append("XSRF-TOKEN",
       tokens.RequestToken, new CookieOptions{HttpOnly = false});
 }

 if (context.Response.StatusCode == 404 &&
     !Path.HasExtension(context.Request.Path.Value))
 {
     context.Request.Path = "/index.html";
     context.Response.StatusCode = 200;
     await next();
 }
});

in angular app.module.ts I am using something like
provider:[{ provide: XSRFStrategy, useFactory: xsrfFactory}],

export function xsrfFactory() {
    return new CookieXSRFStrategy('*******', '********');
}

Answer: Is this guide helpful? http://www.dotnetcurry.com/aspnet/1343/aspnet-core-csrf-antiforgery-token
public class AngularAntiforgeryCookieResultFilter: ResultFilterAttribute
{
    private IAntiforgery antiforgery;
    public AngularAntiforgeryCookieResultFilter(IAntiforgery antiforgery)
    {
        this.antiforgery = antiforgery;
    }

    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is ViewResult)
        {
            var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
            context.HttpContext.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
        }
    }
}

services.AddAntiforgery(opts => opts.HeaderName = "X-XSRF-Token");
services.AddMvc(opts =>
{
    opts.Filters.AddService(typeof(AngularAntiforgeryCookieResultFilter));
});
services.AddTransient< AngularAntiforgeryCookieResultFilter >();

Comment: I have tried this but I think my angular part is not configured properly as I have tried setting header "X-XSRF-Token" and still webapi giving me 400 error.
Comment: Can you try to make a test request with jQuery? Make sure server side works correctly.
Comment: I am sorry for late reply I have tried to make request thru jquery but still I am getting same error it seems like I haven't configured it properly..
Comment: Then you need to make the server side work right first.
Comment: so now my antiforgery is working only when I remove authorize
Comment: Please see 'Protecting controller actions' in the guide. It's not using authorize strategy.


Angular ng-repeat inside directive view

Question: I'm trying to do a ng-repeat inside the view returned by a directive.
Here is my template defined in templateUrl

        {{ cup.nombre }}
        cupcakes.nombre
        {{ cup }}
        cupcakes

    {{ copas[0].nombre }}
    {{ copas }}

The content inside "inside" class is empty, while the content at the bottom of outside class is correct.
What am I missing?
thank you
Answer: It should be cup in copas for your ngRepeat expression:

        {{ cup.nombre }}
        cupcakes.nombre
        {{ cup }}
        cupcakes

    {{ copas[0].nombre }}
    {{ copas }}

Angular ng-repeat inside directive view


Does this small clamp have a special use?

Question: I have this small clamp - its about 2" / 5 cm tall:

I'm not sure where it came from so I don't know what its for. Note the pin on the right side which is removable - I assume this is to allow something to fit in the clamp from the side?
I suppose it could be more of a press than a clamp but I don't think you could get much pressure given the small size of the main knob.
Searching for terms like "castaloy small clamp" returns lots of hits but nothing that seems to match this particular tool.

Update - thanks to Solar Mike's answer I was able to locate the exact clamp, apparently still made which is a "Fisherbrand Castaloy Hosecock Clamp" from Fisher Scientific, with the description

Fine-machined adjustment screw for very accurate regulation of flow

Neat!
The keyword that made the difference was "tube" which was critical to locating it since nothing about the clamp was obvious to me to have anything to do with tubing.
Answer: That style of clamp can be or has been used to compress or close soft tubes or pipes in many situations like drip feed water supply to plants as a simple example.
Comment: Hosecock clamp.+
Comment: I have very similar clamps for aquarium air hose control. The name "castaloy" sounds familiar for lab equipment.
Comment: Found Fisher Scientific has a  line of miscellaneous laboratory clamp type items under the name "castaloy".


Matlab Syntax for Symbolic Solving

Question: I have a symbolic equation equation like
i = 1:n (i=1...n) it takes random values.
G_i = B_i + C_i * D_i  and I have B_i, G_i C_i and D_i equaling to some constraints.
I have to simplify a such equation through matlab.
I used 'syms' to define each symbol but I don't know how to define that 'i' indices.
Also, my second question is if I want to change it to summation format (symsum) where i=1...n how can I write the code for to simplify given some constraints. Any example can be useful for me to understand.
Answer: What you want to do is create an array of symbolic values: Matlab docs show how to do this for A, I'll leave it up to you to do the rest.
A = sym('A',dim)

Then you could do something like:
G(i)=b(i)+c(i)*d(i)

Comment: Let me also add that A = sym('A',dim) code doesn't work for Matlab R2009b or lower version. Symbolic Math Toolbox should have a version higher than 5.4
Comment: Thank you first of all. So, what I'll do basically is define each symbol such as G = sym('G', [1 n]) and same thing for B, C and D.

Matlab Syntax for Symbolic Solving


In PHP 5.2 why is instantiating a class and calling a method on the same line invalid?

Question: This is what I'd like to do:
$app = (new Factory())->GetApp();

However, I get an "unexpected T_OBJECT_OPERATOR" error.
To avoid this, I have to do:
$Factory = new Factory();
$app = $Factory->GetApp();

Why is this necessary?  I'm running PHP 5.2 if it makes any difference.
Answer: A slightly tautological answer, but it's because that's not supported in PHP 5.2.
However, it is in PHP 5.4 - see http://www.php.net/manual/en/migration54.other.php

Added class member access on instantiation (e.g. (new foo)->bar())
  support
Answer: You could also do something like this:
class MyClass {

  public static function init(){
    return new self();
  }

  ....

}

which you can then use like this:
MyClass::init()->doStuff()->Whatever();

which is in my eyes a bit nicer, than using the
(new Myclass())->doStuff()->Whatever();


Why content is not same after parsing with Jsoup

Question: I am trying to parse this url using JSOUP. I am getting parsed doc something like unicode format not the actual data while I am parsing this url gives me proper hindi text as desired. I am using below code to parse URl. BTW url is hosted on my site. Is there any problem with text file on server? I am not able to figure this out.
    Document doc = Jsoup
            .connect(
                    "hindi-stories.kratav.com/content/social_aalha.html")
            .userAgent("Mozilla").timeout(15 * 1000).get();

Answer: I you check the source code of the first URL, there is no encoding specified. whereas the second has a meta:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Try to parse the first URL using a method specifying the charset, i.e:
Document document = Jsoup.parse(new URL(url).openStream(), "UTF-16", url);

Comment: I tried and getting same result.
Comment: Insteed of ISO-8859-1 UTF-16 worked thanks Man
Comment: great. I updating the answer accordingly.


Create Element With EventListener Dynamically in JavaScript

Question: Hi I am struck with this problem.
I need to create a table with Onclicklisteners dynamically. so i prefered this way.

function create_weekmenu(json)
  {
      var column_list=json.week_list;
      var menu_table=document.getElementById("weekmenu");
      var row=document.createElement('tr');
      for(var i=0;i<column_list.length;i++)
      {
        var cell=document.createElement('th');
        var span_ele=document.createElement('span');
        if(span_ele.addEventListener)
        {
          span_ele.addEventListener('click', toggletable(column_list[i]),true);
        }
        else if(span_ele.attachEvent)
        { // IE < 9 :(
          span_ele.attachEvent('onclick', toggletable(column_list[i]));
        }
        span_ele.appendChild(document.createTextNode(column_list[i]))
        cell.appendChild(span_ele);
        row.appendChild(cell);
     }
     menu_table.appendChild(row);
  }

The Resultant element Structure I am getting is

       week_one

      week_two

But i need a Element Structure like this,

              week_one

              week_two

Further to notice: I could see that the onclick listener is triggering while creating the element. but its not binding with the element permanently.
What would be the solution.
I prefered to construct DOM structure using appendChild() than by .innerHTML or document.write().
Comment: I'm not sure if I understand you right. But registering a `click` listener with `addEventListener`/`attachEvent` would not create an `onclick="toggle(week_one)'` on the element, why do you need it that way?
Answer: The problem is that you're calling the toggleTable function when you attach it. That's why it's being triggered when you create the element.
span_ele.addEventListener('click', toggletable(column_list[i]),true);

To avoid that it should be:
span_ele.addEventListener('click', toggletable, true);

But obviously that doesn't pass in the column to toggle so it's not ideal.
I would use something like:
function create_weekmenu(json)
  {
      var column_list=json.week_list;
      var menu_table=document.getElementById("weekmenu");
      var row=document.createElement('tr');
      for(var i=0;i<column_list.length;i++)
      {
        var cell=document.createElement('th');
        var span_ele=document.createElement('span');
        if(span_ele.addEventListener)
        {
          span_ele.addEventListener('click', function(col) {
            return function() {
              toggletable(col);
            }
          }(column_list[i]),true);
        }
        else if(span_ele.attachEvent)
        { // IE < 9 :(
          span_ele.attachEvent('onclick', function(col) {
            return function() {
              toggletable(col);
            }
          }(column_list[i]));
        }
        span_ele.appendChild(document.createTextNode(column_list[i]))
        cell.appendChild(span_ele);
        row.appendChild(cell);
     }
     menu_table.appendChild(row);
  }

You need to make sure you attach a function to the event handler, not the result of a function.
Comment: Thank you so much... :) 50+ for u.. ll accept once i set bountry to u
Answer: function create_weekmenu(json) {
    var column_list = json.week_list;
    var menu_table = document.getElementById("weekmenu");
    var row = document.createElement('tr');
    for (var i = 0; i < column_list.length; i++) {
        var cell = document.createElement('th');
        var span_ele = document.createElement('span');
        span_ele.setAttribute('onclick', 'toggletable(column_list[' + i + '])');
        span_ele.appendChild(document.createTextNode(column_list[i]))
        cell.appendChild(span_ele);
        row.appendChild(cell);
    }
    menu_table.appendChild(row);
};

Comment: This one of the worst ways how this can be achieved.


Image loader isn't displayed

Question: I want to display a background image (loading.gif) while the image is loading. The image loads thanx to the following code :
var item = $('

');
var img = item.find('img');
img
    .hide()
    .one('load', function() { $(this).removeClass('loading').attr('alt', data.title).attr('width', data.width).attr('height', data.height).fadeIn(); })
    .attr('src', data.src)
    .each(function() { if (this.complete) $(this).trigger('load'); });

So there's a "loading" class added to the image at the beginning, and then this class is removed once the image is entirely loaded (and displayed). So the CSS code is :
.loading { background: #FFF url(../img/loading.gif) center center no-repeat; }

The trouble is : the image is loaded, and then it's displayed, BUT the loader is never displayed while the image is loading (this can be seen here).
I thought I should delete the ".hide()"... but then I think the image will be partly displayed BEFORE it's entirely loaded, won't it ???
Thanx for your help !
Comment: Load the img first (with new image), then append it. That way, you can display a spinner while loading.
Comment: Sorry, but I don't understand what I should change precisely...
Comment: Well, if you create an image, load it then append it, you don't have to hide the , so you can display the spinner. Other solution : add the spinner in another element with some CSS.
Comment: So could I only change the last part, like this ? img.one('load', function() { $(this).attr({src: data.src, alt: data.title, width: data.width, height: data.height}).fadeIn(); }).attr('src', '../img/loading.gif').each(function() { if (this.complete) $(this).trigger('load'); }); Would this be fine ???
Comment: You calling each when you have only one element.
Comment: That's because I've been told that the ".load" function sometimes isn't triggered as it should...
Answer: It's because you hide it when it's loaded
var item = $('

');
var img = item.find('img');
$('').attr('src', data.src).load(function() {
      img.removeClass('loading').attr('src', data.src).hide().fadeIn();
});

Comment: But this whole thing look like it belong to the loop over data `for (var i in result) { var data = result[i]; ...`
Comment: It's not the same, you have hiden (Outside the DOM) image, and you attached load event to it (so it's executed when it's loaded) and main (visible) image is changed when this hidden is loaded. And your code add src to hidden element. If you hide something it will be hidden ;)
Comment: Mmm... not sure to understand (sorry, I'm far to be a pro as you can see) : shouldn't it be `img.attr etc.` instead of `$('').attr etc.` ?
Comment: It's different element, new one, which have load attached. It's not displaying on the page you set img.attr when this hidden image is loaded. 2 images.
Comment: So, let me see if I understand well what you mean : is the following code correct ? $('')
 .one('load', function() { img.removeClass('loading').attr({src: data.src, alt: data.title, width: data.width, height: data.height}).fadeIn(); })
 .attr('src', data.src)
 .each(function() { if (this.complete) $(this).trigger('load'); });
Comment: Why you have this `.each(function() { if (this.complete) $(this).trigger('load'); });` you have only one element and load will be triggered when image is loaded. Just remove it.
Comment: As I said above: I've been advised to do this, because I've been told that the ".load" function sometimes isn't triggered as it should (can't remember if it was on Safari or Chrome)... Anyway, the rest of the code is correct ?
Comment: I never have problems with load. and load method it's jQuery thing so they probably fix the issue with browser bugs.
Comment: OK. That's what I thought too... Thanx very much for your help !
Comment: Mmmm... In fact, I've applied it to my page (link in my first post), and it doesn't work : the loader is still never applied... Now I don't understand why ?!
Comment: it work for me in Chrome. but probably should try on slower connection. You can try to preload the loader, maybe it isn't loaded when images are loading, try to add  at the begining of the page.
Comment: Yes, it was just a CSS problem. Thank you very much for your help !
Answer: window.onload = function()
{ document.getElementById("loading").style.display = "none"; }

Image loader isn't displayed


Association named 'echo_producer_apis' was not found on EchoProducerApi; perhaps you misspelled it?

Question: I think I am doing some naming error so please help me out...!!
class EchoProducerApi < ActiveRecord::Base
  has_one :echo_practice_api
end

class EchoPracticeApi < ActiveRecord::Base
  belongs_to :echo_producer_apis
end

@producer_data = EchoProducerApi.joins(:echo_producer_apis).select("echo_practice_apis.*,echo_producer_apis.*").paginate(:page => params[:page] , :per_page => 10)

Answer: Change
belongs_to :echo_producer_apis

to
belongs_to :echo_producer_api

With belongs_to :echo_producer_apis, Rails will look for a class name called EchoPracticeApis, but you have EchoPracticeApi. That's why it is not working. Change to the association name will fix it.
Note: Generally association name for belongs_to and has_one should be a singular.
Answer: Remember Rails relationships and associations are self-explanatory. belongs_to essentially means that an instance of your object belongs_to only one object of other class, therefore you should specify it as a singular value. Hence you should change from:
class EchoPracticeApi < ActiveRecord::Base
  belongs_to :echo_producer_apis
end

To:
class EchoPracticeApi < ActiveRecord::Base
  belongs_to :echo_producer_api
end

Comment: after changing the code
Unknown key: :foregin_key. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :dependent, :primary_key, :inverse_of, :required, :foreign_type, :polymorphic, :touch, :counter_cache
Comment: class EchoPracticeApi < ActiveRecord::Base
 belongs_to :echo_producer_api, :foregin_key => 'practiceTypeID'
end
Comment: in echo_practice_api table I have a column practiceTypeID_id
Comment: Please carefully read the error message. It has your answer. Spelling of foregin_key is wrong. It should be foreign_key
Comment: Actually I have posted wrong question sorry..I have corrected the foreign_key issue .. but after that  get another MySQL error/
 .My question is
(I am new to rails )
 Mysql2::Error: Unknown column 'echo_practice_apis.echo_producer_api_id' in 'on clause': SELECT  echo_practice_apis.*,echo_producer_apis.* FROM `echo_producer_apis` INNER JOIN `echo_practice_apis` ON `echo_practice_apis`.`echo_producer_api_id` = `echo_producer_apis`.`id` LIMIT 10 OFFSET 0
Comment: Your model that has belongs_to should have the foreign_key of the association table. In your case `echo_practice_apis` should have a column named `echo_producer_api_id`


StringIndexOutOFBoundsException: 0

Question: I am a relative beginner to Java and am having an issue with a user controlled do-while loop that accepts user input to repeat. Here is the code at the end of the loop.
System.out.print("Do you wish to continue? (Y for yes " +
                            "/ N for no)");
        input = keyboard.nextLine();
        input.length();
        repeat = input.charAt(0);

        }while (repeat == 'Y' | repeat == 'y');

I know it's throwing the exception because of the value, but can't figure out what to do to fix it, as I'm sure it's relatively simple. Thanks for the help.
Edit 1:
Stacktrace:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at FractionTest.main(FractionTest.java:59)

Comment: Looks like you read empty line.
Comment: Sorry I left the stacktrace out. Here it is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
 at java.lang.String.charAt(Unknown Source)
 at FractionTest.main(FractionTest.java:59)
Comment: possible duplicate of [IndexOutOfBoundsException when taking character input from the user](http://stackoverflow.com/questions/27619851/indexoutofboundsexception-when-taking-character-input-from-the-user)
Comment: Post stacktrace inside question. It is unreadable as comment. To do so use [edit] option.
Answer: It looks like you read empty line which returned you empty string "" so there is no characters there (not even 0th).
It usually happens when you are using nextLine right after other nextABC methods like nextInt since such methods doesn't consume line separators, and nextLine reads text until next line separator (or end of stream).
In that case you can add nextLine after that nextInt to consume line separator.
Anyway to avoid reading character from empty string and exception you can use something like
} while (input.toLowerCase().startsWith("y"));

instead of
    input.length();//this actually doesn't change anything, you can remove it
    repeat = input.charAt(0);

} while (repeat == 'Y' | repeat == 'y');

Comment: I added the above if statement and it's still throwing the same exception.
Comment: @Steve I updated my answer to add alternative way of skipping this error, and probable cause of getting empty string.
Answer: As @Phesmo mentioned you may be getting a 0-length line. This is an obscure problem. Have you called nextInt(), nextLong(), nextShort(), nextByte(),  or nextBoolean() on the Scanner before calling nextLine()?

Try this
System.out.print("Do you wish to continue? (Y for yes / N for no)");

char ans;
do {
   ans = keyboard.next().charAt(0);
   // filter input
} while (ans == 'Y' || ans == 'y' || ans == 'N' || ans == 'n');

repeat = ans;

} while (repeat == 'Y' | repeat == 'y');

From documentation:

String Scanner#next()
  Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

Or this
System.out.print("Do you wish to continue? (Y for yes / N for no)");
repeat = keyboard.next("[YyNn]").charAt(0);

} while (repeat == 'Y' | repeat == 'y');

From documentation:

String Scanner#next(String pattern)
  Returns the next token if it matches the pattern constructed from the specified string.

"[YyNn]" is a character class pattern, it means match any character from the set.
Comment: ++ for idea of using `next` instead of `nextLine` (but you could add more info about why you wanted to use it here)
Comment: This fixed the exception issue. Thanks naXa. I have never seen that format for an input argument to cover all the possible inputs.
Comment: @Steve, it's an advanced topic. If you want to know more, read about regular expressions.

StringIndexOutOFBoundsException: 0


raytracing with CUDA

Question: I'm currently implementing a raytracer. Since raytracing is extremely computation heavy and since I am going to be looking into CUDA programming anyway, I was wondering if anyone has any experience with combining the two. I can't really tell if the computational models match and I would like to know what to expect. I get the impression that it's not exactly a match made in heaven, but a decent speed increasy would be better than nothing.
Comment: Just a pointer to [my open-source, portable (Windows/Linux) GPL implementation of a CUDA raytracer](http://users.softlab.ntua.gr/~ttsiod/cudarenderer-BVH.html).
Answer: One thing to be very wary of in CUDA is that divergent control flow in your kernel code absolutely KILLS performance, due to the structure of the underlying GPU hardware.  GPUs typically have massively data-parallel workloads with highly-coherent control flow (i.e. you have a couple million pixels, each of which (or at least large swaths of which) will be operated on by the exact same shader program, even taking the same direction through all the branches.  This enables them to make some hardware optimizations, like only having a single instruction cache, fetch unit, and decode logic for each group of 32 threads.  In the ideal case, which is common in graphics, they can broadcast the same instruction to all 32 sets of execution units in the same cycle (this is known as SIMD, or Single-Instruction Multiple-Data).  They can emulate MIMD (Multiple-Instruction) and SPMD (Single-Program), but when threads within a Streaming Multiprocessor (SM) diverge (take different code paths out of a branch), the issue logic actually switches between each code path on a cycle-by-cycle basis.  You can imagine that, in the worst case, where all threads are on separate paths, your hardware utilization just went down by a factor of 32, effectively killing any benefit you would've had by running on a GPU over a CPU, particularly considering the overhead associated with marshalling the dataset from the CPU, over PCIe, to the GPU.
That said, ray-tracing, while data-parallel in some sense, has widely-diverging control flow for even modestly-complex scenes.  Even if you manage to map a bunch of tightly-spaced rays that you cast out right next to each other onto the same SM, the data and instruction locality you have for the initial bounce won't hold for very long.  For instance, imagine all 32 highly-coherent rays bouncing off a sphere.  They will all go in fairly different directions after this bounce, and will probably hit objects made out of different materials, with different lighting conditions, and so forth.  Every material and set of lighting, occlusion, etc. conditions has its own instruction stream associated with it (to compute refraction, reflection, absorption, etc.), and so it becomes quite difficult to run the same instruction stream on even a significant fraction of the threads in an SM.  This problem, with the current state of the art in ray-tracing code, reduces your GPU utilization by a factor of 16-32, which may make performance unacceptable for your application, especially if it's real-time (e.g. a game).  It still might be superior to a CPU for e.g. a render farm.
There is an emerging class of MIMD or SPMD accelerators being looked at now in the research community.  I would look at these as logical platforms for software, real-time raytracing.
If you're interested in the algorithms involved and mapping them to code, check out POVRay.  Also look into photon mapping, it's an interesting technique that even goes one step closer to representing physical reality than raytracing.
Comment: maybe time to update this. it was fun reading 10 years later and with nvidia doing all gpu raytracing
Answer: It can certainly be done, has been done, and is a hot topic currently among the raytracing and Cuda gurus.  I'd start by perusing http://www.nvidia.com/object/cuda_home.html
But it's basically a research problem.  People who are doing it well are getting peer-reviewed research papers out of it.  But well at this point still means that the best GPU/Cuda results are approximately competitive with best-of-class solutions on CPU/multi-core/SSE.  So I think that it's a little early to assume that using Cuda is going to accelerate a ray tracer.  The problem is that although ray tracing is "embarrassingly parallel" (as they say), it is not the kind of "fixed input and output size" problem that maps straightforwardly to GPUs -- you want trees, stacks, dynamic data structures, etc.  It can be done with Cuda/GPU, but it's tricky.
Your question wasn't clear about your experience level or the goals of your project.  If this is your first ray tracer and you're just trying to learn, I'd avoid Cuda -- it'll take you 10x longer to develop and you probably won't get good speed.  If you're a moderately experienced Cuda programmer and are looking for a challenging project and ray tracing is just a fun thing to learn, by all means, try to do it in Cuda.  If you're making a commercial app and you're looking to get a competitive speed edge -- well, it's probably a crap shoot at this point... you might get a performance edge, but at the expense of more difficult development and dependence on particular hardware.
Check back in a year, the answer may be different after another generation or two of GPU speed, Cuda compiler development, and research community experience.
Comment: Are you certain it is an embarrassingly parallel problem? Solving to find the next object of reflection and variations in material handling (as pointed out by Matt J) seem like they might break parallelism significantly. But please correct me if I am wrong.
Comment: I have a small project building my first raytracer and have never done any CUDA work so I'm in a poor position to make anything great, but over the next year I'm working with GPGPU technology. This leads me to get familiar with CUDA and I was wondering to which extend I can use this knowledge.

raytracing with CUDA


having trouble with loops in java

Question: im working on seeding a procedural generated map but when i go to run it it just does work in the background when it is supposed to show a map with different colored squares. The method i need help with picks a few random locations on the map and assigns a random type as a starting point.
here is the entire method
public void seed(){//seeds the map
double seedNum = (mapWidth*mapHeight*.02);//determine number of seed positions needed
if((int)seedNum < 1){//will always seed at least 1 square
  seedNum = 1;
}

int seedListX[]= new int[(int)seedNum];//list of seeded coordinates to check for dupilcates
int seedListY[]= new int[(int)seedNum];

int seedX = (int)Math.random()*mapWidth;
int seedY = (int)Math.random()*mapHeight;
seedListX[0] = seedX;
seedListY[0] = seedY;

for(int i =1; i < (int)seedNum; i++){
  int error = 0;
  seedX = (int)Math.random()*mapWidth;
  seedY = (int)Math.random()*mapHeight;
  seedListX[i] = seedX;
  seedListY[i] = seedY;

   for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
    if(seedX == seedListX[j] || seedY == seedListY[j]){
      error = 1;
    }
  }

  int type = (int)Math.random()*5+1;//choose random type

  if(error != 1){
    this.setType(seedX,seedY,type);
  }else{
    i--;
  }//end inner loop
}
}//end outer loop

I tested the code and it worked fine once I removed this block
for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
    if(seedX == seedListX[j] || seedY == seedListY[j]){
      error = 1;
    }
  }

  int type = (int)Math.random()*5+1;//this line is fine

  if(error != 1){
    this.setType(seedX,seedY,type);
  }else{
    i--;
  }//end inner loop

Im sure its an infinite loop but i am not seeing it, any help is gratefully appreciated.
Comment: check the closing brackets of the loop
Comment: also when i run it without the smaller code block it always sets the very first square to type 1, any idea why?
Answer: This is happening everytime
else{
  i--;
}

so the for loop will never increment and finish
Maybe when you do (occurs everytime so check that i != j)
error = 1;

you want to break
Answer: for(int j = 0; j < seedNum;j++){//goes through seed coordinates list to check for duplicates
    if(seedX == seedListX[j] || seedY == seedListY[j]){
      error = 1;
    }
}

For i == j the condition will always yield true(because seedX == seedListX[i] and seedY == seedListY[i]) - you are colliding with yourself...
Also, you really shouldn't check for collisions with seed coordinates you haven't filled yet.
Let's say seedNum = 2. First iteration you create the first seed:
i: 0
seedListX: [12, #JUNK#]
seedListY: [34, #JUNK#]
seedX: 12
seedY: 34

Now, in the first iteration of the inner loop:
j: 0
seedListX[j] == seedListX[0] == 12 == seedX
seedListY[j] == seedListY[0] == 34 == seedY

The problem is clear - you are comparing the first coordinate with the first coordinate - of course they will collide!
But - there is another problem. Let's look at the second iteration of the inner loop:
j: 1
seedListX[j] == seedListX[1] == #JUNK#
seedListY[j] == seedListY[1] == #JUNK#

#JUNK# will happen to be 0, because that's how Java initializes things, but it's still a junk - it contains an arbitrary(although determinant) value, not the actual coordinate of the second seed(which was not yet created!)
You should only check collisions with seeds created in the previous iterations:
for(int j = 0; j < i; j++) { //...

having trouble with loops in java


Alternative to toggle bolt for toilet roll holder?

Question: My toilet roll holder comes off the wall every 6-12 months. Regular plastic anchors aren't helping much.
I saw that toggle bolts are a great option, but I only have about 1.5" of depth to work with, and can't find any toggle bolts shorter than 2".
Aside from the asking the hardware store to cut them down for me, are there any recommendations for this scenario please?
Comment: "*but I only have about 1.5" of depth*"  What kind of wall is the TP holder attached to that only has 1.5" of depth? I use these anchors https://www.lowes.com/pd/TOGGLER-2-Pack-Assorted-Length-x-1-4-in-Dia-Toggle-Bolt-Drywall-Anchor-Screws-Included/3183821  overkill for a TP holder but it will never come off by itself.
Comment: Indeed, what is the wall? I'd consider opening up a section of wall between studs (assming there are studs) and placing a solid wood board there, then finishing over that, to provide a solid base. Having been through a few rounds of "people getting older" I'd look to mount a grab handle solidly as well while I was at it. If a masonry wall, I'd look to lead anchors.
Comment: Until we get more info from the OP  then we can not really provide an informed answer.
Comment: @alaskaman thank you all for the comments. It is dry wall, I believe, but there isn't a significant amount of space between this wall and the outside brick wall. Pardon me for not being any more certain. At this point, I am looking at Hollow Wall Anchors, any thoughts on those please?
Comment: you can't make the toggle bolts any shorter than half the wingspan+thickness of wings + thickness of wall + thickness of holder's eylets; otherwise the wings won't ever "flap out"...
Comment: Actually, now I am thinking that maybe the Cobra Walldriller #6 might work best. #8 is exactly 1.5" so I'm worried it won't quite fit. Any thoughts on those please?
Comment: "Regular plastic anchors" don't work in drywall for anything more than a small picture frame. Use proper drywall anchors - you'd know if you're using "proper" drywall anchors if the drywall gets torn apart with the anchors if they're pulled out.
Comment: have you tried the larger screw in drywall anchors?
Answer: Mount the holder to the center of a notebook size piece of wood, sort of like a thin cutting board. Then mount the wood panel to the wall with a screw in each corner. If you like, you can add a bit of glue/adhesive.
Comment: The wood can be stained or painted any color to blend with the wall.
Comment: That sounds like a good idea. For now, I think my partner wouldn't be too keen on it aesthetically. I may have to come back to this in the future tho if all else fails. Thank you, John.
Answer: How about an off-the-wall suggestion -- have you ever seen a TP pedestal?  We just bought a new house and I was thinking about how to mount new TP holders when I saw this new(?) pedestal thingy.  Sits on the floor and holds a roll or three.
We got one for each bath and I love 'em.  Didn't have to get any wall dust on my hands.
Search for "pedestal TP holder" or the like.
Comment: That's not a shabby idea, thank you. Unfortunately, there isn't much room to put one of those. Thanks tho.
Answer: 40mm mollys tick all the boxes,  good pull strength, short length, resistant to vibrations.
Comment: this  idiom: https://www.yourdictionary.com/tick-all-the-boxes
Comment: "tick all the boxes"  What's this??
Comment: Well what do you know about that...  learn something new everyday on this site.
Comment: thank you, that's very helpful. I am having a heck of a time finding out what 40mm translates to tho. All I see are notations such as #8 or 1/8S, etc. Any idea what might be the equivalent please? Perhaps it's noted differently in Canada where I am? :)
Comment: 40mm is the over-all length - about 1.5"  I saw some that were 1.25" on amazon but you had to buy 100
Comment: pardon me, Jasen. What I mean is that when I look for these online, they are never listed with the length (neither mm nor inches). It's always just something cryptic like "#8" or "1/8S". I know that means something to some people, but to someone inexperienced it's unclear. I will try to contact the company. I'm not sure why they make it so difficult to get actual lengths (looking at you Cobra).


React Carousel renderArrow consts is not defined

Question: I'm using react-elastic-carousel and i am trying to render my own custom arrows.
This is my code (taken from an example in the docs)
function App() {
  return (

      <Carousel
        renderArrow={({ type, onClick }) => {
          const pointer = type === consts.PREV ? '' : ''
          return <button onClick={onClick}>{pointer}</button>
        }}
      >
        <Item>1</Item>
        <Item>2</Item>
        <Item>3</Item>
        <Item>4</Item>
        <Item>5</Item>
        <Item>6</Item>
      </Carousel>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I'm getting the error:

consts is not defined

I have 2 questions here:
1. What is this consts variable and how can i define it?
2. What is this style of code, why do we need to pass a function and not just a component to renderArrow?
Answer:
What is this consts variable and how can i define it?

In the source code it's this file, and you can import it like this:
import { consts } from 'react-elastic-carousel';

Or to import both the carousel and the consts:
import Carousel, { consts } from 'react-elastic-carousel';

What is this style of code, why do we need to pass a function and not just a component to renderArrow?

It's called a "render prop", and it's more flexible than just passing in a reference to a component. If all you passed in was a component, then they would have to guess what you wanted them to do with type and onClick, and so the best they could do would be to just pass them both in as props to your component.
With a function, then will call the function and hand you the props. You then decide what to do with them, and then return components that do what you want. If all you want to do is put those props onto a component, you can:
renderArrow={props => <button {...props}/>}

But you can also do more complicated things
Comment: thank you, but if i import consts how should i import the Carousel?
Answer: 1.There is a consts.js file where consts.PREV and consts.NEXT are defined.
2.If you just passed a component, where would the logic for direction of the arrow be?


How to get an a String from an array list of objects in java?

Question: I am having the user input an index. That index will be used to find a particular object called Movie in the list array called movieList. In that object i want to find the value of genreOfMovie and convert it to String.
I am using this line of code:
Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);
to set the veritable to what the user is looking for.
However when i run the program I dont get a string of a genre , what i get is some thing similar to database.Movie@71aa1ce9. Database if the name of the program and Movie is the name of the object so what is @71aa1ce9 and how do i change this like
Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);

of code to print some sort of string like action because that is what was stored in there.
      String index  = TxtSearch.getText();
      Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);
      int counter = 0;
      do {
          counter++;
      } while (CbxGenres.getComponent(counter) != genreOfGame.toString());

Comment: Side note: it is a bad idea to directly parse a string and assume it represents a valid index in a list. Input coming directly from a user should **always** be handled with great care. You should: handle at least two error cases (input is not a number; parsed number is not a valid index)
Comment: besides other things already mentioned, you can't compare strings directly, better you use `.equals()` method: `CbxGenres.getComponent(counter).equals(genreOfGame.toString())`
Answer: You need to override the toString() method in your Movie class.  Here, you can assemble a description of the object using its instance fields as well as any other String.
public class Movie {
    private String name;
    private String genre;

    ...

    @Override
    public String toString() {
        return genre;
        // alternatively, you can concatenate data into a String and return that, e.g. return name + " (" + genre + ")"
    }
}

On a side note, why doesn't your movieList have a generic type, e.g. List<Movie> ?
Comment: i am sorry i am very new to this, what does @Override actually do ? And how does  concatenating data in this case work?
Comment: `@Override` indicates that you're explicitly overriding a method from an ancestor.  If you annotate a method with this, but you're not actually overriding anything - maybe through a typo - the compiler will complain.
Comment: You could make your `toString()` method body look like this: `return "Movie: " + name` - this concatenates the String literal `Movie: `  with the name of the movie held by the Movie object.
Comment: Just to clarify, in my case i need to go to my object class Movie and enter

@Override
public String toString() {
return genreOfMovie;
}
Comment: I've updated the example.  Another side note: you don't need to call it genreOfMovie, just genre - it's a property of a Movie, so you're essentially repeating yourself.
Comment: It works however my object has more than one variable eg
`nameOfMovie
genreOfGenre
 nameOfDirector`
it is very important to keep the data speared because I want to write the information back into text boxes because this is a part of an editing method .
Comment: Those should be separate instance variables in your Movie objects.  `toString()` isn't changing anything, it's just creating a new string that represents those fields as a single string that describes your object.
Comment: You should probably check the MVC pattern, it might help you organise your thoughts and design.
Comment: What im trying to do is have the user input an index of "record" want to append. The index will be used to look at a specific object in the array list. Everything stored in that object will be written to the input from.  The user will then be able to append their input and write it back to the same object. What I'm stuck on is the taking data from the object and adding it to the from controls. I am very sorry for pestering you.
Comment: I think you should ask a separate question if you're stuck on this.
Answer: What you are doing is printing the String interpretation of the Movie object. What you want, is create your own string interpretation. You do this by overriding the toString() method in your movie object and returning the genre.
An example:
@Override
public String toString() {
   return this.genre;
}

Answer: "@71aa1ce9" is name of object instance
Movie genreOfMovie = (Movie)

this is instance of one movie, to get genre you probably need to call some method on movie it self .. like .getGenre() or something like that


Why is the neutral conductor sometimes undersized in AC applications?

Question: Why are electricians allowed to sometimes lower the size of the grounded (neutral) conductor?
If alternating current is bidirectional then wouldn't the neutral technically be an ungrounded (hot) conductor 60 times a second? (For 60hz)
I can get my head around multiwire branch circuits sharing a neutral and phases and what not, but this one stumps me.
Thanks for the quick reply.
Comment: It depends if it is a "return neutral", as in single phase systems, or a "star center neutral" as in 3 phases systems.
Comment: Seems to me it might be the other way around. Two lives returning through one larger neutral. But some sort of reference would help clear this one up. Though with GFI breakers that would be a bad idea.
Comment: Archonosx has the code referenced below for a good answer. Another case is the multi wire branch circuit where 2 hotts are using only 1 neutral. This specific case won't overload the single neutral because L1 & L2 are 180 degrees out of phase.
Answer:
Why are electricians allowed to sometimes lower the size of the grounded (neutral) conductor?

As DrMoishe points out some pieces of equipment use mostly 240 volts and very little 120 volt power. It is the 120 volt power that uses the neutral. Therefore the National Electrical Code allows the downsizing of the neutral in limited application. This is NOT blanket permission to downsize all neutrals. It is only applicable in a few instances.
It is possible to downsize a feeder or service neutral according to the calculations in the National Electrical Code here:

220.61 Feeder or Service Neutral Load.
(A) Basic Calculation.  The feeder or service neutral load shall be the maximum unbalance of the load determined by this article. The maximum unbalanced load shall be the maximum net calculated load between the neutral conductor and any one ungrounded conductor.
Exception: For 3-wire, 2-phase or 5-wire, 2-phase systems, the maximum unbalanced load shall be the maximum net calculated load between the neutral conductor and any one ungrounded conductor multiplied by 140 percent.
(B) Permitted Reductions.  A service or feeder supplying the following loads shall be permitted to have an additional demand factor of 70 percent applied to the amount in 220.61(B)(1) or portion of the amount in 220.61(B)(2) deter‐ mined by the following basic calculations:
(1) A feeder or service supplying household electric ranges, wall-mounted ovens, counter-mounted cooking units, and electric dryers, where the maximum unbalanced load has been determined in accordance with Table 220.55 for ranges and Table 220.54 for dryers
(2) That portion of the unbalanced load in excess of 200 amperes where the feeder or service is supplied from a 3-wire dc or single-phase ac system; or a 4-wire, 3-phase system; or a 3-wire, 2-phase system; or a 5-wire, 2-phase system
Informational Note: See Examples D1(a), D1(b), D2(b), D4(a), and D5(a) in Informative Annex D.
(C) Prohibited Reductions.  There shall be no reduction of the neutral or grounded conductor capacity applied to the amount in 220.61(C)(1), or portion of the amount in (C)(2), from that determined by the basic calculation:
(1) Any portion of a 3-wire circuit consisting of 2 ungrounded conductors and the neutral conductor of a 4-wire, 3-phase, wye-connected system
(2) That portion consisting of nonlinear loads supplied from a 4-wire, wye-connected, 3-phase system
Informational Note: A 3-phase, 4-wire, wye-connected power system used to supply power to nonlinear loads may necessitate that the power system design allow for the possibility of high harmonic neutral conductor currents.

Regarding branch circuits, the code allows the downsizing of ranges and cooking equipment here, attention to exception 2:

210.19(A)(3) Household Ranges and Cooking Appliances.  Branch-circuit conductors supplying household ranges, wall-mounted ovens, counter-mounted cooking units, and other household cooking appliances shall have an ampacity not less than the rating of the branch circuit and not less than the maximum load to be served. For ranges of 8 3∕4 kW or more rating, the minimum branch-circuit rating shall be 40 amperes.
Exception No. 1: Conductors tapped from a 50-ampere branch circuit supplying electric ranges, wall-mounted electric ovens, and counter-mounted electric cooking units shall have an ampacity of not less than 20 amperes and shall be sufficient for the load to be served. These tap conductors include any conductors that are a part of the leads supplied with the appliance that are smaller than the branch-circuit conductors. The taps shall not be longer than necessary for servicing the appliance.
Exception No. 2: The neutral conductor of a 3-wire branch circuit supplying a household electric range, a wall-mounted oven, or a counter-mounted cooking unit shall be permitted to be smaller than the ungrounded conductors where the maximum demand of a range of 8 3∕4-kW or more rating has been calculated according to Column C of Table 220.55, but such conductor shall have an ampacity of not less than 70 percent of the branch-circuit rating and shall not be smaller than 10 AWG.

There are no other allowances for a downsized neutral that I can find in the National Electrical Code.
Most dryers and ranges are wired with NM cable and will therefore have full sized neutrals anyway. If you are wiring with conduit, you could use this exception for the range.
The dryer circuit neutral has to be able to carry the full imbalance of the load. Since that load is unknown because you are wiring a receptacle not a piece of equipment, then the neutral must be full sized. These circuits are normally #10 wire and the range exception sets the minimum at #10 so there would be no reduction even if dryers used the same exception.
Hopefully, this will help to clarify this subject.
Answer: For some devices, most current is consumed across the 240 V L1 and L2, while the neutral gets only an amp or two. For example, an electric dryer heating element might draw 30 amps when hot (and a considerably higher surge current before it warms, since cold resistance is lower) across the 240 V lines. The electric motor, timer and other 120 V devices in the dryer need perhaps 5 A.
That said, it depends on the electric code whether a smaller neutral is allowed.
Comment: @Transistor North America uses a center-tapped **single** phase system.
Comment: You seem to be describing a North American centre-tapped 2-phase system where the phases at 180°. You should probably clarify this in your answer.
Comment: @Transistor Not necessarily. In a Y configuration 3-phase system load can be connected either line-neutral or across lines. A lot of three phase appliances do exactly that (even if for increased voltage). Norway uses delta three phase config where there is no neutral and all connections are more or less equivalent to line-neutral. Typical 4 (or 5) conductor wire has all conductors of the same diameter, not one 3 times the size of others
Comment: @Tester101 that is a matter of perspective and naming conventions. It can equally well be called a two-phase 180degree system. The fact that the two phases are generated from one phase of the three phase transmission system is not overly relevant to the customer..
Comment: @Trevor_G From [Wikipedia](https://en.wikipedia.org/wiki/Split-phase_electric_power): "*A split-phase or single-phase three-wire system is a type of single-phase electric power distribution.*".  Which is not the same as a [Two-phase](https://en.wikipedia.org/wiki/Two-phase_electric_power) system.
Comment: @Transistor, the question states, " the size of the grounded (*neutral*) conductor," so it is clear this is not a three-phase system.
Comment: Only from the perspective of the neutral are the two legs 180°out of phase. Two phases that are 180°out of phase would add to zero. Instead, the two legs on the system add to twice one of the hot legs to the neutral. This means the two are actually in-phase. The main problem is the use of the term "phase" at all when referring to these systems. It is misleading to novices.
Comment: @Tester101 oh I agree with you, just saying colloquially  they are called two phases by many.
Answer:
why are electricians allowed to sometimes lower the size of the grounded (neutral) conductor?

Because in the USA, houses are typically provided with a "split phase" supply. In most of the rest of the world, houses mostly use a single-phase supply - which is what you probably have in mind as it is the simplest system. Industry and some houses are supplied with a three-phase supply which I will ignore here.
In a single phase AC supply, you are right, the polarity reverses many times a second so that current flows in the other direction. This also means that the voltage is reversed. A single phase system has two conductors. In the US these are described as hot and neutral. In other countries the hot is known as live or line.
Since the current/voltage reverses many times a second, it may seem that these labels are arbitrary. However there is a convention that one of these wires is connected to ground near the main panel. It is a convention that all the fuses, breakers and switches are in the other wire. This makes for a more safe arrangement.
In a split phase system, you have three conductors, We can call these h1, h2 and neutral. There is 240 VAC across h1 and h2. This allows high-powered appliances to be connected by thinner wires than would be needed by a 120V appliance of the same power. losses in the wires are also lower. It is important to note that none of the current for a 240V appliance runs through neutral, it all flows through h1 and h2.
So wires to a 240V receptacle can use a thinner neutral wire where the appliance uses 240V for its main load, even if it also uses 120V for a small part of its load. The same would apply to wires serving a mixture of 240V and 120V outlets.
There is more current flowing back and forth along the h1 and h2 wires than flows back and forth through the neutral wire.

If alternating current is bidirectional then wouldn't the neutral technically be an ungrounded (hot) conductor 60 times a second? (For 60hz)

No.
You should remember that voltages are relative. there are no absolute voltages. The labels hot and neutral are arbitrary so far as the electron flow is concerned.
Note that you can take a 9V PP3 battery and label the two connectors 1000000 volts and 1000009 volts. Or -509 and -500. All the usual calculations can then be applied (e.g. ohms law V=IR) and get the correct results. This is because we are always dealing with voltage differences between two points. We are used to labelling one connector 0V for simplicity and we usually choose the least positive connector to label as 0V. This is DC of course. For AC the choice is even more arbitrary. Nevertheless the convention is useful.
Neutral is always tied to ground and there should be very little difference in voltage between neutral and ground. There will be some difference  because of the resistance in the wire - but this should never be more than a few volts.
Neutral is never "ungrounded hot" as that would imply a significant voltage difference between neutral and ground - which doesn't happen.
What this means is that we are arbitrarily labelling neutral as 0V and measuring the voltage on the hot side relative to the neutral or ground conductors.
Answer: What is called "netural" is not decided by directionality of current.  It's decided by which conductor is pegged to be near ground.
In low-voltage DC design, you may feel obligated to put battery - to backplane/return/GND, because you are working in semiconductors, and they care, and most semiconductors are architected for Vcc+.  But you get a pre-semiconductor toy, say that is motors and limit switches, and put the batteries in backwards - it works fine!  So the idea of dirctionality relating to ground doesn't even apply in DC world.
The AC transformer output is always varying in voltage.   Until it's grounded, it is an isolated system - none of it has a relation with ground.  We establish that relationship for a number of reasons, but it's arbitrary.  You could tie L1 pole to ground if you like; then L1 would be neutral, N would be 120V, and L2 would be 240V.  When we peg it in the middle, we get 240V from the poles, but each pole is only 120V from earth.
Still, neutral is not ground.  It's just near ground because of our best efforts to peg it at ground inside the main service.  As soon as you get outside the main panel, neutral may not be at ground potential, differing by voltage drop, or more if there is a wire problem.
As such, calling it the grounded conductor is misleading and wishful thinking, and a weird glitch because of what happens when lawyers write code books.  It is a conductor (it is meant to carry current under normal circumstances), but it is certainly not grounded except inside the main service.
Answer: The neutral wire only carries the imbalance current between phase a and phase b, that's the main reason that it is allowed to be smaller.  Neutral wire is tied to ground and also the center tap on the secondary (output) of your transformer out on the pole (right in the center of the secondary coil, making a reference point to 0v gnd, that splits the 240v potential into two usable half, or it's full 240v potential)
In other words, imagine you only have 2 breakers on in your house, 120volts only.  One breaker is on phase a and the circuit is pulling 15 amps, the other breaker is on phase b pulling only 12 amps.  You will see roughly 3 amps on the neutral wire at the service, even though a total of 18 amps is seen between phases a and b.
Keep in mind that the neutral size is only usually reduced on the service entrance conductors and not on branch circuits.


When to use Application_Start vs Init in Global.asax?

Question: I am wondering under what circumstances I should be putting application initialisation code in Application_Start() vs Init() in my Global.asax file?
The distinction between the two doesn't seem very obvious to me, other than Application_start gets called first, then Init().

Why would I use one over the other?
Does it really make a difference?
What changes in the application state
between the two events?

So far the only real pointer I can find is that IHttpModule only has an Init() method, so if what I'm doing may at some point be better suited to implement IHttpModule I should use the Init() method of Global.asax, if nothing else for consistency.
Answer: From the MSDN docs:

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

Init:

Called once for every instance of the
  HttpApplication class after all
  modules have been created.

UPDATE: if you need to make sure a certain code is called only once in the app. lifecycle, Application_Start is a better solution. Examples: configuring log4net?
Comment: Bit of a follow-up question: when is an instance of HttpApplication created? I'm assuming each time the worker-process is restarted and it will contain one instance for each worker-thread?
Comment: @roryf - asp.net maintains a pool of application instances that can be resused. Under the covers, requests are serviced using the CLR threadpool and incoming requests will be queued beyond a certain threshold. I doubt they initialize the application instance pool to that threshold level since most sites won't see that kind of traffic. I suspect they create the pool with a small number of instances and then increase the size of the pool as demand ramps up.
Answer: Yes
There are differences between them. Application_Start() event is called just one time while Init() method is called on each time when instance of the application is created.


Reusing ADT motion sensors

Question: I bought a 4 level house that had an ADT security system with a motion sensor in every room. I never used it since moving in.
But I have a fun project in mind: I'd like to drive my kids nuts when playing hide-and-seek.
Is there a relatively easy and inexpensive solution to reusing the motion sensors. It would be sufficient to have an app (or a webapp) that gives me a flat list of the most recent motion-detector "hits". Any suggestions?
Comment: You realize this is not a simple project, and will involvee a buch of cross discipline work.  The hardware build alone will be considerable, and then it has to talk to the Internet somehow, a piece of engineering of its own. An engineering firm might bill it at $100k, or a kid might do it for 2 months of evenings if slipping grades were no object...
Comment: Probably not. If it is an older system, the dumb sensors will only trigger a phone call to the monitoring company. If it is a newer system, you will need a subscription to access it via the internet.
Comment: if the sensor is wired, then it is posible that the sensor acts as a switch .... check to see if wires are getting shorted together when motion is detected
Comment: Raspberry pi to monitor the sensors, and talk to a website on the internet (or use your home computer) of course you need to write some software and program the pi... Would be a very cool project, not to hard either if you can code :-) I would of course do this in assembly
Comment: are they already powered on? if so, that makes it trivial to monitor the feedback line, which will go high/low depending on activity. I would suggest have a time-based indication instead of a state indicator, maybe fading the alert away. That lets you see where the last activity occurred, were the kid staying still while you search.
Answer: First we must determine whether your motion sensors are wired or wireless.
Wired
The wired PIR motion sensors used in security systems since roughly forever are pretty simple devices. You feed them 12 volts dc to power the electronics; they contain a relay which opens or closes to indicate motion. Some will have a SPDT relay so that the installer can choose whether to use the normally open or normally closed contact. "Normally" means the inactive or resting state of the device, ie no motion detected.
If your ADT system is wired there'll be a control panel buried in a closet or utility room somewhere in the house. Open it up and you'd most likely find a 4-conductor cable for each motion sensor. If the motion sensors are grouped into zones then it's possible you'd have one cable for each zone; each sensor might not have its own "home run" cable back to the panel.
All these wired sensors could be fed into some kind of multi-input interface. That might be built around an Arduino, a Raspberry Pi, or some other experimenter/hobbyist platform.
Wireless
If your motion sensors are wireless then things aren't necessarily harder, just different. First you'll have to figure out what RF frequency and protocol they use. At very least they should be labelled with an FCC ID number which reveals the manufacturer and model of the device, and from there the rest can be discovered. They might also simply be labelled such that a person familiar with the industry would recognize them. GE/Interlogix is one particular make that's quite prolific. Each sensor has a unique serial number which it periodically transmits along with its battery state, contact state, and other info. Receivers are available that can listen for these sensor transmissions and send it over a serial bus like RS-232.
Pulling it together
Identifying what sort of sensors you're working with is the easy part. From here you're probably going to be looking for some kind of open source home automation platform such as openHAB, Home Assistant, etc. These may provide a software framework for receiving the security sensor inputs and putting them into a web or mobile app front end you can use. This all goes beyond the scope of the DIY stack exchange, but hopefully I've given enough ideas and key words to help your research get started.

Reusing ADT motion sensors


"Converse" of second Fundamental Theorem of Calculus?

Question: Let $f: \mathbb{R} \to \mathbb{R}$ be continuous. Let $F: \mathbb{R} \to \mathbb{R}$ be such that $F(b) - F(a) = \int_{a}^{b} f(x) \, dx$ for all $a, b \in \mathbb{R}$. Is $F$ differentiable, and is $F' = f$?
One reason I am asking is in the context of probability. Given the cumulative distribution function $F$ of a continuous random variable $Y$, $F(y) := P(Y \leq y)$, can the probability density function $f := F'$ be (alternatively) characterized by the property $F(b) - F(a) = \int_{a}^{b} f(x) \, dx$ for all $a, b \in \mathbb{R}$?
Comment: Are you familiar with the first fundamental theorem of calculus?
Comment: The answer to your question is yes, and that is called the first fundamental theorem of calculus. That said, you should be careful when you are using this in probability theory: the probability density function does not always exist.
Comment: @Jackozee Thanks. I didn't realize it was a formulation of the first fundamental theorem.
Answer: Yes. Fix any $a \in \mathbb{R}$. Define $G: \mathbb{R} \to \mathbb{R}$ by $G(x) = F(x) - F(a) = \int_a^x f(t) \, dt$. Differentiating and applying the Fundamental Theorem of Calculus, we get $G'(x) = F'(x) = f(x)$, so $F' = f$.


How long does it take to get to the center of the Galaxy?

Question: After finishing the Atlas path I am now trying to get to the Center of the Galaxy but it seems to take an awful long time to get there. According to the game it will still take 175869 light years to get there? At the pace I am playing this will take longer than a year I think to get there... Or are there some black holes that will make a huge difference, so far it doesn't seem to help me much further at all...
Also is this different for everyone depending on where they start in the universe?
Will I be able to meet other players as well there?
Comment: This all really depends on the player and how much time you spend trying to get there. There is no concrete answer for this. It could take 30 hours or 300 hours depending on what you do, how much of your stuff breaks and how long it takes to find resources to fix it.
Comment: "Will I be able to meet other players as well there?" No, NMS is not multiplayer. You will never be able to meet other players, period. [See this question](http://gaming.stackexchange.com/q/280918/145980) for more details.
Comment: Black holes vary in how far you travel when you go through them.  They're better than using the hyperdrive but the variety in distance makes it impossible to say how much they help.  Also, everyone starts at a totally random location, so one persons experience will not reflect your own.
Comment: @Archer Also just to note, sometimes Black Holes will break parts of the equipment on your ship.
Answer: The time it takes to get to the centre of the Galaxy is different for everyone as everyone starts in different parts of the Galaxy. The time it took the first to reach the centre on ps4 was a little over a week I believe, but that was rushing through the game upgrading his hyperdrive and gathering resources for warp cells...


Multiple RTSPs receive method

Question: I am trying to code a project which I have at least 20 rtsp CCTV URL going to access at same time.
I tried to use ffmpeg to reach out my goal via multiple input method. However, there is a problem.
ffmpeg -i URL_1 -i URL_2 -

The command above is the example I tried. I wish that I can access two rtsps via ffmpeg and output them into two different queues for the future use. If I use this command and read bytes after that, I can not distinguish which bytes belongs to which input rtsp.
Is there any other way which I can access more rtsp at same time?
Edit: Adding Code
import ffmpeg
import numpy as np
import subprocess as sp
import threading
import queue
import time
class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, name):
        super().__init__()
        self.name = name
        self.q = q
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell ffmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell ffmpeg to copy the video stream as is (without decding and encoding)
                        "-an", "-sn",       # No audio an no subtites
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**3)  # Don't use shell=True (you don't need to execute the command through the shell).

        # while True:
        for i in range(1024*10):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(1024)  # Read data from pip in chunks of 1024 bytes
            self.q.put(data)

            # Break loop if less than 1024 bytes read (not going to work with CCTV, but works with input file)
            if len(data) < 1024:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

        if self.q.empty():
            print("There is a problem (queue is empty)!!!")
        else:
            # Write data from queue to file vid_from_queue.264 (for testingg)
            with open(self.name+".h264", "wb") as queue_save_file:
                while not self.q.empty():
                    queue_save_file.write(self.q.get())

# Build synthetic video, for testing begins:
################################################
# width, height = 1280, 720
# in_stream = "vid.264"
# sp.Popen("ffmpeg -y -f lavfi -i testsrc=size=1280x720:duration=5:rate=1 -c:v libx264 -crf 23 -pix_fmt yuv420p " + in_stream).wait()
################################################

#Use public RTSP Streaming for testing
readers = {}
queues = {}
dict = {
        "name1":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name2":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name3":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name4":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name5":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name6":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name7":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name8":{"ip":"rtsp://xxx.xxx.xxx.xxx/",
        "name9":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name10":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name11":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name12":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name13":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name14":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        "name15":{"ip":"rtsp://xxx.xxx.xxx.xxx/"},
        }

for key in dict:
    ip = dict[key]["ip"]
    name = key
    q = queue.Queue()
    queues[name] = q
    cctv_reader = CCTVReader(q, ip, name)
    readers[name] = cctv_reader
    cctv_reader.start()
    cctv_reader.join()

Answer: You already have all the infrastructure in your previous question.
All you need to do is creating multiple objects of your 'CCTVReader' class.
Here is a working code sample, reading two streams:
import numpy as np
import subprocess as sp
import threading
import queue
import time

class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, chunk_size):
        super().__init__()
        self.q = q
        self.chunk_size = chunk_size
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell FFmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell FFmpeg to copy the video stream as is (without decoding and encoding)
                        "-an", "-sn",       # No audio an no subtitles
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**3)  # Don't use shell=True (you don't need to execute the command through the shell).

        # while True:
        for i in range(100):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(self.chunk_size)  # Read data from pip in chunks of self.chunk_size bytes
            self.q.put(data)

            # Break loop if less than self.chunk_size bytes read (not going to work with CCTV, but works with input file)
            if len(data) < self.chunk_size:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

#in_stream = "rtsp://xxx.xxx.xxx.xxx:xxx/Streaming/Channels/101?transportmode=multicast",

#Use public RTSP Streaming for testing
in_stream1 = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

in_stream2 = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

q1 = queue.Queue()
q2 = queue.Queue()

cctv_reader1 = CCTVReader(q1, in_stream1, 1024)  # First stream
cctv_reader2 = CCTVReader(q2, in_stream2, 2048)  # Second stream

cctv_reader1.start()
time.sleep(5) # Wait 5 seconds (for testing).
cctv_reader2.start()

cctv_reader1.join()
cctv_reader2.join()

if q1.empty():
    print("There is a problem (q1 is empty)!!!")
else:
    # Write data from queue to file vid_from_queue1.264 (for testing)
    with open("vid_from_q1.264", "wb") as queue_save_file:
        while not q1.empty():
            queue_save_file.write(q1.get())

if q2.empty():
    print("There is a problem (q2 is empty)!!!")
else:
    # Write data from queue to file vid_from_queue2.264 (for testing)
    with open("vid_from_q2.264", "wb") as queue_save_file:
        while not q2.empty():
            queue_save_file.write(q2.get())

Update:
I don't think you can use a syntax like ffmpeg -i URL_1 -i URL_2 -...
The code you have posted has few issues:

The cctv_reader.join() must be in a second loop, because it waits for the thread to end, and blocks execution.
Saving the data to files should be after all threads ended (it's just for testing).
In case you want to record the data, try saving each chunk right after grabbing it.
Reduce size of bufsize=1024**3, try bufsize=1024**2*100.
In case OS actually allocate buffer size of 1GB per process, you might get out of memory.

Note: Python multi-threading performance is not so good, check the CPU load.
Here is a code sample (reading from files):
import numpy as np
import subprocess as sp
import threading
import queue

class CCTVReader(threading.Thread):
    def __init__(self, q, in_stream, chunk_size):
        super().__init__()
        self.q = q
        self.chunk_size = chunk_size
        self.command = ["ffmpeg",
                        "-c:v", "h264",     # Tell FFmpeg that input stream codec is h264
                        "-i", in_stream,    # Read stream from file vid.264
                        "-c:v", "copy",     # Tell FFmpeg to copy the video stream as is (without decoding and encoding)
                        "-an", "-sn",       # No audio an no subtitles
                        "-f", "h264",       # Define pipe format to be h264
                        "-"]                # Output is a pipe

    def run(self):
        pipe = sp.Popen(self.command, stdout=sp.PIPE, bufsize=1024**2*100)

        # while True:
        for i in range(100):  # Read up to 100KBytes for testing
            data = pipe.stdout.read(self.chunk_size)  # Read data from pip in chunks of self.chunk_size bytes
            self.q.put(data)

            # Break loop if less than self.chunk_size bytes read (not going to work with CCTV, but works with input file)
            if len(data) < self.chunk_size:
                break

        try:
            pipe.wait(timeout=1)  # Wait for subprocess to finish (with timeout of 1 second).
        except sp.TimeoutExpired:
            pipe.kill()           # Kill subprocess in case of a timeout (there should be a timeout because input stream still lives).

    def save_q_to_file(self, vid_file_name):
        # Write data from queue to file (for testing)
        if self.q.empty():
            print("There is a problem (q is empty)!!!")
        else:
            with open(vid_file_name, "wb") as queue_save_file:
                while not self.q.empty():
                    queue_save_file.write(self.q.get())

#in_stream = "rtsp://xxx.xxx.xxx.xxx:xxx/Streaming/Channels/101?transportmode=multicast",

#Use public RTSP Streaming for testing
#in_stream = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"

#Use public RTSP Streaming for testing
readers = {}
queues = {}

# Read from file (for tesing)
dict = {
        "name1":{ "ip":"vid1.264",  "fname":"vid_from_q1.264"},
        "name2":{ "ip":"vid2.264",  "fname":"vid_from_q2.264"},
        "name3":{ "ip":"vid3.264",  "fname":"vid_from_q3.264"},
        "name4":{ "ip":"vid4.264",  "fname":"vid_from_q4.264"},
        "name5":{ "ip":"vid5.264",  "fname":"vid_from_q5.264"},
        "name6":{ "ip":"vid6.264",  "fname":"vid_from_q6.264"},
        "name7":{ "ip":"vid7.264",  "fname":"vid_from_q7.264"},
        "name8":{ "ip":"vid8.264",  "fname":"vid_from_q8.264"},
        "name9":{ "ip":"vid9.264",  "fname":"vid_from_q9.264"},
        "name10":{"ip":"vid10.264", "fname":"vid_from_q10.264"},
        "name11":{"ip":"vid11.264", "fname":"vid_from_q11.264"},
        "name12":{"ip":"vid12.264", "fname":"vid_from_q12.264"},
        "name13":{"ip":"vid13.264", "fname":"vid_from_q13.264"},
        "name14":{"ip":"vid14.264", "fname":"vid_from_q14.264"},
        "name15":{"ip":"vid15.264", "fname":"vid_from_q15.264"}
        }

for key in dict:
    ip = dict[key]["ip"]
    name = key
    q = queue.Queue()
    queues[name] = q
    cctv_reader = CCTVReader(q, ip, 8192)
    readers[name] = cctv_reader
    cctv_reader.start()

# Wait for all threads to end
for key in readers:
    readers[key].join()

# Save data for testing
for key in readers:
    fine_name = dict[key]["fname"]
    readers[key].save_q_to_file(fine_name)

Comment: Hello Rotem, thank you for taking time to help me again. I tried to use multi-thread to query data before actually. However, after I tried to put 15 threads to query 15 different CCTV, there is a serious data loss happen. I put the code I tried before above in the question space. I will try what you provide to test again. Thank you very much.
Comment: I don't think you can use a syntax like `ffmpeg -i URL_1 -i URL_2 -`..., Your code has few issues: **1.** The `cctv_reader.join()` must be in a second loop, because it waits for the thread to end, and blocks execution. **2.** Saving the data to files should be after all threads ended (it's just for testing). In case you want to record the data, try saving each chunk right after grabbing it. **3.** Reduce size of `bufsize=1024**3`, try `bufsize=1024**2*100`. **4.** Python multi-threading performance is not so good, check the CPU load.
Comment: I have updated my most. I have no way for testing it with 15 CCTV cameras. I used video files instead.
Comment: Rotem, one little question about the thread issue you mention. If I change the multi-threading by using GPU threading, will it preform better?
Comment: I don't think using GPU threading fits your case. The thread reads data from PIPE, and store in a queue, and GPUs are not built for that kind of tasks. Read [this post](https://stackoverflow.com/questions/44793371/is-multithreading-in-python-a-myth), to learn mote about Python multi-threading issues. I don't think the task is a CPU heavy task, and it can be done is a single core. You can increase chunk size, for reducing the number of threads context switching.

Multiple RTSPs receive method


Java recursion output different from expected

Question: Just when I thought I was starting to understand recursion this one seems simple when n is 1  but when n is 2  In my head I  end up with [[, [, [,]
public void ps (int n){

  if (n==0) {
    System.out.print ("*");
  }
  else {
    System.out.print ("[");
    ps (n-1);
    System.out.print (",");
    ps (n-1);
    System.out.print ("]");
  }
}

Comment: well what do you think it should do and what does it do? Start with that.
Comment: Edit your question. Make it clear. Tell what you want to achieve, what you expect to happen, and what happens instead. Use the preview, and don't post your question until it's perfectly clear.
Comment: Sorry was typing on my phone that type o  was not in the program
Comment: For 1 it's  [*,*] 2 it's [[*,*], [*,*]]
Comment: Well that's not at all what I typed
Comment: @Jason signature of your method should look like `public void ps(int number)` instead of `Public void ps (int n)`.
Answer:   ps(2):
     Current output ""
     n != 0 so else: print [ output = "["
     call ps(1)
     ps(1):
       Current output "["
       n != 0 so else: print [ output = "[["
       call ps(0)
       ps(0):
        Current output "[["
         n == 0: print "*" output = "[[*"
         return
     ps (1): after first call
       output = "[[*"
       print "," output = "[[*,"
       call ps(0):
       ps(0):
         current output "[[*,"
         n == 0: print "*" output = "[[*,*"
         return
    ps(1): after second call
       output = "[[*,*"
       print "]" output = "[[*,*]"
       return
  ps(2): after first call
    output = "[[*,*]"
    print , output = "[[*,*],"
    call ps(1)
             ps(1):
       Current output [[*,*],
       n != 0 so else: print [ output = "[[*,*],["
       call ps(0)
       ps(0):
        Current output "[[*,*],["
         n == 0: print "*" output = "[[*,*],[*"
         return
     ps (1): after first call
       output = "[[*,*],[*"
       print "," output = "[[*,*],[*,"
       call ps(0):
       ps(0):
         current output "[[*,*],[*,"
         n == 0: print "*" output = "[[*,*],[*,*"
         return
    ps(1): after second call
       output = "[[*,*],[*,*"
       print "]" output = "[[*,*],[*,*]"
       return
   ps(2): after second call
       output = "[[*,*],[*,*]"
       print "]" output = "[[*,*],[*,*]]"
       return

Final output: "[[*,*],[*,*]]"
Comment: Thank you for your help just what I needed
Answer: Well, you probably heard the terms stack frame and call stack already. They are quite important to understand what happens in a recursion.
My tip is to draw the stack frames in a tree, according to their invocation.
In this case it would look like:
ps(2)
  |
  |--ps(1)
  |    |
  |    |--ps(0)
  |
  |--ps(1)
  |    |
  |    |--ps(0)

Now add to this the output from each invocation, and you should be fine.

As mentioned, on future questions try to explain what you expect or what you are trying to achieve.
Comment: Call stack yes  stack frame no better back up it sounds like
Comment: Have a look here http://stackoverflow.com/questions/10057443/explain-the-concept-of-a-stack-frame-in-a-nutshell -- Basically, it is the information passed to an invocation of a funtion, the most interesting part are the parameters, but it also includes stuff like a return address (what code should be executed when done) and an address where to put the return value (if it is not void) and such. The last two are normally taken for granted, but usefull to look at when learning recursion.


How to change the terminal title

Question: I'm currently using Hyper terminal on a mac, but this question also applies to other types of terminals, e.g. iTerm
How do you change the terminal title from username@devicename:~ into just ~ or zsh.
Currently my shell is zsh with oh-my-zsh installed.  I'm not looking for workarounds through powerline or themes.
One more question:
How do you reset back after running echo -n -e "\033]0;SERVER\007"?
Answer: Within ~/.zshrc
Uncomment the following line to disable auto-setting terminal title.
DISABLE_AUTO_TITLE="true"

Comment: I had to Restart the terminal after making the change to make this work
Answer: I'm using this in my .zshrc:
# oh-my-zsh seems to enable this by default, not desired for
# workflow of controlling terminal title.
DISABLE_AUTO_TITLE="true"

function set_terminal_title() {
  echo -en "\e]2;$@\a"
}

Answer: Have you googled to search for an answer? How about the following:
https://alvinalexander.com/blog/post/mac-os-x/change-title-bar-of-mac-os-x-terminal-window
echo -n -e "\033]0;YOUR TITLE HERE\007"

Comment: That didn't do what I wanted.  I tried on my mac's built in terminal with `echo -n -e "\033]0;SERVER\007"` and now it looks like `username@devicename -- ~ -- -zsh`.  How do I reset it back?  Also, is there more of a .zshrc type of approach?
Comment: this does not work if remotely connected to a machine
Answer: If you can to set terminal name to "Terminal" instead of "username@devicename:~PWD" everytime you open a new zsh terminal you can do this:
nano ~/.zshrc

Uncomment (you can find the line by ctrl+W)
DISABLE_AUTO_TITLE="true"

Apply changes to your terminal by
source ~/.zshrc

If you want to set custom names to your terminals you can write this funcation at the end of ~./zshrc file and apply changes using source.
function stitle() {
  echo -en "\e]2;$@\a"
}

Can be used by:
source ~/.zshrc
stitle new title

Answer: With iterm 2 3.3.3 there's a setting under preferences->profiles->general-basics->title that you can set to PWD (and a few other options). It seems they changed a few things related to this recently and this overrides whatever is in the .zshrc.
I'm guessing one of these options might turn of this behavior as well. In my case PWD is exactly what I want.
Answer: This works for me:
DISABLE_AUTO_TITLE="true"

case $TERM in xterm*)
    precmd () {print -Pn "\e]0;%~\a"}
    ;;
esac

Answer: For Mac, first:
brew install wmctrl

then for Mac or Linux
wmctrl -r :ACTIVE: -N "~"

in the active window. Type man wmctrl if you want to say ways to select a window that is not active.

How to change the terminal title