Login fails due to loop on localhost. Any ideas why?

Question: I have git cloned a site and used Backup and Migrate to bring the database over the the local host.
Working on the remote host the login works fine. Not locally. Well not anymore it worked for about an hour I'd say.

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

I've cleared all history, tried different browsers, and restarted apache a few times.
Any ideas?
EDIT:
I can install it and after installation I stay logged in for about 60 seconds after migrating the database. I'm then redirected in a loop.
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.

I've cleared the browsers cookies and cache
I've cleared drupals cache
restarted apache
tried different browsers

I'm beginning to think it may have something to do with how I'm setting up the site. I'm doing it in a very round-about way I think.

backup database from dev site
git clone site and point httpd.conf and hosts file at it
create database with same name, user and password from settings.php file
install site
go in an enable backup and migrate
import database from backup

site loads. drops after 60 seconds or so with the firefox message from above. I'm not 100% sure where to start troubleshooting.
Answer: You could find out for sure by adding some logging code in drupal_goto() to backtrace what function fired the redirect. Then inspect why that function fired the redirect and work back from there.
Or, some more "guesswork" approaches -

Check you don't have $base_url set in settings.php.
Clear your cache tables after installing to copy (or don't back up the cache table contents).

drush cc all

Disable modules which might be confused by relocation - securepages, canonical_url, logintoboggan (guessing here).

drush dis securepages canonical_url logintoboggan

Check your variables table for (and delete) any entries with values like '%http://your.old.domain%'.

drush vget | grep your.old.domain
drush vdel some_variable_name
Comment: well that sounds right, above my ability right now though
Comment: @ Chris Burgess Any other ideas on the import / export method I edited above?
Comment: Your import method seems fine, but there are still variables which change across servers - URL, Apache rewrite config, directory paths ... Good on you for being brave enough to set up a local dev site; it makes debugging a whole lot easier. Now is the perfect time to get your hands dirty. Don't be afraid of breaking your local Drupal install, you can just unpack a fresh copy in a moment ... get stuck in! Stefan's advice to watch your local server logs while the redirect happens, and use the debug tools in your browser to watch the requests redirect, are good steps to take also.
Comment: Another approach might be to disable some modules which might get sore about relocation - securepages, canonical_url, logintoboggan (guessing here). You can do this in your local DB, or via Drush -
Comment: I feel stupid, this was all on a new virtual machine and I had not enabled a2enmod rewrite yet. with a little help from a friend it was fixed. Thanks a lot for your help.
Answer: sudo a2enmod rewrite fixed it. That is all.
Answer: You should also check your server error log and also install Firebug (if you don't have it already) and check the "Net" tab to see the HTTP requests. From these 2 sources you should normally have something to point you in the right direction.
Answer: Same issue happened to me, infinite redirect loop- I could see all the pages within my website but when I try to login with my credentials, it gives me this error. So, I couldn't access my site as an admin. I found some solutions like adding a module, but I can't add/disable any modules. It took me around a day to resolve this,
Following steps worked for me in resolving this error:

Modified .htaccess file
RewriteBase /drupal
uninstalled a module Voting api module, deleted the voting api folder.
cleared the cache_* tables in the database through phpmyadmin
Modified my.ini/my.cnf file - max_allowed_packet = 32M.

hope it would help someone.
REF:
https://www.drupal.org/node/706986


Why don't mouseover or mouseout events fire from tests?

Question: I have the following QUnit test:
test 'can view saved status and undo if needed', ->
    save_link = $('.save-link')
    my_profile_div = $('.searchbar .span5')
    undo_save = $('#undo-save')

    my_profile_div.mouseover()
    equal(undo_save.css('visibility'), 'hidden')
    my_profile_div.mouseout()

    save_link.click()

    my_profile_div.mouseover()
    equal(undo_save.css('visibility'), 'visible')
    my_profile_div.mouseout()
    equal(undo_save.css('visibility'), 'hidden')

It clicks a link, then expects some hover behavior to be present for the element my_profile_div. Unfortunately, the mouseover and mouseout events don't fire from the tests. I get no alerts when using this implementation:
$('.searchbar .span5').mouseover ->
    alert('mouseover')

$('.searchbar .span5').mouseout ->
    alert('mouseout')

In the browser I do get the alerts, but not when I run the test above, which makes me think I'm not triggering the events properly. I also tried trigger('mouseover') to no avail.
Thanks for taking the time to read this, guys. I appreciate your help greatly.
NOTE: The test is for the desired behavior. The implementation is just to make sure the test is doing what it's supposed to.
Answer: I would rather use trigger to fire an event.
$('targetElement').trigger('eventName');

Comment: Okay what is your actual error you are getting? Another thing. I take it your test code is inside a function which is called after $(document).ready or a button click?
Comment: I'm not getting an error. As you can see, if the mouseover/mouseout events fire, you'd have to see two alerts, which doesn't happen when I run my tests, but does happen when I load the script into a webpage.

I'm using QUnit, so the test code is a webpage and tests are triggered from within a


Android SSH does nothing

Question: I created an app that connects to ssh with my raspberry Pi and executes a python file. The command and the python file work like a charm when I connect from my windows pc but the app does nothing for some reason.
Here is the code:
import android.content.pm.PackageInstaller;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.ByteArrayOutputStream;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {
                try {
                    executeRemoteCommand("pi", "123456", "192.168.1.6", 22);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.execute(1);
    }

    public static String executeRemoteCommand(String username, String password, String hostname, int port)
            throws Exception {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, port);
        session.setPassword(password);

        // Avoid asking for key confirmation
        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);

        session.connect();

        // SSH Channel
        ChannelExec channelssh = (ChannelExec)
                session.openChannel("exec");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        channelssh.setOutputStream(baos);

        // Execute command
        channelssh.setCommand("cd /home/pi/Desktop | nohup python red.py");
        //System.out.print("cd /home/pi/Desktop | nohup python red.py");
        channelssh.connect();
        channelssh.disconnect();

        return baos.toString();
    }
}

This is the Android Studio output:
10/13 17:22:17: Launching app
No apk changes detected since last installation, skipping installation of D:\Android\Projects\LEDControl\app\build\outputs\apk\app-debug.apk
$ adb shell am force-stop com.example.seth.ledcontrol
$ adb shell am start -n "com.example.seth.ledcontrol/com.example.seth.ledcontrol.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 6987 on device samsung-gt_i9195-02de24f3
I/InstantRun: Instant Run Runtime started. Android package is com.example.seth.ledcontrol, real application class is null.
W/InstantRun: No instant run dex files added to classpath
I/PersonaManager: getPersonaService() name persona_policy
W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
W/dalvikvm: VFY: unable to resolve interface method 15423: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
W/dalvikvm: VFY: unable to resolve interface method 15427: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
W/dalvikvm: VFY: unable to resolve virtual method 658: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
W/dalvikvm: VFY: unable to resolve virtual method 680: Landroid/content/res/TypedArray;.getType (I)I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
W/dalvikvm: VFY: unable to resolve virtual method 621: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
W/dalvikvm: VFY: unable to resolve virtual method 623: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8960_KK_2.7_RB1__release_AU ()
              OpenGL ES Shader Compiler Version: 17.01.12.SPL
              Build Date: 03/25/14 Tue
              Local Branch:
              Remote Branch: quic/kk_2.7_rb1.32
              Local Patches: NONE
              Reconstruct Branch: NOTHING
D/OpenGLRenderer: Enabling debug mode 0
I/dalvikvm: Total arena pages for JIT: 11
I/dalvikvm: Total arena pages for JIT: 12

Comment: That logcat does not appear to be filtered for your app
Comment: Don't know how to do that...
Comment: Android Studio has a drop down next to that output for the options by which to filter. Basically, what I'm trying to point out, is that there's no errors there, nor messages from your app
Comment: The filter is set to "Show only selected application" and the only error in red is this:

10-13 17:28:22.055 12222-12222/? E/dalvikvm: >>>>> Normal User
10-13 17:28:22.055 12222-12222/? E/dalvikvm: >>>>> com.example.seth.ledcontrol [ userId:0 | appId:10174 ]
Answer: cd cannot be piped like that
Why are you not using the full path to the program?
nohup python /home/pi/Desktop/red.py

Comment: Thx! that worked! I used the previous command cause that is how I connect from my windows pc terminal!
Comment: I don't think it should work from any connection with a pipe like that. This is the correct usage

Android SSH does nothing


Access to JavaScript root level object THIS keyword value

Question: On my basic JavaScript object example below for how I often structure my JavaScript projects.
in my TestApp.init() function I call this function this.cache.cacheFuncOne(); which is another function that is 1 level deeper inside another object named cache.
Inside this.cache.cacheFuncOne(); I try to access the property on the main object this.prop1 which results in undefined.
When I access this.prop1 from other functions that are not 1 level deeper nested in another object, then it works as expected and shows the value.
So I have come to realize that in the cache{} object, this keyword is not the same value as this on the root level object.
Based on this simple demo, how would I access the root level this value within the cache{} object below?

var TestApp = {
  prop1: 'property1',

  init: function() {
    this.cache.cacheFuncOne();
    alert(this.prop1);
  },

  funcOne: function() {

  },

  funcTwo: function() {

  },

  cache: {

    cacheFuncOne: function() {
      alert(this.prop1);
    },
  }

}

TestApp.init();
Comment: Since it's a singleton object, use `TestApp.prop1`.
Comment: I think you can use .bind(this) to get the this value of a parent scope.
Answer: What you are looking for is either call() or apply(). Both of them are part of the Function's prototype, and their first argument is the object that will be the this inside the function.
So in your case, you could do this:
// ...
init: function() {
  this.cache.cacheFuncOne.call(this);
  alert(this.prop1);
}
// ...

Also, if you use ES6, you can just use the arrow function.
Answer: Can you use ES6/ES2015? If so you can just use arrow functions
cacheFuncOne: () => {
  alert(this.prop1);
},

this will refer to the object with prop1.

Another option is to use bind(this)
cacheFuncOne: function () {
  alert(this.prop1);
}.bind(this),


How can i use redefineClasses() method in javaagents

Question: I have been using premain() with addTransformer(). Since, it gives javassist.ClassNotFound exceptions for certain classes when i run the agent with a server, i thought to try the agentMain() with redefineClasses(). I went through many links, but so far i am unable to find a piece of code that gives me clear idea on how to set up a simple java agent using these two methods. Some help would be really appreciated.
Can we use redefineClasses() with premain()? (When we use redefineClasses() do we still need the transform method?)
I am trying to instrument set of methods of set of classes, where i know the fully qualified name of those classes as com.test.Foo. I wanted to instrument them without going through the entire set of classes loaded onto JVM. I have been reading those documents back and forth, but still i am unable to get a clear idea on how to use that redefineClasses method?
Comment: Well those documentations explains the method, but there is no clear example on how to use it. I mean like a simple end to end example.
Comment: You should tell, what you are trying to achieve and why the documentation found [here](http://docs.oracle.com/javase/8/docs/api/?java/lang/instrument/package-summary.html) and [here](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#redefineClasses-java.lang.instrument.ClassDefinition...-) is insufficient.
Comment: I came across a few articles with actual examples. http://www.fasterj.com/articles/hotpatch1.shtml and http://sleeplessinslc.blogspot.com/2008/09/java-instrumentation-with-jdk-16x-class.html
Answer: You can call redefineClasses from anywhere, also from a premain method which is nothing but an extension to a normal Java program run by the same JVM process previous to a main method.
A trivial example for running a redefinition is:
instrumentation.redefineClasses(new ClassDefinition(Foo.class, new byte[] {...}));

This way, Foo is set to be represented by the byte array that must contain a valid class file for Foo where all signatures of fields and methods are the same as by the loaded Foo.class. You can use a tool like ASM for instrumenting the class.
If you really only want to instrument Foo, then this might just be the way to go instead of using a ClassFileTransformer.


How can I find the form ID of a form?

Question: How do I get the form id of my form? I've just begun to make my modules and I'm at a standstill. I got this code from someone else and am trying to customize it:
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the form id for the node form') {
    $form['#submit'][] = 'my_custom_submit_handler';
  }
}

Answer: Finding FORM ID without installing module
Finding the Form ID is very easy no need to install modules and all
STEP 1: Open you from go to its edit page(OR inspect your form).
STEP 2: if its a node form find "node-form" in the inspect element
 check you are in the form element.
STEP 3: see attached image the highlighted green text is the ID of the form
STEP 4: IMPORTANT Finally if you want to use it in hook_form_alter() replace the hypen with underscore
For example: yourform_id_with_content_type_name_form
Like wise you can find id of any form in drupal all you have to do is inspect->find form element and search for the ID attribute and use it
Hope it helps :)
Comment: This didn't work for me when I wanted to protect the comment form in a Drupal 8 site. I found a solution in [this comment on drupal.org](https://www.drupal.org/project/captcha/issues/2674288#comment-11174249), where it says: 1) Find a hidden input element whose `name` attribute has value "form_id". 2) Look at the input element's `value` attribute - the attribute's value is the desired form ID. Example: The comment form on story nodes has the form ID "comment_comment_node_story_form". If you like you can incorporate this new information in your answer.
Comment: sometime the id changes depending on the context. niksmak suggestion is a better approach
Answer: Try printing the form variables with PHP function print_r.
function hook_form_alter(&$form, &$form_state, $form_id) {
  print_r($form);
}

When you visit the page the form is on, the variables (and name) will be displayed.
An easier way of accessing (or rather viewing) the information would be using dpm() function provided by the Devel module. You can use it in the same way you would use print_r.
Comment: Also $form_id is a param you can directly print it !!
Comment: If you have [Devel](https://www.drupal.org/project/devel) enabled, just `dpm($form_id);`
Comment: Given the reported code, there is no need to see the content of the `$form` variable.
Answer: If your webform is located at "www.mydomain.com/node/351" then your form ID will be "webform_client_form_351". So, whatever your nid is - that's your form ID.
Comment: The question is not about the Webform module. It is about the node edit form.
Comment: The question is about the node edit form but if you want to find any webform form ID this works correcty.
Comment: This answer is right, just tested it.
Answer: If you know where the code is that defines the form you want to alter, look there. The form id is just the name of the function defining that form.
For example, Views defines the function views_ui_edit_view_form on line 875 of views/includes/admin.inc. The Hierarchical Select views filter looks for that form id on line 50 of hierarchical_select/modules/hs_taxonomy_views.module in a hood_form_alter function.
Answer: Use drupal_set_message() function to display the form id.
function hook_form_alter(&$form, $form_state, $form_id) {
drupal_set_message($form_id);
// other codes
}

Comment: `drupal_set_message($form_id);` is deprecated in Drupal 10. You can use `\Drupal::messenger()->addMessage($form_id);` instead.
Answer: Use the Get Form ID module to easily find out form id of any form in Drupal.
Here is a quote about it from its project page:

By hovering over any form you will see a contextual link available. By expanding the link you will see the form ID. Click on the link and you will see a modal window with copyable form id and hook_form_FORM_ID_alter() hook suggestion.
This module is deprecated. It was improved, extended and rebranded as Devel form debug; use it instead.

Disclosure: I'm maintainer of these modules.
Answer: As the code you reported is looking for the form ID of the node form, there are two cases.
Drupal 6
If the code is trying to alter the form used to set the settings for a content type, then it should use the following IF-statement.
if ($form_id == 'node_type_form' && isset($form['identity']['type'])) { /* … */ }

If the code is trying to alter the node edit form, then the code should use the following IF-statement.
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) { /* … */ }

Drupal 7 and higher
In the first case, the IF-statement should be the following one:
if ($form_id == 'node_type_form') { /* … */ }

Using a different approach, supposing that mymodule is the short name of your module, you could use mymodule_form_node_type_form_alter(&$form, &$form_state, $form_id). Since Drupal 7, all the hooks used to alter the form implemented by another module gets $form_id as last parameter. See hook_form_alter(), hook_form_FORM_ID_alter(), hook_form_BASE_FORM_ID_alter().
In the second case, the IF-statement is the same used for Drupal 6.
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) { /* … */ }

Answer: First install Devel module.Then create a module like the code below
function hook_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

Then you can see ALL details of a form, like form ID, field names of a form etc.
Answer: In Drupal 8 you can get a form id like this.
You have to write this code in your .module file
function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  echo "my form id is : ".$form_id;
}

How can I find the form ID of a form?


Can you suggest a program for shutting down many Win7 PCs at set times?

Question: Can anyone suggest a program for shutting down many Windows 7 PCs at set times? I need to shot down over 1000 PCs every night. We have Active Directory and Windows 200 R2 servers.
Thanks
John
Comment: I think shutdown command supports remote hosts. I suppose they're all in the same AD domain.
Answer: Another option would be to assign a scheduled task to perform the shutdown, via Group Policy:
http://technet.microsoft.com/en-us/library/cc725745.aspx
Answer: you can use psexec and execute shutdown command.
ps. indeed if computers are in same domain - you dont even need psexec.
Answer: You could batch script it...
Shutdown /s /t 0 /m \\computer1
   Shtudown /s /t 0 /m \\computer2
Then schedule the job to run on one of your DCs, have the job run as a Domain Admin.
Answer: You want a script which does this for each named machine:
shutdown -s -t 0 -f -m \\machinename


How can i get Class from Generic Type

Question: I do not know how I will explain, I have a class something like
public class MyClass<T>{
    private Class <?> type;
    public MyClass(string className){
        this.type = Class.forName(className);
        Field[] fields = type.getDeclaredFields();//why i need type
    }
}

Then i create an object of that class:
MyClass<Person> persons = new MyClass<>("packageName.Person");

Is there anyway to do this like
MyClass<Person> persons = new MyClass<>();

Comment: You are calling the constructor `MyClass(string className)`, so it expects a String.
Comment: how can get that class name from T
Comment: like `typeof(T)` in C#
Answer: You can't because of the way generics are implemented in Java. You can often see a Class<T> clazz parameter being passed to work around it.
In fact, it doesn't make sense for you to pass in a String. Pass in Person.class instead, so you won't need the Class.forName().

How can i get Class from Generic Type


Error when using self static function

Question: I have a sample code:
class Assets {
    public static $my_static = '';

    public static function custom_js()
    {
        return self::add_custom_js();
    }

    public static function add_custom_js($str)
    {
        return self::$my_static = $str;
    }
}

And php
<?php
Assets::add_custom_js("ABC");
?>

 ...
 <?php echo Assets::custom_js(); ?>
 ...

Error can't show data string is "ABC"
Comment: you are not passing the argument when calling add_custom_js() inside custom_js()
Answer: I think you want to return $my_static value to get ABC in echo Assets::custom_js();. Consider following:
class Assets {
    public static $my_static = '';

    public static function custom_js()
    {
        // return self::add_custom_js();
        return self::$my_static; //This is what you want i believe
    }

    public static function add_custom_js($str)
    {
        return self::$my_static = $str;
    }
}

Answer: You have to return $my_static from custom_js() so  Your class should be as follow:
<?php
class Assets {
    public static $my_static = '';

    public static function custom_js()
    {
        return self::$my_static; //<-------------change this line
    }

    public static function add_custom_js($str="")
    {
        return self::$my_static = $str;
    }
}
?>

Error when using self static function


How to represent known size set of unknown size elements with Java?

Question: So I have 256 elements(that are lists of unknown length) and I want to represent them in Java.
In c++ I would use something like this:
vector<int> aList[255];//This is C++ example

In Java I tried using:
ArrayList<Integer>[] aList = new ArrayList<Integer>[256];

But the Java compiler forbids "Generic Array Creation"
I also tried using:
ArrayList<ArrayList<Integer>>  bList = new ArrayList<>(256);

But when I do
bList.get(67) //or any other value

I get an index out of bounds Exception(the bList size is 0), so my question is how to represent best such data or should I just populate bList with null values(256 null values in this example)?
Edit: Ok, by the answers i think i will use the solution with
ArrayList<ArrayList<Integer>>  bList = new ArrayList<>(256);

And then just populate the outer array with new ArrayLiist(), since i need to iterate over it in order i do not know
Comment: Did you read the documentation of what `new ArrayList<>(256)` means? It's allocating an *empty* (size 0) list with *capacity* 256.
Comment: The bList approach is actually the proper one, but just remove the constructor parameter and fill them on demand when creating the sublists.
Answer: An array list is a self-resizable array. Therefore it has two important internal values. The capacity (size of allocated internal array) and the size (the actual number of elements). From the documentation:

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

For your case this means that your are allocating an ArrayList that allows adding 255 elements without resizing. It does not mean that you are allowed to access any of those indices yet.
Therefore you have to initialize the values first like this:
ArrayList<ArrayList<Integer>>  bList = new ArrayList<>(256);
for(int i = 0; i< 256; i++) {
    bList.add(new ArrayList<>());
}

This is actually creating an array of arraylists.
Answer: A list in Java is not the same as an Array. Think of a list as a sequence of elements (without gaps!).
ArrayList is just an implementation of a list. Although it uses an array to internally store its elements, it still has to behave like any other list (e.g. a LinkedList).
Java lists (so even if it is an ArrayList) keeps track of how many elements have already been added. So even when you create list like that:         List<List<Integer>> list = new ArrayList<>(256);, it still knows that it is empty at this point, so accessing the 67th element fails.
If having a behaviour like that is not suitable for you, then you should not use a list here, you could simply use an array instead of an ArrayList.
Answer: Lists are resizable arrays. You don't have to (but you can)declare ther initial size - they will grow as needed, just add elements to them.
Since you have been using arrays in c++, you can do the same thing in java eg
int[] yourArray=new int[256];

and access it like yourArray[67]
As for lists, you will have to initialize them first (aka add elements) as those keep track of what you have added to them. To do this you can eg
for(int i=0;i<size;i++){
    myList.add(null);
}

and then myList.get(67);
will return null but will not throw an exception.
All of those applies to 2d arrays and lists.
Comment: I think OP wants to create an array of generic arraylists for some reason.
Comment: Yes, but i want to represent sort of Array of Arrays, or just a table. Lets say its an table of size n by k. I know n and don't know k. What is the Pest representation of such data from performance/optimalization perspective?
Comment: thats just int And as I wrote, the same applies to 2d arrays (your *table*)
Answer: You can't instantiate an array of a generic type like that. Your best alternative is a 2D array:
Integer[][] aArray = new Integer[256][];

If you need to use a List<Integer>[], then you can circumvent the limitation by creating your own non-generic sub-class:
class IntList extends ArrayList<Integer> {}
...
ArrayList<Integer>[] aList = new IntList[256];

Just note that with this option you can't add new ArrayList<Integer>() to aList (array store exception), so you'd have to create new IntList() objects
Answer: Is the size really unknown or just arbitrary/dynamic?

If it merely has an arbitrary size (which is known but may change
over time), use Set (distinct, unordered) or List (ordered,
non-distinct) or Deque (ordered, with double ended stack
operations).
If the size is really unknown, treat the list as
Iterable (can produce a finite or non-finite Iterator for looping
over the elements) or expose it as Stream (which again can be
finite/non-finite).


Update number from api after an interval

Question: So I want to update the request to my Github page after an interval. I want to count how many commits I've done to a repo and then in the HTML count the number given from 0. I also want it to update automatically without so the user has to update the page. What happens now is that it gets a request and number and counts, I want the interval to be 10 minutes. As it is now it requests but the counting on the website should start directly not according to the interval after 5 seconds
Comment: Post your code please.
Comment: http://jsfiddle.net/95pfB/
Comment: You want the interval to be 10 mins? 5 seconds? confusing!
Comment: the interval itself is not a problem, sorry for crappy text. But I want the HTML to load when page loads, but after that I want to keep the number updated through request to github every 10 minute
Comment: turn all the code inside the setinterval function in to a function. say, function runcode. then, call runcode on doc ready. then let the setinteval call your method every 10 minutes.
Comment: can you show how you mean? @LShetty
Answer: Ok, thank you LShetty. It worked, heres the complete code:
<code>$(document).ready(function() {
runCode();

    function runCode() {

    var uri = "your url to github";
    var totalCom = 0;
    $.getJSON(uri, function(r) {
        for (var i = 0; i < r[0].total; i++) {
            totalCom = r[0].total;
        }
    //count numbers from zero
    $({countNum:
        $('.row-one-first .number').text()}).animate({countNum: totalCom}, {
            duration: 5000,
            easing:'linear',
            step: function() {
            // What todo on every count
            $('.row-one-first .number').text(Math.floor(this.countNum));
            },
            complete: function() {
            $('.row-one-first .number').text(this.countNum);
            }
        });
    })
}
setInterval (function() {
    runCode();
}, 300000);
</code>
});


Get a list of variables with a specified prefix

Question: Is there a way to get a list of user-defined variables that have a specified prefix? For example:
set(vars_MyVar1 something)
set(vars_MyVar2 something)
getListOfVarsStartingWith(vars_)

?
Comment: The function getListOfVarsStartingWith will do what? Store all variables into a single variable?
Comment: It would create a list of variables that could then be traversed with a foreach.
Answer: The function getListOfVarsStartingWith can be written in the following way:
function (getListOfVarsStartingWith _prefix _varResult)
    get_cmake_property(_vars VARIABLES)
    string (REGEX MATCHALL "(^|;)${_prefix}[A-Za-z0-9_]*" _matchedVars "${_vars}")
    set (${_varResult} ${_matchedVars} PARENT_SCOPE)
endfunction()

The functions uses the CMake function string(REGEX MATCHALL to compute all matched variable names without a loop. Here is a usage example:
set(vars_MyVar1 something)
set(vars_MyVar2 something)
getListOfVarsStartingWith("vars_" matchedVars)
foreach (_var IN LISTS matchedVars)
    message("${_var}=${${_var}}")
endforeach()

If the search should only return cache variables, use the following function:
function (getListOfVarsStartingWith _prefix _varResult)
    get_cmake_property(_vars CACHE_VARIABLES)
    string (REGEX MATCHALL "(^|;)${_prefix}[A-Za-z0-9_]*" _matchedVars "${_vars}")
    set (_resultVars "")
    foreach (_variable ${_matchedVars})
        get_property(_type CACHE "${_variable}" PROPERTY TYPE)
        if (NOT "${_type}" STREQUAL "STATIC")
            list (APPEND _resultVars "${_variable}")
        endif()
    endforeach()
    set (${_varResult} ${_resultVars} PARENT_SCOPE)
endfunction()

This function queries the CACHE_VARIABLES property and also makes sure that cache variables of type STATIC, which are used by CMake internally, are not returned.
Comment: What I am doing with this is this: http://www.cmake.org/Wiki/CMake/Tutorials/SettingVariableGroups - I noticed when I applied it to my real case (where I add_library a library called MyLibrary, then have many variables called MyLibrary_Something that I want to enable/disable all at the same time) that it also catches a variable that I did not create called MyLibrary_LIB_DEPENDS. Is there a way to avoid this?
Comment: Since your script only deals with cache variables, use `CACHE_VARIABLES` instead of `VARIABLES` upon search (see updated answer). This will return fewer false positives.
Comment: That makes sense, but it still finds this MyLibrary_LIB_DEPENDS. Here is the real code: https://github.com/daviddoria/PTXTools/blob/master/CMakeLists.txt - your function is near the bottom. I have grepped my source tree for LIB_DEPENDS (in this it is changing PTX_LIB_DEPENDS) and don't find anything, so it is certainly not something I am creating. It seems like it could be very bad that I am accidentally changing that variable? haha
Comment: The `_LIB_DEPENDS` variables are created by CMake internally to track library dependencies. Because CMake uses a special type `STATIC` for these cache variables, it is possible to filter them out. See updated answer.
Answer: I don't know any function to do that, but you can easily build one yourself by requesting all defined variables with GET_CMAKE_PROPERTY and then filtering the list with a regex.
For example:
SET(my_prefix_var1 "bob1")
SET(my_prefix_var2 "bob2")

# Get all variables
GET_CMAKE_PROPERTY(vars VARIABLES)

# Filter by prefix and build the "res" list
FOREACH(var ${vars})
    STRING(REGEX MATCH "^my_prefix" item ${var})
    IF(item)
        LIST(APPEND res ${var})
    ENDIF(item)
ENDFOREACH(var)

Comment: Hm, if I add a "message("Item: ${item}")" inside the if(item), the output is:

 Item: my_prefix

 Item: my_prefix

Shouldn't it be my_prefix_var1 and my_prefix_var2?


How to serve static files very fast?

Question: I'm looking for a solution need to serve a few XML files to as many users as possibly. My current solution are static files and a Nginx server. The files a small so I could them also hold in memory.
Does everyone have a good solutions?
Comment: nginx is extremely fast when serving static files.  some benchmarks show that it serves static files even faster than blobs from `memcached` when the filesystem is given enough RAM to cache everything.
Answer: Using Nginx seems reasonable. Just make sure the server has an adequate amount of RAM, hopefully enough to hold your entire set of XML files. As they get served, the OS kernel will automatically cache these files in memory, allowing them to be served very quickly.
Answer: Lighttpd is a good option for speedy serving of static files, as well.

How to serve static files very fast?


How would I find the minimum non-trivial cut in a graph?

Question: I know that there is an algorithm which computes the minimum cut in a graph $G$.
I have a situation where I am trying to compute the minimum non-trivial cut of $G$, where I say that a cut is trivial if one of the sides has only one vertex. In other words, I don't want to consider cuts which are merely the set of edges exiting a single vertex.
What is the best algorithm for this problem?
Comment: Suppose that $G$ contains two vertices of degree $1$, and we delete the two edges exiting those vertices. Is this cut nontrivial?
Comment: Yeah, I consider that non-trivial
Answer: Here is a starting point that makes $O(n^2)$ calls to a max-flow subroutine:

Let $\{v,w\}$ be an arbitrary pair of vertices in $G$. Iterate over pairs of vertices $\{x,y\}$ disjoint from $\{v,w\}$. (If you want both sides of your cut to be connected, then limit $\{v,w\}$ and $\{x,y\}$ to adjacent pairs of vertices.)
For each case of $\{v,w\}$ and $\{x,y\}$, let $H$ be the graph obtained by contracting $\{v,w\}$ to a single vertex $s$, and contracting $\{x,y\}$ to a single vertex $t$. (We allow double edges out of $s$ and $t$ when $v,w$ or $x,y$ have a common neighbor.) Find a minimum $s,t$-edge cut in $H$.
If there is a minimum nontrivial cut in which $v$ and $w$ are on the same side, one of the cases above will find it. So it remains to consider the case where $v$ and $w$ are on opposite sides.
For this, iterate over pairs $\{x,y\}$ disjoint from $\{v,w\}$ again, but define $H$ by contracting the pairs $\{v,x\}$ and $\{w,y\}$ instead; otherwise, do exactly what we did in step 2.

Compare this to an algorithm that finds a minimum cut with $O(n)$ calls to a max-flow subroutine, by fixing a vertex $v$ and looking for cuts that separate $v$ from each possible vertex $w$. (That's not the best algorithm out there, but it is pretty good.)
Comment: Thanks for your answer. This algorithm did occur to me, and it is pretty good. I was hoping to just do some preprocessing on the graph so that the trivial cuts become large, then run a single min-cut computation. I think this might be possible but I'm not sure
Comment: Karger's algorithm would find all connected non-trivial cuts without many changes, but unfortunately it can't possibly find nontrivial cuts like the one with two degree-$1$ vertices :(


How to count the occurance of all elements of list in python?

Question: I have to write all the elements separately along with their count.
It's the program i have made. It is counting correctly but not giving required output
The output is like this
I want output to be like this. All digits showing individual complete count
Comment: In StackOverflow we don't put images of code, could you please paste your code here and mark it as `code` so that the syntax highlighter does its job.
Comment: Does this answer your question? [How to count the frequency of the elements in an unordered list?](https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-an-unordered-list)
Answer: You can count the number of occurrence of a special element with count() method:
grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
letters = ['a', 'b', 'c', 'd', 'f']

print(list(map(lambda letter: {letter: grades.count(letter)}, letters)))

Output:
[{'a': 4}, {'b': 4}, {'c': 2}, {'d': 2}, {'f': 1}]

If you want to do this without using letters. you can do this:
grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

print(list(map(lambda letter: {letter: grades.count(letter)}, set(grades))))

Output:
[{'f': 1}, {'b': 4}, {'c': 2}, {'d': 2}, {'a': 4}]

For your expected output:
grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']

occurrence = map(lambda letter: (letter, grades.count(letter)), set(grades))

for item in occurrence:
    print(f"{item[0]}={item[1]}")

Output:
c=2
b=4
d=2
f=1
a=4

Update
You can use defaultdict() to count the occurrence of each element:
from collections import defaultdict

grades = ['b', 'b', 'f', 'c', 'b', 'a', 'a', 'd', 'c', 'd', 'a', 'a', 'b']
occurrence = defaultdict(lambda: 0)

for character in grades:
    occurrence[character] += 1

for key, value in occurrence.items():
    print(f"{key}={value}")

Output:
b=4
f=1
c=2
a=4
d=2

Comment: How to do it without using predefined function like count/
Comment: You can use ``defaultdict`` to count the occurrence of each element. I updated the answer.


Custom Formula in Condition Format Rule Builder Script

Question: I have a custom formula that I've been using within the conditional formatting rules. However I am trying to write a script that builds the rules automatically on open so that they 'reset' to the correct order (the ranges get messed up when rearranging cells) The code I currently have is:
<code>function onOpen() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("C1:D600");

  var rule = SpreadsheetApp.newConditionalFormatRule()
                           .whenFormulaSatisfied(=$E1="x")
                           .setBackground("red")
                           .setRanges([range])
                           .build();

  var rules = sheet.getConditionalFormatRules();

  rules.push(rule);
  sheet.setConditionalFormatRules(rules);
}
</code>
In the conditional formatting menu I have it set to Custom Formula Is... =$E1="x"
How can I get that formula to work within the script conditional format rule builder? I get syntax errors for it currently.
Answer: You just need to place the formula in quotation marks as it is a string:
<code>'=$E1="x"'
</code>


Why do we need the action to be effective?

Question: Let $G$ be a group of homeomorphisms of a connected, locally path connected, locally compact metric space $X$. Let Homeo$(X)$ be the group of homeomorphisms of $X$ endowed with the compact open topology. Sets of the form $V(K, U) = \{f \in \text{Homeo} (X) $ | $f(K) \subset U \} $ where $K$ is a compact subset of $X$ and $U$ is an open subset of $X$ form a subbasis for this topology.
While reading a paper I came across the following statement - if $G$ acts effectively on $X$ then we can consider it as a subgroup of Homeo $(X) $ endowed with the compact open topology.

Why is this true? Isn't $G$ automatically a subgroup of Homeo$(X)$?
Does the fact that it acts effectively make it a topological group when given the subspace topology? If so then how do I show that group multiplication (in this case composition) and taking inverses are continuous maps?  I tried showing that the inverse image of a subbasic open set is open but got nowhere with it.

Thanks.
Answer: Any group action of $G$ on $X$ gives a homomorphism $G \to \text{Homeo}(X)$, by $g \mapsto \varphi_g$, $\varphi_g(x)=g \cdot x$. That the action is effective is the same thing as that this homomorphism is injective.
If $G$ is a topological group then the above homomorphism is continuous if and only if $G$ acts continuously on $X$ in the sense that the map $G \times X \to X$, $(g,x)\mapsto g \cdot x$, is continuous.
Any subgroup of a topological group, when given the subspace topology, is a topological group. Perhaps it will be easier to see in this level of generality.
Answer: I think the $G$ in the first paragraph and $G$ in the second paragraph are different things. If $G$ is a group of homeomorphisms of a $X$, then of course it is a subgroup of the group of homeomorphisms of $X$, and of course it acts effectively.
On the other hand, if you have any group $G$ acting on $X$ by homeomorphisms, this means that you have a group homomorphism $G\to \operatorname{Homeo}(X)$. Faithfulness of this action corresponds to injectivity of this homomorphism.
In that case, you can use the action (as you could any injective homomorphism), to embed $G$ as a subgroup of $\operatorname{Homeo}(X)$ (in other words, a group of homeomorphisms), and then restrict the compact-open topology of $\operatorname{Homeo}(X)$ to $G$ (seen as a subgroup), or, more formally, you can pull back the topology through the homomorphism (however, in case of a non-injective homomorphism, this will inevitably give you a non-Hausdorff topology).


Multithreading Keep threads active

Question: I am struggling with multi threading my code. I want to ALWAYS have 10 active threads, but I am not sure how.
Current code:
import threading
from random import randint
import os
import names
import random
import time

threads = 10

def f():
    print("my actual function is 200+ lines")
    return

for i in range(threads):
    t = threading.Thread(target=f)
    t.start()

My current code starts 10 threads, but does not maintain them, keep active. Thank you for the help
edit: have also tried with while True, but no luck.
Answer: To keep your loops active, you should have a loop in your thread function as you said. But in this piece of code there is a return callback that will exit from your loop after print. You should write somethings like this:
def f():
    while True:
        print("my actual function is 200+ lines")

And if you want to manage your thread to stop sometimes, you should write a stop function and use a Boolean flag to control your while loop (instead of while True).
thread_status = True

def stopThread():
    thread_status = False

def f():
    while thread_status:
        print("my actual function is 200+ lines")

Comment: It just spams my log over and over with so much text. Are you please able to post my code with your examples in my code?
Comment: This is your code, I've just remove return statement, and added stop function. That printed logs are showing you that threads are actively running! This is just an example you should add other part of your code to it.

Multithreading Keep threads active


how to get input from console in Xcode 4 in C++

Question: i want to run project in xcode but i can not get input from console i have checked websites but i can't get it.
#include <iostream>
#include <stdio.h>
using namespace std;
int main (int argc, const char * argv[])
{

cout<<"\n"<<argc<<"\n";

i am getting the ouput as 1 but i don't know how to get input from the console
output that i am getting is
GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Mon Aug  8 20:32:45 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000
[Switching to process 8492 thread 0x0]
1
Program ended with exit code: 0
Answer: argc is not "input from the console", it's the number of arguments passed to your program on the command line (and those arguments are contained in argv).
If you want to get input from the console, you would need to read from standard in (std::cin)
See: http://www.cplusplus.com/doc/tutorial/basic_io/
Comment: thats right but argc is 1. i want to enter some value to it but at the time of compiling console does not require arguments
cin is for input from console but i want to do it like this ./a.out 2 34 45 here argc will be 2 and argv will be 34 and 45
Comment: You can't "enter some value into it". It's the number of arguments. If you give your program arguments, it will reflect the number of them. In the example you just gave, `argc` would be `4` (the first element in `argv` is the program name) and `argv` will be 2,34,45
Comment: thats what i am talking i want to give program arguments only
Answer: To get input from console, use std::cin:
int main()
{
    cout << "please input: ";
    std::string str;
    while(str!= "quit")
    {
        cin >> str;
        cout<< "your input is : " << str <<endl;
    }
}

Answer: From your comments on the other answer it sounds like you're actually asking how to enter program arguments, not console input. If you want argc to be a different number you have to give the program some arguments. You can do that in the options window for the scheme you're using. Find the Edit Scheme menu item and enter some arguments for your program.
Comment: thanks for the answer

so now each time we have to set the arguments from cmd+< this seems lots of work
Comment: my console window disappear after some run is there any way to pop out the console window
Comment: You can change the behaviors to make it not disappear (I think it's in the menu Xcode > Edit Behaviors), or you can just open the console window up again using the toolbar (there's a button for displaying the bottom pane), or you can use the navigator to view any previous session. You can also pop it out into a separate window by creating a tab, making the console view fill that tab, and then drag the tab out of the xcode window, but I don't think that's the best way.
Comment: Yes, changing the command line arguments is not as easy as when you run programs from the command line. Usually IDEs don't expect that you'll be changing arguments much. Visual Studio has a similar problem. However Xcode does have a nice feature; you can enter a whole bunch of command line arguments as a single item in the argument list, and then you can use each item in the list as a different set of arguments, which you select between using the checkboxes. This way, if you have a few different argument sets you want to switch between you can save them all and switch just with the checkboxes.


Epsilon-n proof confusion

Question: So, I'm told I did something wrong on this epsilon-n proof but I really don't know what.
I'm told to prove that $$\lim_{n\to\infty} \frac{5n+1}{n+3} = 5 $$
I begin by setting $\epsilon > 0$ and searching for $k$ such that for every $ n > k$, $$\left|\frac{5n+1}{n+3} - 5\right| < \epsilon$$
$$\left|\frac{5n+1}{n+3} - 5\right| = \left|\frac{5n+1 - (5n+15)}{n+3}\right| =  \left|\frac{-14}{n+3}\right| = \frac{14}{n+3} < \epsilon$$
(the last equality being valid since $n>0$ is definitely  true)
$$14 < n\epsilon + 3\epsilon$$
$$ n > \frac{14-3\epsilon}{\epsilon}$$
So set $k = \left \lceil{\frac{14-3\epsilon}{\epsilon}}\right \rceil$ and for every n > k, $$\left|\frac{5n+1}{n+3} - 5\right| < \epsilon$$  by what's shown above.
The issue I'm having is that I'm told (by my instructor, who deducted a point from this problem because of it) a better $k$ is in fact $\left \lceil{\frac{14}{\epsilon}}\right \rceil$, and I don't know why that would be or how I would get that $k$ to begin with.
Answer: Hint: Use the inequality
$$\frac{14}{n + 3} < \frac{14}{n} < \epsilon.$$
to determine $k$.
Comment: Does that mean that my k (or N, same thing) is wrong? Or is it just a simpler way to do the problem?
Comment: Yes, I edited my answer.
Comment: @StatGod I fail to see how this is a "better" $k$. It's merely a trick to make your work easier in finding a $k$ that fits the inequality. Correct me if I'm somehow wrong here, but the poster explicitly and algebraically solved for the minimum $k$ and therefore, in my eyes, an ideal one to use.
Comment: Of course, this is not ``better" but just simpler. The OP's answer is of course also acceptable. I just want to let him know how to get the $k$ that he was told.
Comment: Could you clarify why that's "allowed"? I mean, couldn't $\frac {14}{n}$ actually be $ > \epsilon$?
Comment: If you take $k$ to be $\lceil \frac{14}{\epsilon} \rceil$, then for all $n > k$, of course you can get $\frac{14}{n} < \frac{14}{k} < \frac{14}{14/\epsilon} = \epsilon$.
Answer: The problem is not that the lower bound is "wrong"; it is that the lower bound is unnecessarily complicated.
For all $n \geq 1$ we have
$$
\bigg| \frac{5n+1}{n+3} - 5 \bigg| = \bigg|\frac{5n+1 - 5n - 15}{n+3} \bigg| = \frac{14}{n+3} < \frac{14}{n};
$$
from this it is clear that
if $\varepsilon > 0$, then to make $14/n < \varepsilon$ it suffices to make $n > 14/\varepsilon$; hence for every $\varepsilon > 0$, we have $n \geq \lceil 14/\varepsilon \rceil + 1$ only if
$$
\bigg| \frac{5n+1}{n+3} - 5 \bigg| < \varepsilon.
$$
Answer: Contrary to what has been said in the comments on StatGod's answer, I would say the instructor's value for $k$ is better than yours.  It's equally good for the proof and it makes the working simpler; how is that not better?
However I would also say that your instructor was being extremely harsh in deducting marks for this.
On the other hand, it's worth noting that in other cases, the "straightforward" approach you have given may not quite work.  For example, show that
$$\lim_{n\to\infty}\frac{n^2}{n^2+1}=1\ .$$
We have
$$\left|\frac{n^2}{n^2+1}-1\right|=\frac1{n^2+1}\ ,$$
and making this less than $\epsilon$ in the "obvious" way gives
$$n>\sqrt{\frac1\epsilon-1}\ .$$
Problem is, the RHS is meaningless if $\epsilon>1$.  Now in a sense this is irrelevant since we are interested in small $\epsilon$, but on the other hand if we want to do things precisely we must recognise that the property is supposed to be true for all positive $\epsilon$.  So in this case it is definitely better to say that
$$\frac1{n^2+1}<\epsilon$$
is true if
$$\frac1{n^2}<\epsilon$$
which is true if
$$n>\frac1{\sqrt\epsilon}\ .$$

Epsilon-n proof confusion


Limit point of a sequence and range

Question: Anyone can please give some examples where limit point of the sequence is different from limit point of range of that sequence.
Answer: Let $x_n = (-1)^n \frac{1}{n}$. The limit point of that sequence is $0$, but the since the range of the sequence $[-\frac{1}{2}, 1]$ is continuous, every point in the range is a limit point.
Here I take it that your definition of "limit point" is any point $L$ with all its open neighborhood ("interval around the point") having points in that neighborhood other than $L$ itself.
Comment: Why is the range of the sequence continuous?  It's only countable, isn't it?  e.g. there're no points between -1 and -1/3.
Answer: It's late, but for future reference, here's a simple example: Let
$$p_n\triangleq\left\{\begin{array}{cc} 1, & n\le 5 \\ 2, & n>5 \end{array}\right.$$
Then '$2$' is the limit and the only limit point of the sequence $\{p_n\}$.  But the range of the sequence is a finite set $\{1,2\}$, so it clearly has no limit points.

Limit point of a sequence and range


Abstracting markup/markdown

Question: A classic and basic problem in finance is getting people to realize that percentages don't add. This may seem trivial, but if something goes up 10% then down 10% it has gone down, overall, 1%.  The problem, of course, is that after it goes up 10%, the -10% is a bigger number.  This is usually called the markup/markdown problem.
Algebraically this is simple: $(1+r)(1-r)=1-r^2<1$, for all $r$ other than zero.
I know this is trivial, but I am trying to think of why (or if) this can be related to some deeper or more profound insight or theorem from analysis. But it is so obvious arithmetically that I keep drawing a blank.
Comment: What's the actual question?
Comment: Most people will be unfamiliar or at least unconfortable with exponentials / logarithms (which would be the best way to explain). I would rather draw attention to the factor of change (1+r) then to the relative change (r). It should then become clearer to "people" that 2 times a 20% rise amounts to $1.2 \cdot 1.2 = 1.44 > 1+(0.2 + 0.2) = 1.4$ which is easier to grasp then the  third binomial formula. The advantage is that you can calculate it by hand / in your head and that you can convince yourself that it works for any r.  The main obstacle is to get to that factor, leaving the r behind.
Comment: I guess the actual question is this: is there any more general principle that could be called on to make claims about the relation of arithmetic and geometric averages?  Clearly, a markup/markdown of equal percentage leaves an amount that is less than the sum/average, so that always has a geometric average smaller than the arithmetic.  If r is always positive, I believe the same occurs.  If r is always negative, I believe the opposite occurs (-10% followed by -10% take 100 to 81).  If they are mixed, hard to say.  I am trying to shoehorn this into an general inequality theorem or convexity.
Answer: Displacements are what people are usually used to, and to put two displacements together we use addition: "walk forward one step and then back two" will clearly leave you one step behind where you started.
Ratios of course are composed using multiplication, which is hard. Logarithms and exponentials can change this into addition instead. Imagine a world where "increase the price by 10 percent" actually meant multiplying the price by $e^{0.1} \approx 1.1052$. Then "decrease the price by 10 percent" would be multiplication by $e^{-0.1}$, and would correctly cancel. I've just written down my operations using different numbers, so I can add the numbers instead. (Aside: this is pretty much what decibels are: turning the volume up 2 decibels is actually something like multiplication by $10^2$)
Notice how $e^{0.1}$ is pretty close to $1.1$ in value. This will work for any small numbers, since the first order Taylor approximation of $e^x$ is $1+x$. I think the fatal flaw is conflating this exponential with its approximation, which works pretty well for small $x$, and few operations. It breaks outrageously for larger $x$ though: the operation which undoes increasing a price by 100% is decreasing it by 50%, not 100%.

Abstracting markup/markdown


Where do I put image style definition in a module?

Question: I'm writing a custom node formatter that needs to use a certain image style. Since I don't want to rely on that image style being defined by the admin, and I want to be sure the style is not deleted, I am going to provide the style definition in code.
Should MYMODULE_image_default_styles go into the .install or .module file?
Answer: I think its better to use features and export it, then in your .info file add dependency to it.
other solution is what you say, put it inside MYMODULE_image_default_styles in your .module and re-install your module to make it locked in admin
Answer: Most of the hook implementations go in the module file, not the in the installation file.
Hooks that needs to be in the installation file are, for example, hook_install(), hook_requirements(), hook_schema(), and hook_uninstall().
hook_image_default_styles() needs to be in the module file, or the file that hook_hook_info() reports to contain that hook implementation.
image_image_default_styles(), for example, is contained in the image.module file.


String's replace all is replacing none

Question: I have the following code:
System.out.println("Trace: #" +"2");
System.out.println(rv);
        rv.replaceAll("$t",sTAB);
System.out.println("Trace: #" +"3");
System.out.println(rv);

The rv and sTAB are of type String.  And sTAB has a value of a tab character.  The output is as follows:
Trace: #2
is$thi$t
Trace: #3
is$thi$t

But I expect:
Trace: #2
is$thi$t
Trace: #3
is{tab}hi{tab}

Of course with {tab} being actual tab characters. Can you explain what is wrong with my code?
Answer: replaceAll() takes a regular expression and returns the replaced String.
$ is a regular expression meta character that matches the end of a line.
Try using:
rv = rv.replaceAll("\\$t", sTAB);

Comment: @Kevin Did you reassign the return value of `replaceAll()` to `rv`? I just tested this and it works correctly.
Comment: rv.replaceAll("\$t",sTAB); gives an "illegal escape character" error when compiling.  rv.replaceAll("\\$t",sTAB); compiles but gives the same result as before.
Comment: I cannot believe I forgot rv=rv.rep... but that did not work either but that plus adding the two slashes did.  Thanks!
Answer: Java Strings are immutable.  Once you have a String it won't change.  replaceAll actually returns a new string with the replacements.
You should do
rv = rv.replaceAll("$t",sTAB);

Also note that replaceAll takes a regular expression. You should probably escape the $.
rv = rv.replaceAll("\\$t", sTAB);

Answer: No?
rv = rv.replaceAll("$t",sTAB);

Answer: You need to reassign the string rv = rv.replaceAll("$t",sTAB);

String's replace all is replacing none


Angular: No provider for depenency of dependency

Question: I am building a small toy app in Angular, which has the following classes (among others): ProductDetailComponent, and ProductService. The service contains a method for making an http GET request for a product. The compnent displays the details of a product, and uses the service to retrieve the product information. After adding the HttpModule to the application (and to the service within it), my component tests are failing, saying "Error: No provider for Http!".
If I import the HttpModule, the tests pass again. However, I'm confused as to why it needs HttpModule in the first place, because that is a ProductService dependency, and I am mocking out the ProductService using a provider.
So my question in short is why do the tests tell me I need this dependency when the class under test does not use it?
product-detail.component.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {ProductService} from "../product.service";
import {Product} from "../product";
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css'],
  providers: [ProductService]
})
export class ProductDetailComponent implements OnInit {
  product: Product;

  constructor(
    private productService: ProductService,
    private route: ActivatedRoute,
  ) { }

  ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this.productService.getProduct(+params['id']))
      .subscribe(product => this.product = product);
  }
}

product.service.ts
import {Injectable} from "@angular/core";
import {Product} from "./product";
import {Http} from "@angular/http";
import "rxjs/add/operator/toPromise";

@Injectable()
export class ProductService {
  private products: Product[];

  constructor(private http: Http) { }

  getProducts(): Promise<Product[]> {
    return this.http
      .get('/api/products/')
      .toPromise()
      .then(response => response.json() as Product[])
      .catch(error => {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error)
      });
  }

  getProduct(id: number): Promise<Product> {
    return this.http
      .get(`/api/products/${id}`)
      .toPromise()
      .then(response => response.json() as Product)
      .catch(error => {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error)
      });
  }
}

product-detail.component.spec.ts:
import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {ProductDetailComponent} from "./product-detail.component";
import {ActivatedRoute} from "@angular/router";
import {Observable} from "rxjs";
import {ProductService} from "../product.service";
import {Product} from "../product";
import {By} from "@angular/platform-browser";
import {DebugElement} from "@angular/core";
import {HttpModule} from "@angular/http";

describe('ProductDetailComponent', () => {
  let component: ProductDetailComponent;
  let fixture: ComponentFixture<ProductDetailComponent>;
  let debugElement: DebugElement;
  let element: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ProductDetailComponent],
      //imports: [HttpModule], //un-commenting this fixes the breakages
      providers: [{
        provide: ActivatedRoute,
        useValue: {params: Observable.from([{'id': 1}])},
      }, {
        provide: ProductService,
        useValue: {
          getProduct: (id: number) => Promise.resolve(new Product(id, 'Example Product Name', 20))
        }
      }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ProductDetailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should be stable', () => {
    fixture.whenStable().then(() => {
      expect(fixture.isStable()).toBe(true);
    });
  });

  it('should display the title', () => {
    fixture.whenStable().then(() => {
      debugElement = fixture.debugElement.query(By.css('.name'));
      element = debugElement.nativeElement;
      expect(element.textContent).toEqual('Example Product Name')
    });
  });

  it('should display the price', () => {
    fixture.whenStable().then(() => {
      debugElement = fixture.debugElement.query(By.css('.span'));
      element = debugElement.nativeElement;
      expect(element.textContent).toEqual('$ 20.0')
    });
  });
});

Answer: Try to:

import HttpModule to your NgModule
set ProductService as a provider in NgModule or ProductDetailComponent

For example:
product.module.ts
import { HttpModule } from '@angular/http';
import { ProductDetailComponent } from './product-detail.component';
import { ProductService } from 'product.service';

@NgModule({
  imports: [
    HttpModule,
    NgbModule.forRoot(),
  ],
  declarations: [
    ProductDetailComponent
  ],
  providers: [
    ProductService
  ],
})
export class ProductModule { }

Answer: In your module you have to add the ProductService provider to your providers property :
providers: [ProductService]


Unbounded function with integrable weak derivative

Question: I was wondering whether it is possible to construct a function $\space f:\left( -1,1 \right) \rightarrow \mathbb{R} \space$ such that following holds:
(1) $\space f \in L^1 \left ( -1,1 \right )$
(2) $\space f \notin L^{\infty} \left ( -1,1 \right )$
(3) $\space$there is a weak derivative $\mathrm{D}f$ of the function $f$ on $ \left ( -1,1 \right )$
(4) $\space \mathrm{D}f \in L^1 \left ( -1,1 \right )$.
In other words: $\space f \space$ belongs to the Sobolev space $\space W^{1,1} \left ( -1,1 \right ) \space$ but doesn't belong to $L^{\infty} \left ( -1,1 \right )$.
$\space$
I know that this is not possible in terms of classical derivatives, but I'm curious whether it can be done weakly. Unfortunately my knowledge of Sobolev spaces is not deep enough to solve this problem.
I will appreciate any help.
Answer: This situation can not happen in $1$D. This is because $W^{1,1}(I)$, where $I$ is an open interval, coincides with the space of absolutely continuous functions. As absolute continuity implies uniform continuity you can continuously extend your function to $\overline I$ by Heine-Cantor theorem, and easily infer the boundedness.
You can find a function with the desired properties in higher dimensions. Namely, you are looking for some set open, bounded  $D$ with Lipschitz boundary such that $W^{1,1}(D)$ is not embedded in $L^\infty(D)$.
Sobolev embeddigs theorem say that, given $D\subset \mathbb{R}^n$
$$W^{k,p}(D) \hookrightarrow W^{h,q}(D)$$
if and only if
$$\frac{kp-n}{p} \ge \frac{hq-n}{q}$$
with strict inequality if $q=\infty$ (unless $n=1$, in which the large inequality suffices).
In particular, as soon as $W^{k,p}$ magic number $(kp-n)/p$ is non positive, you do not have the embedding in $L^\infty$.
Comment: It maybe is worth pointing out that the first part of your answer implies that the strict inequality required in the second paragraph for $q=\infty$ is not actually necessary when $n=1$. This is an exception though, as for $n>1$ there are functions that are in $W^{1,n}(\mathbb{R}^n)$ but not in $L^{\infty}(\mathbb{R}^n)$
Comment: Ops, you are right. I started writing with in mind only the $n=1$ case, then got excited by the whole thing and went a bit deeper!
Answer: No such functions exist, and this is a particular case of the Sobolev embedding theorem (https://en.wikipedia.org/wiki/Sobolev_inequality).


How to determine if Varnish/Pressflow is caching content in a useful way?

Question: I recently converted one of my D6 sites to Varnish/Pressflow and saw a very modest improvement in average load speed (from ~550ms before to ~450ms now). But, I also noticed that the initial load time for the first load in a round of tests were consistently much higher --- around 1000ms. They quickly fall down to ~450ms during subsequent reloads during the same test.
This makes me think that I've configured something incorrectly, and Varnish isn't serving from the cache until after the (anonymous) user has already visited the page in question. Perhaps the session IDs are causing each session to be cached independently from eachother (though I understand that shouldn't happen for anonymous users under Pressflow).
The X-Varnish headers appear in both the initial page load, and subsequent loads, so I know the content is at least getting passed through Varnish.
Is there a way to get details about part of the Varnish cache is serving a particular page (e.g. when the cached page was created)? I've tried looking at the logs generated by varnishlog, but apart from various apearances of "X-Drupal-Cache: HIT" I'm not sure what to look for.
Answer: Below is the text that can been seen when using Google Chrome and under Network inspecting the response for you webpage. Observe the very last line. There you should get two numbers X-Varnish:1125490268 1125489929.
I've had problems before setting up Varnish and everything seemed to be going fine, then I noticed that only one number was present in X-Varnish. When fixed the two numbers appeared with a decrease in response time form 500ms to 45ms :)
Hope it can help you on the way.
Request URL:http://www.somepage.com/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:www.somepage.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.52 Chrome/28.0.1500.52 Safari/537.36
Response Headersview source
Accept-Ranges:bytes
Age:230
Cache-Control:public, max-age=900
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:6411
Content-Type:text/html; charset=utf-8
Date:Tue, 30 Jul 2013 08:03:13 GMT
Etag:"1375164849-1"
Expires:Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:Tue, 30 Jul 2013 06:14:09 +0000
Server:Apache
Vary:Cookie,Accept-Encoding
Via:1.1 varnish
X-Drupal-Cache:HIT
X-Generator:Drupal 7 (http://drupal.org)
X-Powered-By:PHP/5.3.10-1ubuntu3.6
X-Varnish:1125490268 1125489929

Comment: Exactly what I needed -- thanks! My X-Varnish values were indeed only one number on certain page loads, due to a misconfiguration in how cookies got set. I was able to find and fix it.
Comment: @anschauung Can you let us know what is the exact fix you did? It may help me.. I'm also facing a similar problem
Comment: How did you "fix" having two numbers? I only have one as well
Comment: This is fixed by making sure NO cookies are sent with the request https://www.varnish-cache.org/docs/4.0/users-guide/increasing-your-hitrate.html#cookies


Wrong initial intuition about the limit of $\frac{\sin(x)}{x}$ as $x$ goes to 0

Question: I'm following the MIT OpenCourseware course on calculus, and when proving the derivative of $\sin(x)$ the following assumption is needed
$\lim\limits_{x\to0}  \frac{\sin(x)}{x} = 1$
The proof for this is given and I can follow it.
My question however relates to my initial intuition. Which is that the limit of $\sin(x)$ at 0 is defined: $\sin(0) = 0$. So Why is it wrong to just plug that in
$ \frac{\sin(0)}{0} = 0$
I would have never looked further because this seems like a simple problem. What is wrong with my intuition here?
Comment: I had thought this was a duplicate, but the issue might really be about $\frac{0}{0}$, not $\frac{\sin(x)}{x}$.
Comment: Intuition should always be driven by computation, not by appearances. If you had ever calculated, for instance, $\sin(.01)/.01$, you would never have gotten that "intuition".
Comment: Your intuition was based on a single point (x = 0). Limits are based on the behaviour in an area around the point. sin (0.1) / 0.1 is quite close to 1 already. Your intuition was also wrong, because 0/0 isn't zero, it's actually undefined, so your intuition should have been "this might be tricky and needs a closer look".
Answer: You are making two fundamental mistakes:
First: after substituting $x=0$, you wind up dividing by $0$.
This is an undefined expression;
so, you should suspect that things have gone awry.
In your example, an even worse thing happens: you wind up with $0\over0$;
which (if it makes any sense) is even more "undefined" than, say, $1\over 0$.
For instance $\lim\limits_{x\rightarrow 0}{2x\over x}=2$
and $\lim\limits_{x\rightarrow 0}{ x\over 2x}={1\over2}$.
In fact a 0/0 form could possibly be anything.
Secondly, when taking limits, you should really avoid just plugging in the limit point into the expression.
This only works in certain cases (when the  limit exists and the function is continuous at the limit point),
and, more importantly,  hides the true nature of what a limit is:
Informally,
you write $$\lim_{x \rightarrow a} f(x)=L$$ if the values of $f(x)$ get closer and closer to $L$ as $x$ gets
closer and closer to, but not equal to, $a$.
Note the phrase "not equal to" in the above. This is an important restriction and is the reason why just
substituting the limit point into what you're taking the limit of can lead to trouble.
As an example of determining the limit of a 0/0 form,  let's try to find
$$
\tag{1} \lim_{x\rightarrow 1}{(x+1)(x-1)\over (x-1)}
$$
Formally substitutiing $x=1$ in the above gives $0/0$.
If, however, $x$ is close to one, but different from 1, then  substitution into the
right hand side of (1) gives a well-defined number;   moreover, the $(x-1)$ terms will cancel and the final result will be just $x+1$.
Thus, if $x$ is close to 1, but different from 1,
the expression ${(x+1)(x-1)\over (x-1)}$ is close to 2.
As it turns out, the closer $x$ is to 1, but different from 1, the closer
${(x+1)(x-1)\over (x-1)}$ is to 2; and thus
$\lim\limits_{x\rightarrow 1}{(x+1)(x-1)\over (x-1)}=2$.
Finding your limit ($\thinspace\lim\limits_{x\rightarrow0}{\sin x\over x} \thinspace$)
is a bit more complicated than the above. You can find the standard derivation of this limit, which utilizes the
Squeeze Theorem
and simple geometry here (or at your course site, as you said).
Answer: You can just use L'Hôpital's rule.
$$\begin{align*}
\frac{d}{dx} \sin(x) &=\cos(x) \\
\frac{d}{dx} x &= 1 \\
\lim_{x\rightarrow0} \frac{\sin(x)}{x}&=\lim_{x\rightarrow0}\frac{\cos(x)}{1}=1
\end{align*}$$
Edit: I think this rule is very helpful to evaluate limits involving indeterminate forms. Not as proof but as a sanity check of an intuitive answer.
Comment: Not only that L'H would be circular reasoning, but that limit is actually the definition of the derivative of sin: $\lim_{x\rightarrow0} \frac{sin(x)}{x}=\lim_{x\rightarrow0} \frac{\sin(x)-\sin(0)}{x-0}$... So using the derivative to calculate it is wrong on many levels...
Comment: While this is formally correct, how do you know that derivative of sine is cosine? The normal derivation of this fact relies on knowing the limit $\frac{\sin h}{h}$ already. So, to avoid circular reasoning, it has to be proved another way. (Also, you did not answer the question why plugging 0 is incorrect.)
Comment: @sdcvvc read my edit. I think it's a quick and helpful way of putting intuition to the test.
Comment: Yes, but this limit is (supposed to be) taught **way before** someone is taught how to differentiate trigonometric functions...
Comment: +1. This question is about intuition. When you're supposed to quickly tell the result of some expression, it doesn't matter if there's circular reasoning involved, it only matters that you start your reasoning from something you know to be true – and $\tfrac{\mathrm{d}}{\mathrm{d}x}\sin(x)=\cos(x)$ is a far easier (and in general more useful) identity to memorize than that limit. What's more, @N.S., it is possible to define the trig functions _by their derivative_ (as a solution to a system of differential equations), in fact I consider this the best definition.
Comment: @leftaroundabout The poster clearly stated that he needs this limit to calculate the derivative of $\sin(x)$...... And I think you confuse an intuitive formula with one which is easy to remember... Last but not least, I am curious why you think this is the best definition? How would you introduce these functions to someone who, like the poster, is just learning derivatives and has never seen a differential equation. You'd need to explain why an equation like $y''=-y$ has solutions, and why you get uniqueness if you add extra conditions....
Comment: .... (cont) Also, while defining sin by some differential equations, or Taylor series might be better mathematically, I don't think they yield any intuition ;)
Comment: @N.S. ok I didn't see that it's for proving $\partial_x\:\sin(x)=\cos(x)$. In this case it's indeed ridiculous to _use_ that equality in calculating the limit expression. — Why I consider the definition by differential equation best? There are four definitions I can think of: geometric, Taylor series, real and imaginary part of $e^{ix}$, solution to diff.eq / eigenfunctions to $-\nabla^2$. The geometric definition is doubtlessly the most intuitive, but it makes it rather harder to prove the analytic properties than it is to prove the geometric properties from the analytic definitions.
Comment: (cont) Taylor series is indeed not intuitive at all. Real and imaginary part, useful though this picture is, suggest that it is intrinsically necessary to use complex numbers for calculus. It also obviously requires you to define the complex exponential first. The differential equations, on the other hand, _are_ intuitive due to their abundance in physics. Sure, you need the concept of Lipschitz continuity to prove existance and uniqueness, but it's not a problem if you don't immediately understand those proofs, you will still memorize the definition of the functions and be able to use it.


How to test withRouter() and uselocation() wrapped component in React using jest?

Question: I am getting below error. Please tell how to write test case to test a component wrapped in withRouter and component using useLocation()
●
Test suite failed to run
TypeError: (0 , _reactRouterDom.withRouter) is not a function

Answer: This error happens because the route component tree is not attached to the render method.
I recommend create a TestUtils which abstract the render from react-testing-library and the router hierarchy:
This would be more or less:
export const renderWithRouter = (
  children,
  {
    path = '/',
    initialRoute = '/',
    history = createMemoryHistory({ initialEntries: [initialRoute] })
  } = {}
) => {
  return {
    ...render(
      <Router history={history}>
        <Route path={path}>{children}</Route>
      </Router>
    ),
    history
  };
};

Usage:
Without params in route:
const wrapper = renderWithRouter(<Component />);

With params in route:
const wrapper = renderWithRouter(<Component />, { path: '/route/:id', initialRoute: '/route/1' });

where :id will be replaced by 1
Comment: do we need to import withRouter in the test file?
Comment: no... just use renderWithRouter instead render from testing library
Comment: still getting error when i try to do expect(wrapper).tomatchsnapshot(); Error is TypeError: (0 , _reactRouterDom.withRouter) is not a function

      21 | }
      22 |
    > 23 | export default withRouter(ScrollToTop);
Comment: can you show your app.js, index.js and your test file/utils?


jQuery Cycle2 Advanced Pager via API

Question: I've been using this jQuery Cycle2 plugin (http://www.malsup.com/jquery/cycle2/api/advanced.php), and I've been trying to build a custom pager using a title from inside each slide.
The documentation for cycle 2 focuses more on data attributes in the HTML, however I need to execute the cycle2 plugin via it's javascript alternative.
I've been looking at this buildPagerLink via API but can't figure it out.
$('.p-slider').on('cycle-bootstrap', function(e, optionHash, API) {
    API.buildPagerLink = function(opts, slideOpts, slide) {
        //CODE TO GET H2 TITLE
    }
});

Basically what I want is this. Each slide has a
 element. I want the text inside that to be the link text for the pager. Sounds simple, but I can't figure it.
Any help would be appreciated.
Thanks.
Dave
Answer: There is a known bug with the cycle-bootstrap and therefor in order to use this with the buildPagerLink you need to bind it to the document.  The following will pull the h2 text and build the pager with it:
$(document).on('cycle-bootstrap', function( e, opts, API ) {
    API.buildPagerLink = function(opts, slideOpts, slide) {
       var pagerLink;
    var pagers = opts.API.getComponent( 'pager' );
    pagers.each(function() {
        var pager = $(this);

            var markup = $('').text($('h2', slide).text());
            pagerLink = $( markup ).appendTo( pager );
        pagerLink.on( opts.pagerEvent, function(e) {
            e.preventDefault();
            opts.API.page( pager, e.currentTarget);
        });
    });
    }
});

$('.slideshow').cycle();

Working demo:  http://jsfiddle.net/lucuma/FetC8/1/
Issue as reference:  https://github.com/malsup/cycle2/issues/157
Comment: Thanks for the help, however I do actually require an API method of fixing this problem due to the CMS I'm working with.
Comment: I don't understand your comment.  What I provided matches your question of providing a "javascript alternative".

jQuery Cycle2 Advanced Pager via API


SMS Framework - Multiple destination numbers

Question: I'm using SMS Framework module to send sms from Drupal site; Clickatell is setted as my default gateway. Using Rules module I'm able to notify users via sms when new node is created, but i can only setup one destination number.
Is there anyway to setup mutiple destination number?
A screenshoot of my rule configuration below:
Comment: Hi, I am wondering how much do you pay for a sms-message because I'am working on a custom Module to verify Users per sms
Comment: As I already said in question above, I'm using clickatell as gateway to send message so you can check their pricing at https://www.clickatell.com/
Answer: Assuming your question is about D7, you could try to create a view (using the Views module) of those users that you want to send an SMS to.
After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions (in the rule you already have in place):

Load the VBO list of those users.
Add a loop to perform a Rules Action "send an SMS" (similar to what your current rule already does), for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Multivariate linear mixed model using lmer

Question: I want to detect differences between 4 treatments of a food product based on the results from a sensory evaluation, where 9 panelists assessed the 4 products (i.e. treatments) following a number of sensory attributes. The output variables are scores (on a scale from 0 to 100) reflecting the intensity of each attribute. For each attribute I want to know how the 4 products differ (or not) from each other. To achieve this, I use a multivariate linear mixed model using the lmer() function. Here's how the data looks like:
panelist treatment repetition Odor1 Odor2 Odor3 Flavor1 Flavor2 Flavor3 Flavor4 Texture1
    1     CTRL           1    35    25     0      64      83      21      20       84
    1     T1             1    29    19    48      29      38      53      53       58
    1     T2             1    28    22    38      36      44      51      51       39
    1     T3             1    28    28    67      27      66      46      45       72
    1     CTRL           2    19    32     0      42      43      22      21       42
    1     T1             2     6    32    11      65      57      79      79       71
    1     T2             2    46    32    78      38      63      63      63       63
    1     T3             2    31    31    78      85      31      61      60       48
    1     CTRL           3    64    51    50      50      67      67      67       76
    1     T1             3    42    37    59      82      58      35      34       67
    1     T2             3     0    26    58      57      70      21      21       54
    1     T3             3     0    41    69      49      70      24      24       57

In order to perform the multivariate analysis with lmer(), I reshaped the dataset to a long-format table as explained here (and there) so that the scores are grouped in one column and indexed to the "attribute" variable (listing all sensory attributes):
panelist treatment repetition attribute value
    1    CTRL          1        Odor1     35
    1    T1            1        Odor1     29
    1    T2            1        Odor1     28
    1    T3            1        Odor1     28
    1    CTRL          2        Odor1     19
    1    T1            2        Odor1     6
    1    T2            2        Odor1     46
    1    T3            2        Odor1     31
    1    CTRL          3        Odor1     64
    ...

"Panelist" is treated as a random factor to adjust for different uses of the scale among the assessors.
I then used the following model as a starting point:
mod <- lmer(score ~ treatment + (1|panelist) + (1|attribute), data)

I feel that treating "attribute" as a random effect is the only way to go and the results obtained make sense with my data as opposed to treating it as fixed effect. But it only returns the significance between the 4 groups based on the 12 attributes all together.
So my questions are:
•   How can I figure out the significance (or not) among treatment groups for each attribute?
•   Is this model the right choice in this case or should I use a generalized linear mixed model instead?
Answer: With regard to your first question, you should include attribute also as a fixed effect, and potentially also consider its interaction with treatment.
The choice of linear mixed model vs a generalized linear mixed model depends on the outcome variable. Namely, linear mixed models assume that the distribution of your outcome conditional on the random effects is normal. A generalized mixed model would be used if you would have, for example, a binary outcome (Binomial distribution) or a count (Poisson distribution).
Comment: Thanks for your answer. I am fairly new to this method but this sounds contradictory since `(1|attribute)` defines the random slope shared by scores from the same `attribute` while we define that the effect of `attribute` is constant across `score`. The results from `lmer(score ~ treatment * attribute + (1|panelist) + (1|attribute), data)` returns rather similar significance values for the fixed effect of treatment (from Satterthwaite's method) but not surprisingly all p-values for the fixed effect of `attribute` equals 1.0.
Comment: The truth is I am not sure how to handle the index variable `attribute` in this case. Including it as a fixed factor in the model as you suggested could be an easy way out as I would get the answer to my first question directly from the summary output. However, based on the results from `lmer(score ~ treatment * attribute + (1|panelist), data)` this model do not seem appropriate to my data due to highly significant results for `attribute` in which scores are very similar across `treatment`.
Comment: Should the fixed effect of `attribute` be nested into `treatment`? And how would I define this in the formula?
Answer: I actually found the solution using the SensMixed package (cran.r-project.org/web/packages/SensMixed/SensMixed.pdf) with no need to reshape the dataset.
Pretty good explainations are also available from the package author's PhD thesis


testing if the absolute value of the mean is inferior to a threshold

Question: I would like to test
$H_0:|\mu|\leq\tau$ vs $H_1:|\mu|>\tau$
where $\mu$ is the expected mean and $\tau>0$.
Do you know which test statistic I have to use ?
For instance, one can use the Wald statistic $\frac{\hat{\mu}-\mu}{\sigma}$ to test the nullity of $\mu$, but I think it is not adequate for this purpose.
Thank you.
Answer: Well the trick is to observe that to control type-I error control it is enough to calculate the null distribution under the two simple hypotheses $\mu = \tau$ and $\mu= - \tau$. Notice that in both cases you get that $|\mu|= \tau$. In other words under both these simple hypotheses you get the same distribution for the absolute value of $|\hat{\mu}|$.
Thus you can just calculate a two-sided p-value as follows:
$$ P = 2\int_{|\hat{\mu}|}^{\infty} \phi(x, \tau, \sigma^2) dx $$
Here $\phi(x, \tau, \sigma)$ is the density at $x$ of a normal distribution with mean $\tau$ and variance $\sigma^2$.
As per usual reject $P \leq \alpha$ to control type-I error rate at $\alpha$.


$\sigma$-weak continuity of $x \mapsto x \otimes 1$ from $B(H)$ to $B(H \otimes H)$

Question: Let $H$ be a separable Hilbert space. Write $B(H)$ for the set of linear bounded operator on $H$ and $H \otimes H$ the tensor product of Hilbert space. For every $A,B \in B(H)$ we can define an operator $A \otimes B$ on $H \otimes H$ by $(A \otimes B)(x \otimes y) = Ax \otimes Ay$. Thus, we can define $\omega : T \mapsto T \otimes 1$ from $B(H)$ to $B(H \otimes H)$. Given how simple $\omega$ is, I guessed that it should be continuous with respect to both $\sigma$-weak topology. That's what I want to show. Here is what I've done so far :
Let $(A_i)_i$ be a $\sigma$-weak converging net in $B(H)$ and let $A$ be it limit. Let $(\xi_n)_n, (\eta_n)_n$ be sequences in $H \otimes H$ such that $\sum_n ||\xi_n||^2, \sum_n ||\eta_n||^2 < +\infty$. We have to show that $\sum_n (\omega(A_i)\xi_n \mid \eta_n) \xrightarrow[i \to +\infty]{}\sum_n (\omega(A)\xi_n \mid \eta_n)$. For every $n$, we can write $$\eta_n = \sum_r x_r^n \otimes y_r^n , \hspace{2mm} \xi_n = \sum_s z_s^n \otimes t_s^n$$
First I'll do things formally and then try to justify every step.
We have
\begin{align*}
\sum_n (\omega(A_i)\xi_n \mid \eta_n) &= \sum_n \sum_r \sum_s (A_i z_s^n \otimes t_s^n \mid x_r^n \otimes y_r^n) \\
&= \sum_n \sum_r \sum_s (A_iz_s^n \mid x_r^n) (t_s^n \mid y_r^n) \\
&= \sum_n \sum_s (A_i z_s^n \mid \psi_n^s)
\end{align*}
Where $\psi_n^s = \sum_r (t_s^n \mid y_r^n)x_r^n$. I then want to use the $\sigma$-weak convergence of $(A_i)_i$ by re-indexing both sequences $(z_s^n)$ and $(\psi_n^s)$ but I'm not quite sure if I can control the series of norm of those sequences. For instance, we could have that $||z_1^s|| = s$ and $||t_1^s|| = \frac{1}{s^3}$ so that $||\xi_1|| = \sum_s ||z_1^s|| ||t_1^s||$ converges. This issue makes me think that my approach won't work. What I'm asking for is either an hint that would help me fix the issue I have or another proof idea. Thanks in advance.
Answer: Here is something useful to keep in mind.
A linear map $\pi: M\to N$ between von Neumann algebras is normal if its adjoint $\pi^*$ maps $N_*$ into $M_*$. In your case, you have
$$\pi: B(H)\to B(H\otimes H): x \mapsto x\otimes 1.$$
Consider vectors $\xi, \eta, \xi', \eta'\in H$. Then we have for $x\in B(H)$ that
$$\pi^*(\omega_{\xi, \eta}\otimes \omega_{\xi', \eta'})(x) = \omega_{\xi, \eta}(x) \langle \xi', \eta'\rangle$$
so that
$$\pi^*(\omega_{\xi, \eta}\otimes \omega_{\xi', \eta'}) = \langle \xi', \eta'\rangle \omega_{\xi, \eta} \in B(H)_*.$$
Since the functionals $\omega_{\xi, \eta}\otimes \omega_{\xi', \eta'}$ are linearly dense in $B(H\otimes H)_*$, we conclude that
$$\pi^*(B(H\otimes H)_*))\subseteq B(H)_*$$
whence $\pi$ is normal.
Remark: No separability of $H$ was used, and you can replace the second factor of the tensor product by an arbitrary Hilbert space.
Alternatively, you can use that a $*$-isomorphism between two von Neumann algebras is automatically $\sigma$-weakly continuous (although using this is a sledgehammer argument in this case). Your map $\pi$ defines a $*$-isomorphism $B(H)\cong B(H)\bar{\otimes}\mathbb{C}$ and is therefore normal.
Comment: Thanks a lot for your answer. I'm very new to Von Neumann algebra theory and operator theory in general, do you know where I could find a proof of the characterization you're using ? I guess in Takesaki's book ?
Comment: @ValentinMassicot You can use that $m_i \to 0$ $\sigma$-weakly if and only if $\omega(m_i)\to 0$ for all $\omega \in M_*$. From this, the proof of the characterisation I mention is pretty straightforward.
Comment: I just realized that's the usual characterization for continuity relatively to a topology given by a family of functions. I feel so idiotic.
Comment: "Since the functionals are linearly dense" Don't you need some sort of continuity on pi* (hence the sigma-weak continuity of pi) to guarantee that it maps the closure of a set into the closure of the image ?
Comment: @ValentinMassicot $\pi^*$ is norm-continuous. That's all you need.


Is it possible to reuse existing test suite from OpenJDK to test new collection classes?

Question: I implemented a custom collection and want to test it by using unit-tests from open-jdk.
Is the test suite used to test the OpenJDK implementations open? Are there other alternatives?
Answer: Use the ones from Guava instead:
http://code.google.com/p/google-collections/source/browse/trunk/testfw/com/google/common/collect/testing/
Comment: @thinker I think you should accept the answer


Converting xls to xlsx and deleting the old file

Question: I am using the following macro to convert an xls file to xlsx.  The problem with it is the line that says SaveAs.  This creates a second file, one with the original xls extension and the second with the xlsx extension.  If I simply say Save, I get an error.  How can I either delete the xls file or have the macro do a Save instead of SaveAs?  The reason we need to convert the file is so that when we email the file it is smaller in size.
Dim s As String
s = ActiveWorkbook.FullName
s = Replace(s, "xls", "xlsx")
ActiveWorkbook.SaveAs Filename:=s, _
      FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Comment: There are two separate operations here - Creating a new file (in xlsx format) and deleting an old file.  There really isn't a way around this.  Sounds like you have the first task covered.  Here's some answer related to the second: http://stackoverflow.com/questions/67835/deleting-a-file-in-vba
Answer: In terms of saving your current file, you have 2 choices:  overwrite your current file (with the same type), or generate a new file.  This is a limitation (feature?) of Excel, not VBA.
So, to acheive what you want, we will need to do some more work.  What we need for this is the FileSystemObject.  This basically allows you to interact with the files and directories on your computer through VBA.  The first thing we need to do is keep the original file name;  This will allow us to delete it by name.  From there, we will create the FileSystemObject, and use it to call the DeleteFile method.  So, your code should look like
Dim old_name As String, new_name As String
old_name = ActiveWorkbook.FullName
new_name = Replace(old_name, "xls", "xlsx")
ActiveWorkbook.SaveAs Filename:=new_name, _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Dim FSO as FileSystemObject
Set FSO = New FileSystemObject
FSO.DeleteFile old_name
Set FSO = Nothing

Note that you will need to set a reference to Microsoft Scripting Runtime in order to create and use a FileSystemObject.


button into tooltip using qtip plugin doesn't work

Question: I wrote this code below used qtip plugin for html link :
    $(document).ready(function() {
        $('#login').qtip({
            content: '

Username	<INPUT type="text" value=""   name="username" title="Enter Username" class="txtbx"/>	' +
            'Password	<INPUT type="password" value="" name="password" title="Enter password" class="txtbx"/>	' +
            '<button id="loginbtn" type="submit" >login</button>

',
            show: { when: { event: 'click' },
                effect: { type: 'fade', length: 200 }
            },
            hide: { when: { event: 'unfocus' },
                effect: { type: 'fade', length: 430 }
            },
            position: {
            adjust: { resize: true

        },
                corner: {
                    target: 'bottomLeft',
                    tooltip: 'topLeft'
                }
            },
            style: {
                name: 'dark',
                width: { max: 700 }
            }
        });
     });

but the submit button doesn't work !!!!??? any help here !!
Comment: How do you define "work"? Is an ajax request to be submitted? Is there an event that runs when a user clicks on the button? Is a form supposed to be submitted?
Answer: Does replacing <button id="loginbtn" type="submit" >login</button> with
<input name="loginbtn" id="loginbtn" type="submit" value="login" />

work?
Also, I don't see a form element anywhere with an action or method attribute wrapping all of your form inputs. Hence, I don't think the browser knows what to do when you submit the form.
Comment: yes ur right about form element !! so what do u recommend for that?
Comment: as the link says, it depends on what you aim to do. the action attribute takes an address to a server side script to be run. the method attribute notes what type of request is made. i would read up on form elements and server side scripting.
Comment: acually i am start working on design didn't write server side code yet
but check up this link for complete code
http://aspspider.info/termi/
Comment: I think its better if i put login controls into div and hide/show it as i want , its much better that using tooltip ?