How do I add a super admin, either programmatically or directly through the database or another

Question: $new_user = array(
  'name' => 'Sg',
  'mail' => 'firstname.lastname@example.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' =>'S'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
 //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);

I've seen this above code but where should I implement this code? I tried adding it and I got the error:

user_save() is an undefined function.

I just need to be able to login to the system as a super-admin.
Comment: where did you tried to add it? have you tried people > roles ?
Comment: Im sorry I could not login into the admin dashboard so I cant access people>roles.
Answer: You have to create a super admin role(admin/people/permissions) and check all the boxes. And then you need to assign this role to the user.
Comment: The question here consists of 2 completely different questions (the last phrase in it is what is the 2nd question). This answer is, IMO, the "best" answer to most of the question, ie as in the title ...
Answer: I found what I was looking for. You can use drush to generate a one time login link which allows you to get into the system.
drush user-login or its alias drush uli
Comment: In fact, you can use `drush uli [username]` to login as any existing user in your website.
Comment: Cheers, didn't know that.


Add programmatically exposed filter to view without removing the existing ones

Question: I want to add an exposed filter to a view which contains already exposed filters but without altering them.
When I add the following code it messes up  the exposed filters from the view and only the programmatically coded exposed filter works correctly.
I use the following code:
<code>function music_m_views_pre_view(&$view, &$display_id = null , &$args = null)
{
$filter = $view->display['default']->handler->options['filters'];
$current_latter = arg(1);
$filter['field_last_name_value']['value'] = $current_latter;

$view->display_handler->override_option('filters', $filter);
}
</code>
Answer: The hook function used was wrong. I had to use hook_views_pre_build(&$view)
so I have now the following (and the other exposed filters don't get messed up):
<code> function music_m_views_pre_build(&$view) {

$view_filters = $view->display['default']->handler->options['filters'];

 $current_latter = arg(1);

 if($current_latter)
 {
    $view_filters['title']['value'] = $current_latter;

 }
$view->display[$view->current_display]->handler->handlers['filter']['title']->value = $current_latter;
</code>
}


Convergence of the variance of the posterior expectation

Question: Consider a classical Bayesian model :
$$ \begin{array}{cc}
\theta \sim \pi \\
X = (X_1, ..., X_n) \overset{i.i.d.}{\sim} \pi(.\mid\theta)
\end{array}
$$
where the prior does $\pi$ and the likelihood $\pi(.\mid \theta)$ do not change with $n$ and data $X$ are i.i.d. conditionnaly on $\theta$ (no weird stuff here).
I'm wondering wether the variance of the expectation a posteriori should coincide asymptotically with the variance of $\theta$. That is, wether the following property is true:
$$ \mathrm{Var}\left(\mathbb{E}[\theta \mid X]\right) \underset{n\to\infty}{\longrightarrow}\mathrm{Var}[\theta] .$$
I expect it to be true from an informal reasonning based on variance decomposition, but I would like to have that intuition confirmed (or unvalidated) by a more formal argument.
So my questions are :

Is this result true ? If yes, under what hypothesis ?
How would one prove this rigorously ?
Are there cases (not totally degenerated like a point mass prior) where this result does not hold?
What about the posterior variance ? Shouldn't it provide information on the variance of the posterior expectation ?
Answer: This is a bit related to When do posteriors converge to a point mass?
If the prior is covering the entire range then $\hat{\theta} \xrightarrow{P} \theta$, the parameter estimate will converge to the true parameter. So a Bayesian type of estimate will converge to the true parameter and the sample distribution of the estimate will converge to the distribution of the true parameter.
If the prior is also equal to the true distribution of the parameter (this doesn't need to be the case) then the convergence of the sample distribution of the estimate to the sample distribution of the true parameter will also be convergence to the prior distribution. (and the variances will equal)


Improve performance of NOT EXISTS in case of large tables

Question: What I am trying to accomplish is getting rows from one table that do not match another table based on specific filters. The two tables are relatively huge so I am trying to filter them based on a certain time range.
The steps I went through so far.

Get the IDs from "T1" for the last 3 days

SELECT
id
FROM T1
WHERE STARTTIME BETWEEN '3 days ago' AND 'now';

Execution time is 4.5s.

Get the IDs from "T2" for the last 3 days

SELECT
id
FROM T2
WHERE STARTTIME BETWEEN '3 days ago' AND 'now';

Execution time is 2.5s.

Now I try to use NOT EXISTS to merge the results from both statements into one

SELECT
CID
FROM T1
WHERE STARTTIME BETWEEN '3 days ago' AND 'now'
AND NOT EXISTS (
  SELECT NULL FROM T2
  WHERE T1.ID = T2.ID
  AND STARTTIME BETWEEN '3 days ago' AND 'now'
);

Execution time is 23s.
I also tried the INNER JOIN logic from this answer thinking it makes sense, but I get no results so I cannot properly evaluate.
Is there a better way to construct this statement that could possibly lead to a faster execution time?
19.01.2022 - Update based on comments

Expected result can contain any number of rows between 1 and 10 000

The used columns have the following indexes:

CREATE INDEX IX_T1_CSTARTTIME
   ON T1 (CSTARTTIME ASC)
   TABLESPACE MYHOSTNAME_DATA1;

CREATE INDEX IX_T2_CSTARTTIME
   ON T2 (CSTARTTIME ASC)
   TABLESPACE MYHOSTNAME_DATA2;

NOTE: Just noticed that the indexes are located on different table spaces, could this be a potential issue as well?

Following the excellent comments from Marmite Bomber here is the execution plan for the statement:
---------------------------------------------------------------------------------------------
| Id  | Operation            | Name  | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
--------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |       | 21773 |  2019K|       |  1817K  (1)| 00:01:12 |
|*  1 |  HASH JOIN RIGHT ANTI|       | 21773 |  2019K|   112M|  1817K  (1)| 00:01:12 |
|*  2 |   TABLE ACCESS FULL  | T2     |  2100K|    88M|       |  1292K  (1)| 00:00:51 |
|*  3 |   TABLE ACCESS FULL  | T1     |  2177K|   105M|       |   512K  (1)| 00:00:21 |
---------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

1 - access("T2"."ID"="T1"."ID")
2 - filter("STARTTIME">=1642336690000 AND "T2"."ID" IS NOT NULL
           AND "STARTTIME"<=1642595934000)
3 - filter("STARTTIME">=1642336690000 AND
           "STARTTIME"<=1642595934000)

Column Projection Information (identified by operation id):
-----------------------------------------------------------

1 - (#keys=1; rowset=256) "T1"."ID"[CHARACTER,38]
2 - (rowset=256) "T2"."ID"[CHARACTER,38]
3 - (rowset=256) "ID"[CHARACTER,38]

Comment: By the way: rewriting your NOT EXISTS condition as a NOT IN condition or as a join (plus some condition) won't make your query faster. Oracle re-writes your condition (regardless of which syntax you use) into its own version of a join, using the most efficient approach (or what the optimizer "thinks" is the most efficient approach, anyway). That's the wrong thing to look at; your query is fine as it is right now. Look for indexes, for statistics - are they current, etc., not the structure of your query.
Comment: The problem itself may cause this longer time for the anti-join (the "not exists" condition). If each table has, say, 1 million rows, and each query selects 10,000 rows (last three days in each table), the three-days filter on each table may take a few seconds. But then, the anti-join step must compare 10,000 rows from the first table to 10,000 rows from the second table; that is 100 million comparisons, which of course will take much longer than the initial filtering.
Comment: You didn't tell us what indexes exist on the two tables (if any). Separate indexes on the ID columns and the date columns may help; the indexes on the date columns may make the initial steps faster, but the really important indexes would be those on the ID columns, because they would affect the execution of the anti-join.
Comment: @Yanis Petras, You could try this one combining LEFT JOIN and WHERE clauses :

SELECT T1.CID
FROM T1
LEFT JOIN  T2
    ON T1.ID = T2.ID
        AND T2.STARTTIME BETWEEN '3 days ago' AND 'now'
WHERE T1.STARTTIME BETWEEN '3 days ago' AND 'now'
    AND T2.ROWID IS NULL
Comment: Like I said (and you just confirmed), writing the same query using different syntax won't help. Oracle rewrites them all, internally, to the same query it sends for execution. Regarding indexes: see if you get meaningful improvement from adding indexes on ID. (In a big organization, you would do this in the development environment first, before asking your DBA to allow you to create the same indexes in production.)
Comment: Welcome to Stack Overflow! To help you with your [tag:query-optimization] question, we need more information. Please [read this](https://stackoverflow.com/tags/query-optimization/info), then [edit] your question.
Comment: @Mahamoutou Thanks for the suggestion. Unfortunately, performance-wise this statement was almost the same is my initial one :/
Comment: @mathguy I just checked the indexes and we have them only on the STARTTIME columns on both tables.
Answer:
Is there a better way to construct this statement that could possibility lead to a faster execution time?

Your basic responsibility is to write the SQL staement, the basic responsibility of Oracle is to come with an execution plan
If you are not satified (but you should know that a combination of two sources using NOT EXISTS will take longer that the sum of the time to extract the data from the sources) your fist step should be to verify the execution plan (and not try to rewrite the statement).
See some more details how to proceede here
EXPLAIN PLAN  SET STATEMENT_ID = 'stmt1' into   plan_table  FOR
SELECT
PAD
FROM T1
WHERE STARTTIME BETWEEN date'2021-01-11' AND date'2021-01-13'
AND NOT EXISTS (
  SELECT NULL FROM T2
  WHERE T1.ID = T2.ID
  AND STARTTIME BETWEEN date'2021-01-11' AND date'2021-01-13'
);

SELECT * FROM table(DBMS_XPLAN.DISPLAY('plan_table', 'stmt1','ALL'));

This is what you should see
-----------------------------------------------------------------------------
| Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |      |  1999 |   150K| 10175   (1)| 00:00:01 |
|*  1 |  HASH JOIN RIGHT ANTI|      |  1999 |   150K| 10175   (1)| 00:00:01 |
|*  2 |   TABLE ACCESS FULL  | T2   |  2002 | 26026 |  4586   (1)| 00:00:01 |
|*  3 |   TABLE ACCESS FULL  | T1   |  4002 |   250K|  5589   (1)| 00:00:01 |
-----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("T1"."ID"="T2"."ID")
   2 - filter("STARTTIME"<=TO_DATE(' 2021-01-13 00:00:00', 'syyyy-mm-dd
              hh24:mi:ss') AND "STARTTIME">=TO_DATE(' 2021-01-11 00:00:00',
              'syyyy-mm-dd hh24:mi:ss'))
   3 - filter("STARTTIME"<=TO_DATE(' 2021-01-13 00:00:00', 'syyyy-mm-dd
              hh24:mi:ss') AND "STARTTIME">=TO_DATE(' 2021-01-11 00:00:00',
              'syyyy-mm-dd hh24:mi:ss'))

Note that the hash join (here anti due to the not exists) is the best way to join two large row sources. Note also that the plan does not use indexes. The reason is the same - to access large data you do not want to go over index.
Contrary to the case of low cardinality row sources (OTPL) where you expects to see index access and NESTED LOOPS ANTI.
Some times is Oracle confused (e.g. while seeing stale statistics) and decide to go the NESTED LOOPway even for large data - which leads to long elapsed time.
This should help you at least to decide if you have a problem or not.
Answer: Perhaps a simple MINUS operation will accomplish what you are looking for:
    select id
      from ( select id
               from t1
              where starttime between '3 days ago' and 'now'
             MINUS
             select id
               from t2
              where starttime between '3 days ago' and 'now'
           );

for however you actually define starttime between '3 days ago' and 'now'. This literally uses your current queries as is the MINUS operation removes from the first those values which do exist in the second and returns the result.  See MINUS demo here.
Comment: Thanks for the suggestion. This one actually gave worse performance - 33s.
Comment: Does anyone know how you can accomplish something similar in MySQL? MySQL doesn't have the MINUS operator. A regular left join takes forever.


md-form-field must contain a MdFormFieldControl

Question: I am trying to insert an input field in my component using angular-material2. This is my HTML:
<md-form-field>
    <input type="text">
</md-form-field>

In the console, I get this error but I don't understand why I get the error:

md-form-field must contain a MdFormFieldControl. Did you forget to add mdInput to the native input or textarea element?
Answer: First you need to import MdFormFieldModule,MdInputModule modules in your app.module. Then you need to add an mdInput directive in your <input>.
<md-form-field>
  <input type="text" mdInput>
</md-form-field>

Link to working demo.
Comment: Fixed it, i had forgotten to import some modules.
Comment: I was already importing both of those modules and still received the error. I ended up viewing the link that you provided and just importing everything and it works. Was just curious as to which specific module needed to be added.
Comment: Which version of material? Same error? Thats not possible - have you seen the demo?
Comment: ...what modules?
Comment: `MdFormFieldModule`,`MdInputModule`  ... @MatthewMeppiel please upvote if this answer helped you :) please refer to this answer as well for more details: https://stackoverflow.com/a/45954825/1791913
Comment: @Faisal, I imported MdFormFieldModule, MdInputModule and the code in the html is just like what you wrote. I don't get any errors, but the input looks as a regular html input, no floating label etc. do you have any idea why? I am using material beta.10
Comment: You need to add theme in your app.
Comment: What do you mean? as I mentioned I imported them in my app module


How to create a proper custom exception class?

Question: I am trying to create a custom exception class and I'm having a lot of trouble. Can someone help me out! I just started programming very recently and i'm hoping to get some pointers.
import java.util.Random;
import java.util.Scanner;
import java.util.InputMismatchException;

public class GuessingGame {

    public static void main(String[]args) throws BadGuessException
    {
        int min = 1;
        int max = 10;
        Random rand = new Random();

        int numberToGuess = rand.nextInt((max - min) + 1) + min;

        Scanner input = new Scanner(System.in);
        int guess;
        boolean win = false;
        int numberOfTries = 0;

        while (!win)
        {

            System.out.println("Guess a number between 1 and 10: ");
            try
            {
                guess = input.nextInt();
                numberOfTries++;

                if (guess == numberToGuess)
                {
                    win = true;
                    System.out.println("YOU GOT IT!");
                    System.out.println("It took you " + numberOfTries + " tires.");

                }
                else
                {
                    throw new BadGuessException();
                }
            }
            catch(InputMismatchException e)
            {
                e.getMessage();
            }
        }
    }

}

    import java.util.*;

public class BadGuessException extends Exception {

    String message = "Sorry, that was an invalid guess!";

    //Default Constructor
    public BadGuessException()
    {
        super();
    }

    //Parameterized Constructor
    public BadGuessException(Throwable cause)
    {
      super(cause);
    }

}

I'm supposed to create 2 constructors, one default and one parametrized. If the user enters a number between 1-10, i should catch it in a catch block and print the message "invalid guess" And if they enter a letter or something, the output should be something like "Invalid input" ( Should I catch invalid input in BadGuessException and then pass it to InputMismmatch? If so, how do I do that?)
Right now, when I run this code, if I enter a letter, it doesn't crash, but the while loop iterates continuously and I'm not able to enter anymore inputs. It just keeps repeating "Guess a number between 1-10."
I'm assuming it's because once the try block executes once, it doesn't execute again? How do I fix this? Sorry for any confusion, happy to clarify! any help is much appreciated.
Also, I'm not sure how to catch 2 different exceptions at the same time. One for invalid guess and one for invalid input. :/
Comment: How are two exceptions supposed to be thrown at the same time?
Comment: You're almost there. Just add a `catch ( BadGuessException e ) { System.out.println( e.getMessage() ); }` below the `catch` that's already there (also: `e.getMessage();` on itself doesn't do anything, you'll want to print it!). Idk about scanner but perhaps you need to `input.next()` to fetch (and discard) that letter.
Answer: I think what you want is if they make a guess and it is incorrect, that your loop should run again, right? In that case, you should adjust your loop, as I've shown below. Also, where you are catching the InputMismatchException, you are swallowing the exception without printing it or handling it: This is VERY BAD PRACTICE. I've updated this too for you.
while (!win)
        {

            System.out.println("Guess a number between 1 and 10: ");
            try
            {
                guess = input.nextInt();
                numberOfTries++;

                win=true;

                if (guess == numberToGuess)
                {
                    win = true;
                    System.out.println("YOU GOT IT!");
                    System.out.println("It took you " + numberOfTries + " tires.");

                }
                else
                {
                    throw new BadGuessException();
                }
            }
            catch(InputMismatchException e)
            {
                System.out.println("Please input a number betwee 1 and 10!");
            }
            catch(BadGuessException ex) {
                System.out.println("Sorry, you guessed the wrong number!");
            }
        }

Comment: Hello, thakn you so much! that catches the wrong input, however, when I input a letter, it repeats continuously. It doesn't ask me for another input again. :/ (I removed the win = true about the if statement) That error was a silly mistake on my part.
Comment: When I enter a letter, the program goes into an infinite loop and displays the following messages continually and never asks me for an input "Guess a number between 1 and 10:
Please input a number between 1 and 10!"  @ControlAltDel
Answer: Exceptions should be used for handling errors, invalid input, illegal, unusual situations. If not guessing the correct number is an error, that sounds like not being a mind reader is an error. So BadGuessException is misused here.
For a better use case, how about throwing this exception for non-sense input? For example, since the program asks the user to input a number between 1 and 10, inputting -3 or 99 would be clearly an error.
The loop in the middle can be corrected accordingly:
while (!win) {
    System.out.println("Guess a number between 1 and 10: ");
    try {
        guess = input.nextInt();
        numberOfTries++;

        if (guess == numberToGuess) {
            win = true;
            System.out.println("YOU GOT IT!");
            System.out.println("It took you " + numberOfTries + " tires.");
        } else if (guess < 1 || guess > 10) {
            throw new BadGuessException();
        }
    } catch (InputMismatchException e) {
        input.nextLine();
    }
}

As for creating a custom exception class, you already did that. It's written a bit messy way, cleaning it up (removing unnecessary stuff) it becomes:
public class BadGuessException extends Exception {

    private static final String message = "Sorry, that was an invalid guess!";

    public BadGuessException() {
        super(message);
    }
}

UPDATE
I fixed another bug in your code: if you enter non-integer input, a InputMismatchException will be thrown. Repeatedly. Forever.
This is because the input.nextInt() doesn't consume the input if it's not valid. So the invalid input stays there, and input.nextInt() will keep failing, putting your program in an infinite loop.
To fix that, you must consume the bad input somehow, for example by reading the line:
    } catch (InputMismatchException e) {
        input.nextLine();
    }

Comment: I wanted to create a parametrized constructor also. But when i looked at the documentation for Exception, it seems that you can have multiple parameters. Which parameters would I use? Just a type Throwable? or a String?
Comment: Use just what you need, nothing more. If you don't need anything else, don't add anything else. In this example, there's really need to for a `Throwable`
Comment: WHen I do e.getMessage inside a print statement, it says cannot find symbol
Comment: So when I catch the InputMismatch exception, the code never goes back to the asking me for an input, it just repeats "guess again" continually. (I posted the comment in more detail in ControlAltDel's answer. Can you please help me clarify this?
Comment: Oh I see. I have a fix and explanation for that, see my updated answer.
Answer: You never catch the BadGuessException so it will be thrown out of the while loop and program will exit. You must catch the exception inside the loop if you want to continue.
I agree with janos comment that this is not a good use of exceptions. Guessing wrong is part of the normal game flow, no?
But doing it for the practice, I'd for example pull all logic inside the loop into a new private method, let it throw this exception, and catch it in the loop. You can catch multiple exceptions in a row like this.
while (!win) {
    try {
        win = makeGuess();
    } catch (InputMismatchException e) {
            e.getMessage();
    }  catch (BadGuessException e) {
        System.out.println("Wrong guess");
    }
}

private boolean makeGuess() throws BadGuessException, InputMismatchException {
   ...
 }


The session setup from the computer  failed to authenticate

Question: Every once in a while, I get a client PC that won't be able to log into the domain. This morning it was telling us that the trust relationship between the pc and the domain failed. I checked the event logs on the primary domain controller and I see this for 2 PCs (the one that had the problem and one that can log in today).
The session setup from the computer  failed to authenticate. The name(s) of the account(s) referenced in the security database is .  The following error occurred:
Access is denied.
I know how to fix this, by rejoining the PC to the domain... But why does this happen and how can I prevent it so I don't have to keep rejoining PCs to the domain?
Answer: Computers joined to a domain manage their membership by use of a shared secret. Basically, all computers on the domain have their very own account password, just like all your user accounts.
The difference is that the computers maintain this themselves, without any involvement from you and without you ever seeing what that password is. The machine periodically goes through a password change where a new password is generated and updated on both the computer and the AD computer account object.
What you're seeing is a situation where the password stored on the domain and the password the computer believes is valid, are not the same. This could happen for a multitude of reasons but the most common ones are:

Restoring a computer from backup, and restoring an invalid password along with it
Reverting a computer VM to a snapshot which was taken before the latest password update
Reverting a domain controller vm to a snapshot or restoring a DC from a backup without using recovery mode, and causing a USN Rollback scenario (don't do this!)
Replication errors on the domain leaving a domain controller with outdated password information.

So to fix it, watch for issues similar to the above. Any cases where either the domain or the workstation could be ending up with a stale or corrupted account password will bring you this issue.


Validate URL alias before saving Node

Question: I have a custom content type which has a url alias pattern of [node:type]/[node:title].
How can I validate the node form in order to prevent the url alias from becoming [node:type]/[node:title]-0 in case the same title is used somewhere else.
Basically, I would like to prevent the node from saving, and display an error message if the url alias will end up having a "-0" at the end.
Answer: How about using the Unique field module for this? Here is a quote about the module's project page:

This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.

Validate URL alias before saving Node


How to build a carrier-neutral data center?

Question: We need to set up a very small datacenter. This needs to be carrier-neutral. What are the things we need to do to make it a carrier-neutral datacenter?
I assume that we need internet connections from multiple internet service providers (ISPs). If one network is down then we can switch to another one. But, how can we keep the IPs of the servers the same, even after switching the ISP? Normally, changing the ISP changes the server computer's IPs.
Comment: Carrier neutral datacenters suggest to me a datacenter  that won't be operated exclusively by and for one customer, but that a (co-location) datacenter operator rents out rack space, rows of racks and cages/suites to third parties. Those customers are not required to use IP-space that belongs to the datacenter operator, they can connect to the ISP's of their choice. Typically several ISP's/transit providers etc. will  already present and/or will be allowed access to a [meet-me-room](https://en.wikipedia.org/wiki/Meet-me_room) and patches can be made from there to their racks/cages/suites.
Answer: What you need is Autonomous system. This will help you route the same IPs independently of the provider. Here is the first paragraph from the link:

An autonomous system (AS) is a collection of connected Internet
Protocol (IP) routing prefixes under the control of one or more
network operators on behalf of a single administrative entity or
domain, that presents a common and clearly defined routing policy to
the Internet.1 Each AS is assigned an autonomous system number
(ASN), for use in Border Gateway Protocol (BGP) routing. Autonomous
System Numbers are assigned to Local Internet Registries (LIRs) and
end user organizations by their respective Regional Internet
Registries (RIRs), which in turn receive blocks of ASNs for
reassignment from the Internet Assigned Numbers Authority (IANA). The
IANA also maintains a registry of ASNs which are reserved for private
use (and should therefore not be announced to the global Internet).

As it is explained in comment:

In other words: unlike the typical "consumer and small business"
internet connectivity that comes with only the public IP-addresses
owned by the ISP, you will be using your own / provider independent
public IP-address range(s). That allows traffic to and from your
IP-range(s) to be routed via different ISP's , different carriers.
Comment: erm, not quite. Something expensive, difficult to test and maintain is not a requirement. Just use SNAT/proxying at the edge instead of DNAT.
Answer: To repeat and expand on my initial comment:
Carrier neutral datacenters suggest to me a datacenter that won't be operated exclusively by and for one customer, or by an ISP, but a datacenter where a (co-location) datacenter operator rents out rack space, rows of racks and cages/suites to third parties.
Those third-parties, those customers are not required to use IP-space that belongs to the datacenter operator, (optionally) their rack space comes with neither internet connectivity/bandwidth nor IP-addresses,  but rather they can connect to the ISP('s) of their choice.
Typically that is facilitated by having several ISP's/transit providers etc. already present and/or allowing them access to what's commonly called a centralized meet-me-room and patches can be made from there to the racks/cages/suites of the customers that want to subscribe to a particular ISP. That significantly reduces the amount of cabling required and often reduces or even eliminates the lead time whenever a (new) datacenter customer wants to subscribe to a new/different/additional ISP/transit provider.
Note that doesn't require that the customers of the carrier neutral datacenter all need to have their own provider independent IP-address ranges and/or ASN's. (They can still choose to use public IP-addresses from ISP of their choice.)  Nor does it require that they subscribe to two or more different ISP's.  A single ISP can (and often will) provide two independent lines (to that meet-me-room) providing full redundancy there and their customers  can connect with two patches from the meet-me-room to their own equipment.
Some carrier neutral datacenters will allow also interconnects to be made  between their customers directly and not only to/from ISP's and/or offer facilities for public/private peering.
Comment: Thanks @HBruijn. Our requirement is not to use a colocation service from another data center provider. We intend to build a small data center for our customers. We already have a 'cloud management software' and we provide Virtual Machine instances to our customers.  Right now, we are depending on a data center from a third party.


Problema em reconhecer o this.id no jQuery

Question: Tenho um código abaixo em JavaScript que pega o td que foi clicado e copia para a área de transferência, porém ele não está funcionando. O erro que apresenta no console é:

(teste).select(); is not a function

O alert(teste) retorna o número do id certinho. O que eu preciso é copiar esse id para área de transferência do clipboard.
$("td").click(function(e){
            var teste = e.target.id;
            alert(teste);

            (teste).select();

             document.execCommand('copy');
               alert('Texto copiado para a área de transferência');

        });

Comment: Para fazer isso, você precisa colocar o texto em um textarea.
Comment: Crie um textarea pequeno e coloque ele transparente com o css
Comment: Mude para `$(teste).select();`
Comment: Mas mesmo se eu colocar um textarea ele retorn o erro (teste).select(); is not a function
Comment: Eu deixei assim : teste
Comment: E meu jquery ficou assim:$("td textarea").click(function(e){
          var teste = $(this).text();
          alert(teste);

          $(teste).select();

           document.execCommand('copy');
             alert('Texto copiado para a área de transferência');
      });
Comment: não seria `teste.select();` ??
Comment: teste.select() hugo ele ta erro: .teste.select() is not a function...
Comment: var teste = $(this).text();
          alert(teste);

          (this).select();

           document.execCommand('copy');
Comment: Acredito que você precisa copiar o elemento em si e não o valor. Faça como os colegas falaram, copie o texto do TD para o textarea e faça o "var teste = $('#2')", sendo o seu textearea e veja se funciona.
Answer: Você precisa colocar o texto em uma TextArea primeiro, e depois fazer o .select() no próprio elemento, e não no valor que será copiado.
Primeiro coloque um TextArea invisível em sua página:
<textarea id="texto" style="display:none;"></textarea>

Então, na sua function:
$("td").click(function(e){
    var valor = e.target.id;

    $('#texto').val(valor).select();
    document.execCommand('copy');
    alert('Texto copiado para a área de transferência');
 });

Veja outro exemplo aqui
Answer: Pode fazer desta forma, sem a necessidade de usar a id, usando os objetos Range e Selection do JavaScript:
$("td").click(function(e){
//   var teste = e.target.id;
//   alert(teste);

   var range = document.createRange(); // cria o objeto range
   range.selectNodeContents(this);   // adiciona o conteúdo do elemento clicado
   var sel = window.getSelection();  // cria o objeto Selection
   sel.removeAllRanges(); // limpa o objeto Selection
   sel.addRange(range); // seleciona o texto

   document.execCommand('copy');
   alert('Texto copiado para a área de transferência');

});

Answer: Para obter um id de um elemento especifíco através do jQuery tem uma abordagem um pouco melhor ao invés de usar o event, o que você fazer é pegar através do comando $(this).attr('id');
Assim ele vai pegar o elemento clicado no caso this e pegar o atributo id desse elemento.
No caso do .select() você vai ter que pegar ele usando também o $, ficaria mais ou menos isso:

$(teste).select();

Espero ter ajudado


"bouncing" between points in Google maps api

Question: Is there any way to implement the same "bounce" functionality from Google Earth when shifting from one point to another in Google Maps? e.g. If you switch between the listed earthquakes at:
http://earthquakeproject.com/?earth
the gui "bounces" you between the locations on the globe
if you do the same thing at http://earthquakeproject.com/?maps it simply slides between those locations. I'd like the functionality to feel the same between the two.
Answer: So.. couldn't find a solution so tis is what I ended up doing, in case anyone else needs to do the same thing. and yes, I know it could be neater...
first I found a function to determine the distance, and used that to come up with a relative jump amount ranging from 1 to 4
<code> function sloc(lat,lon){
            sloc_obj.lat1=sloc_obj.lat2;
            sloc_obj.lon1=sloc_obj.lon2;
            sloc_obj.lat2=lat;
            sloc_obj.lon2=lon;
            var R = 6371; // km
            var d = Math.acos(Math.sin(sloc_obj.lat1)*Math.sin(sloc_obj.lat2) +
                Math.cos(sloc_obj.lat1)*Math.cos(sloc_obj.lat2) *
                Math.cos(sloc_obj.lon2-sloc_obj.lon1)) * R;

            if(d<1000){
                return 1;
            }
            if(d<5000){
                return 2;
            }
            if(d<10000){
                return 3;
            }
            return(4);
        }
</code>
then I used that to stagger out a set of time-delayed actions...
<code>   var l1=$(this).data('lat');
                    var l2=$(this).data('lon');
                    //set up array for times actions
                    var cmd=[]
                    //get the zoom-level based on the distance between two lat/lon spots
                    var d=sloc(l1, l2);
                    //based on our max flyout level, populate our times commands
                    if(d>=1){cmd[cmd.length]="map.setZoom(5)";}
                    if(d>=2){cmd[cmd.length]="map.setZoom(4)";}
                    if(d>=3){cmd[cmd.length]="map.setZoom(3)";}
                    if(d>=4){cmd[cmd.length]="map.setZoom(2)";}
                    cmd[cmd.length]="map.panTo(new google.maps.LatLng("+l1+","+l2+"),"+(1+d)+");";
                    if(d>=4){cmd[cmd.length]="map.setZoom(3)";}
                    if(d>=3){cmd[cmd.length]="map.setZoom(4)";}
                    if(d>=2){cmd[cmd.length]="map.setZoom(5)";}
                    if(d>=1){cmd[cmd.length]="map.setZoom(6)";}
                    timer_offset=0;

                    //get the number of steps for our cmd iterator. subtract 1 so we get the middle step in our math since the number of steps will always be odd
                    steps=cmd.length-1
                    //iterate over ALL the steps.
                    for(x=0;x<=steps+1;x++){
                        //for the middle step, wait a bit more than normal
                        if(x>=steps/2){
                            timer_offset=(100*d);
                        }
                        //at the end of the middle action pan, wait a bit even more than that
                        if(x>=(steps/2)+1){
                            timer_offset=(100*d)+200;
                        }
                        //set our timeout
                        time=200+(x*100+timer_offset)
                        //load the command on the timeout
                        setTimeout(cmd[x],time);
                    }
</code>
This way I get a reasonably smooth transition out, over and in that is reflective of the amount of distance actually traveled. I'll try to do this more neatly, maybe with a more logarithmic ease in and out, but it's better than flat panning.


Changing the properties of the Tools Palette in LiveCode

Question: I inadvertently set all preferences to default in live code 9 and now the width of the Tools Palette is wider (I guess it's three columns wide). I would like to set the width to two columns width.
Also when I start a stack I now see a grey 'background' instead of the desktop. I use MacOS High Sierra on a MacBook Pro and LiveCode 9.0.0.
How can I change these values, since I don't see those items in the Preferences-window.
Thanks in advance.
Answer: The tools palette width can be set by clicking on the preferences icon in its upper right corner.
The way to fix your "backGround" issue is to select the "backDrop" menuItem in the "View" menu. Your choice will stick between sessions/


Predição com Redes Neurais TensorFlow

Question: Olá, estou com dificuldades para implementar uma rede neural. O meu problema é que só consigo implementar ela com um atributo 'X'
Preciso de ajuda nesse código por exemplo, como faço para colocar dois atributos de entrada? No caso desse código só tem o atributo X eu queria colocar um outro atributo que também influencia a formula seila algo do tipo: linear_model = W1 * x1 + W2 * x2 + b
Como ficaria o código?
 import tensorflow as tf
    W = tf.Variable([.3], dtype = tf.float32)
    b = tf.Variable([-.3], dtype = tf.float32)
    x = tf.placeholder(tf.float32)
    y = tf.placeholder(tf.float32)
    linear_model = W * x + b
    init = tf.global_variables_initializer()
    sess = tf.Session()
    sess.run(init)

    squared_deltas = tf.square(linear_model - y)
    loss = tf.reduce_sum(squared_deltas)

    # Teste com aprendizado

    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(loss)
    sess.run(init) #reset values to incorrect defaults
    for i in range(1000):
        sess.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})

    print(sess.run([W, b]))

Comment: Sei que pode parecer um exagero, mas gostaria de te pedir para colocar o seu código aí. Se não, fica algo muito genérico.
Comment: @VictorStafusa passei abaixo uma descrição melhor com um código simples do meu problema! Obrigado.
Comment: Quando você diz "como faço para colocar dois atributos de entrada", você esta falando sobre adicionar mais classificadores para melhorar a margem de acerto da model? Ou de colocar diferentes dados para treinar?
Answer: Toda entrada de dados no TensorFlow é realizada com placeholder. Basta adicionar outro campo de placeholder
import tensorflow as tf

W1 = tf.Variable([.3], dtype = tf.float32)
b = tf.Variable([-.3], dtype = tf.float32)
x1 = tf.placeholder(tf.float32)

W2 = tf.Variable([.3], dtype = tf.float32)
x2 = tf.placeholder(tf.float32)

y = tf.placeholder(tf.float32)
linear_model = W1 * x1 + W2 * x2 + b

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)

# Teste com aprendizado

optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)
sess.run(init) #reset values to incorrect defaults
for i in range(1000):
    dict = {
        x1: [1, 2, 3, 4],
        x2: [5, 6, 7, 8],
        y: [0, -1, -2, -3]

    }
    sess.run(train, dict)

print(sess.run([W1, b]))

Predição com Redes Neurais TensorFlow


SVM machine learning - How to define the target in the training set?

Question: I am working on a project where I have to implement SVM machine learning algorithm. I am trying to predict the forearm movement intention. I am using accelometer (attached to my forearm) for measuring the angle change for x,y,z axes. I have never used machine before. The problem I am having is I do not exactly know how to structure the training set. I know the angle changes for each of the axis and I know i.e if x=45 degrees, y = 65 degrees, z=30 degrees gesture performed i performed is flexion. I would like to implement 3 gestures.So the data I am having is :
x y z Target
20 60 90 flexion
100 63 23 internal rotation
89 23 74 twist
. . . .
I have a file with around 2000 entries. I know I have to normalize the training set so the data are scaled. I would like to scale it so they are in this range [0.9, 0.1]. The problem I am having is I do not know how to represent the target in my training set. Can I just use random numbers as 1 for flexion, 2 for internal rotation, 3 for twist??
Also once the training is completed can I do the predictions based on values for x,y,z only?? without having to supply the target value. Is my understanding correct??
Many thanks
Answer:
The problem I am having is I do not know how to represent the target in my training set. Can I just use random numbers as 1 for flexion, 2 for internal rotation, 3 for twist??

This depends on the software you're using. In e1071 for R, you could just read in the file as-is and work with the labels as factors.

Also once the training is completed can I do the predictions based on values for x,y,z only?? without having to supply the target value. Is my understanding correct??

Yes, prediction is done without the class labels. The reason we use SVMs and similar technology to make predictions is because the class labels aren't available. If they were available, we would use the class labels.
Comment: I am using python. I have imported svm from sklearn.                        http://scikit-learn.org/stable/modules/svm.html
Comment: @userMilka I guess you'll have to learn how to use python, then.
Comment: I went through the tutorial for svm. I used python for different projects in the past. I have training data stored in excel sheet I can import the data into  python. Just do not know how to represent them. I know i need to normalize the data before feeding it to learning algorithm. I just do not know how to represent the target data .(as i described in my question)
Comment: Questions about how to use software are off-topic here. http://stats.stackexchange.com/help/on-topic


Table Com Input type File de Upload apenas uma linha escuta o evento

Question: Olá, senhores eu tenho uma table aonde nela possui uma coluna que possui um input type file, ao pressionar o input apenas a primeira linha escuta o evento, vocês saberiam me dizer o que estou fazendo de errado?

$("#uploadBtn").on('change', function(e) {

  });

  <input id="uploadBtn" type="file" class="upload" onchange="UploadFile(this)" name="Anexar   Documento" />

Comment: acredito que seja devido ao fato de esta selecionado pelo `ID`, tente selecionar uma classe: `$(".upload").on('change', function(e) { ... })`, se for preciso, adicione uma classe adicional para esta finalidade.
Comment: @TobyMosque funcionou obrigado.
Answer: Se entendi a sua pergunta, acredito que o problema aconteça porque ID's devem ser utilizados somente uma vez dentro do documento.
Você pode selecionar os elementos input's dessa maneira:
$('input[type=file]')

Lembrando também que você pode definir quais são os arquivos aceitos pelo seu input type usando o atributo accept, dessa maneira:


Gradle zip task: Specify destination path inside zip file individually

Question: Here's my project file layout
ROOT
|-src
| |- main
|    |- java
|    |   \- [rest of java files]
|    |- scripts
|        \- run.bat
|-build
|-build.gradle
|-settings.gradle

What I'm trying to do is to create a 'dist' Gradle task that will create a zip file under dist folder with the following internal layout:
ROOT
|
:
|- dist
    \- myproject.zip
        |-lib
        | |-myapp.jar
        \-bin
          |-run.bat

Here's my build.gradle
plugins {
  id 'java'
}

/* other tasks */

tasks.register('dist', Zip) {
  dependsOn('build')
  from "build/libs/myapp.jar"
  into "lib"

  from "src/main/scripts/run.bat"
  into "bin"  // <<<--- this wont work as it will overwrite "lib" as destination

  archiveName "myproject.zip"
  destinationDir(file('dist'))
}

My problem is that Zip task is only allow for one 'into' destination. What I need is to specify the destination of each and every source individually.
Am I doing this correctly?
Answer: you can use the 'distribution' plugin ; that would give most of your zip needs ; just need to add additional paths see https://docs.gradle.org/current/userguide/distribution_plugin.html#header
Comment: distribution plugin have just knocked about 50 lines out of my gradle build. Thanks.


update dojo datagrid

Question: I need to display a data grid in my website. When user logs into website, an ajax request is send to get whole data for the grid. After that cell updates will come(json response) from dojo ajax requests to server. So how to update those cells only in data grid automatically.
Answer: To update items in the datagrid store :
<code>grid.store.fetch({query:{/*find items to update*/},
  onItem : function(gridItem){
     grid.store.setValue(gridItem, attr, value);
});
grid.store.save();
</code>
Setting the attributes you want to update to the appropriate value from the xhr response.

update dojo datagrid


How execute a combination key on node-webkit like c# sendkeys

Question: I made a Webkit app that register small codes on txt like snippets to use later on other apps. I can find my "snippet" and set the content on clipboard.
But also , I would like run "Ctrl+v" keys combination on Node-Webkit like the SendKeys function on C#.
Now I need press manually keys combination "Ctrl+v" to paste in another app.
Also i was thinking how run another file like a small exe program that do it the SendKey function and close it. But I prefer a node-webkit function without call other script or exe program.
It ´s posible to do it , and How can i do it ? Thanks guys.
Answer: Well, I was looking for an answer on the Internet without results.
But the best solution i 've implemented is to use a VBScript help file .
And it works well !!
The app calls the Paste function to execute the " paste.vbs " file.

paste.vbs
set shell = CreateObject("WScript.Shell")
WScript.Sleep 300
shell.SendKeys "^V"

myapp.js
var gui = require('nw.gui');
var win = gui.Window.get();

function getCommandLine() {
   switch (process.platform) {
      case 'darwin' : return 'open';
      case 'win32' : return 'start';
      case 'win64' : return 'start';
      default : return 'xdg-open';
   }
}
function Paste(){
    var sys = require('util');
    var exec = require('child_process').exec;
    exec(getCommandLine() + ' ' + "paste.vbs");
}
function useSnippet(content){
    var clipboard = gui.Clipboard.get();
    clipboard.set(content, 'text');
    win.minimize();
    Paste();
}

Now you can get the file contents for pasting into other applications.
If you want compatibility with other operating systems, you must use another command file similar to VBS
I use a list of files and reading passages content of a search list .
I can create a project on GitHub to load the code so that other people can use it or help me improve the code.


Normal subgroup of prime index

Question: Generalizing the case $p=2$ we would like to know if the statement below is true.
Let $p$ the smallest prime dividing the order of $G$. If $H$ is a subgroup of $G$ with index $p$ then $H$ is normal.
Comment: Hint: I think you should try to work with what Alex suggested. It is usually referred to as the "[Strong Cayley Theorem](http://math.la.asu.edu/~kawski/classes/mat444/handouts/strongCayley.pdf)".
Comment: @S.SundaraNarasimhan , here is another link: https://math.stackexchange.com/questions/2714715/applications-of-the-strong-cayley-theorem
Comment: @Ludolila the link no longer works, can you update it?
Answer: This is a standard exercise, and the answer is that the statement is true, but the proof is rather different from the elementary way in which the $p=2$ case can be proven.
Let $H$ be a subgroup of index $p$ where $p$ is the smallest prime that divides $|G|$. Then $G$ acts on the set of left cosets of $H$, $\{gH\mid g\in G\}$ by left multiplication, $x\cdot(gH) = xgH$.
This action induces a homomorphism from $G\to S_p$, whose kernel is contained in $H$. Let $K$ be the kernel. Then $G/K$ is isomorphic to a subgroup of $S_p$, and so has order dividing $p!$. But it must also have order dividing $|G|$, and since $p$ is the smallest prime that divides $|G|$, it follows that $|G/K|=p$. Since $|G/K| = [G:K]=[G:H][H:K] = p[H:K]$, it follows that $[H:K]=1$, so $K=H$. Since $K$ is normal, $H$ was in fact normal.
Comment: @hermes: If $x \in K$ then $xaH = aH$ for every coset $aH$. In particular this is true for the coset $H$ itself: $xH = H$, and so $x \in H$. It's easy to verify that $K = \cap_{g \in G}(gHg^{-1})$, which is the largest normal subgroup of $G$ which is contained in $H$. This normal subgroup $K$ is called the **core** of $H$ in $G$: https://en.wikipedia.org/wiki/Core_(group)
Comment: @sequence: $|G/K|$ has $p$ as a prime factor since $|G/H| = p$ divides $|G/K|$. Also, $|G/K|$ divides $p!$, which does not have $p^2$ as a factor, so $p^2$ is not a factor of $|G/K|$. No prime smaller than $p$ divides $|G/K|$ because no such prime divides $|G|$. No prime larger than $p$ divides $|G/K|$ because no such prime divides $p!$. Conclusion: $|G/K|$ must be exactly $p$.
Comment: @sequence: If $p-1$ is composite, then it can be expressed as a product of prime numbers, each of which will be smaller than $p-1$, then the argument in my previous comment applies.
Comment: How does it follow that if $p$ is the smallest prime dividing $|G|$ then $|G/K|=p$?
Comment: @Wlliam: Yes, your reading is correct; no, it is not particularly "powerful", because the condition (i) only applies to a single value for each finite group; and (ii) "most" of the time you don't have such subgroups. The *idea* of using the action on cosets to get a morphism to a finite group is really the take-away you want to take from this result.
Comment: Frankly I was impressed by the result because really, what other theorems do we have that determine a subgroup $H$ is normal, just from it's cardinality? I know you could *sometimes* show the subgroup is unique using Sylow, and hence it's normal but that's only sometimes when the subgroup is maximal $p$-subgroup or you could use the counting statement where you have $|H \cap K|$ copies of elements in $|H| \cdot |K|$ . Are there other theorems to conclude a subgroup is normal from its cardinality?
Comment: Thanks. The part 'it follows that $|G/K|=p$' is crucial. Now everything is done! Bye.
Comment: Is there a simpler homomorphism that would work for the case $|G|=p^2$?
Comment: What is $S_p$? The symmetric group?
Comment: @SquiresMcGee yes
Comment: @Bungo: why does $|G/K|$ have to be of prime order? Can't $|G/K|=p(p-1)$?
Comment: The standard trick in this solution was isolated in this post: https://math.stackexchange.com/questions/88719 , where a "a little bit" stronger result was proved.
Comment: ... And the same trick is used in classifying groups of order six: https://math.stackexchange.com/questions/496096
Comment: Just to be sure if I understand "$p$ is the smallest prime" part. Suppose $H≤G$ and $|G|/|H| = 5$ so this would mean $H$ is a normal subgroup of $G$ if $|G| =5^2 \cdot 7$ or $5^{100} \cdot 19^{51}$ but for $G'$ where $|G'| = 3 \cdot 5^3 $ this test theorem would be inconclusive. So $H$ may or may not be normal in $G'$. Am I getting this right? Looks like a powerful theorem. The only tradeoff I see is that for $p=2$, it works even when $G$ is infinite but this theorem only works when the group is finite.
Answer: Here is a slightly different way to prove the result:
We will do it by induction on $|G|$. If $G$ has just one subgroup of index $p$ then clearly that subgroup is normal, so let $H_1$ and $H_2$ be distinct subgroups of index $p$. We then have that $|H_1H_2|$ is a multiple of $|H_1|$, but due to the choice of $p$ we must in fact have $H_1H_2 = G$ which means that if we let $K = H_1 \cap H_2$ then $K$ has index $p$ in $H_1$ and $H_2$ so by induction we know that $K$ is normal in $H_1$ and $H_2$ and thus normal in $G$. Now we know that $G/K$ has order $p^2$ so it is abelian. Now since both $H_1$ and $H_2$ contain $K$ they correspond to subgroups of $G/K$ and since this is abelian, they correspond to normal subgroups, which shows that they are normal in $G$ as desired.
Comment: That is a very neat argument which I have not seen before.
Comment: That's OK!- but you could finish in other ways too. Since $H_{1}H_{2} = G$, it is clear that $H_{1}$ and $H_{2}$ are not $G$- conjugate (and we may assume that $H_{2}$ does not normalize $H_{1}$). Then $H_{1}$ has $p$ different conjugates, all containing $K$, which forces $H_{2}$ to be normal as it is the only other subgroup of index $p$ containing $K$ ( just by counting).
Comment: @GeoffRobinson Yeah, I found it quite appealing as well when I found it, though it does slightly hide some technicalities in the fact that it uses that groups of order $p^2$ are abelian.
Comment: The conclusion that $K$ is normal in $G$ could use a little clarity.
Comment: How is it clear that if $G$ only have one subgroup of index $p$, it must be normal?
Comment: Aha: $[H_1:K] \leq [G:H_2]=p$ but $1<[H_1:K] | G$ so this must be exactly $p$.
Comment: @leo If a group has only one subgroup of some fixed order, then that subgroup is normal, since any conjugate of a subgroup is a subgroup of the same order.
Comment: Thanks for the explanation.
Comment: where does this proof use that $p$ is the smallest prime dividing the order of $G$?
Answer: Hint: Consider the set of cosets $G/H$ of which there are $p$. Then $G$ acts on these cosets by left multiplication. So you have a homomorphism $\phi: G \rightarrow S_p$. If $p$ is the smallest prime dividing $|G|$ then what can you say about $|\mathrm{im} \phi|$ and what does this imply about $\ker \phi$?
Comment: @J: Is it possible to do it as follows:
As $|H| \le |N(H)|$, implies $[G: N(H)] \le [G:H]$, as p is the smallest prime, this means $N(H)=H$ or $N(H)=G$. how do I show that $N(H) \ne H$
Answer: proof: If $H$ is not normal then assume $H\neq H^g$ for some $g \in G$. But a classical formula says
\begin{equation}
|HH^g|=\dfrac{|H|\cdot |H^g|}{|H\cap H^g|} .
\label{1} \tag{1}
\end{equation}
Notice that $H\cap H^g$ is a proper subgroup of $H$ (proper since $H \neq H^g$). Hence, $|H\cap H^g|$ is a proper divisor of $|H|$. Since every prime divisor of $|H|$ is $\geq p$, this leads to $\dfrac{|H|}{|H\cap H^g|}\geq p$. Thus, \eqref{1} yields $|HH^g|\geq p|H^g| = |G|$. Therefore, $HH^g=G$.
Thus, $g=hg^{-1}kg$ for some $h,k\in H$. Therefore, $g=kh\in H$. As a result, $H=H^g$, which is a contradiction.
Comment: Since $H\neq H^g$, $H\cap H^g<H$. Since $1\neq |H:H\cap H^g|$ is a number dividing the order of $G$ then it must be greater  than $p$. (if $q$ is prime dividing the |H:H\cap H^g| then $q\geq p$).
Comment: you are welcome :)
Comment: I corrected some mistakes in your proof. Can you tell me why $|H|/|H\cap H^g| \geq p?$
Comment: Since $p$ is the smallest prime dividing the order of $G$.
Comment: Can you elaborate? I have thought about it for a while.
Answer: Here's yet another, slightly different proof:
Instead of considering the action of $G$ on the left cosets of $H$, let us consider the action of $H$ on left cosets of $H$.
By the orbit-stabilizer theorem, the size of every orbit of cosets divides $|H|$, and hence also $|G|$. Since there are exactly $p$ cosets of $H$ and $p$ is the smallest prime dividing $|G|$, it must be that either there is a single orbit of size $p$ or there are $p$ different orbits, all of size $1$.
The first option, however, is impossible, since for every $h\in H$, $hH=H$, meaning the action fixes the coset corresponding to the identity. Hence, there exists an orbit of size $1$, so they must all be of size $1$.
This means that for every $h \in H, g \in G$ we have:
$$hg^{-1}H=g^{-1}H\implies \exists h_1\in H \space s.t.\space hg^{-1}=g^{-1}h_1\implies \\ ghg^{-1}=h_1\in H$$
And we are done.
Answer: Another answer if you know character theory over the complex numbers. Let $H$ be a subgroup of order $G$ of index $p$, smallest prime dividing $|G|$. Look at the trivial character of $H$ and induce it to $G$. Then $1_H^G=\sum_{\chi \in{\rm Irr}(G)} a_{\chi}\chi$, with $a_{\chi} \in \mathbb{Z}_{\geq 0}$. Since $[1_H^G, 1_G]=[1_H,1_H]=1=a_{1_G}$, it follows that the irreducible constituents of $1_H^G$ have degree $\chi(1) \leq p-1 \lt p$. Since these degrees divide $|G|$ it follows that all the irreducible constituents $\chi$ must be linear, that is $\chi(1)=1$. Hence $H \supset \ker(1_H^G)=\cap\{{\ker(\chi) \in{\rm Irr}(G): a_{\chi} \gt 0}\} \supseteq G'$, whence $H \lhd G$.
Answer: Hint: Let $G$ act on $G/H$ by left multiplication. This gives you a homomorphism $G\to S_p$. Try to show that $H$ is the kernel of this map--note that if $q$ is a prime larger than $p$ then $q\nmid p!$.
Comment: Better: Note that $H$ leaves $H$ fixed, hence we get $H\to S_{p-1}$ - and that $q\ge p$ (we can't rule out $q=p$) implies $q\nmid(p-1)!$.
Comment: @HagenvonEitzen This is practically the same idea--this was just perhaps why my answer was in "hint" form.
Comment: It just looked to me like your hint would silently assume that $p^2\nmid |G|$.
Answer: In addition to the things answered here, I just want to add this one.
Proposition Let $G$ be a finite group and $H$ a subgroup of prime index $p$, with gcd$(|G|,p-1)=1$. Then $G' \subseteq H$.
 Note that this implies that $H \unlhd G$, and that it is in fact sufficient to prove that $H$ is normal, since then $G/H \cong C_p$ is abelian.
Proof  Firstly, we may assume by induction on $|G|$, that $H$ is core-free, that is core$_G(H)=\bigcap_{g \in G}H^g=1$. This means that $G$ can be homomorphically embedded in $S_p$. Let $P \in Syl_p(G)$ and note that because $|S_p|=p \cdot (p-1) \cdots \cdot 1$, $|P|=p$. By the $N/C$-Theorem, $N_G(P)/C_G(P)$ embeds in Aut$(P) \cong C_{p-1}$. By the assumption gcd$(|G|,p-1)=1$, we get that $N_G(P)=C_G(P)$. Since $P$ is abelian we have $P \subseteq C_G(P)$, whence $P \subseteq Z(N_G(P))$. We now can apply Burnside's Normal $p$-complement Theorem, which implies that $P$ has a normal complement $N$, that is $G=PN$ and $P \cap N=1$. Note that $|G/N|=p$. Look at the image of $H$ in $G/N$. Then $G=HN$, or $HN=N$. In the latter case $H \subseteq N$, and $|G:H|=|G:N|=p$, whence $H=N$ and we are done if we can refute the first case. If $G=HN$, then $|G:H \cap N|=|G:N|\cdot|N:H \cap N|=|G:N|\cdot |G:H|=p \cdot p=p^2$, contradicting the fact that $|G| \mid |S_p|$. The proof is now complete.
Corollary 1 Let $G$ be a finite group and let $H$ be a subgroup with $|G:H|=p$, the smallest prime dividing the order of $G$. Then $G' \subseteq H$. In particular, $H$ is normal.
Corollary 2 Let $G$ be a finite group and let $H$ be a subgroup with $|G:H|=p$ and gcd$(|H|,p-1)=1$. Then $H$ is normal.
Observe that this last result renders a well-known result for $p=2$! Finally for fun:
Corollary 3 Let $G$ be a finite group of odd order and $H$ a subgroup with $|G:H|=65537$. Then $H$ is normal.
Answer: If $X$ is a (left) $G$-set, $x$ in $X$ with stabilizer $G_x$, then the stabilizer of $g\cdot x$ is $G_{gx} = g G_x g^{-1}$.
Now consider the transitive action of $G$ on $G/H$ by left translations. The stabilizer of $e \cdot H$ is $H$, and the stabilizer of $g \cdot H$ is $gHg^{-1}$. Therefore, the kernel of the map
$$G \to \operatorname{Sym}(G/H)$$
is
$$C_G(H) \colon =\bigcap_{g\in G} g H g^{-1}$$
which is the largest normal subgroup of $G$ contained in $H$ ( the normal core of $H$), so we have an embedding of groups
$$G/C_G(H) \hookrightarrow \operatorname{Sym}(G/H)$$
With Lagrange we get the divisibility
$$|G/C_G(H)| = [G\colon H] \cdot [H\colon C_G(H)]\,  \mid \, |\operatorname{Sym}(G/H)|$$
so
$$[H\colon C_G(H)]\,  \mid \, \frac{|\operatorname{Sym}(G/H)|}{[G\colon H]}$$
But from the hypothesis, no prime dividing $[H\colon C_G(H)]$ can divide $\frac{|\operatorname{Sym}(G/H)|}{[G\colon H]}$, so there are none, and
$[H\colon C_G(H)]=1$ , $H = C_G(H)$ is normal.

Normal subgroup of prime index


Calculating Word Frequency Using StreamTokenizer () , HashMap() , HashSet(). in Java Core

Question: <code>import java.io.*;
import java.util.*;
class A {
    public static void main(String args[]) throws Exception {
        Console con = System.console();
        String str;
        int i=0;

        HashMap map = new HashMap();
        HashSet set = new HashSet();

        System.out.println("Enter File Name : ");
        str = con.readLine();
        File f = new File(str);
        f.createNewFile();

        FileInputStream fis = new FileInputStream(str);
        StreamTokenizer st = new StreamTokenizer(fis);
        while(st.nextToken()!=StreamTokenizer.TT_EOF) {
         String s;

         switch(st.ttype) {
             case StreamTokenizer.TT_NUMBER:  s = st.nval+"";
             break;
              case StreamTokenizer.TT_WORD:    s = st.sval;
               break;
                default: s = ""+((char)st.ttype);
            }

            map.put(i+"",s);
            set.add(s);
            i++;
        }

        Iterator iter = set.iterator();
        System.out.println("Frequency Of Words :");
        while(iter.hasNext()) {
          String word;
          int count=0;
          word=(String)iter.next();

            for(int j=0; j<i ; j++) {
             String word2;
              word2=(String)map.get(j+"");
               if(word.equals(word2))
                count++;
            }
            System.out.println(" WORD : "+ word+" = "+count);
        }
        System.out.println("Total Words In Files: "+i);
    }
}
</code>

In This code First I have already created a text file  which contains the following data :

@ Hello Hii World #  * c++ java salesforce

And the output of this code is :

**Frequency Of Words :
WORD : # = 1
WORD : @ = 1
WORD : c = 1
WORD : salesforce = 1
WORD : * = 1
WORD : Hii = 1
WORD : + = 2
WORD : java = 1
WORD : World = 1
WORD : Hello = 1
Total Words In Files: 11**

where i am unable to find why this shows c++ as a seperate words . I
want to combine c++ as a single word as in the output
Comment: What is your definition of "word"?
Comment: @ Sweeper words means  strings present in the txt files
Comment: Yes, but what constitutes _one_ word? Why is `c++` a word? Should `word$$$$` be one word or two words or 5 words? How do I know what is a "word"?
Comment: @sweeper word$$$$ constitutes a singles word
Comment: @sweeper help me sir
Comment: Didn't you say that if you use `StringTokenizer` it works?  So do you mean words are separated by spaces? `xxx.xxx xxx` would be two words?
Comment: @ sweeper yes sir it shows xxx.xxx and xxx are two different words.  But as in the same way I want to do with the streamTokenizer
Comment: @sweeper tell me what wrong in this code
Answer: You can do it in this way
<code>    // Create the file at path specified in the String str
    // ...
    HashMap<String, Integer> map = new HashMap<>();
    InputStream fis = new FileInputStream(str);
    Reader bufferedReader = new BufferedReader(new InputStreamReader(fis));

    StreamTokenizer st = new StreamTokenizer(bufferedReader);
    st.wordChars('+', '+');
    while(st.nextToken() != StreamTokenizer.TT_EOF) {
        String s;

        switch(st.ttype) {
            case StreamTokenizer.TT_NUMBER:
                s = String.valueOf(st.nval);
                break;
            case StreamTokenizer.TT_WORD:
                s = st.sval;
                break;
            default:
                s = String.valueOf((char)st.ttype);
        }
        Integer val = map.get(s);
        if(val == null)
            val = 1;
        else
            val++;
        map.put(s, val);
    }

    Set<String> keySet = map.keySet();
    Iterator<String> iter = keySet.iterator();
    System.out.println("Frequency Of Words :");
    int sum = 0;
    while(iter.hasNext()) {
        String word = iter.next();
        int count = map.get(word);
        sum += count;
        System.out.println(" WORD : " + word + " = " + count);
    }
    System.out.println("Total Words In Files: " + sum);
</code>
Note that I've updated your code using Generics instead of the raw version of HashMap and Iterator. Moreover, the constructor you used for StreamTokenizer was deprecated. The use of both map and set was useless because you can iterate over the key set of the map using .keySet() method. The map now goes from String (the word) to Integer (the number of word count).
Anyway, regarding the example you did, I think that a simple split method would have been more appropriate.
For further information about the wordChars method of StreamTokenizer you can give a look at #wordChars(int, int)
Comment: Integer is the wrapping class of the int primitive type and it is used for storing the number of each word repetition.
Comment: Sir when I try to solve with primitive int data type so at run time compiler shows the classcasteException..  So is it not possible with int datatype
Comment: You cannot use int instead of Integer as for the hashmap. If you want to use int instead of Integer as for the "val" variable, you should do in the following way
`int val = 1;
if(map.get(s) != null))
    val = map.get(s) + 1;
map.put(s, val);`
but there aren't advantages using this solution because there is the autoboxing of the int value. Moreover, note that you cannot compare int primitive type and null.


Reading Blobs in IE11

Question: I used this article to read a CSV file using JavaScript. The code below works fine in Chrome and Firefox, but IE 11 throws the following error:
Object doesn't support property or method 'readAsBinaryString'

when calling:
reader.readAsBinaryString(blob);

According to this MSDN article, however, readAsBinaryString is a method supported by FileReader. Am I missing something / is there a different way of reading files in IE 11?
HTML code:

        Import CSV File
        <input type="file" id="files" name="file"/>

<button id="read" href="#">Read</button>

JS code:
//read a file
function readBlob() {

var files = document.getElementById('files').files;

if (!files.length) {
    alert('Please select a file!');
    return;
}

var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();

// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        makeJSON(evt.target.result);
    }
};

var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);

}
Answer: FileReader also supports readAsText method, which can be used to read a File or Blob object into memory as a text string across all three browsers (Chrome, FF, and IE11).
Replacing reader.readAsBinaryString(blob) with reader.readAsText(blob) fixed the problem.
Answer: maybe you can use this:
var binary = "";
var bytes = new Uint8Array(buffer);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
  binary += String.fromCharCode(bytes[i]);
}

Reference : Link

Reading Blobs in IE11


Cross Validation in application of clustering on a collection of similarly behaving time series

Question: I'm trying to understand how and at which point can one apply Cross Validation for time series data. If i'm not wrong CV increases generalisation so that our model has less bias in case the data is ordered/distributed in a certain particular way. But time series inherently has a direction (it can only move forward) and if i'm using some unsupervised algorithms on it, how should one apply Cross validation on it if any. I read a related question on it here : (Cross-validation techniques for time series data ) although as opposed to the question above for supervised learning i'm planning on some unsupervised clustering algorithms to group a set of time series together. So basically i have two doubts :

How to approach the problem of CV for my time series problem.
majority of questions related to cv and timeseries and cv used supervised algorithms? So an insight taking into account the clustering technique i would be using would be preferable.
Comment: 1) What does it mean that you have a "stack" of time series? Properly designing a CV scheme requires accounting for dependencies in the data, so we need more information about how your data is structured. 2) CV for unsupervised learning can be complicated. Certain things work in some cases and not in others. We need more information about what you're trying to do. 3) Are you using CV for model selection or for reporting performance? What criterion are you using to measure performance?
Comment: 1. Stack of time series : The time series are somewhat correlated in the sense that they are behaving similarly, like web server pools processing requests. So yes the time series is correlated.
2. CV process: I understood what you meant. What I'm trying to achieve is cluster all the servers behaving similarly while as in above example processing requests.
3. Yes CV for performance evaluation is my main aim. I'm also really stuck at measuring performance too, as i really don't have any true_labels to be honest.
Any help on this could be helpful.
Answer:
If i'm not wrong CV increases generalisation so that our model has less bias in case the data is ordered/distributed in a certain particular way.

No, your understanding is wrong here. CV in itself does not help with generalization, it can only help in measuring the generalization abilities of a model.
And even that is only possible if you have a suitable figure of merit that is evaluated. Such figures of merit that measure the performance of predictions are readily availbe for supervised models. For unsupervised models such as cluster analysis it is much more difficult to formulate them. Models can differ in ways that are unimportant to the generalization ability and/or they can differ in ways that are important, and only the latter differences are of interest to us. You may also say that of all ways how a model can differ, we are only interested in a subset and the question is how to catch that subset.
Predictive models have one easy to capture type of important differences: differences in the prediction, and the usual figures of merit track exactly those differences. For your cluster analysis, you'll have to specify what differences are important and what differences are unimportant/benign. This is something that needs to be done in close relation to the application (data generating processes, characteristics of your data, and the question(s) you want to answer).
Using a clustering technique pretty much implies that you do not have a ground truth to compare the clustering with. This is what limits the general possibility of having figures of merit similar to the ones we have for predicitive models.  However, if you do have something like a ground truth, you may derive a figure of merit based on that ground truth.

Ensemble models can help with generalization in certain situations and they are linked to resampling validation (such as CV) in that they also use a resampling step.

Time series cross validation: one crucial question that makes a lot of difference in how to set up the splitting is whether you are looking along time series.

For prediction that is training on past events and then predict future developments of the same time series. An example in process analysis would be to train a model predicting current (or future) concentration based on past readings of some sensors.
Or, whether you look across a large number of time series, e.g. series of sensor readings for past runs of a batch process against the achieved final product concentrations and then want to predict final product concentration for unknown batches based on the respective full time series of sensor readings for the batch in question.

Sliding window cross validation is for the first scenario, the 2nd scenario uses each time series as its own case and then "normal" cross validation.

Correlation and stack of time series. The crucial question here is not whether there's a similarity in the time series but what causes the similarities. If there's an underlying factor causing similarity (i.e. you have several pools of servers in your data and the server data is more similar with each pool than compared to a server of another pool), you need to take that into account for CV splitting. If on the other hand the similarity is not caused by other factors but is just the phenomenon you're modeling, that is fine.
Comment: Thanks cbeleites for your answer and particularly about explaining about what CV really does. You are right i don't have any ground truths and that's why i went with the clustering approach, and the only metric that i can seem to use right out of the box is silhouette score. I understood your approach of determining the differences that really matter and then maybe using them for improving on our base algorithms.
Comment: Also my use case here is not to predict some future value but just study the behaviour of lets say 5 servers (lets say their memory utilisation in 1 min ticks) running together and then find whether any of them is behaving abnormally by clustering the similar behaviours together and others not in that group. sliding window CV i get but what is normal "CV". Is it like ensemble average i.e. CV across multiple signals? Should we do that and how to do that ? I know it's asking too much but can you provide an example or a more complete description. It will be a lot of help. Thanks.
Comment: 3. In your third point where you mentioned "correlation and stack of time series" you mentioned that the underlying similarity has to be taken into account if an underlying factor causes similarity. But how would we judge that?. And i get that.
Comment: 4. Also when you say that this has to be taken into account, does that mean all the series with let's say high similarity to each other to be first grouped together , then CV and clustering applied only on that particular group to find the abnormal behaviour (in my case) and so on to the second group of similar time series stack and then third and so on. Please correct me if i'm wrong.


Is there a name for this kind of prolonged tension?

Question: There's this song I really like, with a fairly long and elaborate chord scheme in a major key (probably C, but I'm not too sure). The last two lines of the chord scheme sound very common, however:
|IV  |V   |vi  |vi
|IV  |V   |I   |I

Now, since IV-V-I progressions are extremely common, the vi chord is fairly unexpected in this location. To me it seems like it resolves the tension created by the V chord, but only partially, since everybody expects that chord to be resolved to I instead.
Subsequently, the IV-V buildup is repeated, and finally does resolve to the expected I chord. By first resolving to an unexpected chord and then repeating the first two bars of that line, I feel like the iv chord helps to create a prolonged tension that is eventually resolved with the I chord.
Does this make sense at all? I haven't seen this pattern very often in other music, but I find it quite fascinating and it works very well for me. I think there might be a name (and an explanation) for this kind of chord progression, so I thought I'd check whether anyone on music.SO knows about it. :)
Comment: This "haha tricked you" cadence works in a minor key too.  Here's a very over the top example haha https://www.youtube.com/watch?v=Mbg1nEXQ1fI
Answer: The resolution V to vi is called deceptive cadence. In C major this would indeed be G => Am, and in C minor you would get (maybe even more convincingly) G => Ab. The vi chord (or VI in minor) replaces the tonic and it usually contains the expected melody note but replaces the expected harmony (the tonic chord). This is possible because the vi (or VI) chord shares two of the three chord tones of the tonic chord.
This device is quite common in classical music as well as in popular music. Also relatively common is the more general idea of harmonizing an expected melody note with an unexpected harmony. E.g., at a point where the root of a piece is expected to be harmonized by the tonic chord (at some supposedly final point), it can be harmonized by the IV chord, or - mainly in a jazz context - by a bIImaj7 chord. An example for the latter is a Dbmaj7 chord replacing a C chord (in C major) with C as a melody note (which is the major 7th of the Dbmaj7 chord).
Comment: I was going to correct you to "interrupted cadence", but I see from the Wiki that they're both acceptable terms :)
Comment: Technically, the deceptive cadence may move from "V" to *any* other chord.  Most often it moves to "vi" however.


Restrict media files to other users once uploaded

Question: I'm using Media Entity Browser to let users add new or existing media files in a content type.
I have two groups. Business-A uploaded an image in a content. Business-A can re-use the image in writing other contents but Business-B should not be able to add it as an existing media for their own article.
I want that only a group can get access to its uploaded media. Because when I upload images using media browser, in default, all files get public accessed.
How can I restrict uploaded media files be added by other users.
Comment: this is the same issue with https://www.drupal.org/node/2764491 which is not updated/resolved.
Answer: If you have Groups on your site with grouped access permissions, I would recommend using the Group module for less complex group permissions like this and OG for configuring more involved group permissions.
Using the Group module you will be able to section off the media and other content like this.
EDIT:
I suggest you configure Group functionality / permissions directly on the File / media entity, rather than just the nodes they are added / used from. Failing that, I believe you will have to (clone and) override the view that the media entity browser uses and do some filtering based on group(s) of the media file author.
Then try using the user id of the author initially using static values to test your view. If the UI of the view does not provide what you are looking for, you might need to write your own Views Access Plugin. Here is one I wrote for Message Private module: InboxPermission.php. You could do similar.
Comment: Yes, I am actually using Group module on this. And I see no section of media on Group permissions. There is under /admin/people/permissions/ but don't have permission I wanted. All media uploaded by different users of different roles can still be accessed publicly.
Comment: Have you configured Group functionality / permissions directly on the File / media entity though, rather than just the nodes they are added / used from?

I believe you will have to (clone and) override the view that the media entity browser uses and do some filtering based on group(s) of the media file author.
Comment: I think the solution is on the filter criteria. I added filter as: Publisher ID of media. Operator: is equals to "value: with text box below", but what should be the value I put to be able to identify that it is filtered by the media file author? I tested with an author name, but the view is not showing any result. Also tried it in an actual implementation of adding media file. Thanks!
Comment: Have you tried using the user id of the author? You might be doing so, but I suggest just using static values to test your view first. If the UI of the view does not provide what you are looking for, you might need to write your own [Views Access Plugin](https://api.drupal.org/api/drupal/core%21modules%21views%21src%21Plugin%21views%21access%21AccessPluginBase.php/group/views_access_plugins/8.2.x). Here is one I wrote for Message Private module: [InboxPermission.php](http://cgit.drupalcode.org/message_private/diff/src/Plugin/views/access/InboxPermission.php?id=5561003). You could do similar.
Answer: Okey, it seems that view filter criteria is not the proper way to achieve this goal.
Contextual filter did the trick.
I added:

Contextual filter of Media: Publisher ID
Under WHEN THE FILTER VALUE IS NOT AVAILABLE: Provide default value
Type: User ID from logged in user

Thanks to @mccrodp for helping out.


What causes my error "Illegal choice in Sorted by element"?

Question: Drupal 7.50 commons
The following error shows dozens per minute when I run drush ws --tail,  but there are no reports of users encountering errors or features that are non-operational. Does anyone know what could be causing this? Reporting for anonymous user.
error     form  Illegal choice  in Sorted by element.

Below is a screenshot of one of the errors, for detail.

Below is a screenshot of part of the page content that might be generating the problem, from admin/reports/dblog.

The error seems to be affecting more than one group or all of our groups. Here is an example URL from another entry:
http://example.com/groups/oregon?sort_by=&sort_order=DESC&page=0,0,1
Here is the Commons Browsing Widget View Sorting Criteria:
Comment: Ok, so when you look in that /admin/reports/dblog watchdog do you see these Illegal choice errors there as well? If yes, can you add the full error info into your answer?
Comment: when you say `but the error isn't being reported on the site` you mean it doesn't show in your log /admin/reports/dblog?
Comment: No, I'm sorry. I meant users don't encounter the error when using the site. i.e. nothing seems to be non-operational. I'll edit my post.
Comment: Thank you for the help finding more information. I posted a screenshot. I can at least see which content that it's coming from now. Sure enough, there is an error showing on that page.
Comment: looks like the sort in the url does not have a value `&sort_by=&sort_order=DESC` it cannot order descending if you don't give it a sort by. You might be able to fix this by changing the sort filter in your view to require the sort by, however you could still have this happen if someone deletes the sort_by value from the url manually.
Answer: I was able to figure out what view was being used on group pages (The Commons Browsing Widget) and see that there were three sorting criteria. One of them is the Radioactivity module.
I checked the general status report (admin/reports/status) to see that there was an issue with RadioActivity module.
I removed this sorting feature for now, but it should work now that I cleared up the issues with the module. I guess no one could have known that this was the cause. I'm keeping this up in case anyone else finds it helpful.


Multiple UIManagedDocument For Read & Write

Question: I'm building a tab bar application for iPhone and i'm using Core Data with two UIManagedDocuments. In the first tab, i write the data to database and in the second i read them into UITableView with UIFetchedResultsController.
At the start of application, if i write data first, and after then i read results, it works fine. Results appear in the second tab immediately. However, if i read some data first and after then if i write something to database, results appear in second tab with considerable delay (almost 1 minutes). If is there any synchronization problem between two UIManagedObjectContexts or two UIManagedDocuments, how does it works in the first condition? And, is there any solution for this delay?
Answer: The way that you can ensure that your UIManagedDocument is up to date is to make sure you're saving your changes properly.  Given the information you've shown above, I'm not really sure about how you're managing your documents or your managedObjectContexts.  There are just too many factors that could be affecting this to be able to give you a 100% concrete answer.
So without knowing what your code looks like and without knowing how you're managing your context, the only thing I can do is give you what I use in my own projects.  This may or may not help you, but it helped me - more times than one - when it comes to handing core data by UIManagedDocument.
When it comes to Context:
I use a singleton to manage UIManagedDocument.  I do this because I don't want to have to deal with what you're talking about above - having more than one managedObjectContext.  When you start dealing with multiple contexts, you have the issue where the data will not be consistent unless you manage all of your contexts properly.  If you save on one but don't update the other - then your data can become out of sync.  You also have to make sure that each context is working on the property thread - the Apple Docs is a great resource for understanding the whys ad hows this even matters.
The point is, though, that this is one of the biggest problems with working with UIManagedDocument that isn't as bad as when you're working with pure core data and using a SQL persistent store.  The main reason that I've found is because of how UIManagedDocument actually saves to its UIDocument store.  It is very unpredictable about when it wants to save.  This makes knowing when your UIManagedDocument will actually persist and have your data a freaking shot in the dark.  You end having to do all kinds of stupid stuff just to make sure that it is always readily available.
Considering I have a belief (that many, maybe rightfully so, believe is an ignorant belief) that working with core data is hard, and UIManagedDocument makes it easier than it would be if you didn't work with it at all.  That being said, I don't like it when working with something as simple as UIManagedDocument begins to get complicated - so I use the one thing that has always kept it simple, and that is a singleton, shared-instance of a single UIManagedDocument so that I only have 1 managedObjectContext, ever, to have to work with.
When it comes to saving:
Whenever I make any significant change to a model ( Create, Update, Delete, Edit ), I always make sure to call [document updateChangeCount:UIDocumentChangeDone];  I do this because I do not use the "undo manager" (NSUndoManager) when working with UIManagedDocument.  Simply because I haven't needed to yet, plus because I hate all the "workaround" garbage you have to do with it.
Working only on the Main Thread:
Whenever I do anything with my UIManagedDocument or Core Data, I always make sure its on the main thread.  I think I've already said it once, but I'll say it again:  working in threads is helpful when you need it, but also when you actually understand threading in general.  I like working in threads, but it comes at a cost of complexity that makes me not want to work in them when it comes to core data.  With that being the case, I tend to stay strictly on the main thread as this keeps things simple and easy (for me).
Saving the Document
When I absolutely need to make sure that the UIManagedDocument is "saved" ( written to disk ), I have 2 methods that I wrote and use that are always readily available for me to call: saveDocument and forceSaveDocument.
The first one ( saveDocument ) merely checks the context for changes.  If it has any, it then checks to see if we have any newly inserted objects.  When insertedObjects are found, it obtains the perm ids for these items.  You can think of this one as a good way to ensure that your core data model is up to date, and that your managed context is in a safe state, so that when your document is actually saved, that you get everything saved in the state that it needs to be in (your ids are realized, your contexts are clean, and what you are about to save represents a state of your model once all work has been complete on it).
Its big brother, forceSaveDocument, actually calls saveDocument first.  Again, to make sure that your actual model/context is saved and proper.  If it returns successful ( YES ), then it will actually do the real saving and write the document to disk by means of saveToUrl.
Some Code (hopefully it helps):
Here are those 2 methods in case it helps:
-(BOOL)saveDocument {
    NSManagedObjectContext *context = self.document.managedObjectContext;
    if(!context.hasChanges) return YES;

    NSSet *inserts = [context insertedObjects];
    if([inserts count] > 0) {
        NSError *error = nil;

        if(![context obtainPermanentIDsForObjects:[inserts allObjects] error:&error] && error) {
            [self reportError:error];
            return NO;
        }
    }

    return YES;
}

-(void)forceSaveDocument {
    if( [self saveDocument] ) {
        [self.document saveToURL:self.document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:self.onSaveBlock ? self.onSaveBlock : nil];
    }
}

General Rules/Guidelines
Overall, these are my guidelines that I follow ( and have worked for me for about 3 years now ) when working with UIManagedDocument and Core Data.  I'm sure there are better out there from guys/gals much smarter than me, but these have what I use.  The benefit I get out of them is that it makes me have to worry less about managing my data and gives me more freedom to work with everything else:

Use a singleton to manage my UIManagedDocument until the need of multiple threads is absolutely necessary - then migrate over to start using multiple contexts ( i've never needed to do this yet - but then again I try to keep things simple )
Always call updateChangeCount:UIDocumentChangeDone when I make any change to a model.  It is very light weight and has little impact.  If anything, it will help ensure your document stays up to date and never gets too out of sync with your data.
Don't use undo manager unless you actually need it ( I have yet to need it )
Use save/ForceSave sparingly, and only when absolutely necessary (deletes are a good reason to use it.  Or if you create a new item on one view controller and need it on the next one, but can't wait for core data and the document to sync up - its kind of like kicking it in the ass and saying "I object to you saving whenever you want - save now lol.. )

Final Thoughts
All of the above is my own belief and understandings.  These come from a lot of research, reading, and being a pain the ass when it comes to wanting to do things right, all while keeping it simple.  Anyone can write a complex solution - but I think the fundamental question is always: do you really need the complexity, or do you just need it to work so you can focus on more complex issues?
I'm sure the above is way more than you probably wanted, and may even add more questions than you have.  If you need some links and resources, let me know and I'll try to throw a few together.
Either way, hope that helps.
Comment: Using a single shared UIManagedDocument instance solved my problem. This code was very helpful for me : https://gist.github.com/JJSaccolo/5584804
Thank you for your reply.
Comment: No problem, glad to have helped


Riemann Sums in Work Questions

Question: So given the question "A conical tank of radius $5\mathrm{m}$ and height $10\mathrm{m}$ is filled with a liquid whose density is $3.42 \mathrm{kg/m^3}$. how much work is needed to lift the liquid out of the tank?"
The answer can be found by taking the integral $$\int_{0}^{10} 3.42 \cdot \pi \cdot 9.8 \cdot (10-h) \cdot (h/2)^2\ dh $$
However, I'm confused about one thing. The equation
$$ (10-h)\cdot (h/2)^2\cdot 9.8\cdot 3.42\cdot \pi \cdot dh $$
gives us the work required to lift a disc of height $dh$ out of the tank.
Why does the integral of this expression within the limits 0-10 give us the work required to lift all the water out of the tank?
Thanks,
newtondiedavirgin
Comment: Welcome to Maths SX! That is because the total work is the sum (integral) of the elementary works.
Comment: Youve split the cylinder with height $10$, into a bunch of disks with thickness $dh$, so you have to sum them all, from $h=0$, to $h=10$...
Answer: a) the tank is a cone with the vertex at the top, and base on ground;
b) $h$ is actually the distance from the vertex, the height being $H=10-h$, at which the radius is $h/2$;
c) the integrand is the potential energy acquired by disk $\rho \pi r^2 dH$ at height $H$;
d) the integral is the work needed to fill the tank (= potential energy), i.e. for the liquid to start and pour from the top, with the substitution $h$ for $H$.

Riemann Sums in Work Questions


How to add onBlur attribute to ZIP code field in Address Field

Question: In order to control the input format in the ZIP code field in the dynamic address fields provided by the Address Field module (I use it in Drupal Commerce) I need to add the attributes onKeyUp and onBlur to this field. My plan is to use Javascript to manage the formatting, but I need to add the above attributes first. How do I do that? I imagine I should use hook_form_alter in my template.php, but I could need a pointer on how to do it.
if($form['#id'] === "edit-customer-profile-billing-commerce-customer-address-und-0-postal-code"){
  dsm($form); // devel message does not show up in the checkout page in question
  $form['#attributes']['onBlur'] = '(this)';
}

EDITED: I have now managed to add the attributes this way:
  function mytheme_form_alter(&$form, &$form_state, $form_id) {
    if($form_id === "commerce_checkout_form_checkout"){
      // Merge new attributes with existing ones.
      $form['customer_profile_billing']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
      $form['customer_profile_shipping']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
    }
  }

And this is the js script (I found it here):
(function($) {
        $(document).ready(function(){
            'use strict';
        var setZip, setLimit;
        console.log('outside');

        function setZip(theField){
          console.log('setzip');
          var num = theField.value.replace(/\D/g,"");
          theField.value = num.substr(0,3)+" "+num.substr(2);
        }

        function setLimit(theField, maxDigit){
          console.log('setlimit');
          var num = theField.value.replace(/\D/g,"");
          if(num>maxDigit){
            theField.value = theField.value.substr(0,maxDigit);
          }
        }

    });

})(jQuery);

The problem now is that I get a javascript reference error like this:

Uncaught ReferenceError: setZip is not defined at
  HTMLInputElement.onblur

I suspect this has something to do with the scope, so I have tried to place the js script with the setLimit and setZip functions in the header, in the body and in the footer, with the same error message. I also tried to remove the $(document).ready(function()... but the reference error reamins.
Any ideas?
Comment: The form ID will never be the HTML ID of an input buried somewhere in the form. The form alter has a `$form_id` param, use that to work out what the correct value is
Comment: Thanks, thanks to your pointer I now found out that the ID is commerce_checkout_form_checkout, but it does not seem to be an easy thing to add an attribute to a single field in this dynamic field group. I keep looking.
Comment: Yeah the checkout pane fields are really heavily nested
Answer: In case anyone else has this same problem. I have learned that it's a better practise to only use Javascript with an addEventListener to do this job, due to the scope rules.
This is how I finally did it. Change the code to adapt the formatting to the standard format in your country. This one changes the ZIP code format to five digits with a space inserted between digit 3 and 4.
  if($("#edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").length){
    document.getElementById("edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").addEventListener("blur", function(){
        if(this.value.length>5 && /\s/.test(this.value)){
          this.value = this.value.substr(0,6);
        }   else if(this.value.length>5 && !(/\s/.test(this.value))){
                        this.value = this.value.substr(0,5);
                    }
        if(this.value.length===5 && this.value.substring(3,4) !== " "){
            this.value = this.value.split(/(?=.{2}$)/).join(' ');
        }
    });
}


How to sort the language detection methods

Question: In a two languages Drupal 7 site, I am using the following order of language detection methods:

URL
Session
User
Browser
Default

With this order, every time I visit the site as an anonymous user it comes in the default language.
Instead I would like to:

display the default language in the first visit.
if a language selection is made, display that language in the next visit

Is there a way to achieve this?
Comment: The problem wit the "best" is that depends only on the needs of the one who's asking.
Answer: Well I think you are doing just fine, and don't get obsessive over this, it's ok!
the URL thing is the most important and should be always on top, I think session should be second since it can be generated via a request or parameter.
User I'm not sure since mostly users don't pay attention about their language preferences while registering on a webiste.
past these steps the rest doesn't really matter that much, but I'd put Browser the last one since it seems it can vary quite easy with plugins/extensions.