javascript performance between thin client and pc

Question: I have a web app using thin clients (bosanova terminals) as the front end for users.  I've noticed some performance differences in JavaScript between the thin client and a PC.  The terminals are running windows XP embedded with IE6, and the pages I'm referring to are utilizing prototype JS framework to do some rather simple validation on form elements.
for example the following is what I'm using to make sure required fields are populated.
There are two more like this for .numeric and .alaphanumeric that test acordingly and push errors to stop the form form getting submitted.
$$( '.requiredfield' ).each( function ( elem ){
   if ( ( $( elem ).value.length == 0 ) || ( $( elem ).value == null ) ) {
        $( elem ).addClassName( "nonvalid" );
        $( elem ).siblings().first().addClassName( "error" );
        requiredErrors.push( $( elem ) );
   }

});

The problem I'm seeing is a PC in Firefox or IE a form with 5-20 fields on the page takes maybe a half second to process longer than with out the validation. On the Terminal however, it takes anywhere from 15-25 seconds longer to run the validation than the same page with out it.  As I believe I've mentioned I've tested this in IE6 on a PC and do not see the performance loss.  A call to Bosanova led me to upgrading the memory in the terminal which I did just before this posting and the results hadn't changed.
I can change the script so I loop through the form fields only once and handle .required .numeric .alphanumeric as I go and it will help I'm sure. As it is now there is such a difference in performance between the PC and Terminal (thin client). I'm curious to find out why.
If anyone has any experience troubleshooting or knows why prototype/javascript would suffer such a performance loss on a terminal I'd greatly appreciate some tips.
Update: >>>>>>>>>>>>>>>>>
I have still been testing and looking into this issue and thought I'd share this.  We received a newer Terminal yesterday which I loaded up and tested.  The new terminal running IE6 worked flawlessly just as any other browser.  of course it was a tad slower than a PC because 1. its running IE6 and 2. its a thin client but the speed difference was in the hundreds of a second vs. a 10-50 second difference running the same scripts.  The physical specs of the 2 different thin clients are not that different  1.2 ghz(old) vs 1.6 ghz(new) memory was the same and the HD/DOM was 512MB (old) vs 1gig(new).  Still have'nt been able to pin point what is going on in the old terminal but looks to be related to that specific model/revision of the terminal.
Update: >>>>>>>>>>>>>>>>>
Answer: Well, IE6's Javascript engine is slow — remember that it dates from a time when Microsoft insisted that any real application development for the Web should of course be done with ActiveX. On a thin client with a cheap, probably not-too-fast CPU, it's going to be really slow.
You could speed up that code a little by changing the selector:
$$( 'input.requiredfield' ).each( function ( elem ){

Comment: I thought CPU at first also but one of My clients has a terminal with a CPU double the size of my test box.  It actually took longer to run a nearly identical page.  a LOT longer actually, almost 40 seconds to run the validation across approximately 25 fields.
Comment: If it were happening to me, I'd probably code up a little timer routine and start narrowing down where the time is being spent. Note that things like adding class names - which triggers a re-layout - can also be really slow in IE6. Other than that, however, I would be quite surprised to learn that the IE6 running in that client were any different from the IE6 on a PC with XP.
Comment: yup,  put a timer in right off the bat.  many different forms use this code with various numbers of required / numeric / alphanumeric fields and no single one jumps out as a resource hog.  the time taken for each is proportional to the number of that field type in the form, as expected. Just a lot higher on the terminal than anywhere else.  I've observed difference in the way the Terminal makes connections ( it opens way more ports ) than a standard PC per connection, but as the browser goes I would have been surprised also.. now I'm starting to wonder =)
Comment: running portable firefox on the thinclient page times are very quick, not pc quick but blinding speeds compaired to IE6 on the thinclient.  so far the tests i've ran show portable firefox on the thinclient running 2-4.5 seconds to complete the ajax request and validation vs the 15-20 i was seeing in IE.
Comment: Well I wish I could help out - I really appreciate your question because that's some very interesting data I can pack away for future reference.
Comment: on a side note.  would you suggest `$$( 'input.required, textarea.required' ).each( function(){}); ` over ` $$( '.required' ).each();` also?
Comment: Yes - when you *just* provide a classname pattern, the engine has no choice but to look at every element in the DOM. If you can constrain it, then it can narrow down the search.
Answer: I don't know too much about Prototype, but you should cache that element in a local variable instead of wrapping the $ function around it.
$$( '.requiredfield' ).each( function ( elem ){
   var el = $(elem)
   if ( (elem.value.length == 0 ) || elem.value == null ) ) { // is elem.value ever null?
        el.addClassName( "nonvalid" );
        el.siblings().first().addClassName( "error" );
        requiredErrors.push(el);
   }
});

I don't think that will fix all of the performance issues, but maybe it'll shave a few seconds off. I would suggest going ahead with that change you mentioned so it checks all errors/classes in one loop instead of looping through all elements for each type of class.
Maybe something like (again, I don't know prototype well so somethings might be off):
var errors = {};

var rules = {
   ".required": function (elem) { return elem.value.length == 0; },
   ".alphanumeric": function (elem) { return /[a-zA-Z0-9]+/.test(elem.value);  }
};

$$( "input", "#your_form_id" ).each(function ( elem ) {
   var el = $(elem)
   var classes = (function () {
      var cls = elem.className.split(' '), classMap = {};
      for (var k in cls) classMap[cls[k]] = true;
      return classMap;
   })(); // get the classes for this element

   for ( var rule in rules ) {
       error[rule] = [];
       if ( rule in classes && !rules[rule](elem) ) {
          el.addClassName("nonvalid");
          el.siblings().first().addClassName("error");
          errors[rule].push(el);
       }
   }

});

Your errors will be in errors.. to access any elements that failed the required rule, you would do errors["required"] which would return an array.
Comment: thanks for the tips.  I'll happily admit I'm still learning JavaScript. I'm a Server side programmer by trade that has been dabbling in Front-end JavaScript over the past year as projects need.  I'll rework it a bit in the morning and see if i can make tolerable.
Comment: just to update.  I've added some of your suggestions and did speed the script up some. doing it this way I was able to bypass a lot of logic untill a user makes a mistake.  So this helped some  (down to 8-15 seconds rather than 15-20). There is still a drastic difference between the PC and thinclent.
Comment: @Nathan: Have you considered using one of the many validation libraries out there? A lot of them will make your life a lot easier I'm sure. Unless you need some very very custom behavior I'm sure they'll capture all all the features you would need. I actually have my own library that I've been working on for a while.


Azure Dev Ops CICD copy publish not working as expected

Question: I have the following YAML in my build pipeline.
<code>  #Step 3, Copy Files
    - task: CopyFiles@2
      inputs:
        #SourceFolder: '$(Build.SourcesDirectory)'
        Contents: '**'
        TargetFolder: '$(Build.ArtifactStagingDirectory)'
        CleanTargetFolder: true
        OverWrite: true

     #Step 4, Publish artifacts
    - task: PublishBuildArtifacts@1
      inputs:
        TargetPath: '$(Build.ArtifactStagingDirectory)'
</code>
I have a seperate release pipeline, which is attempting to deploy these files to an Azure Function App. However once this completes, the functions are missing. Using KUDU I can see the files have made their way up, however I think something is configured incorrectly.
This is what the artifact structure looks like when I browse for a 'Package or Folder', which to me seems incorrect.
Can anyone advise why my artifacts are not being produced in the format required for a function app?
Comment: Is there any update about this ticket? Feel free to let me know if the answer could give you some help.
Answer: From you screenshot about artifacts content, it seems that  you are directly packaging and publishing your project to Azure Function.
As far as I know, you should be missing the Build step.
You first need to add a build step according to your project type, and then deploy the built product to Azure function.
For more detailed info, you can refer to this doc: Deploy an Azure Function


reverse proxy in Azure

Question: I need to build a reverse proxy to host a website that is running in an azure server. To protect the server and the URLs due to some bad design. That I cannot change.
I was thinking to call http://myhiddenserver.com/?id=126.96.36.199:9035
id is the IP and port for some special functions.
The problem is I can't seem to figure out how to get the query parameters into the request.  The whole site runs off the same url http://{id}/setup.html. it reloads the main page via javascript and stays on setup.html.
<code>{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "stunnelsetupdevice": {
            "matchCondition": {
                "route": "/{id}"
            },
            "backendUri": "http://{id}/setup.html"
        }
    }
}
</code>
Edit:
I tried to just make the proxy call the URL I am trying to build. This does not work either. The only way it works is if I put the whole URL into the backenduri.
<code>{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "stunnelsetupdevice": {
            "matchCondition": {
                "route": "/"
            },
            "backendUri": "http://{id}/setup.html",
            "requestOverrides": {
                "backend.request.querystring.id": "220.127.116.11:9087"
            }
        }
    }
}
</code>
Comment: If this is a REST API service then you might want to look into _[Azure API Management](https://azure.microsoft.com/en-us/services/api-management/)_.  It allows you to encapsulate as well as obfuscate somewhat services in the backend without exposing them directly
Comment: I started with API mgmt. I cant find documentation to explain how to do this.
Comment: see the link I posted.  There you will find a further link to documentation
Comment: As i already said, there is nothing in the documentation or the setup that shows how to change a query string parameter for my use case. even googling got me no where.  If you have a direct link to something else that will work. then ill take a look.
Comment: Ah I thought you were asking for doco for Azure APIM in general, not to worry
Comment: @SteveColeman Why not use Azure Application Gateway? Or create an Azure App Service and use its built-in ARR+UrlRewriting functionality...
Comment: @SteveColeman I'm trying to understand your "hidden" web-services' design... what is the purpose of the `id=` parameter... and why are you passing it IP addresses? What does the IP address represent? (And what happens if a user using only IPv6 visits?)
Answer: I think you can use {*restOfPath} along with {id} here. According to the following MS docs: https://learn.microsoft.com/en-us/azure/azure-functions/functions-proxies#request-parameters

Route template parameters
Parameters that are used in the route template are available to be referenced by name. The parameter names are enclosed in braces ({}).
For example, if a proxy has a route template, such as /pets/{petId}, the back-end URL can include the value of {petId}, as in https://.azurewebsites.net/api/pets/{petId}. If the route template terminates in a wildcard, such as /api/{*restOfPath}, the value {restOfPath} is a string representation of the remaining path segments from the incoming request.

Try if something like this works for you:
<code>{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "stunnelsetupdevice": {
            "matchCondition": {
                "route": "/{id}/{*restOfPath}"
            },
            "backendUri": "http://{id}/setup.html/{*restOfPath}"
        }
    }
}
</code>
Comment: that didn't work either and I updated my answer with something else i tried.

reverse proxy in Azure


how to avoid fieldset in drupal date field

Question: I have a date field in registration form, I am using template for that. When I using  its outputs the html with fieldset. How can I remove that I wanna style likebleow fields.
Please see the image

Its drupal 7
Answer: Use the latest full release or the 7.x-2.x-dev version of the Date module.
There is an new option Render as a regular field available there:

The option was added at the Make it possible to disable fieldset for date field issue.
Answer: You can simply add this to your template.php file
function MYTHEME_date_combo($variables) {
  return theme('form_element', $variables);
}

Here 'MYTHEME' should be you theme name defined in you .info file placed inside your theme directory.
Source: http://codekarate.com/blog/removing-fieldset-drupal-7-date-field
Answer: It's easiest to do so with CSS.
#fieldset-wrapper-id {
  margin: 0;
  padding: 0;
  border: 0 none;
}
#fieldset-wrapper-id legend {
  display: none;
}

Comment: Since there is an API available to achieve this, I would highly recommend to follow that first.


How to create fast runs (i.e. speedy notes)?

Question: I am a competent composer. I am trying to improve a particular skill: creating sequences of very fast notes that sound pleasant.
Examples:
Chopin's Fantasie Impromptu
Chopin's Etude Op. 10 No.5
I have both read neuroscience articles and measured the speed at which the fastest notes can be (1) distinctly perceived versus (2) perceived at all as anything tonal or musical. Many of Chopin's pieces (including as those cited above) surpass the speed at which notes can be distinctly perceived yet are slow enough they are still musical/tonal.
My question:
does anyone know of any books or resources that discuss the experience of fast notes? I am looking for something that might give me suggestions for how to make pleasing fast note combinations.
Remark:
If you have never tried, creating fast sequences of notes isn't like creating a standard melody. As I mentioned, the brain processes the notes differently and so creating such sequences is actually a distinct skill in itself.
Thanks!
EDIT:
By "fast", I mean notes around 86 milliseconds in duration. That's about 698 ± 24 BPM and 11-12 beats per second.
Comment: Definitely an interesting topic, and I know what you mean but I'm not entirely in sync with the idea of 'surpass[ing] the speed at which notes can be distinctly perceived yet . . . still . . . tonal.'  To me that basically manifests itself as the phenomenon of knowing the chord that was just outlined, but not knowing precisely the order in which the notes where played (yet still maintaining awareness that the notes WERE played in sequence).  I posit that once a person has intuited a particular passage enough these sequences become obvious and are immediately recognizable. So, practice ;p
Comment: How fast are the notes we're talking about? 16th notes at high tempos? 64th notes and faster? Hundreds of notes per second? Thousands of notes per second? I think most of us haven't read or heard of the research you're taking about, so we'll be able to help you more if you described it a little.
Comment: I think one important concept for this is the notion of these sequences not being melodic but gestural. Each individual note is important, but they are not being perceived as individual notes -- the entire sequence (in the case of Chopin) is perceived by the listener as one.
Comment: Not qualified for a full answer, but you can get some clues from chopin to be sure: when he sweeps across the entire keyboard, the intervals tend to be larger at the bottom and smaller at the top -- this is consistent with how the ear likes to hear harmony (see harmonic series).
Comment: As you mention Chopin I assume that you are thinking about high-speed playing on a piano.  The fastest note sequences I can think of would be trills (look at Ashkenazy, especially when he was younger)  and glissandi.  Also, although they are usually very short, ornaments in much of Bach's music (and others around that time).  I think Glenn Gould's playing would be a great example of that.
Answer: You need to have a clear concept of what constitutes a "pleasing" sequence.  For some people, the sequence should be all diatonic.  For others, entirely dissonant intervals are more preferable.
As others have noted, the speed of the sequence is gestural and not melodic, therefore greater attention must be paid to beginning / ending notes of the sequence (registral resolutions / counterpoint as well as the over-arching harmony / tonality of the sequence).
I'd also like to point out that BPM's of 698 are just silly.  At a certain point, around 224bpm, the brain starts perceiving beats in terms of hypermeter.
That said, you'd want to focus your research toward music "semiotics" - specifically looking for melodic sequences.  I would say that a basic knowledge of Schenkerian analysis would help you as well.
Comment: With respect to your first sentence, isn't that what I am asking though? I am assuming it's probably not likely notes between 86-100ms are melodic so typical ideas about constructing melodies dont apply to them.  Thus, in the absence of some sort of scientific or theoretical analysis, I was hoping some musician who is experienced in runs had published something discussing them.
Comment: My point is that you need to determine your own definition of "pleasing" - someone cannot answer that for you as it is subjective.
Comment: I disagree with that to some extent. One could say all of music is subjective but clearly that isnt true. There's a reason why Chopin or Mozart's music has stuck around. It's because it's good. And there are definite patterns to what makes melodies pleasing. Although not absolute, learning the basic principles helps. And therefore I believe the same could be true of runs. Now, I grant that because runs are gestural, perhaps this means there is less of a pattern. I dont know. Maybe there are no principles for gestural music. But where are arguments for or against by ppl knowledgeable about it?
Comment: Music ***is*** subjective - I can point you to pieces that make you question what you think is music or not. Opinions like "good" are subjective as everyone has a different definition of what that might sound like. Patterns are contextual, and yes, there are principles for gestural music. You came here looking for answers. Perhaps when you receive them, you should think on them instead of just entrenching yourself in your original views.
Answer: One idea would be to explore the Chopin Polonaises. Freddy wrote parts in the polonaises that gave the impression of snare drums. In the Opus 44 Polonaise, he uses a four 32nd note pattern to imitate drums (in 3/4 time). I'm not sure what his rule for the notes was. Mostly I see the first two and second two intervals sort of outlining a V-I or V-I pattern in a key closely related to the next note (not necessarily the key the passage is in.) I think as the pattern is rhythmic rather then melodic per se, a dissonant pattern would work well.
I've tried the same idea to represent an "arrastre" in tango arrangements. The arrastre is a method of playing a note on a string bass where the bow is started slowly and speeded up during the note, without increasing bow pressure. I've been using either things like Chopin or just outlining the vii0 or bii7 around the note (both allow for a semitone approach as the last note.) Of course this doesn't work in the deep bass where a slower approach is more appropriate.
Another place in Chopin to examine fast passagework would be the big runs in the polonaises and Ballades. These are long fast runs over several octaves. Usually the seem to outline little figures. I know pianists who will replace these with glissandi on bad arthritis days.


Nginx: special behaviour for upstream "Host not found" errors?

Question: When nginx's proxy_pass returns a 502, there may be a broad range of reasons. What I want is to be able to detect when 502 was returned because upstream host was not found (that is, failed to resolve).
I know of proxy_intercept_errors, but it doesn't seem to be helpful in my case.
What I have
I have an nginx gateway server running on a Kubernetes pod. It is configured to route requests to appropriate Kubernetes services according to the first part of the hostname (the word before the first dot, e.g. service-name.example.com should route to a service called service-name).
Here is a simplified config section responsible for this logic:
server {
  listen 80;
  resolver 172.16.2.3; // Pod IP address
  server_name "~^(?<svc>[\w-]+)\.";

  location / {
    # Each Kubernetes service has an internal domain name matching the following pattern
    proxy_pass "http://$svc.default.svc.cluster.local";
    proxy_set_header Host $host;
    # Proxy `X-Forwarded` headers sent by ELB: http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/x-forwarded-headers.html
    proxy_set_header X-Forwarded-For $http_x_forwarded_for;
    proxy_set_header X-Forwarded-Port $http_x_forwarded_port;
    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
  }
}

Problem
No matter why upstream is not accessible (if it refuses connections, fails internally or just does not exist), nginx returns 502. It's only the nginx error log where you can see the actual cause.
Since the gateway is publicly available through AWS ELB, it gets often accessed by IP or just random names, which creates noise in monitors set up to react on 5XX error spikes.
What I want to do
Set up nginx to return some less aggressive error (say, 404) in case if the service's hostname can't be resolved by Kubernetes resolver.
For example, I send the following request:
curl -H "Host: non-existent-service.example.com" http://gateway.example.com

I want nginx to be able to detect the fact that the hostname corresponding to the service could not be internally resolved, and then return a 404 instead of 502.
Currently the logs look as follows:

error log:
2017/11/10 16:03:58 [error] 22#22: *482894 non-existent-service.default.svc.cluster.local could not be resolved (3: Host not found), client: 172.16.1.2, server: ~^(?<svc>[\w-]+)\., request: "GET / HTTP/1.1", host: "non-existent-service.example.com"

access log:
172.16.1.2 - - [10/Nov/2017:16:03:58 +0000] "non-existent-service.example.com" "GET / HTTP/1.1" 502 173 "-" "curl/7.43.0" "188.8.131.52" "EE"

UPDATE
Should have mentioned this in the first place. A "catch-all" default server block was the first thing to try. Turned out that this block never gets reached, because virtually any hostname matches the regexp.
Comment: use a catchall server {} block that just returns a 404 response?
Comment: That was the first thing to try - this block never gets reached, because virtually any hostname matches the regexp.
Answer: Just re-enable the default virtual host and ignore anything that hits it (as such requests are querying the IP directly, or are malicious).
For example, as seen in the nginx 1.12.x nginx.conf:
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

Comment: This approach doesn't work, because the regexp in the main server block triggers on virtually any hostname, so the catch-all block doesn't get reached.
Comment: Did you actually try it? See [How nginx processes a request](http://nginx.org/en/docs/http/request_processing.html).
Comment: I did, and I studied this article too. The idea of a catch-all block is putting an invalid name (i.e. an underscore) into server_name, which, according to nginx logic, has the lowest priority. The "catch-all" block is only supposed to trigger if no other block has triggered. Replacing the underscore with a specific hostname or a hostname with a wildcard takes precedence over the regexp, but this way it wouldn't be a catch-all block anymore.
Comment: this needs basically more input but i think that the question can be closed after 5 years


I cannot update object property which is an array using push()method , I get Typescipt error that object is not extensible

Question: I have an onClick function which aim is to update currently existig array of objects (values), but precisely it will update only one property of the array(persons).
 const addPersonHandler = (index: number) => {
    if (!values.length) return;
    const val = values;
    const persons = val[index].persons;
    console.log('persons', persons);
    console.log('type', typeof persons);
    persons.push({
      name: '',
      lastName: '',
      type: '',
      cooperationForm: null,
    });
    console.log(persons);
  };

Here You can find what is persons property from first console.log and it's type

It makes me confused as persons looks like array, but it's type is object.
Due to that I cannot update persons property with .push() method and lower console.log() throws me an error like :

Line 80 from comment point directly to .push()method.
I'm wondering what is wrong and why persons has type of object as initial array of objects - values has type LuxmedsType. Below You can find how values is typed.
export type PersonType = {
      name: string;
      lastName: string;
      type: string;
      cooperationForm: string | null;
    };
    export type LuxmedsType = {
      luxmedType: {
        package: string;
        type: string;
        cost: number;
      };
      persons: PersonType[];
      companyCost: number;
      comment: null | string;
    };

Can You please suggest what is wrong here that persons type is object although should be an array ?
Comment: Note ,  Array is an object.  To test specially if it's an array its ,  `Array.isArray()`
Comment: It's can't be a TypeScript error, it's JS error, somewhere in your code might be: ```Object.preventExtensions(obj);``` called, which prevents extension of objects
Comment: It looks like `persons` has been frozen..  `Object.freeze()`..
Comment: Where do you get `values` from?
Comment: Anserwing Your all questions:
when I console.log(Array.isArray(persons)) is returns true to me ; Object.preventExtensions(obj) or Object.freeze() don't exist in the app code.

Values I get from API call and it's array of objects
Comment: What "API call"? In any case, that makes it quite clear that the API is trying to prevent you from making mistakes by having frozen the array.
Answer: A quick and dirty way would be to recreate the array and push to that recreated array instead of the original array. As others have noted, somewhere along the line, Object.freeze() or Object.preventExtensions(obj) has been called (even if you haven't called it yourself in your source code)
const addPersonHandler = (index: number) => {
    if (!values.length) return;
    const val = values;
    const persons = val[index].persons;
    console.log('persons', persons);
    console.log('type', typeof persons);

    if (!Array.isArray(persons)) return;

    const newPersons = [...persons]
    newPersons.push({
      name: '',
      lastName: '',
      type: '',
      cooperationForm: null,
    });
    console.log(newPersons);
  };


Playing live http stream in vlcj

Question: I'm trying to use vlcj to play live internet radio stations in a project. I've played around with some sample programs for a few hours, but I cannot get either the sample programs or programs that I've played around with to play the stream from the URL.
An example of a URL I'm trying to play is: http://network.absoluteradio.co.uk/core/audio/wmp/live.asx?service=vr
Is there anything special I have to do in order to get vlcj to play this stream? I couldn't find anything to help in the API. (Assuming it can because it can be played through the VLC media player!)
Thanks a lot
Answer: Ok, the MRL you have provided us http://network.absoluteradio.co.uk/core/audio/wmp/live.asx?service=vr is a MMS server that may pull a ASX (XML) metafile which may contain at least one sub-item.
http://all-streaming-media.com/faq/streaming-media/Metafiles-ASX-Advanced-Stream-Redirector.htm
To be able to play this type of streaming media and go through each sub-item, you need to do the following code snippet:
VideoPanel.getMediaPlayer().setRepeat(true);
VideoPanel.getMediaPlayer().setPlaySubItems(true);
VideoPanel.getMediaPlayer().prepareMedia(media, options);

try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

for(String s: VideoPanel.getMediaPlayer().subItems()) System.out.println(s);
VideoPanel.getMediaPlayer().play();

For the example MRL above, it will list down all sub-items as follows:
http://wms.absoluteradio.co.uk/g1/absoluteradio.co.uk/prerolls/ar_account_1310455302_hi.wma
mms://wms.absoluteradio.co.uk/absoluteradio.co.uk/vr_lo?u=
http://wms.absoluteradio.co.uk/absoluteradio.co.uk/vr_lo?u=
mmsu://wms.absoluteradio.co.uk/absoluteradio.co.uk/vr_lo?u=
mmst://wms.absoluteradio.co.uk/absoluteradio.co.uk/vr_lo?u=
mms://wms.absoluteradio.co.uk/absoluteradio.co.uk/prerolls/problems_lo.wma

To stop playing all of them, set the following code snippet:
VideoPanel.getMediaPlayer().setRepeat(false);
VideoPanel.getMediaPlayer().setPlaySubItems(false);
VideoPanel.getMediaPlayer().stop();

For a better explanation, refer to: http://code.google.com/p/vlcj/wiki/HowToHandleYouTubeMedia
Comment: This is the solution I eventually went for and it worked successfully!
Answer: You cannot use the http to play such link directly.  You will ve to use the port number of the radio station router.  this is because if i want to receive my home live video streaming from the internet at my workplace, i type the following on url:  http://my dns server ip address:8080   The 8080 is the port number I opened on my router.

Playing live http stream in vlcj


Arranging distinct objects into different boxes

Question: How would you arrange, let's say n different objects into r different groups. Is there some separate formula for calculating this?
I found this formula in a book, but I don't understand it
$r^n - rC_1*[(r-1)^n] + rC_2[(r-2)^n] - \cdots$
Also why the alternating plus minus signs?
Comment: @user32304 I have added TeX code to this to make it look nicer. To do this I simply typed

\$r^n - rC_1*[(r-1)^n] + rC_2[(r-2)^n] - \cdots\$

to obtain $r^n - rC_1*[(r-1)^n] + rC_2[(r-2)^n] - \cdots$.
Comment: Thanks, I'm not very familiar with latex
Comment: @user34304 Can I ask from which book this is?
Comment: @user34304 That's okay. If you right click on the formula above, then click Show Math As >> Tex Commands, you can see the TeX that is required to create the "nice" version. Just put that code between \$ \$ and you have it. You can do this with any of the questions and answers on here.
Comment: Perhaps this is a simplified reference to stirlings numbers of second kind.
Answer: I'm assuming you want each group to have at least one item. If you remove this last requirement, then you have $r^n$ ways. But this also counts situations in which one group does not have any items, so we remove those:
$$ r^n - \binom{r}{1}(r-1)^n$$
But now we're double counting situations where two groups do not have items, so we add those back:
$$ r^n - \binom{r}{1}(r-1)^n + \binom{r}{2}(r-2)^n $$
and so on.
This is the complementary form of the inclusion-exclusion principle. Let $A_i$ be the situations in which group $i$ does not have any items, and let $S$ the set of all possible situations. Then
$$ \biggl|S - \bigcup_{i=1}^n A_i\biggr| = \left| S \right| - \sum_{i=1}^n\left|A_i\right|\; + \sum_{1 \le i < j \le n} \left|A_i\cap A_j\right|
- \ldots + (-1)^{n} \left|A_1\cap\cdots\cap A_n\right| $$
Answer: This is because of Inclusion-Exclusion Principle.


prove this $\int_{0}^{2}f^2(x)dx\le\int_{0}^{2}f'^2(x)dx$

Question: let $f\in C^1[0,2]$,and such $\int_{0}^{2}f(x)dx=0,f(0)=f(2)$,
show that
$$\int_{0}^{2}f^2(x)dx\le\int_{0}^{2}f'^2(x)dx$$
I think we must use $Cauchy$ inequality
my idea:I have see this
let $f(x)\in C^1([a,b],R)$,and $f(a)=f(b)=0$,show that:$$\displaystyle\int_{a}^{b}f^2(x)dx\le\dfrac{(b-a)^2}{8}\displaystyle\int_{a}^{b}[f'(x)]^2dx$$
pf:
$$|f(x)|=|f(x)-f(a)|\le\sqrt{x-a}\left(\displaystyle\int_{a}^{x}[f'(t)]^2dt\right)^{\frac{1}{2}}$$
then $$f^2(x)\le(x-a)\displaystyle\int_{a}^{x}[f'(t)]^2dt\le(x-a)\displaystyle\int_{a}^{b}[f'(t)]^2dt$$
so we can $a$to $b$ we have;
$$\displaystyle\int_{a}^{b}f^2(x)dx\le\displaystyle\int_{a}^{b}\left[(x-a)\displaystyle\int_{a}^{b}[f'(t)]^2dt\right]dx=\dfrac{(b-a)^2}{2}\displaystyle\int_{a}^{b}[f'(x)]^2dx$$
then we use $\dfrac{a+b}{2}$to $b$,then we
$$\displaystyle\int_{a}^{\frac{a+b}{2}}f^2(x)dx\le\dfrac{(b-a)^2}{8}\displaystyle\int_{a}^{\frac{a+b}{2}}[f'(x)]^2dx$$
other hand ,for any $x\in[\frac{a+b}{2},b],f(x)=-\displaystyle\int_{x}^{b}f'(t)dt$, so
$$f^2(x)=\left(\displaystyle\int_{x}^{b}f'(x)dx\right)^2\le(b-x)\displaystyle\int_{x}^{b}[f'(t)]^2dt$$
we can $\dfrac{a+b}{2}$to $b$ have :
\begin{align}
&\displaystyle\int_{\frac{a+b}{2}}^{b}f^2(x)dx\le\displaystyle\int_{\frac{a+b}{2}}^{b}(b-x)\left(\displaystyle\int_{a}^{b}[f'(t)]^2dt\right)dx\le
\displaystyle\int_{\frac{a+b}{2}}^{b}(b-x)dx\left(\displaystyle\int_{\frac{a+b}{2}}^{b}[f'(t)]^2dt\right)dx\\
&=\left(\displaystyle\int_{\frac{a+b}{2}}^{b}(b-x)dx\right)\left(\displaystyle\int_{\frac{a+b}{2}}^{b}[f'(x)]^2dx\right)\\
&=\dfrac{(b-a)^2}{8}\displaystyle\int_{\frac{a+b}{2}}^{b}[f'(x)]^2dx
\end{align}
then
$$\displaystyle\int_{a}^{b}f^2(x)dx\le\dfrac{(b-a)^2}{8}\displaystyle\int_{a}^{b}[f'(x)]^2dx$$
let $b=2,a=0$,then we have
$$2\int_{0}^{2}f^2(x)dx\le\int_{0}^{2}f'^2(x)dx$$
Comment: [Closely related question](http://math.stackexchange.com/q/282095/46120).
Answer: The hypothesis allow to see $f$ as a continuous $2$-periodic function, piecewise $C^1$. Working in $L^2(0,2)$, the Fourier coefficients of $f$ and $f'$ are
$$
c_n(f)=\frac{1}{2}\int_0^2f(x)e^{-i\pi nx}dx\qquad c_n(f')=i\pi nc_n(f)
$$
where the second formula follows from an integration by parts. In particular, $c_0(f')=0$.
Note that we have $c_0(f)=0$ by assumption. Hence Parseval for $f$ and $f'$ yields
$$
\frac{1}{2}\int_0^2|f(x)|^2dx=\sum_{n\geq 1}|c_n(f)|^2\leq \sum_{n\geq 1}\pi^2n^2|c_n(f)|^2=\frac{1}{2}\int_0^2|f'(x)|^2dx.
$$
Note that this is strict as soon as there exists $n$ such that $c_n(f)\neq 0$. Since $f$ is piecewise $C^1$, it is equal to its Fourier series which converges normally. So we have equality if and only if $f=0$ under the given assumptions.

Finally, note that this argument yields the sharper inequality
  $$
\int_0^2|f(x)|^2dx\leq \frac{1}{\pi^2}\int_0^2|f'(x)|^2dx.
$$
  And this is optimal, considering $f(x)=\sin (\pi x)$.
Comment: sorry, I edit,This condition is $f(0)=f(2)$
Comment: @math110 Then my argument is still valid, but not yours.
Comment: Thank you,can you use $cauchy-Schwarz$ inequality.thank you
Comment: @math110 Probably, yes, since the estimate is far from sharp. The function must vanish somewhere since it is continuous with zero integral. So using such a point, you can repeat your argument and see what bound this gives. Note however that this is a standard application of Parseval, which yields the best possible bound.
Comment: Hi, julien, thanks to your nice answer, it gives me a chance to review Wirtinger's inequality. +1.
Comment: @Landscape Thanks. I did not even know it was called that way...
Comment: @julien: You are welcome. I didn't know either until I learned it from a comment of Ju'x to my answer in the linked post.


Meaning of "Query results" and "Rendered output" in Views cache?

Question: Previously I've set the "Query results" and "Rendered output" cache to 1 hour.
What I need is:

Cache for 1 hour
Update the cache immediately when related node updated

But when updating node, it takes exactly 1 hour for the views page to be updated.
I'm quite confuse about what is "Query results" and "Rendered output"?
Is "Query results" the GET request?
Answer: "Query results" are raw data from DB. After fetching data you often do some additional work (modifications, templates) with data and then render it to HTML in some way — so you get a "Rendered output". For more flexibility you have two levels for caching here.
As I think (I can be wrong!) here is no sense to set "Query results cache" time less than "Rendered output cache".
Your use case, as I can see, to flush View cache immediately after new content added. You can solve it with additional staff Cache Actions, which requires Rules.
For example, you can create a rule with event "After saving new content" or "After updating existing content", condition "Content is published" and one of the Cache actions.

Cache will be flushed regardless of cache settings in your view.


If $f,g\in C[a,b]$, then is $\max_{a\le t\le b} |f(t) + g(t)| \le \max_{a\le t\le b} |f(t)| + \max_{a\le t\le b} |g(t)|$ true?

Question:
If $f,g\in C[a,b]$, then is $$\max_{a\le t\le b} |f(t) + g(t)| \le \max_{a\le t\le b} |f(t)| + \max_{a\le t\le b} |g(t)|$$ true?

Intuitively, this feels right. Also, I think that $$\min_{a\le t\le b} |f(t) + g(t)| \ge \min_{a\le t\le b} |f(t)| + \min_{a\le t\le b} |g(t)|$$ must be true. What if we remove the absolute values, i.e. we talk about
$$\max_{a\le t\le b} f(t) + g(t) \le \max_{a\le t\le b} f(t) + \max_{a\le t\le b} g(t)$$ and
$$\min_{a\le t\le b} f(t) + g(t) \ge \min_{a\le t\le b} f(t) + \min_{a\le t\le b} g(t)$$
Do any of these hold? I'm not able to come up with formal methods to prove/disprove these, and I'd appreciate any help! I ended up using the very first inequality in a proof, so I hope it is right. About the rest, I am only speculating, but I would love to know how to approach inequalities like these. Thanks a lot!
P.S. $C[a,b]$ denotes the set of continuous functions on $[a,b]\subset \mathbb R$.
Comment: A correct version of #2 would be $\min |f(t) + g(t)| \ge \min |f(t)| - \max |g(t)|$
Comment: Won't it be nicer to find something with min all throughout?
Comment: You can write it as $\min |f(t) + g(t)| \ge \min |f(t)| + \min (- |g(t)|)$ if you prefer.
Comment: Thank you, should've seen that!
Answer: Yes, all you wrote is correct except for the second inequality (with the $\min$'s and the absolute values). To see e.g. $$\max_{a\leq t\leq b}|f(t)+g(t)|\leq\max_{a\leq t\leq b}|f(t)|+\max_{a\leq t\leq b}|g(t)|$$
note that for all $s\in [a,b]$ we have $$|f(s)+g(s)|\leq |f(s)|+|g(s)|\leq\max_{a\leq t\leq b}|f(t)|+\max_{a\leq t\leq b}|g(t)|$$
Now taking the maximum over all $s\in [a,b]$ we get the inequality above. The other inequalites can be proven in the same way.
Notice that the inequality may be strict since $f$ and $g$ can attain their maxima at different points, consider e.g. $f(t)=t, g(t)=1-t$ on $[0,1]$.
To see why the second inequality fails, take e.g. $f=-g$.
Comment: @MartinR Good point, then we would just need to replace $\max$ with $\sup$.
Answer: It has already been pointed out in leoli1's answer that the second inequality is wrong. A correct lower bound for $\min |f(t) + g(t)| $ can be obtained by using the "reverse triangle inequality":
$$
|f(t) + g(t)| \ge |f(t)| - |g(t)| = |f(t)| + (- |g(t)|)
$$
implies
$$
\min_{a\le t\le b} |f(t) + g(t)| \ge \min_{a\le t\le b} |f(t)| + \min_{a\le t\le b} (-|g(t)|) =  \min_{a\le t\le b} |f(t)| - \max_{a\le t\le b} |g(t)| \, .
$$


Nodes they have reference to the nodes of current user

Question: I use node reference and want to display with views to the user only the nodes they have reference to its nodes :
A*<----B
^----C
E**<-----D
*: node created by the current user.
**: node created by an other user.
The views for current user will only show : B,C.
Comment: Do you mean that you want to display to a particular user any nodes that are referencing any nodes that they have created? Sorry, this question just reads a little bit funny - just want to get clarification :-)
Comment: yes "nodes that are referencing any nodes that current user have created" :)
Answer: I assume you already have the view. In it under 'Advanced' add a contextual filter on Content:Author:UID. When you configure the filter select 'Provide default value' under 'When the filter value is NOT available' and set the Type to 'User ID from currently logged in user'. This will limit the display to nodes the current user created.
EDIT:
Misunderstood. If you are trying to create a list if nodes which reference the current node (eg, view displayed as a block when the page is displayed) the method is the same. Create a view of the nodes, and a Contextual filter on the Node Reference field. The default value type should then be set to 'Content ID from URL'. This will limit the list to those nodes which refer to the current node.
Comment: But the current user created A not B and C, you will only show A with you views !
Answer: This can be done by using a view Relationship.

In Relationships, add the content field that you are using as a node reference. This should be something like: Content: Reference (field_parent_node).
When editing the new relationship, make sure Require this relationship is checked.
In Fields, Add the corresponding fields that you want in your view. When selecting node fields, like Node: Title, be sure to set the Relationship to be the name of your relationship. In my example, this would be Reference.
In Filters, add filter User: Current.
When editing this filter, set the Relationship to be the name of your relationship (example: Reference) and set the Is the logged in user to be Yes.

I tested this briefly and it worked for creating a view that only lists the node references authored by the currently logged in user.


Problema com Slider

Question: Quando carrega a página desse site o título da descrição do slider aparece no topo e depois desce.
Como resolver?
O site está em WordPress. Plugin Huge IT Slider
Acredito que o problema talvez seja de CSS.
Comment: Que eu saiba isso acontece quando tem um elemento vazio que recebe conteúdo e o `height` aumenta de repente. Se a altura é fixa, é fácil resolver, se for variável são outros 500.
Answer: Verifique se você possuí algum script com $(document).load(function()) ou $(window).load(function()) e altere para $(document).ready(function()). É claro, altere apenas os elementos que correspondem o ID ou Class de gatilho da sua função.
Acredito que o problema não seja no CSS.
Um problema do CSS é a frase "Mais de 150 trabalhadores são resgatados no Piauí" que está sobrepondo o campo "Notícias"
Comment: Acho que ele deve procurar o ID ou Class que chama esse slider e jogar dentro do `$(document).ready(function())`, se ele simplesmente mudar, pode comprometer outros elementos do site, não?
Comment: Alterei mas continua a mesma coisa. A impressão que tenho que alterando o load p ready o carregamento fica mais rápido.
Comment: @FelipeStoker sim, de fato. Deveria ter adicionado essa linha em minha resposta, algo que farei.
Comment: @kadupereira não sei se foi a minha solução que pra produção mas, seu site está abrindo corretamente aqui agora.
Comment: Obrigado @RafaelBarbosa fiz a alteração que você indicou no post. $(window).load(function()) por $(document).ready(function()).

Problema com Slider


Iterating arraylist until find an specific character and stop the iteration

Question: I'm trying to iterate an arraylist and then make it stop when it finds a character, in this case, a comma. This is what I have:
This is the arraylist:
List<String> collection = Arrays.asList(new String[]{"I", "f", " ", "y", "o", "u", " ", "g", "e", "t", " ", "a", " ", "t", "e", "x", "t", " ", "m", "e", "s", "s", "a", "g", "e", " ", "f", "r", "o", "m", " ", "a", "n", " ", "e", "m", "a", "i", "l", " ", "a", "d", "d", "r", "e", "s", "s", " ", "o", "r", " ", "n", "u", "m", "b", "e", "r", " ", "y", "o", "u", " ", "d", "o", "n", "'", "t", " ", "r", "e", "c", "o", "g", "n", "i", "z", "e", ",", " ", "i", "t", "'", "s", " ", "p", "r", "o", "b", "a", "b", "l", "y", " ", "b", "e", "s", "t", " ", "t", "o", " ", "i", "g", "n", "o", "r", "e", " ", "i", "t"});

And this is the method I'm using on main: showUntil();
private static void showUntil() {

    for(String g : collection){
        if(g.equals(",")){
            System.out.println(g);
        }

    }
}

I'm using java for this exercise.
Comment: Does this answer your question? [How do you stop a loop from running in Java](https://stackoverflow.com/questions/5006972/how-do-you-stop-a-loop-from-running-in-java)
Answer: You can use the indexOf function and iterate till that index. This is one approach
List<String> collection = Arrays.asList(new String[]{"I", "f", " ", "y", "o", "u", " ", "g", "e", "t", " ", "a", " ", "t", "e", "x", "t", " ", "m", "e", "s", "s", "a", "g", "e", " ", "f", "r", "o", "m", " ", "a", "n", " ", "e", "m", "a", "i", "l", " ", "a", "d", "d", "r", "e", "s", "s", " ", "o", "r", " ", "n", "u", "m", "b", "e", "r", " ", "y", "o", "u", " ", "d", "o", "n", "'", "t", " ", "r", "e", "c", "o", "g", "n", "i", "z", "e", ",", " ", "i", "t", "'", "s", " ", "p", "r", "o", "b", "a", "b", "l", "y", " ", "b", "e", "s", "t", " ", "t", "o", " ", "i", "g", "n", "o", "r", "e", " ", "i", "t"});

for(String chr : collection.subList(0, collection.indexOf(","))) {
    System.out.println(chr);
}

If you want to correct the code you have written, you need to break from the loop if you find a match like below
for(String g : collection) {
    if(g.equals(",")) {
        System.out.println(g);
        break; //exit the loop if comma is found!
    }
}

Comment: And the first one did the trick, thank you!
Comment: Perofrmance-wise it's a horrible choice. It traverses the list twice when one traversal would suffice and creates an unnecessary throwaway object. You need to understand what each library method does before you call them.


How PEAR:Mail can save a copy of email in sent items?

Question: Is that possible to save our emails when we use PEAR:Mail and send them trough SMTP server?
ex. when an email is sent with IPhone, we can see a copy of that email in Sent folder on our web mail access
I'm looking for a solution base on PHP code.
Answer: Your iphone (and every other mail client) does it the following way:

send the mail via smtp
store the mail via IMAP in the "Sent" IMAP folder

It's basically sending the mail 2 times to the server, once with SMTP to get it out to the world, and another time to store it in your mailbox.
Answer: sending a mail will not automatically create  a copy of it in the 'sent' folder. Use imap_ append(). imap_append()


Sharepoint UpdateList Method : Newly created Columns are not visible

Question: I worked on  code .It is working successfully.
But Problem i am facing is:
New Columns are not visible in List ( I tried with With Setting Required = "TRUE" ).
I tried with compairing Field Value of Both Visible and No-Visible Columns.
Difference i found is : Visible Columns (Created Manually) doesn't contain Version value.
wereas columns i am creating have it.
So i tried with passing null value to "ndVersion.Value".
But it is still not working and automaticaly putting some value to version.
Can you help me out in this?
I tried Solution given Here .
But it din't Worked again. :(
Answer: There are actually several things that happen when you add a column to a list in the browser:

Field is added to the list
Field is added to list content types
Field is added to the default view

When you add a column using code, you may only be modifying the list, but not the content type (which defines new/edit forms) or the view (which defines list views)
<code>                var field = list.Fields[fieldName];

                var ctype = list.ContentTypes[contentTypeId];
                var fieldref = new SPFieldLink(field);
                ctype.FieldLinks.Add(fieldref);
                ctype.Update();

                var view = list.Views[viewName];
                view.ViewFields.Add(field);
                view.Update();
</code>
Comment: Thanx Tom,
But i don't know how to Modify "content type and view" of list ?
Can provice me sample code links?
Comment: I added some code - you'll need to expand on it depending on your requirements of course, but those collections/objects should give you a good starting point.
Answer: There's a good amount of useful information on this on MSDN.
Adding Columns to Content Types
HowTo: Add a column to a list (Code Links)
Answer: Try with setting ReadOnly property to "FALSE"
Answer: I would use the object model provided using Microsoft.Sharepoint.dll instead of using the web services.
There is problems in Sharepoint when you are adding new columns to the content type that changes are not always pushed down to the lists. I think the Sharepoint UI does this for you when you edit a content type, but when you do it yourself in code then you have to make sure that your changes are pushed down to the lists.
There are 2 ways to add content type data to a list programmatically

via schema.xml -> Then you have to let the list inherit from your content type, but you still have list up all the fields that you want to use from your content type.
via code -> Add your field to the content type, but then you have to add the content type to the list again to make sure that all fields are populated in the list


Analytic function taking prescribed values

Question: From Ahlfors, exercise 5.2.3 #1:

Suppose that $a_n\to \infty$ and that the $A_n$ are arbitrary complex
  numbers. Show that there exists an entire function $f(z)$ which
  satisfies $f(a_n)=A_n$.
Hint: Let $g(z)$ be a function with simple zeros at the $a_n$. Show that $$\sum_{n=1}^\infty g(z)\frac{e^{\gamma_n(z-a_n)}}{z-a_n}\cdot
 \frac{A_n}{g'(a_n)}$$ converges for some choice of the numbers
  $\gamma_n$.

I see that $$\lim_{z\to a_i}g(z) \frac{e^{\gamma_n(z-a_n)}}{z-a_n}\cdot \frac{A_n}{g'(a_n)}=\begin{cases} A_n&n=i\\0&n\neq i \end{cases}$$
for any choice of $\gamma_n\in \mathbb{C}$, so the terms do what we want. In trying to choose $\gamma_n$ to ensure convergence, it doesn't seem like just a matter of making $\gamma_n$ be real numbers going to $-\infty$, for instance, since $e^{-z}$ takes every value in a neighborhood of infinity, not just values of small modulus. So we have to figure a way to use some symmetry to get the different $e^{\gamma_n(z-a_n)}$ to cancel, right?
Comment: @BettyMock Weierstrass product theorem
Comment: I'm blank on what symmetries one might find because of the random nature of the $A_n$.  Also, he didn't say g must be analytic or entire, but we must have g'($a_n$) exists for all the n's.  So how do we know there is even such a g? Proving that might be equivalent to the original problem, unless Ahlfors has shown you how to construct it.  If he did, that might throw some light on this.
Comment: @Cocopuffs  Thank you for the tip. That theorem is very neatly done.  I knew I could (trivially) construct a polynomial if the sequence is finite, and that extending it to be infinite would not work.  Not being Weierstrass, I didn't think of his approach.
Comment: Isn't it possible to write an $n$-dimensional analogue of the function in the above proof, so that we can have a holomorphic $f : \mathbb{C}^n \to \mathbb{C}$ having prescribed values at a discrete sequence?
Answer:
get the different $e^{\gamma_n(z−a_n)}$ to cancel

No, that's not going to work.

$e^{-z}$ takes every value in a neighborhood of infinity

Yes, it does. But we are not looking to control the series at a neighborhood of infinity. What we need is  its uniform convergence on every compact set.
So: think globally, act locally -- get the series to converge on every disk.

Let $$h_n(z)= \dfrac{A_n g(z)}{(z-a_n)g'(a_n)}$$
The goal is to have uniform convergence of $\sum e^{\gamma_n(z-a_n)}h_n$ on every disk $D_R=\{z:|z|\le R\}$. For this, it suffices to have
$$
  \max_{D_R}\left|e^{\gamma_n(z-a_n)}\right| \le \frac{2^{-n}}{
\max_{D_R} |h_n |} \tag{1}
$$
for all $n\ge N_R$, where $N_R$ depends on $R$.
As you know, this means we want the real part of $\gamma_n(z-a_n)$ to be very negative on $D_R$. There is no way to do this until $a_n$ go out of $D_R$. Fortunately, they eventually do. If $|a_n|\ge 2R$, then by choosing $\gamma_n$ to have the same argument as $a_n$, we make sure that the argument of $\gamma_n(z-a_n)$ is between $\pi\pm \pi / 6$ for all $z\in D_R$. It remains to make the   magnitude of $\gamma_n$ large enough. For example, make it large enough so that  (1) holds for $R=n/2$.
Then for any fixed $R$ the inequality (1) holds when $n\ge 2R$.
Comment: Great answer...thanks!
Comment: I spent some time on this, and was even willing to accept pointwise convergence.  But I didn't connect with the need to restrict things to a compact set.  Good work.
Comment: One thing that's confusing me: we want $\text{Arg}\gamma_n(z-a_n)$ between $\pm \pi/6$? I thought we wanted the real part very negative. (But the above arguments lie in the first and fourth quadrants.)
Comment: @EricAuld Should have been $\pi\pm \pi/6$; fixed now.
Comment: @PostNoBulls Thanks, that makes sense now.


Drupal PHP views - how to reference nested braket array variables?

Question: I did a dpm() on the path variable i have and I'm running into the issue of figuring out how to reference this variable. When I do a print_r() on the variable it shows that its [[path]]
I'm not sure how to reference that. I thought it might be $var[['path']] but that doesnt work.
Comment: This is a plain PHP question for which the answer didn't change even if you we're not using Drupal.
Answer: You're almost there, since the square brackets are part of the string they need to go inside the quotes, e.g.
<code>$var['[path]']
</code>
Comment: omg. why did they do that.... I was trying to google this as if it was a new variable type that i never noticed. lol thanks clive!


Write the derivative of the lower-triangular matrix $L(t)$ in terms of $L(t)$, $L^{-1}(t)$ and $\frac{d}{dt}A(t)$, where $A(t)=L(t)L^T(t)$

Question: Let $A(t)$ be a symmetric positive definite matrix, thus by Cholesky decomposition, we have $A(t)=L(t)L^T(t)$ where $L(t)$ is lower triangular. Suppose $A(t)$ is differentiable.

I want to write $\frac{d}{dt}L(t)$ as a function of $L(t)$, $L^{-1}(t)$ and $\frac{d}{dt}A(t)$.

I tried $$\frac{d}{dt}A(t)=\frac{d}{dt}L(t)L^T(t) + L(t)\frac{d}{dt}L^T(t).$$ I don't know how to proceed. I know that I need to separate $\frac{d}{dt}L(t)$ out. But it seems a troublesome task. Any hint please? Thank you!
Answer: For compactness I'll write $C' := \frac{d}{dt} C(t)$ for any differentiable matrix-valued function.
Hint By the product rule you've found that
$$A' = L' L^{\top} + L (L')^{\top} .$$
Multiplying both sides on the left by $L^{-1}$ and on the right by $(L^{\top})^{-1}$ and canceling leaves
$$L^{-1} A' (L^{-1})^{\top} = L^{-1} L' + (L')^{\top} (L^{-1})^{\top} = L^{-1} L' + (L^{-1} L')^{\top} .$$
The key observations here are that (1) the first term on the r.h.s. is lower-triangular (it's a product of lower-triangular matrices) and (2) the two terms on the r.h.s. are transposes of one another.
Additional hint If $M$ is lower-triangular, then
\begin{align}M + M^{\top} &= \pmatrix{
m_{11} & 0 & \cdots & 0 \\
m_{21} & m_{22} & \cdots & 0 \\
\vdots & \vdots & \ddots & \vdots \\
m_{n1} & m_{n2} & \cdots & m_{nn}
} + \pmatrix{
m_{11} & m_{21} & \cdots & m_{n1} \\
0 & m_{22} & \cdots & m_{n2} \\
\vdots & \vdots & \ddots & \vdots \\
0 & 0 & \cdots & m_{nn}
} \\
&=
\pmatrix{
2 m_{11} & m_{21} & \cdots & m_{n1} \\
m_{21} & 2 m_{22} & \cdots & m_{n2} \\
\vdots & \vdots & \ddots & \vdots \\
m_{n1} & m_{n2} & \cdots & 2 m_{nn}
}
\end{align}
In particular, we can read off all of the entries of $M$ from the entries of $M + M^{\top}$.
Applying this procedure to $M = L^{-1} L'$ recovers $L^{-1} L'$ from $L^{-1} A' (L^{-1})^{\top}$.
Comment: I still don't get how to recover $M$ from $M+M^T$. Maybe I misunderstood something. Do you mean $M$ equals $M+M^T$ multiplied by something? Thank you!
Comment: I mean something less sophisticated than that: Reading off the entries of $M + M^{\top}$ tells you more or less immediately what the entries of $M$ are. I've modified the answer to make this more explicit.


How do I use setInterval and clearInterval peoperly?

Question: I want this timer to count down from 20 and stop at 0. timerFunction() is called on the click of a button.
var time=20;
var clicked=false;

function timeDisplay(){
    document.getElementById("timer").innerHTML=
    time;
}
function timerFunction(){
    if(!clicked){
        clicked=true;
        if(time>0){
            var i=setInterval(function(){
                time--;
                timeDisplay();
            },1000);
        }
        else{
            clearInterval(i);
        }
    }
}

Right now, the timer works, but it doesn't stop at zero and I don't understand why. Obviously I am very new to this, so any constructive criticism is appreciated.
Answer: Firstly your timerFunction is run only once. The statement if(time>0) will execute only once and it will always be true because time is 20 initially.
You ideally want your time variable to be checked after regular intervals. Something you can do inside your timeDisplay function. To enable that, you need to ensure that unique interval id (here intervalName) can be accessed by timeDisplay.
var time=20;
var clicked=false;
var intervalName = null;
function timeDisplay(){
    document.getElementById("timer").innerHTML=
    time;
      if(time == 0){
            clearInterval(intervalName);
        }

}
function timerFunction(){
    if(!clicked){
        clicked=true;
       intervalName = setInterval(function(){
                time--;
                timeDisplay();
            },1000);
        }

}

Note: I have replaced i with intervalName.
Answer: Your code has a logic flaw. When you call timerFunction, you set the interval. But since that function is run only once, it will never check your if clause and it also doesn't set the intervall multiple times, as it would have, would it get executed more than once.
Hint: try to check for the time inside the setIntervall callback. I'm not 100% sure, but you can probably clear the intervall inside aswell with something like clearIntervall(this). Maybe you wanna try this out. :)
Answer: Actually your if condition is checking for once and when the execution goes inside if it is not checking if condition again so you should have a condition inside interval function checking the value of time variable and clear interval.
`
var time=20;
var clicked=false;
function timeDisplay(){
    document.getElementById("timer").innerHTML= time;
}
function timerFunction(){
    if(!clicked){
        clicked=true;
        var i= setInterval(function(){
                time--;
                if(time == 0){
                    clearInterval(i);
                }
                timeDisplay();
        },1000);
    }
}

`


Borel smallest σ-algebra why smallest ? How can there be bigger σ-algebras?

Question: What does "smallest" exactly mean in the definition of $\mathscr B(\mathbb R)$? The only "bigger" σ-algebras I can see are the ones where we count twice, thrice, etc each open set.
It seems to me obvious that we shall not count twice, thrice etc the open sets. Ignoring these double, triple counting σ-algebras, leaves us with only one σ-algebra $-$ the basic one (the one we call smallest I think).
Answer: It means that any $\sigma$-algebra $S$ on $\Bbb R$ that contains all open sets will also contain $\mathscr{B}(\Bbb R)$.
Two examples of strictly larger algebras are the Lebesgue algebra and the trivial power set algebra (all sets are measurable), assuming the axiom of choice as normal in analysis.
Comment: Is it the coursest topology the structure admits?
Comment: @CyclotomicField Do you mean, is the Euclidean topology the coarsest topology contained in the Borel algebra? The answer would be no, eg the indiscrete topology


Como esconder uma div apenas no firefox

Question: Olá,
De qual maneira é possível fazer esconder uma
 apenas no Firefox e exibir em demais navegadores?
Comment: `var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;`
Answer: Segundo Css Tricks, você poderia fazer algo assim, considerando seu div com id meuDiv:
/* Firefox 2 */
html>/**/body #meuDiv, x:-moz-any-link {
    display: none;
}

/* Firefox 3 */
html>/**/body #meuDiv, x:-moz-any-link, x:default {
    display: none;
}

/* Any Firefox */
@-moz-document url-prefix() {
    #meuDiv {
        display: none;
    }
}

E, caso também queira o contrário:
#meuDiv {
    display: none;
}

/* Firefox 2 */
html>/**/body #meuDiv, x:-moz-any-link {
    display: block;
}

/* Firefox 3 */
html>/**/body #meuDiv, x:-moz-any-link, x:default {
    display: block;
}

/* Any Firefox */
@-moz-document url-prefix() {
    #meuDiv {
        display: block;
    }
}

Comment: Esclareceu minha dúvida, obrigado.
Comment: e para demostrar uma div apenas no firefox, como é feito?
Comment: @theflash Atualizei minha resposta. A ideia para mostrar a div apenas no firefox é deixar `display: none` por padrão e, depois, utilizando o seletor específico para o firefox, mudar para `display: block`.
Answer: Seguindo a ideia que o Sergio disse:

window.onload = function () {
   var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

   if (is_firefox) {
      document.getElementById('divEspecifica').style.display = 'none';
   }
}
#divEspecifica {
  width: 50px;
  height: 50px;
  background-color: red;
}

#divTodos {
  width: 50px;
  height: 50px;
  background-color: blue;
}

Comment: Obrigado Maicon!

Como esconder uma div apenas no firefox


Infinite limits

Question: Does a limit that has the value of infinite exist or not?
I've recently come across certain sources that say that if the value of a limit is infinite, then that limit does not exist. This contradicts what my calculus teachers and lecturers taught me however, that a limit doesn't exist if the right hand limit and left hand limit differ.
So which one is it?
Comment: IVlad: Whenever you get a result of ∞ (resp. -∞) from a limit calculation, simply consider it to mean that no matter how close you take your independent variable to the value of interest, you will never manage to find an upper bound (resp. lower bound). But there is still the issue of making sure both the left and right hand limits are consistent: one can probably say that the limit of xֿ² as x→0 is ∞, but the limit of xֿ¹ as x→0 does not exist in any sense of the word.
Answer: Obviously it depends on the definition of "exists". Some authors explicitly work over the extended real line with $\pm\infty$ adjoined, so that such infinite limits do explicitly "exist" as first-class values. But there is no consensus. One needs to pay attention to the author's definitions and conventions.
Perhaps it is worth mention - even though this case is rather trivial - that adjoining points at infinity is a special case of various constructions that attempt to simplify matters by some type of existential closure. Below I append an excerpt from my Oct 15, 1996 sci.math post.

This thread originated in a query as to whether infinity or $1/0$
could be admitted as a "value", and soon drifted into discussion
of the Riemann sphere and other topological manifestations of
infinity via compactification. Below I point out a couple of
marvelous references on these topics; further I would like to
bring to your attention a much wider perspective on such topics,
namely that of existential closure as studied in model theory.
There is a beautiful exposition of points at infinity, projective
closure, compactifications, modifications, etc. in [FM][1] Chapter 7,
Points at Infinity, by H. Behnke and H. Grauert. This is volume III
in the excellent "Fundamentals of Mathematics" series,
which deserves to be on the bookshelf of every budding mathematician.
A much deeper appreciation of the methodology behind these constructions
can be had by studying them from a model-theoretic perspective, in
particular from the standpoint of existential closure and model
completion. Kenneth Manders has written a series of thought
provoking papers [2],[3] from this perspective.
I close with an excerpt from the introduction to [2]:

"The systematic adjunction of roots, or solutions to other simple
conditions, as in formation of the complex numbers by adjoining
imaginaries, or in adjunction of points "at infinity" in traditional
geometry, may be analysed as existential closure and model
completion. 'Existential closure' refers to a class of processes
which attempt to round off a domain and simplify its theory by
adjoining elements -- more properly, it refers to the formal
relationship that obtains in such a process. 'Model completion' is
one of the terms employed when this process is successful. The
formation of the complex numbers, and the move from affine to
projective geometry, are successes of this kind. Thus, the theory of
existential closure gives a theoretical basis of Hilbert's "method
of ideal elements." I now sketch the theory of existential closure,
to bring out when, how, and in what sense existential closure gives
conceptual simplification."

[FM] Fundamentals of mathematics. Vol. III. Analysis.
Edited by H. Behnke, F. Bachmann, K. Fladt and W. Suss.
Translated from the second German edition by S. H. Gould.
Reprint of the 1974 edition. MIT Press,
Cambridge, Mass.-London, 1983. xiii+541 pp. ISBN: 0-262-52095-8 00A05
[2] Manders, Kenneth
Domain extension and the philosophy of mathematics.
J. Philos. 86 (1989), no. 10, 553--562.
http://www.jstor.org/stable/2026666
[3] Manders, Kenneth L.
Logic and conceptual relationships in mathematics.
Logic colloquium '85 (Orsay, 1985), 193--211,
Stud. Logic Found. Math., 122,
North-Holland, Amsterdam-New York, 1987.
http://dx.doi.org/10.1016/S0049-237X(09)70554-3
Comment: I've seen it said that the limit does not exist both for limits like $\lim _{x \to \infty}x$ and limits like $\lim _{x \to \infty}\tan(x)$. These are clearly different things, because in one case there is no limit in any sense of the word and in the other $x$ increases unbounded. I just want some terminology to distinguish between the two. Is there any way to tell when someone says the limit does not exist if they mean there's just no limit at all or if there's an infinite limit, meaning there is a limit in some sense but that limit just happens to not exist as a number?
Comment: @harry I updated the link. Most of the sci.math post is already here by now.
Comment: Bill, the link seems broken. Could you fix it?
Answer: It is important to consider the context in which you are taking the limit.  When taking the limit of a sequence $\{ x_{n}\}$, we must consider what set the elements of that sequence are coming from.  For example, if $\{ x_{n}\} \subset \mathbb{R}$, then for the limit $L$ to exist (in $\mathbb{R}$) we must have that $L \in \mathbb{R}$.  If $\{ x_{n}\} \to \infty$ as $n \to \infty$, then the limit doesn't exist (in $\mathbb{R}$).
But, there is another notion of limit called $\text{lim sup}$.  According to Baby Rudin (slightly modified):

3.16 Definition Let $\{s_{n}\}$ be a sequence of real numbers. Let $E$ be the set of numbers $x$ (in the extended real number system [which includes $\pm \infty$]) such that $s_{n_{k}} \to x$ for some subsequence $\{s_{n_k}\}$.  This set $E$ contains all subsequential limits* plus possibly the numbers $+ \infty$, $-\infty$.

Now define $$\begin{align}\text{lim sup} \;\; s_{n} &= \sup E, \;\;\;\;\text{and} \\\
\text{lim inf} \;\; s_{n} &= \inf E.\end{align}$$
* A subsequential limit is just the limit of the subsequence, if that subsequence converges.

With this definition we can discuss infinite limits (superior or inferior).
EDIT: Removed my erroneous claim that finite $\text{lim sup}$'s and $\text{lim inf}$'s collapse to the regular old $\lim$.  (Counterexample: $\text{lim sup}_{x \to \infty} \sin(x) = 1$ but $\lim _{x \to \infty}\sin(x) \neq 1$.
Answer: There is no ambiguity about infinite limits. For instance, when we define that a sequence or real numbers $(x_n)$ "tends to infinity", $(x_n) \longrightarrow +\infty$, we just mean that, for each real number $N$ there is some $n_0 \in \mathbb{N}$ such that, for all $n\geq n_0$, we have $x_n > N$. That is, the sequence $(x_n)$ grows indifinitely. There is no implication here that $+\infty$ "exists", or doesn't, nor any problem with the fact that, certainly, $+\infty$ is not a real number. In fact, there is no $\infty$ on the right hand side of the definition, but just real numbers. And symbols on the left hand side of a definition mean just you want them to mean according with what you put on the right hand side.
Comment: Oh, wow. A $-1$. Someone is disappointed by the "non-existence" of $\infty$ perhaps?  :-)
Answer: The language use in my calculus class was that this is an improper limit. So that strictly speaking there is no limit in the proper sense.
The criterion with right hand limits and left hand limits works at points really belonging to the real line (and then first of all both one-sided limits have to exist for themselves).
Answer: While I'll defer to other's answers (e.g. Bill Dubuque's) that in the most general sense "it depends" is the correct answer, it may be worth noting that in the context of AP Calculus and across numerous common AP Calculus texts (at both the AB and BC level), a limit exists if and only if it has a real value, so saying that $\underset{x\to c}\lim f(c)=\infty$ or $\underset{x\to c}\lim f(c)=-\infty$ is saying that the limit as $x$ goes to $c$ of $f(x)$ does not exist and simultaneously giving more information about how the limit does not exist.
Answer: It looks that infinity is a bone of contention among mathematicians. In my view the notation + or - infinity is very useful to highlight the behavior of the graph of a function as the variable x tends to a finite value, remarking the function values are going to very large values impossible to bound with the biggest one. One solution is to accept there are two kind of limits in Mathematics: a finite limit, represented by a real number if it exists, and an infinite limit whose quantity can not be numbered as usually we do when finite limits, and to be happy that + or - infinity is applicable in reliable situations to sort or identify a value incommensurable large. Also I think that philosophic convictions and religious standings are playing strongly in this analysis. There will be light at the end of the tunnel!
sandor
Answer: It depends on what you are working with. For example, one definition of the derivative of a function that the limit: $\lim_{h \rightarrow 0} \frac{f(x+h)-f(x)}{h}$ exists and it is finite. On the other hand, if you're talking about the limit of a sequence ${ x_n }$, then you may want to distinguish between cases when the limit is infinite, or it doesn't exist, which means, like you said, that taken two subsequences you get different values for the limit -in this case you say that the sequence oscillates-.
Definitions, of course, solve a lot of problems, you define in $\mathbb{R}$ $\lim_{x \rightarrow \infty} f(x) = \infty$ as follows: $\forall N >0, \; \exists M >0: \; x > M \Rightarrow f(x) > N$, then you don't really have to call in the extended number line.
Comment: You say that X_1 and X_2 are metric spaces, then use an order; don't confuse things that can be done to R with things that can be done for arbitrary metric spaces.  The thing being done to R is called end compactification: http://en.wikipedia.org/wiki/End_(topology)
Comment: Right, I messed up while I was writing, I should have re-read it. I'll correct

Infinite limits


Different return values of the sum of a row with imputed values using 'complete' (mice) and 'update' (survey)

Question: I need to calculate the sum of some variables with imputed values. I did this with complete --> as.mids --> with --> do.call
I needed to do the same thing but in a survey context. Therefore, I did: update --> with --> MIcombine
The means of the variables calculated both ways do not match. Which one is correct?
You may check this different behavior in this toy database:
library(tidyverse)
library(mice)
library(mitools)
library(survey)

mydata <- structure(list(dis1 = c(NA, NA, 1, 0, 0, 1, 1, 1, 1, 0),
                         dis2 = c(0, 1, 0, 1, NA, 1, 1, 1, 1, 0),
                         dis3 = c(1, 1, 0, 0, NA, 1, 1, 1, 1, 0),
                         sex = c(0,0,0,1,0,1,1,1,1,0),
                         clus = c(1,1,1,1,1,2,2,2,2,2)),
                    row.names = c(NA, 10L),
                    class = c("tbl_df", "tbl", "data.frame") )

imp <- mice::mice(mydata, m = 5, seed = 237856)

# calculating numenf with mice::complete
long <- mice::complete(imp, action = "long", include = TRUE)
long$numenf <- long$dis1 + long$dis2 + long$dis3
imp2 <- mice::as.mids(long)
res <- with(imp2, mean(numenf))
do.call(mean, res$analyses) # mean = 2.1

#calculating numenf with update (from survey)
imp1 <- mice::complete(imp)
imp2 <- mice::complete(imp, 2)
imp3 <- mice::complete(imp, 3)
imp4 <- mice::complete(imp, 4)
imp5 <- mice::complete(imp, 5)
listimp <- mitools::imputationList(list(imp1, imp2, imp3, imp4, imp5))
clus <- survey::svydesign(id = ~clus, data = listimp)
clus <- stats::update(clus, numenf = dis1 + dis2 + dis3)
res <- with(clus, survey::svymean(~numenf))
summary(mitools::MIcombine(res)) # mean = 1.98

Comment: Hi, I tried modifying your post to include all the necessary information, but I cannot seem to replicate it. With `mice::complete` I get 1.9 (instead of 2.1), and the survey route gives me an error. Can you confirm that it works and that the new code is correct? Otherwise, can you adapt where necessary? After that I'll have a look.
Comment: Thank your for your interest, @slamballais. Yes, I've just tried the syntax and obtained the same result with complete. For the record, I've checked by hand that the correct result is 1.98, the one provided by survey/update. This is the mean of the means of numenf in the 5 imputed databases. I cannot understand how mice/complete gets 2.1 (at least in my computer)
Answer: Answer
Replace do.call(mean, res$analyses) with mean(unlist(res$analyses)).

Rationale
In the first code snippet, res$analyses is a list. When entering it into do.call, you are essentially calling:
mean(res$analyses[1], res$analyses[2], res$analyses[3], res$analyses[4], res$analyses[5])

mean takes the average of a vector in its first argument. The other arguments are not used properly (see ?mean). Hence, you're just getting 2.1 back, since that is the (mean of the) value of first analysis.

We can make a vector out of the list by using unlist(res$analyses). Then, we can just feed it to mean as an argument:
mean(unlist(res$analyses))

Comment: Thank you again. Now I get the same (and correct) result with both approaches. Just to make your answer absolutely precise, I was getting 2.1 (not 1.9) because this is the mean of the first element of res$analyses
Comment: Yes, I'm not sure why, but I'm getting different average numbers than you. Probably some seed procedural difference. I'll adapt the answer :)


ruby insert equivalent in javascript

Question: If I have a string like this: "4589" I can do this in ruby:
str.insert(-4,' ')

returns: "4 589"
Is anything similar possible in javascript, or do I need to write a function using split, splice and join?
Comment: @thiebo I don't know why it's downvoted. Ruby has a number of methods for manipulating strings and arrays that JavaScript doesn't have, so you have to do lower-level things to get them done. Ranges, for an example that comes up all the time with me.
Comment: No, there isn't. Yes, you have to.
Answer: Primitives are immutable, and there aren't any single methods that can do what you want except for a regular expression's .replace, which is probably too esoteric to be worth using:
str.replace(/(?=.{3}$)/, ' ')

But there's no need to turn the string into an array to add the space - you can also use .slice twice, to take the 4 part, concatenate with the space, and concatenate with another .slice.

const str = '4589';
const newStr = str.slice(0, 1) + ' ' + str.slice(1);
console.log(newStr);
Answer: There's no single thing built in that will do it for you, so yes you'll probably want a function, but it doesn't have to be as complicated as split, splice, and join:
function insert(str, index, segment) {
    return str.slice(0, index) + segment + str.slice(index);
}

(It can't modify the string because strings are immutable in JavaScript. So it returns the new string instead.)
Live Example:

function insert(str, index, segment) {
    return str.slice(0, index) + segment + str.slice(index);
}

console.log(insert("4589", -3, " "));

Note: In that, I've stuck to standard JavaScript practice where a negative index is calculated by using length + index and specifies where to start the operation. So instead of -4 in the example above, I've used -3 to get the result you got with -4 with Ruby. I was surprised to find that Ruby's insert does that calculation but then inserts at the result plus one (but only if the index is negative). That would be very odd in a JavaScript function, so I haven't done that above. You could, though:
function rubyInsert(str, index, segment) {
    if (index < 0) {
        ++index;
    }
    return str.slice(0, index) + segment + str.slice(index);
}

Live Example:

function rubyInsert(str, index, segment) {
    if (index < 0) {
        ++index;
    }
    return str.slice(0, index) + segment + str.slice(index);
}

console.log(rubyInsert("4589", -4, " "));
Comment: a bit mysterious for me too, but no, "-4" was not a typo
Comment: @thiebo - [Sure enough](https://ruby-doc.org/core-3.0.0/String.html#method-i-insert), it inserts at index + 1...but only if the index is negative. How...odd...

ruby insert equivalent in javascript


Find $f$ if $f(f(x))=ax^2+bx+c$

Question: For polynomials with powers 1 and under, it's easy to find the functional square root.
i.e. if:
$$f(f(x)) = f^{[2]}(x) = ax+b$$
then:
$$f(x) = \sqrt{a}x+\frac{b}{\sqrt{a}+1}$$
Is it possible to find a general form for a quadratic function? I.e what is $f$, given that $$f^{[2]}(x)=ax^2+bx+c$$
Comment: See [Find $f(x)$ such that $f(f(x)) = x^2 - 2$](https://math.stackexchange.com/questions/481017/find-fx-such-that-ffx-x2-2). Note in particular that the answer depends on what the domain requirements are for $f$.
Comment: You could try assuming $g$ has a Taylor Series expansion, and then see what conditions you get on the coefficients in order for $g \circ g$ to equal f.
Answer: There is no solution to such equations in general. For example, there is no solution to $f(f(x)) = x^2 - 2$ - see problem 7 here.
However, some of those equations do have a nontrivial solution, for example $f(f(x)) = x^2 +2$. Can you find one?

Find $f$ if $f(f(x))=ax^2+bx+c$


Do cPHulk Brute Force Protection Settings Effect Hosts?

Question: Question:
Do my settings (shown below) prevent visitors from getting to any of the public web sites on my server if their ISP's IP Address has been blocked/black-listed through cPHulk Brute Force Protection?
Background
Lately, there has been a huge rise in foreign connection attempts to my server's resources. I am trying to prevent hackers from gaining access to my server. At the same time, I do not want visitors to the sites (hosts) on my server to be prevented from gaining access to the public sites. I have set my cPHulk BFP settings as follows:

To complete the loop on buttoning your server down, refer to my other question here --> How to Blacklist a Range of IPs in cPHulk Brute Force Attack Settings
P.S. for even quicker security and since I do not typically forget my password or mess up during login, I have ratched-down the three Maximum Failures settings from "4" to "3".
Comment: If I read this correctly, the first setting at 525949 minutes will ensure that any repeated failures (3), even spread out over this long period, will block the hacker's specific IP. The second setting for 525949 will block ALL IPs, including your own, any time any hackers fail for any account 3  times or more.  According to my read of the documentation this will block ALL IPs (except perhaps white-listed ones) after any hackers try and fail 3 or more times.  So, this effectively blocks ALL IPs (see http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/CPHulk).  Is this correct?
Comment: The way I understood it and set it up is the upon 3 unsuccessful attempts the attacker get blocked for 1-year (ie 525949 minutes). Then with the notifications boxes checked, I get an alert anytime someone is unsuccessful and even when someone is successful logging in. I have added my home office IP and work office IP to the whitelist table and I never get blocked, etc. Whenever I get an alert on an attack from an IP, I add that IP to the blacklist 18.104.22.168/8 (@rholmes)
Comment: Great - thanks for the info.  Take a look at the documentation - - especially the second one "Brute force protection period in minutes" - where I have some concern (but whitelisting may save you):

"In the Brute Force Protection Period in minutes field, enter a number of minutes. If several potential hacker IPs attempt to log in and reach the cPanel user's defined log in attempts during this configured time, then this will be considered a brute force attempt. All IP addresses will be blocked from logging into the cPanel user's account. In addition, this will lock the cPanel user's account."
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: No. cPHulk only blocks sessions that require authentication (such as SSH, mail, and FTP) and not HTTP access. To block that you'd need to manually block them on the server-side.
Comment: Excellent @NathanC. That was the answer I was hoping for. I am the only person authorized and needing access to my server. So I want to prevent any possible attempt to gain access to services or resources on the server other than those that necessary through the http and https service.


Help with ZK component development

Question: I'm developing a simple component. My jar structure is:
br/netsoft/zkComponents/Tef.class
META-INF/MANIFEST.MF
metainfo/zk/lang-addon.xml
web/js/br/netsoft/zkComponents.js
web/zkComponents/tef.dsp

My dsp file is:
<c:set var="self" value="${requestScope.arg.self}"/>

<applet archive="tef.jar" id="tefApplet" code="br.netsoft.applets.tef.TEFProxy" width="0px" height="0px" />

and the language-addon.xml is:
<language-addon>
<addon-name>componentes</addon-name>
<language-name>xul/html</language-name>
<component>
<component-name>tef</component-name>
<component-class>br.netsoft.zkComponents.Tef</component-class>
<mold>
<mold-name>default</mold-name>
<mold-uri>~./zkComponents/tef.dsp</mold-uri>
</mold>
</component>
</language-addon>

When i try to test this component, appears a pop-up showing :
" /js/br/netsoft/zkComponents.js not found"
what is wrong?
Answer: if in ZK 5 , you need widget class
or in 3 , you need to specify the javascript location

Help with ZK component development


How to make pdf to open in viewer instead of downloading in mozila

Question: i am using jspdf library and the pdf opens in the modal viewer incase of chrome and edge, but it downloads the pdf and opens in mozila.
Can anyone help me out to sort out this issue, i want my application to work in same way in mozila as well.
Demo: DEMO
IN html i have used:
<button class="pull-right" (click)="captureScreen()">PDF</button>

<embed id="convertToPdf" type="application/pdf"  width="100%" Content-Disposition= "inline" height="100%" [ngStyle]="{display: (displayTable ? 'block' : 'none')}">

Answer: you need to change your browser setting like this

open Mozila
click on browser setting icon
click on Option
after open option window scroll down and you see the Applications section , under this section you can see the PDF section change it to "SHOW PREVIEW IN FIREFOX"
Comment: Hi, thanks for response, in my firefox browser this was already set, even though it is happening like that


Move template function to custom module

Question: I have a function in my template.php file but I've now created a module that manages these particular tasks so I want to move the function over.
This is what I have in my template.php file:
function MYTHEME_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

This works file but when I move it into my custom module (mymodule.module file) if doesn't work.
I've tried this:
function MYMODULE_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

and this:
function MYMODULE_preprocess_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

but not happening.
Can anyone see where i'm going wrong? or am I way off on this and it can't be done like this?
Comment: You would need to use `hook_theme_registry_alter()` and replace the callback function for that hook; the naming convention for overrides only works for themes
Comment: Thanks @Clive - I don't quite understand. Are you able to elaborate on your response.
Answer: hook_theme_registry_alter() allows a module to step in to override registered theme callback functions. In your case, you're looking to override the menu_tree__main_menu entry and replace its callback function:
/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  if ($theme_registry['menu_tree__main_menu']) {
    // @TODO: override
    // $theme_registry['menu_tree__main_menu']['function']
    // $theme_registry['menu_tree__main_menu']['type']
    // $theme_registry['menu_tree__main_menu']['theme path']
    // for your new module theme function
  }
}

See the Return Value section of hook_theme() for more information on what a theme registry entry contains.

Move template function to custom module


How to hide multiply defined constants

Question: This questions extends the question How to hide defined constants.
I import theory A, B, and C, maybe in future also D, E, ...
All theories define a function f. I want to hide the definition of f in my current theory without changing the imported theories. When I write term f I get A.f. When I add hide_const (open) f to my current theory, A.f is hidden but now I get B.f as f. How can I completely hide f?
I need something like (hide_const (open) f)+.
Answer: The versions of function f from each theory have separate names (A.f, B.f, C.f), and these must all be hidden separately.
You are allowed to hide multiple names with a single hide_const command, though, and this is what I would recommend:
hide_const (open) A.f B.f C.f

Comment: How can you hide a function? Like say I want to hide natural addition. How can I do?

How to hide multiply defined constants


CodeIgniter .htaccess index.php rewrite not working on user directory

Question: I have a little problem with codeigniter, I have a .htaccess for rewrite the index.php it works great if I put my projects on /var/www or if I make a virtual host for it.
But I want to use my user directory such as http://localhost/~userdir/myproject. If I use my user directory when I'm trying to do request to a controller like: http://localhost/~userdir/myproject/signup I get this error:

Not Found
The requested URL /index.php was not found on this server.

This is my current configuration:
.htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|(.*)\.swf|forums|images|css|downloads|jquery|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L,QSA]

application/config/config.php
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['encryption_key'] = 'myencryption_key';
//all remaining is the default config

This config works great on http://localhost/ and also on production enviroments with a domain like http://example.com/ but not on my user directory http://localhost/~userdir/project/
What I doing wrong? Any thoughts?
Thanks in advance.
Answer: Well, I found a solution in codeigniter forums, first I need to add RewriteBase line as follows:
RewriteBase /~userdir/myproject/

Then, remove the slash before index.php on last line.
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

Someone said that
RewriteCond $1 !^(index\.php|(.*)\.swf|forums|images|css|downloads|jquery|js|robots\.txt|favicon\.ico)

is redundant, the following two lines of code cover it,
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

and all other real files/directories. They basically say "if the request is not for a REAL file, and the request is not for a REAL directory, pass the request to index.php. Presumably everything from the above line is a real file or directory, so it's not needed at all.

So, my final .htaccess is like this:
RewriteEngine on
RewriteBase /~userdir/myproject/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

It works well locally with http://localhost/~userdir/myproject also on production with http://example.com/~userdir/myproject
Comment: and dont forget to change the apache configuration as mentioned in http://stackoverflow.com/a/14807463/1537413
Answer: You need to remove the first slash berfore index.php like this
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

Comment: That not work for me, I get this:

The requested URL /home/userdir/public_html/project/index.php was not found on this server.
Comment: sorry, i did't see that you removed the index.php from config. try to put the $config['index_page'] = 'index.php';
Answer: The Local Solution
RewriteEngine On
RewriteBase /ci/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /ci/index.php/$1 [L]
The Online Solution
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]


Is adding indexes to a Drupal database safe?

Question: I have been searching and reading about this, but I have not seen anything definitive about the topic of adding indexes to Drupal tables (both core and contrib).
My main concern is what happens with any custom indexes when you update core or contrib code and there are schema changes.  What happens in this case?
EDIT:
I think some context may help.  I am primarily concerned with adding indexes to tables to tune site performance (queries showing up in the slow query log, pages with slow views, etc).  This may involve adding an index to a table in someone else's module.  For example

I install module foo
Module foo creates table foo
I add an index to table foo
Module foo has an update that changes the schema

What happens?
Answer: Yes, it could result in problems.
If a module wants to do something with the column on which you have added an index, it will remove it's own indexes and then do whatever operation it intends to do.
What exactly will happen will depend on your database type and the actually executed operation. For example, a rename of the column will work fine with MySQL, but will fail on PostgreSQL. But if it tries to delete that column (maybe after migrating data to a different table/colun), it will fail.
The chances that this will happen are relatively low, at least for minor updates (does depend on the actual module however. I usually don't add any changes which could break something to minor releases), but it is possible.
My suggestion would be that you try to work together with the module maintainers. If the problematic query/ies are from the module itself, then the maintainers will probably happily add the indexes, if you provide a patch. Provide DESCRIBE output of the problematic query/ies before and after adding the index. Also provide a patch that updates the schema (include an update function to set it for existing installations).
Someone who is actively working on performance related things and does the above really well is catch, here is an example: http://drupal.org/node/983950
Answer: As reported in DatabaseSchema_pgsql::changeField(), and in db_change_field():

IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

That means that you have to drop all affected keys and indexes with db_drop_{primary_key,unique_key,index}() before calling db_change_field(). To recreate the keys and indices, pass the key definitions as the optional $new_keys argument directly to db_change_field().
For example, suppose you have this field definition and you want to change foo.bar to serial, leaving it as the primary key.
$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

The correct calls sequence is the following one.
db_drop_primary_key($ret, 'foo');
db_change_field($ret, 'foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar'))
);

Similar code is used for Drupal 7.
Keep in mind that, for my experience, you cannot remove a primary key that uses a serial field. On Drupal 6, I got an error all times I tried doing that; I didn't try that on Drupal 7.
Apart that, I don't know any other issue you could have with database indexes.
About adding an index to a database table that is created from another module, I would not suggest doing that, because:

A module doesn't drop an index for a field that is being changed, if the module itself didn't create that index. It would not be possible for the module to do that because it doesn't know the name of the index.
Modifying a database table created by another module is never a good idea, even in the case the module is a core module. If there is another module that changes the same table, how could the modules handle any conflict they have with each other, or with the changes the core module would apply to its own database?

If the database table is being created from another module (a core module or a third-party module), I would suggest to open a feature request for the module, providing a use case for using a new index; if there are any performance issue, adding an index could be the desired thing to do.
If you are going to add an index to a table created from another module to your own site, then be prepared to any changes you need to do to your custom module every time the module is updated, and before you install it in your own site.
It is you who can decide if the extra work is worth the performance you get. Personally, I don't think it is worth, though.
Comment: Also you may consider using [DB Tuner](http://drupal.org/project/dbtuner) which is handy to know which indexes to create.
Comment: Thanks.  How would this work if I add an index to a table to combat a slow query, not just a change to my own module?  I'll try to edit my question to be a bit more clear when I get a chance.
Comment: @tostinni Yeah, the question was almost direct related to implementing recommendations from DB Tuner.