Leitura de array com php

Question: boa tarde, tenho este array que vem de variaveis $form
Array
(
    [nome] => 765hygfy
    [data_nascimento] => ftyftyf
    [email] => email@example.com
    [sexo] => Feminino
    [rg] => ytfytfyt
    [cpf] => fytfty
    [telefone_residencial] => fty
    [telefone_celular] => fyt
    [telefone_recado] =>
    [cep] => fytf
    [estado] => MS
    [cidade] => fytfytf
    [bairro] => ytf
    [logradouro_rua] => ftyf
    [numero] => tyfyt
    [complemento] => fty
    [referencia] => fytf
    [onde_conheceu] => FaceBook
    [revendeu_outras_marcas] => Não
    [quais] => ytftyf
    [horario_de_contato] => Manhã
)

eles estão vindo de um formulário como a names neste padrao
form[nome]
form[email]

e assim vai
o que preciso fazer é o php ler este array printando o key depois o value
já fiz vários foreach ate um for e volta em branco.
meu foreach
foreach($_POST['form'] as $key => $value){
  $nome = arrumanome($key);
  $msg.= $nome.": ".$value."
";
}

ele volta so isso aki
:
:
:
:
:
:
:
:

Comment: Como assim volta em branco? como ficou a estrutura do foreach?
Comment: editei com o meu foreach e o q volta
Comment: Dessa forma, seria melhor fazer 2 `foreach`: um só com `$_POST` e o interno com o `$value`
Comment: pode colocar o código html também?
Comment: Tira o `['form']` do `$_POST` do `foreach` e veja o que retorna.
Comment: olha fiz um var_dump do $_POST e ele retorna todas variaveis e var_dump de $_POST['form'] e volta o array certinho como coloquei na msg la em cima mas o foreach nao ta printando o key nem o value.
Comment: Verifique o console do navegador e veja se seu servidor não está fazendo reload da página.
Comment: Como está a parte HTML? Seria Ajax ou Form normal? Ou a chamada está sendo feita via WebService?
Answer: Rapaz, parece que vc enviou o formulário em branco ou que sua função arrumanome está modificando seus dados e deixando eles em branco.
Veja se te ajuda o código abaixo, que funciona apropriadamente:
Um form html com alguns dos seus dados para testar:
<form action="foreach.php" method="post">

    <input type="text" name="form[nome]" value="Nome Teste">

    <input type="text" name="form[data_nascimento]" value="31/01/1980">

    <input type="text" name="form[email]" value="email@example.com">

    <input type="text" name="form[sexo]" value="Masculino">

    <input type="text" name="form[rg]" value="123456789">

    <input type="text" name="form[cpf]" value="1198765432">

    <input type="submit" value="Enviar">

</form>

foreach.php
<?php

$dados_post = $_POST["form"];

$msg='';

foreach($dados_post as $key => $value)
{
    $msg.= $key . ": " . $value . "
";
}

echo $msg;

Resultado na tela:
nome: Nome Teste
data_nascimento: 31/01/1980
email: firstname.lastname@example.com
sexo: Masculino
rg: 123456789
cpf: 1198765432

Comment: ctz q he algono meu apache coiei e colei o cod aki e continua em branco
Comment: Pode ser no navegador tb. Olha o código fonte da página pra ver se tem algo estranho.

Leitura de array com php


Android AsyncTask and

Question: Hi i have an AsyncTask in my application called in OnCreate() that retrieve some data over the web and display an indeterminate progress bar while downloading.
The problem is when i start the app the screen remain  blank until the AsyncTask is finished.
The code is something like that.
<code> public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    loadData();
    //Several UI Code
    startAsyncTasks();
}

 private void startAsyncTasks(){
    new ConnectingTask().execute();
 }
</code>
Comment: It's probably worth posting the code of your AsyncTask as the problem might lie there.
Comment: So, if you comment out the startAsyncTasks() line, the UI appears much faster?
Comment: Just make sure you do all your networing (long running stuff) inside of ConnectingTask.doInBackGround(). That should guarantee the main UI thead will not be blocked during a heavy job, so it will be able to show the activity's UI elements.
Answer: OnCreate() is executed before the Activity is being shown on the screen, so the whole data download process executes before showing the activity.
Solution could be to start AsyncTask in OnStart() method instead of in OnCreate() (also overriden). OnStart() is executed while activity is going to be shown on the screen (see activity lifecycle).
This is the case I have implemented in my app and it works. You should show a progress dialog in OnStart() method, and update and dismiss it in AsyncTask in proper moments.
This is how it looks in my app:

AsyncTask is started in activity OnStart() along with showing dialog box
Data is being downloaded in inner class extending AsyncTask
After data is downloaded the dialog box is dismissed and further data processing initialized (OnPostExecute())

The drawback could be that OnStart() is called on the first activity call, but also after restoring it (for example after minimizing the application). So AsyncTask can be executed few times in opposite to OnCreate(), that is called only once - when activity is created (not when it is restored).
There can also be some issues if You do the jUnit test of such activity with dialog in AsyncTask - let me know if You do - will post some solution

Android AsyncTask and


Why is $T_fT_g - T_{fg}$ compact?

Question: Let  $ f, g: \mathbb{S}^{1} \to \mathbb{C} $,
be continuous functions. Let $ T_{f} $ be the Toeplitz operator with symbol $ f $ acting on the Hardy space $\mathcal{H}$, as defined in this answer.
There it is also written that

If $ f $ and $ g $ are continuous functions
on $ \mathbb{S}^{1} $, then it is a basic fact that $ T_{f} T_{g} - T_{fg} $
is a compact operator on $ \mathcal{H} $.

How can we see that this "semi-commutator" of Toeplitz operators is compact?
Also, is this related to the commutator of $T_f$ and $T_g$?
Why do we study such object?
Comment: Did you look at the original Axler-Chang-Sarason paper or any reviews thereof?
Answer: Let $P$ be the projection onto $H^2$.
We have
$$
T_fT_g-T_{fg}=PM_fPM_gP-PM_fM_gP=-PM_f(I-P)M_gP.
$$
It is enough to show that $PM_f(I-P)$ is compact. We can write $f$ as a norm limit of polynomials. We will see that $PM_p(I-P)$ has finite-rank when $p$ is a polynomial, and then $PM_f(I-P)$ is compact, being a limit of finite-rank operators.
Since a polynomial is a linear combination of nonnegative powers of $z$, it is enough to show that $PM_{z^k}(I-P)$ is finite rank for each $k$. This follows from
$$\
PM_{z^k}(I-P)z^m=\begin{cases}z^{k+m},&\ -k\leq m<0\\[0.3cm] 0,&\ \text{otherwise}
\end{cases}
$$

Why is $T_fT_g - T_{fg}$ compact?


Isolate iSCSI traffic on a separate VLAN

Question: My question relates to iSCSI connections and VLANing.
My configuration is 2 Hyper-V hosts connected through a pair of stacked layer3 Dell 6224 24 port switches to an Equallogic PS4000 Storage Subsystem.  The Equallogic has 2 iSCSI connections, active and pasive.  All traffic - Ethernet and iSCSI - is in the same broadcast domain.
I want to isolate the iSCSI traffic from the general network traffic using a VLAN.  However, my concern is that if I put the iSCSI ports in a separate VLAN, the host servers will lose access to the storage.
Comment: What switch do you have?
Comment: The Hyper-V hosts would also need the appropriate VLAN setup to be able to communicate with the SAN.  Additionally, you'll likely have to do some switch configuration.  I've got a similar setup (EqualLogic SAN, Dell PowerConnect switches, bunch of hosts) and use VLANs to separate iSCSI traffic.  Additionally, you may want to check if that model switch has "iSCSI traffic optimization".  Basically the switch detects iSCSI flows, and gives that traffic higher priority.
Answer: Here's two possible ways to accomplish this:

separate NICs on the VM Host for the iSCSI traffic and other IP traffic

this provides maximum separation
configure the iSCSI NICs as access ports on the switch going to the iSCSI VLAN, move the Equallogic ports to the iSCSI VLAN and you're off and running.

combined NICs on the VM Host for both iSCSi and other IP traffic

cheapest solution
create a subinterface on the NICs for the iSCSI VLAN, enable trunking on the switch going to appropriate VLANs, move the Equallogic ports to the iSCSI VLAN

If you're concerned about mistakes or losing access to the service, just move one NIC at a time. You do have multipathing set up, right?
Comment: +1 but I wouldn't even bother with the combined NICs option at all: if you can afford a SAN, you can purchase a dual NIC expansion card.
Comment: Right, that's definitely the best thing to do. Sometimes it's not as easy (for example: blades with only two NICs and it's a bigger job to add more)
Answer: The 6224 will have iSCSI optimization, but it will only enable jumbo frames, flow control, and disable storm control. The 5000 series will do all of that, but also provision those ports with a QoS profile that prioritizes iSCSI traffic in the egress queues. :)
As long as you change all of the ports in question to use the SAME vlan, and do not change them from access ports to trunk ports, you'll be fine. You can use the interface range command do this all fairly simultaneously, but I would quiesce or halt whatever is using the storage first. You can then use the 6224 to perform inter-vlan routing, be sure to add the ip routing statement to the main configuration, and beware that the gui turns on some very evil proxy arping. Use the CLI if at all possible.


How to use Matlab xunit without setting Matlab application path

Question: As far as we can see, to use a library in Matlab it is necessary to add its path to the global Matlab application path e.g. to use the xunit unit testing library, its path must be added to the global path through the user interface. The problems with this are:

Each developer must set the dependency paths correctly on their machine, test machines and build machines etc. to be able to run the code correctly
We cannot set the paths for each developer centrally so when dependencies change, we must issue instructions for individuals to manually change their configuration
If different projects use incompatible dependencies then the path must be reconfigured between changing projects

For C++\C#\Java etc. projects, it is possible to refer to libraries with relative paths from within the project and not require changes to global environment variables.
How can we achieve this with Matlab?
Comment: Just FYI, if the issue you're facing is specifically to do with a unit testing framework rather than general project-based path management, you should take a look at the just-released version 2013a of MATLAB. It includes a built-in unit testing framework (no need for path management), much more powerful and flexible than xUnit. I haven't tried it out much yet, but it looks awesome.
Answer: You can use the addpath and rmpath commands to manually edit MATLAB's Path.  Paths added via these two commands can be relative paths.
Comment: +1 for `addpath` and `rmpath`. Also take a look at [`onCleanUp`](http://www.mathworks.com/help/matlab/ref/oncleanup.html) which you can use in combination with `rmpath` to make sure your path setting is always reverted regardless of any exceptions, etc.
Comment: Thanks - is there a recommended practice for how to use these to switch between project specific environments?
Comment: That I can't help you with.  One suggestion might be to have a project  specific init/uninit scripts that sets/remove the project specific paths and have your code call these functions.


OG Subgroups - call function _og_subgroups_get_inherited_users

Question: I am trying to create a custom rule for OG Subgroups to email the members of a subgroup when content is added to it.
In og_subgroups.common.inc I can see the function I wish to use to return the inherited users of a subgroup
<code>function _og_subgroups_get_inherited_users($group_type, $group_id, $states = array(OG_STATE_ACTIVE))
</code>
In my custom rule action I'm not sure what I should be passing to the function as $group_type and $group_id parameters. I have tried things like "node" and the NID of the group:
<code>$array = _og_subgroups_get_inherited_users("node", 27);
</code>
Once I get it working with a hardcoded node e.g. node 27 I will then try to pass the details of the parent groupd that content has been added to.
I'm using OG Subgroups 7.x-2.0-beta1. For the full background into why I'm creating this custom rule action you can see my original drupal answers question
Answer: I was able to solve this by creating a custom og_subgroups.rules.inc file. For details of this see my answer in: Email all Organic Group members when a subgroup is created
The line in question above needed to be:
<code>$inherited_users = _og_subgroups_get_inherited_users("node", $nid);
</code>


How do I implement a time picker?

Question: I tried to implement a time picker for a field opening hours. I used Bootstrap Date & Time picker and I set the FIELD TYPE to date, but I couldn't see any widget for BDT Picker in widget selection.
Then, I used jQuery UI Timepicker. The time picker is showing, but I can select only 0 for hours and 00 for minutes; all other cells are disabled. Also, the default time in the field is the current time.
What could the issue be?
When I select the date field type, the form has a date field with a full calendar. I need a field to pick only the time. How can I do it?
Comment: You can use the [date_popup_timepicker](https://www.drupal.org/project/date_popup_timepicker) module.
Comment: now i used the same ,but the issues i i can't able to hide the date calendar, i need to show only the time field.Is it possible? It is for a field "Opening Hours".
Answer: Create a field , select field type as Date (ISO format) or Date. And choose only year, hour, minutes, seconds(if needed). Select Date entry options under MORE SETTINGS AND VALUES , choose custom format as H:i
Add time format for H:i and also go-to admin/config/regional/date-time and add date type (to display in node view).
In add/edit page for time picker(only hours)

In view page

Hope this helps you with out any help of other modules.
Comment: Thank you @ajay I want a pop up time picker like bootstrap or anything based on jquery.
Comment: You can write custom jQuery popup for particular div/section.
Refer http://jsfiddle.net/moogs/606pgg4o/1/

How do I implement a time picker?


database query questions or other solutions for comparing data between 2 tables

Question: I am creating Windows Application Form using Visual Studio 2010.
For now, I am in this situation:
I allow users to add items into the system, each item they may have different brand, cost & suppliers and selling price for different customers.
For example,
Item1, Name: ABC, Brand: TIM and
Item2, Name: ABC, Brand: LD.
when the users want to insert the cost and suppliers information into Item1, when they click on the "ShowCost" button, another Windows Form will pop out for the users to fill in. And I'm planning to use DataGridView for that. I'm planning to use the Item Name and Brand for identifying the cost and selling price for the item
So here's my question,
How do I set the query or other solutions in order to check that when the name and brand of the item that the users enter, will show up the cost and the price of the specific items? what is the query that i need to write?
I have created 3 database tables which are ItemInfo(Name, Brand, etc), CostList(Name, Brand, SuppliersName, Cost) and SellingPrice(Name, Brand, CustomersName, SellingPrice).
How do I compare the data from ItemInfo tables to show the data in CostList?
Thanks for the help.
Comment: I have google search for the information but none of them get to solve my questions.
Comment: It's quite hard to figure out exactly what your trying to achieve. What is you backend Database? is it MS Access or SQL? You may need to have a Junction Table for this project, as an Item can have multiple suppliers but each Supplier will only have one unique Item. Getting the database setup correctly is your first step. If i'm right in what i'm thinking, You could have 1 Item with 20 different suppliers?
Comment: sql, what I need to know is, when i click the "Show Cost" button, how do I check that the costs list is for the specific Item, not the other item. I am using ItemInfo Name and Brand to identify an item.
Comment: that's right, one item may have 20 different suppliers and of course, costs as different suppliers may have different price. I think for a long time and I can't figure out how, as I'm still new to this.
Comment: From your question and comments I believe that you still do not clearly have defined your database structure, tables, fields, primary keys, etc. Take a look to the [AdventureWorks database provided by Miscrosoft](http://msftdbprodsamples.codeplex.com/). There are several versions of it, for each version of MSSQL Server. You will get a glimpse on how to setup a basic eCommerce database, with Products, Orders, Sales, etc.
Comment: thanks everyone for the help, I will study the knowledge that you all given, thanks!
Comment: As for queries, you will use LINQ, thats something else to study.
Answer: If you are using a database you should consider using Primairy keys. That way you can store information about a certain item in another table. In all three tables you use Name and Brand. I would have modeled my tables like this:
Items

ItemID (make this field an Auto incrementing integer field)
ItemName
Brand
SupplierID
Price

Clients

ClientID
ClientName
DiscountPercentage
PhoneNr

Suppliers

SupplierID
SupplierName

In the clients table the field SupplierID is a unique number. So when you want to refer to a supplier you simple fill in the SupplierID. For example in the items table the ItemID is the unique identifier for an item. The Supplier ID field is refers to the SupplierID field in the Suppliers table. In order to make sure your datamodel remains consistent I would recommend you to use Foreign key constraints. This makes sure you can not fill in any invalid ID's
Here's a short movie explaining some SQL basics
Comment: thanks for the information, I will restructure my database again and may I search for your help again if I have any problems with it?
Comment: So, if i have 2 tables now, ItemInfo with ItemID as primary key, then another table, CostLists to show the item costs and supplier names which depends on the ItemInfo ItemID, should I put ItemID in CostList also? and how do I link them together?
Comment: Yes the Costlist should contain an item id. Otherwise you cannot say that Item A costs x. You can link tables together with Joins http://www.w3schools.com/sql/sql_join.asp
Comment: ok last question, SELECT costprice.costid, costprice.suppliername, costprice.costprice FROM costprice INNER JOIN partsinfo ON costprice.partsid = partsinfo.partsid WHERE CostPrice.PartsID = (textbox1.text from another form) How can I pass the textbox1.text which is from another form to the query???
Comment: You where almost there ;)

`string qry = ¨SELECT costprice.costid, costprice.suppliername, costprice.costprice FROM costprice INNER JOIN partsinfo ON costprice.partsid = partsinfo.partsid WHERE partsinfo.partname = '" + textbox1.text + "'";`

So for instance if the value of your textbox = "screwdriver" then your query would look like:
`SELECT costprice.costid, costprice.suppliername, costprice.costprice FROM costprice INNER JOIN partsinfo ON costprice.partsid = partsinfo.partsid WHERE partsinfo.partname = 'Screwdriver'`
Comment: ok, thanks @sjuul janssen, u've been a great help to me, it needs some coding to pass the value of textbox1.text from another form to this form. i'll figure it out!
Comment: Jansseen, do u have any email or something? It seems like the system cannot get the value of my textbox, I would like to send to ur email and see if you can find out something? is that ok? If you're busy then it's ok


sort a JavaRDD using sortBy

Question: I have a JavaRDD<Tuple2<String, Integer>> and want to sort it based on its Integer field.
If RDD has only one field, it works correctly.
JavaRDD<Integer> sorted = wordSet.sortBy(x -> x, false, 10);

But as its fields are Tuple2, it doesn't work.
I tried the following code:
JavaRDD<Tuple2<String, Integer>> sorted1 = wordSet1.sortBy(new Function<Tuple2<String, Integer>, Integer>() {
        public Integer call(Tuple2<String, Integer> value) throws Exception {
            return value._2;
        }
    }, false, 10);

Also I tried using Comparator but it doesn't work too.
public class TupleComparator implements Comparator<Tuple2<String, Integer>>, Serializable
{
    @Override
    public int compare(Tuple2<String, Integer> o1, Tuple2<String, Integer> o2) {
        return o1._2() < o2._2() ? 0 : 1;
    }
}

Any help would be appreciated.
UPDATE: A complete and verifiable example:
public class sortRDD {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setMaster("local").setAppName("sort");
        JavaSparkContext sparkContext = new JavaSparkContext(conf);

        List<Integer> numbers = new ArrayList<Integer>();
        for (int i = 1; i < 10; i++) {
            numbers.add(i);
        }
        JavaRDD<Integer> numberRDD = sparkContext.parallelize(numbers);
        System.out.println(numberRDD.collect());
        JavaRDD<Integer> sorted = numberRDD.sortBy(x -> x, false, 1);
        System.out.println("sorted:");
        System.out.println(sorted.collect());

        //RDD of tuples
        List<Tuple2<String, Integer>> words = new ArrayList<Tuple2<String, Integer>>();
        for (int i = 1; i < 10; i++) {
            words.add(new Tuple2<String, Integer>("word" + i, i));
        }
        JavaRDD<Tuple2<String, Integer>> wordSet = sparkContext.parallelize(words);
        System.out.println(wordSet.collect());
        JavaRDD<Tuple2<String, Integer>> sorted1 = wordSet.sortBy(new Function<Tuple2<String, Integer>, Integer>() {
            public Integer call(Tuple2<String, Integer> value) throws Exception {
                return value._2;
            }
        }, false, 1);
        System.out.println("sorted:");
        System.out.println(sorted1.collect());

        //Using Comparator
        JavaRDD<Tuple2<String, Integer>> sorted2 = wordSet.sortBy(new TupleComparator(), false, 1);
        System.out.println("sorted:");
        System.out.println(sorted1.collect());
    }
}

Comment: _it doesn't work too_ doesn't tell us anything. Please provide a [mcve]!
Comment: Updated! Please have a look
Answer: I changed the JavaRDD to JavaPairRdd and then using sortByKey, I could get the sorted results.

sort a JavaRDD using sortBy


Construction of tensor product explanation

Question: On this webside
http://www.math.uconn.edu/~kconrad/blurbs/linmultialg/tensorprod.pdf
on page 9, they state, that every element i $F_R(M\times N)$ can be written of a finite sum. My question is why? On page 7 they define it a enormous free vectorspace, whose basis is indexed by $(m,n)$.
Answer: By definition the free module $F_R(S)$ over a set $S$ is the module which elements are formal finite sum of elements of $S$, with coefficient in $R$.
Comment: Thanks a lot. Can you also please explain, why they can conclude that every element in $F(M\times N)/D$ Can be written as a linear combination of those element. Doesn't it require that the map is surjective?
Comment: I don't understand your question. By definition $M \otimes_R N = F(M \times N)/D$ is the quotient of the module $F(M \times N)$ by some relations. Thus you have a surjective map $F(M \times N) \to M \otimes_R N$ by definition, and the kernel of this map is precisely the relation, i.e the elements of $D$.
Comment: @StenHansen : if you want more details you can tell me which points are not clear
Comment: Thanks, sir! Really a lot of thanks
Comment: You made it all clear!
Comment: Perfect then, you're welcome !


How to create a only mute/unmute button (like youtube) in html

Question: I was creating a website, I put background music, and my problem is I dont know how to create a button(only one) for mute/unmute the sound. I would like to have a mute button that can mute/unmute depending on the situation(if the music is muted then the button should have the image of a Loudspeaker,for hearing the sound, if you press it then you begin listening the music and the image of the button changes and  vice versa)
what I have now is this:

I only need to know how to create that button, not the functions for the background music.
Thank you very much in advance
Comment: How are you playing the sound? Just a `bgsound` tag?
Answer: HTML
<input type="checkbox" name="un-mute" id="un-mute">

CSS
input#un-mute {
  display: none;
}

.unmute img {
  display: none;
}

input#un-mute:checked ~ .unmute img {
  display: initial;
}

input#un-mute:checked ~ .mute img {
  display: none;
}

JavaScript
var un_mute = document.getElementById('un-mute');

un_mute.onclick = function() {
   alert('toggle player here');
};

http://jsfiddle.net/Ffccv/2/
using :checked pseudo-class selector
Answer: You can do this To toggle them

and onclick="toggleSound(this);" or create img from script and use addEventListener ("click",toggleSound())

fiddle demo : http://jsfiddle.net/K9553/


Multicollinearity and statistical significance issue in regression model

Question: In a linear regression model, I'm considering adding in two control variables: One for population density and another measure that assesses vehicle ownership. These variables are correlated with each another, which would cause problems with multicollinearity. Neither variable is even close to being statistically significant in the model when only one is added, but both become statistically significant if they're both added to the model.
Any recommendations for what I should do?
Comment: Since your account of "problems with multicollinearity" sounds somewhat speculative, have you actually checked whether there *are* any problems?  What kinds of problems concern you?  (We can't know that without also knowing the purpose of your model and other details of the remaining independent variables.)
Comment: It is not clear what you are asking.
Answer: Based on the information that you have provided, you should include both. My guess is that one of the variables is suppressor variable.
Also, I really doubt you have any multicollinearity, as multicollinearity tends to manifest itself by existing variables ceasing to be significant when a new variable is added. (Note that two variables being highly correlated is not multicollinearity; check out one of John Fox's books on regression if you want to know more about this.)
If you are adding the variables as controls, it is completely irrelevant whether you have multicollinearity or not (unless the correlation between the variables is 1). It is only a problem if the multicollinearity is stuffing up one of the effects you are interested in estimating.
Answer: Check the variance inflation factor (VIF) scores to see the strength of multicorrelation. The VIF would indicate by what degree the standard errors are inflated; meaning you would probably NOT have gotten a significant result if there is strong multicorrelation.
If you use those two variables as controls, check the VIF on the variable of interest. If there is no strong multicollinearity, then there should be no problem.


Fetch content from another website into a new one

Question: I want to fetch content from a website into another website. When I edit that content, it will automatically display changes. I am using Drupal 6.
Does anybody have an idea about I can achieve this?
Comment: Scrape, process, post.  All easily possible with Drupal.  Details about where data is coming from and where it is going would help improve answers.
Answer: You should take a look at the Feeds module. It can import many different things into your Drupal site. I am using it to import RSS feeds as nodes.
Comment: I want to export the content too, and I want it done automatically.


Changing fullscreen gallery navigation to bullet-navigation

Question: I'm a noob at modifying jQuery and have managed to do the odd simple piece of code, but its a bigger task for me to modify this gallery: http://buildinternet.com/project/supersized/ - which currently uses a next/prev button and a digit counter e.g. 1/3, 2/3 etc...
I need to simply change the digit counter to bullet counters as found on sliders like http://wowslider.com/.
I tinkered with the jquery and tried a few things, but the changes could be much more than I anticipated. Any hints or tips to get me going?
Here is the actual JS:
(function($){

//Add in Supersized elements
$(document).ready(function() {
    $('body').prepend('

').prepend('

');
});

//Resize image on ready or resize
$.supersized = function( options ) {

    //Default settings
    var settings = {

        //Functionality
        slideshow               :   1,      //Slideshow on/off
        autoplay                :   1,      //Slideshow starts playing automatically
        start_slide             :   1,      //Start slide (0 is random)
        slide_interval          :   5000,   //Length between transitions
        transition              :   1,      //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
        transition_speed        :   750,    //Speed of transition
        new_window              :   1,      //Image links open in new window/tab
        pause_hover             :   0,      //Pause slideshow on hover
        keyboard_nav            :   1,      //Keyboard navigation on/off
        performance             :   1,      //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
        image_protect           :   1,      //Disables image dragging and right click with Javascript
        image_path              :   'img/', //Default image path

        //Size & Position
        min_width               :   0,      //Min width allowed (in pixels)
        min_height              :   0,      //Min height allowed (in pixels)
        vertical_center         :   1,      //Vertically center background
        horizontal_center       :   1,      //Horizontally center background
        fit_portrait            :   0,      //Portrait images will not exceed browser height
        fit_landscape           :   0,      //Landscape images will not exceed browser width

        //Components
        navigation              :   1,      //Slideshow controls on/off
        thumbnail_navigation    :   0,      //Thumbnail navigation
        slide_counter           :   1,      //Display slide numbers
        slide_captions          :   1       //Slide caption (Pull from "title" in slides array)

    };

    //Default elements
    var element = $('#supersized');     //Supersized container
    var pauseplay = '#pauseplay';       //Pause/Play

    //Combine options with default settings
    if (options) {
        var options = $.extend(settings, options);  //Pull from both defaults and supplied options
    }else{
        var options = $.extend(settings);           //Only pull from default settings
    }

    //General slideshow variables
    var inAnimation = false;                    //Prevents animations from stacking
    var isPaused = false;                       //Tracks paused on/off
    var image_path = options.image_path;        //Default image path for navigation control buttons

    //Determine starting slide (random or defined)
    if (options.start_slide){
        var currentSlide = options.start_slide - 1; //Default to defined start slide
    }else{
        var currentSlide = Math.floor(Math.random()*options.slides.length); //Generate random slide number
    }

    //If links should open in new window
    var linkTarget = options.new_window ? ' target="_blank"' : '';

    //Set slideshow quality (Supported only in FF and IE, no Webkit)
    if (options.performance == 3){
        element.addClass('speed');      //Faster transitions
    } else if ((options.performance == 1) || (options.performance == 2)){
        element.addClass('quality');    //Higher image quality
    }

    /***Load initial set of images***/

    if (options.slides.length > 1){
        //Set previous image
        currentSlide - 1 < 0  ? loadPrev = options.slides.length - 1 : loadPrev = currentSlide - 1; //If slide is 1, load last slide as previous
        var imageLink = (options.slides[loadPrev].url) ? "href='" + options.slides[loadPrev].url + "'" : "";
        $("").attr("src", options.slides[loadPrev].image).appendTo(element).wrap('');
    }

    //Set current image
    imageLink = (options.slides[currentSlide].url) ? "href='" + options.slides[currentSlide].url + "'" : "";
    $("").attr("src", options.slides[currentSlide].image).appendTo(element).wrap('');

    if (options.slides.length > 1){
        //Set next image
        currentSlide == options.slides.length - 1 ? loadNext = 0 : loadNext = currentSlide + 1; //If slide is last, load first slide as next
        imageLink = (options.slides[loadNext].url) ? "href='" + options.slides[loadNext].url + "'" : "";
        $("").attr("src", options.slides[loadNext].image).appendTo(element).wrap('');
    }
    /***End load initial images***/

    element.hide();                 //Hide image to be faded in
    $('#controls-wrapper').hide();  //Hide controls to be displayed

    $(window).load(function(){

        $('#supersized-loader').hide();     //Hide loading animation
        element.fadeIn('fast');             //Fade in background
        $('#controls-wrapper').show();      //Display controls

        //Display thumbnails
        if (options.thumbnail_navigation){

            //Load previous thumbnail
            currentSlide - 1 < 0  ? prevThumb = options.slides.length - 1 : prevThumb = currentSlide - 1;
            $('#prevthumb').show().html($("").attr("src", options.slides[prevThumb].image));

            //Load next thumbnail
            currentSlide == options.slides.length - 1 ? nextThumb = 0 : nextThumb = currentSlide + 1;
            $('#nextthumb').show().html($("").attr("src", options.slides[nextThumb].image));

        }

        resizenow();    //Resize background image

        if (options.slide_captions) $('#slidecaption').html(options.slides[currentSlide].title);        //Pull caption from array
        if (!(options.navigation)) $('#navigation').hide(); //Display navigation

        //Start slideshow if enabled
        if (options.slideshow && options.slides.length > 1){

            if (options.slide_counter){ //Initiate slide counter if active

                $('#slidecounter .slidenumber').html(currentSlide + 1);     //Pull initial slide number from options
                $('#slidecounter .totalslides').html(options.slides.length);    //Pull total from length of array

            }

            slideshow_interval = setInterval(nextslide, options.slide_interval);    //Initiate slide interval

            //Prevent slideshow if autoplay disabled
            if (!(options.autoplay)){

                clearInterval(slideshow_interval);  //Stop slideshow
                isPaused = true;    //Mark as paused

                if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "play_dull.png");   //If pause play button is image, swap src

            }

            //Thumbnail Navigation
            if (options.thumbnail_navigation){

                //Next thumbnail clicked
                $('#nextthumb').click(function() {

                    if(inAnimation) return false;       //Abort if currently animating

                    clearInterval(slideshow_interval);  //Stop slideshow
                    nextslide(element, options);        //Go to next slide
                    if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                    return false;

                });

                //Previous thumbnail clicked
                $('#prevthumb').click(function() {

                    if(inAnimation) return false;       //Abort if currently animating

                    clearInterval(slideshow_interval);  //Stop slideshow
                    prevslide(element, options);        //Go to previous slide
                    if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                    return false;

                });

            }

            //Navigation controls
            if (options.navigation){

                $('#navigation a').click(function(){
                    $(this).blur();
                    return false;
                });

                //Next button clicked
                $('#nextslide').click(function() {

                    if(inAnimation) return false;       //Abort if currently animating

                    clearInterval(slideshow_interval);  //Stop slideshow
                    nextslide();        //Go to next slide
                    if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                    return false;

                });

                //If next slide button is image
                if ($('#nextslide').attr('src')){

                    $('#nextslide').mousedown(function() {
                        $(this).attr("src", image_path + "arrow_right_active.png");
                    });
                    $('#nextslide').mouseup(function() {
                        $(this).attr("src", image_path + "arrow_right_inactive.png");
                    });
                    $('#nextslide').mouseout(function() {
                        $(this).attr("src", image_path + "arrow_right_inactive.png");
                    });

                }

                //Previous button clicked
                $('#prevslide').click(function() {

                    if(inAnimation) return false;       //Abort if currently animating

                    clearInterval(slideshow_interval);  //Stop slideshow
                    prevslide();        //Go to previous slide
                    if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                    return false;

                });

                //If previous slide button is image
                if ($('#prevslide').attr('src')){

                    $('#prevslide').mousedown(function() {
                        $(this).attr("src", image_path + "arrow_left_active.png");
                    });
                    $('#prevslide').mouseup(function() {
                        $(this).attr("src", image_path + "arrow_left_inactive.png");
                    });
                    $('#prevslide').mouseout(function() {
                        $(this).attr("src", image_path + "arrow_left_inactive.png");
                    });

                }

                //Pause/play element clicked
                $(pauseplay).click(function() {

                    if(inAnimation) return false;       //Abort if currently animating

                    if (isPaused){

                        if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "pause_dull.png");  //If image, swap to pause

                        //Resume slideshow
                        isPaused = false;
                        slideshow_interval = setInterval(nextslide, options.slide_interval);

                    }else{

                        if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "play_dull.png");   //If image, swap to play

                        //Stop slideshow
                        clearInterval(slideshow_interval);
                        isPaused = true;

                    }

                    return false;

                });

            }   //End navigation controls

        }   //End slideshow options

    });     //End window load

    //Keyboard Navigation
    if (options.keyboard_nav){

        $(document.documentElement).keydown(function (event) {

            if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow

                if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "arrow_left_active.png");     //If image, change back button to active

            } else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow

                if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "arrow_right_active.png");    //If image, change next button to active

            }

        });

        $(document.documentElement).keyup(function (event) {

            clearInterval(slideshow_interval);  //Stop slideshow, prevent buildup

            if ((event.keyCode == 37) || (event.keyCode == 40)) { //Left Arrow or Down Arrow

                if ($('#prevslide').attr('src')) $('#prevslide').attr("src", image_path + "arrow_left_inactive.png");   //If image, change back button to normal

                if(inAnimation) return false;       //Abort if currently animating

                clearInterval(slideshow_interval);  //Stop slideshow
                prevslide();        //Go to previous slide

                if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                return false;

            } else if ((event.keyCode == 39) || (event.keyCode == 38)) { //Right Arrow or Up Arrow

                if ($('#nextslide').attr('src')) $('#nextslide').attr("src", image_path + "arrow_right_inactive.png");  //If image, change next button to normal

                if(inAnimation) return false;       //Abort if currently animating

                clearInterval(slideshow_interval);  //Stop slideshow
                nextslide();        //Go to next slide

                if(!(isPaused)) slideshow_interval = setInterval(nextslide, options.slide_interval);    //If not paused, resume slideshow

                return false;

            } else if (event.keyCode == 32) { //Spacebar

                if(inAnimation) return false;       //Abort if currently animating

                if (isPaused){

                    if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "pause_dull.png");  //If image, swap to pause

                    //Resume slideshow
                    isPaused = false;
                    slideshow_interval = setInterval(nextslide, options.slide_interval);

                }else{

                    if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "play_dull.png");   //If image, swap to play

                    //Mark as paused
                    isPaused = true;

                }

                return false;
            }

        });
    }

    //Pause when hover on image
    if (options.slideshow && options.pause_hover){
        $(element).hover(function() {

            if(inAnimation) return false;       //Abort if currently animating

                if(!(isPaused) && options.navigation){

                    if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "pause.png");   //If image, swap to pause
                    clearInterval(slideshow_interval);

                }

        }, function() {

            if(!(isPaused) && options.navigation){

                if ($(pauseplay).attr('src')) $(pauseplay).attr("src", image_path + "pause_dull.png");  //If image, swap to active
                slideshow_interval = setInterval(nextslide, options.slide_interval);

            }

        });
    }

    //Adjust image when browser is resized
    $(window).resize(function(){
        resizenow();
    });

    //Adjust image size
    function resizenow() {
        return element.each(function() {

            var t = $('img', element);

            //Resize each image seperately
            $(t).each(function(){
                var ratio = ($(this).height()/$(this).width()).toFixed(2);  //Define image ratio

                //Gather browser size
                var browserwidth = $(window).width();
                var browserheight = $(window).height();
                var offset;

                //Resize image to proper ratio
                if ((browserheight > options.min_height) || (browserwidth > options.min_width)){    //If window larger than minimum height or width

                    if ((browserheight/browserwidth) > ratio){

                        if (options.fit_landscape && ratio <= 1){   //If landscapes are set to fit
                            $(this).width(browserwidth);
                            $(this).height(browserwidth * ratio);
                        }else{                                      //Otherwise handle normally
                            $(this).height(browserheight);
                            $(this).width(browserheight / ratio);
                        }

                    } else {

                        if (options.fit_portrait && ratio > 1){ //If portraits are set to fit
                            $(this).height(browserheight);
                            $(this).width(browserheight / ratio);
                        }else{                                      //Otherwise handle normally
                            $(this).width(browserwidth);
                            $(this).height(browserwidth * ratio);
                        }

                    }   //End dynamic resizing

                }   //End minimum size check

                //Horizontally Center
                if (options.horizontal_center){
                    $(this).css('left', (browserwidth - $(this).width())/2);
                }

                //Vertically Center
                if (options.vertical_center){
                    $(this).css('top', (browserheight - $(this).height())/2);
                }

            });

            //Basic image drag and right click protection
            if (options.image_protect){

                $('img', element).bind("contextmenu",function(){
                    return false;
                });
                $('img', element).bind("mousedown",function(){
                    return false;
                });

            }

            return false;

        });
    };

    //Next slide
    function nextslide() {

        if(inAnimation) return false;       //Abort if currently animating
            else inAnimation = true;        //Otherwise set animation marker

        var slides = options.slides;    //Pull in slides array

        var currentslide = element.find('.activeslide');        //Find active slide
        currentslide.removeClass('activeslide');                //Remove active class

        if ( currentslide.length == 0 ) currentslide = element.find('a:last');  //If end of set, note this is last slide
        var nextslide = currentslide.next().length ? currentslide.next() : element.find('a:first');
        var prevslide = nextslide.prev().length ? nextslide.prev() : element.find('a:last');

        //Update previous slide
        $('.prevslide').removeClass('prevslide');
        prevslide.addClass('prevslide');

        //Get the slide number of new slide
        currentSlide + 1 == slides.length ? currentSlide = 0 : currentSlide++;

        //If hybrid mode is on drop quality for transition
        if (options.performance == 1) element.removeClass('quality').addClass('speed');

        /**** Image Loading ****/

        //Load next image
        loadSlide = false;

        currentSlide == slides.length - 1 ? loadSlide = 0 : loadSlide = currentSlide + 1;   //Determine next slide
        imageLink = (options.slides[loadSlide].url) ? "href='" + options.slides[loadSlide].url + "'" : "";  //If link exists, build it
        $("").attr("src", options.slides[loadSlide].image).appendTo(element).wrap("");  //Append new image

        //Update thumbnails (if enabled)
        if (options.thumbnail_navigation == 1){

            //Load previous thumbnail
            currentSlide - 1 < 0  ? prevThumb = slides.length - 1 : prevThumb = currentSlide - 1;
            $('#prevthumb').html($("").attr("src", options.slides[prevThumb].image));

            //Load next thumbnail
            nextThumb = loadSlide;
            $('#nextthumb').html($("").attr("src", options.slides[nextThumb].image));

        }

        currentslide.prev().remove(); //Remove Old Image

        /**** End Image Loading ****/

        //Update slide number
        if (options.slide_counter){
            $('#slidecounter .slidenumber').html(currentSlide + 1);
        }

        //Update captions
        if (options.slide_captions){
            (options.slides[currentSlide].title) ? $('#slidecaption').html(options.slides[currentSlide].title) : $('#slidecaption').html('');
        }

        nextslide.hide().addClass('activeslide');   //Update active slide

        switch(options.transition){

            case 0:    //No transition
                nextslide.show(); inAnimation = false;
                break;
            case 1:    //Fade
                nextslide.fadeTo(options.transition_speed, 1, function(){ afterAnimation(); });
                break;
            case 2:    //Slide Top
                nextslide.animate({top : -$(window).height()}, 0 ).show().animate({ top:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 3:    //Slide Right
                nextslide.animate({left : $(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 4:    //Slide Bottom
                nextslide.animate({top : $(window).height()}, 0 ).show().animate({ top:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 5:    //Slide Left
                nextslide.animate({left : -$(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 6:    //Carousel Right
                nextslide.animate({left : $(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                currentslide.animate({ left: -$(window).width() }, options.transition_speed );
                break;
            case 7:    //Carousel Left
                nextslide.animate({left : -$(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                currentslide.animate({ left: $(window).width() }, options.transition_speed );
                break;
        };

    }

    //Previous Slide
    function prevslide() {

        if(inAnimation) return false;       //Abort if currently animating
            else inAnimation = true;        //Otherwise set animation marker

        var slides = options.slides;    //Pull in slides array

        var currentslide = element.find('.activeslide');        //Find active slide
        currentslide.removeClass('activeslide');                //Remove active class

        if ( currentslide.length == 0 ) currentslide = $(element).find('a:first');  //If end of set, note this is first slide
        var nextslide =  currentslide.prev().length ? currentslide.prev() : $(element).find('a:last');
        var prevslide =  nextslide.next().length ? nextslide.next() : $(element).find('a:first');

        //Update previous slide
        $('.prevslide').removeClass('prevslide');
        prevslide.addClass('prevslide');

        //Get current slide number
        currentSlide == 0 ?  currentSlide = slides.length - 1 : currentSlide-- ;

        //If hybrid mode is on drop quality for transition
        if (options.performance == 1) element.removeClass('quality').addClass('speed');

        /**** Image Loading ****/

        //Load next image
        loadSlide = false;

        currentSlide - 1 < 0  ? loadSlide = slides.length - 1 : loadSlide = currentSlide - 1;   //Determine next slide
        imageLink = (options.slides[loadSlide].url) ? "href='" + options.slides[loadSlide].url + "'" : "";  //If link exists, build it
        $("").attr("src", options.slides[loadSlide].image).prependTo(element).wrap(""); //Append new image

        //Update thumbnails (if enabled)
        if (options.thumbnail_navigation == 1){

            //Load previous thumbnail
            prevThumb = loadSlide;
            $('#prevthumb').html($("").attr("src", options.slides[prevThumb].image));

            //Load next thumbnail
            currentSlide == slides.length - 1 ? nextThumb = 0 : nextThumb = currentSlide + 1;
            $('#nextthumb').html($("").attr("src", options.slides[nextThumb].image));
        }

        currentslide.next().remove(); //Remove Old Image

        /**** End Image Loading ****/

        //Update slide counter
        if (options.slide_counter){
            $('#slidecounter .slidenumber').html(currentSlide + 1);
        }

        //Update captions
        if (options.slide_captions){
            (options.slides[currentSlide].title) ? $('#slidecaption').html(options.slides[currentSlide].title) : $('#slidecaption').html('');
        }

        nextslide.hide().addClass('activeslide');   //Update active slide

        switch(options.transition){

            case 0:    //No transition
                nextslide.show(); inAnimation = false;
                break;
            case 1:    //Fade
                nextslide.fadeTo(options.transition_speed, 1, function(){ afterAnimation(); });
                break;
            case 2:    //Slide Top (reverse)
                nextslide.animate({top : $(window).height()}, 0 ).show().animate({ top:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 3:    //Slide Right (reverse)
                nextslide.animate({left : -$(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 4:    //Slide Bottom (reverse)
                nextslide.animate({top : -$(window).height()}, 0 ).show().animate({ top:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 5:    //Slide Left (reverse)
                nextslide.animate({left : $(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                break;
            case 6:    //Carousel Right (reverse)
                nextslide.animate({left : -$(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                currentslide.animate({ left: $(window).width() }, options.transition_speed );
                break;
            case 7:    //Carousel Left (reverse)
                nextslide.animate({left : $(window).width()}, 0 ).show().animate({ left:0 }, options.transition_speed, function(){ afterAnimation(); });
                currentslide.animate({ left: -$(window).width() }, options.transition_speed );
                break;
        };

    }

    //After slide animation
    function afterAnimation() {

        inAnimation = false;

        //If hybrid mode is on swap back to higher image quality
        if (options.performance == 1){
            element.removeClass('speed').addClass('quality');
        }

        resizenow();

    }

};

})(jQuery);

in the HEAD
<link rel="stylesheet" href="css/supersized.css" type="text/css" media="screen" />

Body:

            /

Hopefully the above helps.
thanks!
Comment: You'll find that few people on this site are willing to assist in "help me with this plugin" type questions. The chances of someone knowing both of these plugins and how they work is quite low. Post some code, you'll get more responses.
Comment: Thanks, you are right, will try to make it easier for those who can help.
Comment: Omar, I have exactly the same problem as you. To modify supersized with a navigation bullet. After whole weeks of research, I still have nothing to find. Any solution?....I absolutely need this modification. Thank you yoann
Answer: Currently there are two actions happening. First the total number of slides gets set as does the current position (typically 1).. Then later inside the loop, the current position gets updated. So if you crack open supersized.3.1.3.js see the follwing line numbers: 154, 155, 595, and 690.. The first two line numbers initially place the number values in their home. And the last two update the current slide.
First what you need to do is write the html and css for your dots. Write one div class for dot and and one for dotActive. The dot class is the default state. And when it's active, you will be adding and removing the class dotActive to the elements. Make sure to give them all numeric indexes as it will be way easier when you need to add the dotActive class to the correct element. I'm picturing, dot_1, dot_2, and so on.
Basically you will want to use the value of options.slides.length on line 155 to determine how many elements to create and inject into the html: $('#slidecounter .slidenumber'). Then at the update loops, probably just each() through the .slidenumber collection, doing removeClass - then addClass to the element known by your currentSlide value.. And viola!
Answer: A big hint for jQuery: Don't write what's been written!
A popular image slider is EasySlider.  It can be easily modified to use "bullets" for the navigation like that with a bit of styling.  The link I provided is to a sample which uses numbers.  Might be a good starting point.
Comment: Thanks, but I require the whole FULLSCREEN-image slider - Supersized does this already but not the bullet navigation - hence the need to modify it.


Reconciling two ways of interpreting determinant as scaling factor

Question: My Linear Algebra text has some introductory examples of interpreting the determinant as a scaling factor. These all involve interpreting the columns of a matrix B as coordinates to form a square or triangle, then showing that when left multiplying B by another matrix A that has a determinant, det(A), that the area of the shape formed by interpreting the columns of the resulting matrix as coordinates is scaled by det(A). That part all makes sense.
Later they introduce this proposition:

The first confusing thing is they're saying a 3x3 matrix is a box -- that's not true if you interpret the columns as coordinates like before; you need more columns. At best 3 points could describe a plane or a triangle in a plane. If I interpret their A matrix to be a matrix that we multiply by to scale another matrix B with columns as coordinates, I can see why (kA)B=C_1 would have factors that are k times longer than those in just AB=C_2, because the rows of A each in essence describe a linear combination for how to produce the new columns of C_1 and C_2, and if that sum is multiplied by k every column vector in C_2 should be k times longer than in C_1. Then if we separately already accept that det(A) is the scaling factor for the area of a new shape produced when left multiplying by A, I can see the proposition. But in that line of reasoning kA never represents a box; you could interpret it to be one in the sense that you can interpret 3 vectors with a length as describing a cube, but that's inconsistent with how they interpreted things before and it's not clear why that interpretation is supposed to help.
Am I interpreting this correctly? Or is there an easier way of looking at it?
Comment: Can you see how two linearly independent vectors in $R^2$ determine a parallelogram?
Comment: Yes. I mention near the end I can see how it could describe a cube, just not why it's a useful way to think about it. The determinant is a scaling factor for the area of the shape described by C which was originally the shape described by B, but kA is scaling the matrix you're using to do the transform, so it doesn't seem like a justification for the area of C getting bigger.
Comment: In my opinion, the prose in this textbook is vague, indirect, and ambiguous to the point of being misleading. You should find a better textbook to study.
Comment: @ChrisCulter any specific suggestions?
Answer: The columns of the $3\times 3$ matrix are the position vectors of three vertices of the cube. In the case shown above:
$$
v_1 = (1,0,0)
$$
$$
v_2 = (0,1,0)
$$
$$
v_1 = (0,0,1)
$$
With determinant $det([v_1,v_2,v_3]) = 1$. If you multiply each column by $k$, the determinant is $det([kv_1,kv_2,kv_3]) = k^³$.
That is completely general for any parallelepiped in three dimensions. The volume of the parallelepiped is equal to the determinant of the matrix formed by three column vectors along the directions of the three non-redundant edges with length equal to the length of the edge.
It all stems from the fact that the determinant can be writen as this "mixed" product of the columns $det([v_1,v_2,v_3]) = v_1\cdot v_2\times v_3$.
Comment: I don't think this really answers the question. Like I said at the end, I can see a way to interpret it to get a cube (like you describe), but not why that's helpful to reach the proposition. You want to show that the area of C scales by k^n. That you can interpret kA as scaling a cube doesn't help because that's scaling the transformation matrix A, not C. What was established earlier in the text is the determinant is a scaling factor for the area of going from B to C.
Comment: What is $C$ to you?
Comment: C_1 is the resulting matrix from left multiplying by a "transformation matrix" A that has a determinant det(A) by a "coordinate matrix" B whose columns we interpret as coordinates of a shape. If I accept the determinant of A as being area of C_1 over the area of B, the fact that I can separately go and interpret the columns of A in a totally different way to get a cube and can multiply the lengths of As column vectors by k doesn't seem to immediately imply (at least to me) that the area of C_2 (formed by (kA)B) over the area of B must be k^n * det(A).
Comment: $B$ defines a shape, $AB$ is the shape in another space with volume $det(A)det(B)$, $kAB = A(kB)$ so you transfer the rescaling factor to the coordinates and you have a $k^n$ times bigger shape in the original space which, it's intuitively easy to see, will give a $k^n$ times bigger shape in the space of $AB$ under a linear transformation, does that solve your issue?
Comment: you're probably right but I think you're using material I'm not exposed to yet. To be clear are the A and B you're referring to the same as mine or do you just mean two matrices in general? I have only read of determinant as a scaling factor, not an actual area. When you say the area of $AB$ is $det(A)det(B)$, do you mean that that's the area of the shape when the shape is the vertices described by the columns as coordinates, or when it's the parallelogram described by the columns as vectors?
Comment: The equality $det(kA) = k^n det(A)$ holds for any dimension $n$ and any matrix, it just happens to have this nice interpretation in $n=3$. Yes, I am refering to the same matrices as you are: $A$ is the transformation and the columns of $B$ are the edges of the shape.
Comment: The thing that probably confuses you is that the interpretation doesn't care about who's the transformation and who's the coordinates.
Comment: Another thing is that you keep talking about areas... the determinant is the volume. The norm of the cross product of two edges is the area of the parallelogram they define.
Comment: Maybe.. but if $Area(AB) = det(A)det(B)$, then I assume $Area(A) = det(A)$ and $Area(B) = det(B)$, but the shape of A, if we're saying it's a cube but also that it's only a 3x3 matrix, must be formed interpreting the columns of A as 3 vectors defining the lengths of the sides, because if it were the edges we would need more columns. The shape described by B on the other hand is supposed to be described by the columns as edges of the shape. So the two Area functions can't be the same right?
Comment: Also cross product isn't discussed yet either ;p
Answer: I'll take a stab at this:
First, the easy one. The "boxes" that we're dealing with here are parallelotopes: paralallograms, paralallepipeds, and so on. Because of all of the parallelism constraints that they have among edges, faces, &c, an $n$-dimensional parallelotope is completely determined by $n$ edges that meet at a common vertex. In particular, three linearly independent edge vectors and a common vertex completely specify a parallelepiped, which means that the three columns of a $3\times3$ matrix are also enough to define a box with vertex at the origin. You don't need any more columns.
Now, for the proposition at hand, they're transforming a specific parallelotope—the unit $n$-cube—by the matrix $A$. Going back to your first paragraph, all of this cube's side lengths are equal to $1$, so the matrix $B$ for the unit cube is just the identity matrix. Left-multiplying this by the transformation matrix $A$ produces $A$, so you can then proceed to interpret its columns as the edges of a parallelotope just as you did with the product $AB$ for some other matrix $B$.


Attach #ajax to submit button created in hook_form_alter with #markup

Question: I created a custom submit button for the user-login form using #markup because I couldn't alter submit button html to resemble what I needed. The second custom submit button with the needed html is added with:
$form['submit2'] = array(
  '#markup' => '
<button type="submit" name="submit"></button>
');

I then added a "hideme" class to the orginal button with $form['actions']['submit'] ['#attributes'] (deleting it stopped the other submit from working).
So far so good. But now I would like to validate the login form using AJAX. Only if I add the #ajax key to $form['submit2'], the callback is never called. This only seems to work with regular form items.
Is it possible to trigger an Ajax callback on a #markup element (in hook_form_alter)? I'm using Drupal 7.
Answer: You cannot, since the #ajax attribute is not used for the markup item. You can use an image_button form element.
If the image_button form element doesn't render as you want and it is not possible to alter it the way you want, you need to implement a new form element with hook_element_info(), using the definition of the image_button form element as guide.
  $types['image_button'] = array(
    '#input' => TRUE,
    '#button_type' => 'submit',
    '#executes_submit_callback' => TRUE,
    '#limit_validation_errors' => FALSE,
    '#process' => array('ajax_process_form'),
    '#return_value' => TRUE,
    '#has_garbage_value' => TRUE,
    '#src' => NULL,
    '#theme_wrappers' => array('image_button'),
  );

The theme function that renders that form element is theme_image_button(). Changing the value of #theme_wrappers, you can alter the way your form element is rendered.
Keep in mind that theme wrappers, as any other theme functions, need to be declared with hook_theme().
Comment: Defining a new form element with custom theme_wrapper turned out to be the way to go. As a pointer for those trying the same, in addition to defining the new element with hook_element_info, you also need to register your custom theme_wrapper with hook_theme. The custom wrapper allowed me to output the submit button exactly as I wanted it.


Nginx proxy_pass keeps redirecting to localhost

Question: I am trying to set up a reverse proxy from my domain to http://127.0.0.1:4000. My issue is that whenever I try to open https://example.com (not the actual domain) in a browser, I just get redirected to http://localhost on my own machine. There is nothing listening on the server at http://127.0.0.1:4000 yet. I am just trying to see the 504 error screen.
server {
        listen 443 ssl;

        server_name example.com;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        location / {
                proxy_pass http://127.0.0.1:4000;
        }
}

The domain does point to this server. I am able to connect to the server via this domain, but when I view it in a browser I always get redirected to http://localhost.
EDIT: I just tried it in another browser and realized it was Chrome doing the redirect. The server works fine.
Answer: Nevermind, I tried it in another browser and it worked fine. Chrome is just stuck redirecting me for some reason...
Comment: Clear your browser cache?
Comment: @MichaelHampton It's actually the fault of the thing I'm trying to host on the other side of the proxy. It's API Umbrella, and it's putting out a 301 redirect to localhost. So even after I turned off the server, my browser still cached the redirect. So now I'm figuring out how to disable that garbage lol.
Comment: A 301 can be cached permanently. So, yeah, that ought to be fixed...
Answer: 504 Gateway Timeout error means that nginx was able to succesfully connect and send request to the 127.0.0.1:4000 server, but did not receive a response within expected time.
To see that error message, you need to have a server running on the port, and make it not send a reply within timeout specified in nginx configuration.
Comment: Actually no, there is no server running at port 4000 and nginx instantly shows the 504 error. It was just Chrome redirecting me.


Limit prometheus to discover pods in specific namespaces ONLY

Question: I am trying to run Prometheus to ONLY monitor pods in specific namespaces (in openshift cluster).
I am getting "cannot list pods at the cluster scope" - But I have tried to set it to not use ClusterScope (only look in specific namespaces instead)..
I've set:
<code>      prometheus.yml: |
        scrape_configs:
        - job_name: prometheus
          static_configs:
          - targets:
            - localhost:9090
        - job_name: kubernetes-pods
          kubernetes_sd_configs:
          - namespaces:
              names:
              - api-mytestns1
              - api-mytestns2
            role: pod
          relabel_configs:
[cut]
</code>
I get this error - even if I remove the -job_name: kubernetes-pods entirely.. so maybe its something else in prometheus, that needs disabling?
Comment: how did you setup prometheus? point to the docs which you might have followed
Comment: config shown (so its readable now) - I am not allowed to paste the entire file - but the [cut] is just relabel configs etc. - should not be relevant.
Comment: Could you please share your ServiceAccount config for Prometheus? It looks like Prometheus needs more privileges.
Comment: But I cannot give prometheus rights to lookup pods at clusterscope - as I don't have it. I want to run prometheus ONLY for a few namespaces (that I have access to) - and it should not try to lookup pods at clusterscope to do that :(
Comment: So, are you able to share the RBAC config that Prometheus is using in your case?
Comment: @KlavsKlavsen Can you also share the full error message from the logs? "cannot list pods at the cluster scope" looks like the last part of it.
Answer: I found that one had to overwrite server.alertmanagers with a complete copy of the settings in charts/prometheus/templates/server-configmap.yaml - to override the hardcoded default in those, to try and scrape cluster-wide.


Limit requests frequency of each IP using NGINX & Lua

Question: My goal is to prevent the high frequent request based on user IP, and i google the openresty and found it can be played with Lua. So i wrote the following script, i'm a newbie to Lua, could anyone give me some advice on this script, or even correct me.
this script is to block request which requests over 3 times in 100s
local limit_request_times = 3
local expire_time = 100

local user_ip = ngx.var.remote_addr

-- ngx.say("user_ip: ", user_ip)

local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000)
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local res, err = red:get(user_ip)
if res == ngx.null then
    ngx.say("no request record, add this user_ip to redis")
    ok, err = red:set(user_ip, 1)
    if not ok then
        -- ngx.say("add user_ip failed")
        ngx.exit(ngx.HTTP_FORBIDDEN)
        return
    else
        red:expire(user_ip, expire_time)
    end
else
    if tonumber(res) == limit_request_times then
        -- ngx.say("request reach max limit times")
        ngx.exit(403)
        return
    else
        ok, err = red:incr(user_ip)
        if not ok then
            ngx.say("failed to increment request times")
            return
        else
            ngx.say("increment request times: ", res + 1)
        end
    end
end

Answer: Why not just use nginx build-in ngx_http_limit_req_module?
e.g. We limit not more than 2 requests per minute from one IP address。
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=2r/m;

...

server {

    ...

    location /search/ {
        limit_req zone=one burst=3 nodelay;
    }

Comment: @yunfeng.guo please try limit_req_zone $arg_guid zone=one:10m rate=2r/m;  and we can also try to combine IP and guid , e.g. limit_req_zone $binary_remote_addr$arg_guid zone=one:10m rate=2r/m;  we can define serveral zones for different locations
Comment: @xfeep in case this is still relevant for you - [nginx-mod](https://www.getpagespeed.com/nginx-mod-a-better-faster-nginx-build) supports rate limiting per hour, day, week, month and year :)
Comment: Thx @xfeep, that's what i need. But it still can't fully meet my requirement. I need to limit request not only based on IP, and also based on request parameter, e.g /test?guid=blahblah, we need limit requests based on 'guid'.
Comment: @yunfeng.guo Please note that  "Prior to version 1.7.6, a key of limit_req_zone could contain exactly one variable."  So  if your nginx version is less than 1.7.6, you need define a variable and set it at location, e.g. set $myzonekey $binary_remote_addr$arg_guid;
Comment: That's great, i will try it. Thanks a lot
Comment: @xfeep can we block set request rate per hour ?
Comment: @MukeshKamboj AFAIK. per second and per minute are supported. per hour is not supported.
Comment: @Xfeep thanks for the response. Do we have nginx configuration that set limit that an IP can send n request only for a day? I have such requirement that there is a service where i need to support only 20 to 30 requests in a day.
Comment: @MukeshKamboj No, so far ngx_http_limit_req_module has not supported it.
Answer: Also you can use resty.limit.conn and/or resty.limit.req modules via Lua https://nginx-extras.getpagespeed.com/lua/limit-traffic/


How to use restricted groups GPO's

Question: I am going through the process of removing all my users from local admins from their machines. I put each user as local admin when the box was imaged so I could avoid all the trouble. Well, now after a surge of users getting virus/malware I decided it's time to deal with the lesser of two evils.
I know that the best way of doing this will be through the restricted groups GPO. I attempted this last week while most of my users were gone and I had a pretty crappy morning and I reverted all the changes.
What I did was for the group, I specified Administrator (Does this automatically assume local groups? If when I browse and say local computer (being the dc) does that mean every computers local group?) and then I chose the (domain group) domain admins and put them in the "Members of this group:"
Correct me if I am wrong here... but when I did this, all user accounts (not profiles) were "deleted" from the computer. I am assuming this happened because since these users had been set to only local admins, when i set this policy it removed them from local admins and their account was deleted from the computer. Some of these users lost the "link" to their local profiles and I had to move all their stuff and set everything back up. I also had a lot of permission issues throughout the company such as RDC issues and read/write issues.
Sooooo! I am thinking about re-doing this a little bit the other way around and I want some input. This time, I am going to put the initial group as power users (local) and then set all my users as "members of this group:"
Do you guys see any repercussions to doing this? Is this the correct way to solve my problem?
Thanks a lot!
Cory
Comment: Sorry, I am not following what you did, or where trying to do in your description in the second paragraph.
Comment: I have done a decent amount of research that says the best way to remove these users from local admins is to use the "Restricted groups" in a group policy. (Computer config ==> Windows Settings ==> Security Settings ==> Restricted Groups)
Comment: I'm confused.  You say all the user accounts were deleted from the machine, but you obviously have Active Directory if you're using GPO, and as such there shouldn't be any local user accounts on the machine other than Administrator and Guest.  Please clarify
Comment: Sorry for the confusion and just now getting to the party. What I meant by "all the user accounts were deleted" or any confusion about local users is that when you go to control panel then go to users... this is where all the domain users that have logged into the machine and have a local profile. This is also where you can set them as admins or power users ect.

Does this clear up any confusion?
Answer: Ok... I know this question is dead in the water but I finally put some time into this issue and got it solved.
What i did is I set Administrators(local) as the initial group and then in the members section, i put Domain\domain admins
Then I put my user group domain\Power Users as the initial group and in the members of, i chose power users (Local)
Answer: You can't use group-policies to add or remove users from groups.  If local-users (or domain users) are a member of the local-administrators... you'll need to manually remove them... or create a script to do it for you & push it out as a logon script or some such.  (just be sure to exclude "Administrator"... or any needed admin users)
As a rule... NEVER give users more permissions than the absolute minimum.  They DO NOT ever need administrative privileges to do basic tasks.  (Adding printers... can be done by the Printer Operators group... installing applications & drivers should be reserved to administrators only.)
If you have software from a 3rd party that insists on requiring Administrative privileges to run... they're either a) lying... or b) not a vendor you want to do business with.  Install with admin, sure... but it shouldn't be required to run.
This is one of those rules people forget... and will always come back to haunt the admin.
It sounds like you have a lot of work in front of you...
Comment: don't need to manually remove them the gpo's restricted group will remove anybody thats not being enforced.  There are a lot of poorly written apps unfortuanetly so you really need to understand your applications..
Comment: Tony Roth is right here. Last week, I set a GPO that when users logged in, it removed them from being a local admin. The problem was, not everyone logged in that day and the people who did had a lot of problems... So I decided to remove the GPO.

On another note, it was unfortunately my predecessor who did this to all the computers and now I am fixed cleaning the mess and making the users hate me...
Answer: I disagree slightly with TheCompWiz in that in my field (education) you will often see older applications that do require administrative access to run, and which cannot be organizationally removed. That said, in those cases you generally want to use GPOs to restrict what the users are able to do. It won't necessarily cut down on the mischief that viruses and malware can unleash, but it may provide some hedges (depending on the policies you put in place) against the users creating those issues in the first place.
Novell's Zenworks product (which can be run with Active Directory or Novell's own eDirectory) has a feature called "Dynamic Local User" (DLU) which I believe comports roughly with what you are trying do to. It provides a policy that creates a new or manages an existing local user on a machine. Using DLU, you can change which groups a user belongs to at login. It has some other bells and whistles as well -- you can leave the local user on the machine or have it automatically deleted at logout, which gives you some flexibility for times when users may be using multiple machines or machines that jump on and off the network.
That said, you are probably not in a position to use Zenworks, so the scripting solution per TheCompWiz seems to be the best approach. I would advocate a script as follows:
1. When a named user (rather than a generic like "Administrator" or "Guest") logs into a machine ...
2. Check the local administrative group for the user
3. If the user exists in the group, then remove them.
4. Write a little log file to the user's directory with date stamp, username, and machine name to confirm that this was done.
You probably do want to re-word at least the title of your post for clarity.

How to use restricted groups GPO's


R rounding off numbers like 8.829847e-07

Question: How can I round off a number like 0.0000234889 (or in the form 8.829847e-07) to a power of ten, either below or above (whichever is my choice), ie here 0.00001 or 0.0001 ?
I tried  round(...., digits=-100000) but it returns an error NaN error.
Ex: round(2e-07, digits=6) gives 0, while I would like 1e-06 and another function to give 1e-07.
Answer: The digits argument to the round() function must be positive. If you want your number to show up in scientific notation with an exponent n, just just do
round(value, 10^n)

However, this will only get you what you want up to a point. For example, you can do round(0.0000234889, 10^6) but you still get 2.34889e-05. (Notice that an exponent of 6 was specified but you got 5.)
Comment: okay, but `round(2e-07, digits=6)` gives 0, while I would like `1e-06` or `1e-07`
Answer: # Is this what you're looking for?
# find the nearest power of ten for some number
x <- 0.0000234889 # Set test input value
y <- log10(x)     # What is the fractional base ten logarithm?
yy <- round(y)    # What is the nearest whole number base ten log?
xx <- 10 ^ yy     # What integer power of ten is nearest the input?
print(xx)
# [1] 1e-05

Comment: In  a single expression it's: 10 ^ round(log10(x))
You can use "ceiling" or "floor" instead of "round" to change functionality.
Answer: Use options("scipen" = ) like this:
num <- 0.0000234889
> num
[1] 2.34889e-05
options("scipen" = 10)
options()$scipen
> num
[1] 0.0000234889
This will change the global option for the session. Read documentation here:https://stat.ethz.ch/R-manual/R-devel/library/base/html/options.html


Chart.js v3: how to allow tick label overflow?

Question: I recently upgraded from Chart.js v2 to v3. I am drawing realtime line charts with a time-based x-axis that scrolls right as time passes.
In Chart.js v3, as my x-axis tick labels begins to approach the left edge of the chart, it resizes the graph to fit the full label. As shown in the attached image, this creates an empty gap on the left-side of my chart. In Chart.js v2, it would not resize the graph, and would instead allow the label to overflow the canvas.

My x-axis options are:
{
  type: 'time',
  axis: 'x',
  min: minDate.getTime(),
  max: maxDate.getTime()
  time: {},
  ticks: {
    minRotation: 45,
    maxRotation: 45,
    source: 'labels'
  }
};

Is there any option to restore the old behavior and allow the tick labels to overflow?
Answer: You could format the first tick to be empty string, using ticks.callback
{
  type: 'time',
  ticks: {
    callback: (value, index) => index === 0 ? '' : value
  }
}

example in codepen
Answer: I was eventually able to get the desired behavior using the afterFit callback.
{
  type: 'time',
  afterFit: (scaleInstance) => {
    scaleInstance.paddingLeft = 0;
    scaleInstance.paddingRight = 0;
  }
}


dimensionar uma imagem dentro de um botão

Question: Tenho um botão que foi criado usando os botões personalizados de css, porem troquei o fundo por uma imagem personalizada, como eu dimensiono essa imagem pra ela ficar de acordo com o botão?
segue o css
<code>.port {
  -moz-box-shadow: 0px 1px 0px 0px #000000;
  -webkit-box-shadow: 0px 1px 0px 0px #000000;
  box-shadow: 0px 1px 0px 0px #000000;
  background-image: url('../images/br.png');
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ffec64', endColorstr='#ffab23', GradientType=0);
  background-color: green;
  -moz-border-radius: 15px;
  -webkit-border-radius: 15px;
  border-radius: 15px;
  border: 3px solid #000000;
  display: inline-block;
  cursor: pointer;
  color: black;
  font-family: Georgia;
  font-size: 16px;
  font-weight: bold;
  padding: 20px 50px;
  text-decoration: none;
  text-shadow: 0px 1px 0px white;
  position: absolute;
  top: 990px;
  left: 1690px;
}

.port:hover {
  background-image: url('../images/br.png');
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#ffab23', endColorstr='#ffec64', GradientType=0);
  background-color: green;
}

.port:active {
  position: absolute;
  top: 990px;
  left: 1690px;
}
</code>
a imagem é essa ai, queria que o botão ficasse redondo dessa maneira e que á imagem envolvesse todo ele.
http://pt.seaicons.com/wp-content/uploads/2016/09/brasil-icon.png
Answer: É só definir o tamanho do botão, deixando as bordas redondinhas e um background cover para a imagem preencher tudo deixando centralizada, exemplo:
<code>background-size: cover;
background-repeat: no-repeat;
background-position: center;
border-radius: 50%;
width: 100px;
height: 100px;
</code>


How to compare two arrays to find common elements?

Question: I'm trying to find a number x for which x = y^4 = z^6 = 5k = 2l. Is there a way of comparing the arrays of fourth and sixth power numbers to find the smallest common element?
    int[] fourth = new int[1000];
    int[] sixth = new int[1000];
    for (int i = 1; i < 1000; i++) {
        if (i*i*i*i % 10 == 0) {
            int count = 0;
            fourth[count] = (i*i*i*i);
            count++;
        }
    }
    for (int i = 1; i < 1000; i++) {
        if (i*i*i*i*i*i % 10 == 0) {
            int count = 0;
            sixth[count] = (i*i*i*i*i*i);
            count++;
        }
    }

Comment: `1000^6` is quite a bit larger than can fit in an `int`.  The top ends of your arrays are going to be full of gargage.  You might want to change those to `long[]`.
Comment: @azurefrog Sorry it was a joke because of the visually ambiguous choice of variable names
Answer: First thing: i^4 % 10 == 0 means i % 10 == 0, so you have 10, 20, 30, ..., 990.
for (int i = 10; i < 1000; i+=10){
    int count = 0;
    fourth[count] = (i^4);
    count++;
}

To further improve, you can simply do a math trick.
for (int i = 10; i < 1000; i+=10){
    double val = i^(4/6);
    if (val % 10 == 0 and 0<val<1000)
       system.out.println((val^(6/4)) + " is a number you are looking for!!!.");
}

You don't need to iterate 1 to 10 and you don't need to calculate all values.
EDIT:
It seems you want to calculate the x = y^4 = z^6 = 5k = 2l, assuming x,y,z,k,l are integers, x should be divisible by 10 and it should be the 4th and 6th power of some integers which means that 12th power of some integers.
Here is the list of numbers that you are looking for:
for (i = 10; i < 1000; i+=10){
    long long a = i ^ 12;
    System.out.println(a);
}


Using Html5boilerplate's code to load JQuery very slow when run locally

Question: I have been using the following code for loading JQuery in all of my projects.  I grabbed it from http://html5boilerplate.com/.  There is extensive disussion of this technique here.

This code works great and seems pretty darn quick once I've put it up on the interwebs, but when I open my .html file locally it takes ~10 seconds per refresh.  Generally I get fed up and alter the code as follows:

Am I missing something obvious here?  I feel like I should not be getting the super-slow loading times, but it does resolve itself when comment out those lines.
Answer: I'm guessing that you're not serving the HTML through a web server.
The // prefix on the url indicates that it should use the same protocol as the current resource (usually either http or https)
Since you're not serving through http and instead through a file, it's trying to look for it on your local file system, eventually timing out.
The network tab on Chrome inspector shows it trying to load the following for me:

file://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
  file:///C:/Users/[My Username]/Documents/jquery-1.7.1.min.js

It'll try to load those times and the file system (or maybe the browser) will eventually timeout.
The proper way is to serve it through a web server, either IIS if you're on Windows or Apache if you're on Linux/Mac (Apache also works in Windows, but IIS has better UI tools)
Comment: For the record, I'm kinda bummed with this solution though.  For small html/js/css projects I like to work right off the desktop.
Comment: I suppose running it through XAMPP is the solution I'm looking for, I'd try it out now, but the darn thing broke somehow ;-) gotta give it a reinstall when I get a chance.
Comment: @ZachL. if you serve the file through a web server instead of just opening the file, it should work.
Answer: This line:

Attempts to find jQuery in your file system, which means it will take a while to fail.  While looking at the Network tab of the developer panel in Google Chrome, it attempts to look for the file in file://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js.Then, once it has failed to find the file, it loads jQuery (and successfully finds the file) using the next line:

Comment: That looks like it will work, but this will defeat the point of the protocol agnostic approach?


Some Apache requests are slow, most complete instantly

Question: I have two Dell R410 web servers (2x quad core Xeon E5520 w/ 8gb ram) running Debian 5 stable. Their patching had been neglected for a while, so recently we did a patching run to bring everything up to date - neccessitated by a new version of the application it runs which requires PHP 5.3.6. The kernel wasn't updated because it came from the Debian backports repository (the installed version is 2.6.30-bpo.1-amd64).
Since the patching, users have complained that the web site is slow. The majority of requests are served instantly, but now and again it'll get "stuck" on a request. There doesn't seem to be any discernible pattern in the requests that get stuck.
These servers are behind a load balancer, they were updated at the same time and both started exhibiting this issue at the time of the patching run. They were not rebooted at the time, but have been since with no effect.
I setup a script on the servers themselves to loop over time curl localhost:80/alive, which has a simple index.html file in it containing only "OK". Strangely these requests still get delayed with the same frequency and duration as requests for actual php content. The common times are 3 seconds, 9s, 25s 45s and some are over 3 minutes. 45 seconds is a common response time but of course browsers give up well before this so it's effectively no response.
The apache worker config is as follows:
<IfModule mpm_prefork_module>
    StartServers        50
    MinSpareServers     10
    MaxSpareServers     150
    ServerLimit         500
    MaxClients          500
    MaxRequestsPerChild   5000
</IfModule>

It seems sensible to me for a server with 8gb of ram. In practice the worker count seldom goes over 170 so we're not hitting that limit and there is plenty of free memory. Load averages are low, they hover around 0.5-1.5
The kernel is an old backport so I tried updating it to the latest backport for lenny (2.6.32-bpo.5-amd64), but it panicked on boot and I had to get our host to restart it with the old one, so I'd like to explore other options before we try updating their bioses and formatting them with Debian 6.
Apache seems to be a likely culprit, so the next step is to update to the latest apache backport, but the version was a fairly minor bump from 2.2.9-10+lenny4 to 2.2.9-10+lenny9, so I wasn't expecting any significant changes.
PHP is installed, version 5.3.6 from dotdeb. Previous version was 5.3.0 custom compiled. In addition, my boss has just informed me that requests over https do not get delayed but I have not confirmed this myself.
# apache2 -V
Server version: Apache/2.2.9 (Debian)
Server built:   Dec 11 2010 21:34:00
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.12, APR-Util 1.2.12
Compiled using: APR 1.2.12, APR-Util 1.2.12
Architecture:   64-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT=""
 -D SUEXEC_BIN="/usr/lib/apache2/suexec"
 -D DEFAULT_PIDLOG="/var/run/apache2.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="/var/run/apache2/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="/etc/apache2/mime.types"
 -D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

# apache2ctl -t -D DUMP_MODULES
Loaded Modules:
 core_module (static)
 log_config_module (static)
 logio_module (static)
 mpm_prefork_module (static)
 http_module (static)
 so_module (static)
 alias_module (shared)
 auth_basic_module (shared)
 authn_file_module (shared)
 authz_default_module (shared)
 authz_groupfile_module (shared)
 authz_host_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 cgi_module (shared)
 deflate_module (shared)
 dir_module (shared)
 env_module (shared)
 geoip_module (shared)
 mime_module (shared)
 negotiation_module (shared)
 php5_module (shared)
 rewrite_module (shared)
 setenvif_module (shared)
 ssl_module (shared)
 status_module (shared)
Syntax OK

Any assistance greatly appreciated!
Answer: Been banging my against the wall on this for a week now, and my boss has fixed it.
Once we looked at Apache's response times in the logs we saw that it was responding quickly - the delays were happening before the request even reached Apache. Thus he looked at the tcp stack settings, comparing them to another server running Red Hat 5.6.
To cut a long story short, enabling tcp syn cookies (net.ipv4.tcp_syncookies=1 in /etc/sysctl.conf) has fixed the problem. This setting is designed to protect against SYN floods and apparently does allow faster responses. It's possible we're getting flooded accidentally (or deliberately).
More info is in this link, the symptoms described are exactly what we were seeing: http://baheyeldin.com/technology/linux/detecting-and-preventing-syn-flood-attacks-web-servers-running-linux.html
I was looking at netstat -alnt and the vast majority of connections were in state TIME_WAIT, not SYN_RECV (maybe the -l option doesn't show half-open connections).
However we are now seeing this in dmesg frequently:
possible SYN flooding on port 80. Sending cookies.

I shall do some more digging.
Comment: That message means your SYN queue gets repeatedly full. That may be due to legitimate requests or not. If the requests are legitimate, you can increase the size of the queue with  tcp_max_syn_backlog. See http://www.linuxinsight.com/proc_sys_net_ipv4_tcp_syncookies.html and http://www.redhat.com/archives/rhl-devel-list/2005-January/msg00447.html
Comment: I love you!! I really love you!
Comment: Thanks! Yes, it could well be legitimate traffic so I've set net.ipv4.tcp_max_syn_backlog = 4096.
Still seeing possible SYN flood messages though, one would think quadrupling it would be plenty for legitimate traffic.
Comment: I would personally try to use a big number, like 16 or 64K to make sure it's not an attack (on an attack virtually every limit would get surpassed), and if it's not an attack, I would gradually diminish the queue size until a good small value is found)
Comment: I've raised it to 65536 but am still getting possible SYN flooding on port 80. I've been watching the number of connections in SYN_RECV state (on a terminal running `watch --interval=5 'netstat -tuna |grep "SYN_RECV"|wc -l'` and it never goes higher than about 240. Yet I have a Red Hat server which hovers around 512 (limit on this server is the default of 1024). Do you now of any other settings which might impact the maximum size of the backlog?
Comment: Not sure, you should probably now open a followup question on how to tune / debug SYN queue issues


What happens to this infinite sum?

Question: Assume $W$ is $n$ by $n$ matrix and $r<1$ is a real number. Let $$Q = \sum_{i=0}^{\infty} (rW)^i=[I_n-rW]^{-1}$$
Now assume that the $i$'th row of matrix $W$ is multiplied by a constant real number $c$. Let this new matrix $U$. Let $$P=\sum_{i=0}^{\infty} (rU)^i=[I-rU]^{-1}$$ I am very intersted to know the relation between $Q$ and $P$ and if we can express entries of $P$ in terms of entries of $Q$.
Thanks.
Comment: It is worth pointing out that $\sum_{i=0}^{\infty} (rW)^i=(I_n-rW)^{-1}$ does not always hold even if $r<1$.
Comment: Interesting. When it does not hold?
Comment: Yes yes you are right, I forgot to mention that entries of $W$ are all less than 1. Thanks
Answer: We have
$$U = \underbrace{\text{Diagonal matrix}(1,1,\ldots,c,1,\ldots,1)}_C W \tag{$\star$}$$
We have $$I - rW = Q^{-1} \implies W = \dfrac{I-Q^{-1}}r\text{ and } I -rU = P^{-1} \implies U = \dfrac{I-P^{-1}}r$$
Hence, from $(\star)$, we get that
$$\dfrac{I - P^{-1}}r = C\dfrac{I-Q^{-1}}r$$
\begin{align}
P & = \left(I - C\left(I-Q^{-1} \right) \right)^{-1} = \left(CQ^{-1}+I-C\right)^{-1} = \left(CQ^{-1} + (1-c)e_i e_i^T\right)^{-1}\\
& = QC^{-1} - (1-c)\dfrac{QC^{-1}e_ie_i^T QC^{-1}}{1+(1-c)e_i^T QC^{-1} e_i} \left(\text{By Sherman Morrison} \right)
\end{align}
You can look up Sherman Morrison here.
Comment: Thanks for your comment. Yes, but as I said I believe $P$ has some relation with $Q$ (and not $Q^{-1}$) and I am looking for that.
Comment: @user54626 Have updated it now.
Comment: Wow! Thanks a lot for the reference. Very helpful!
Comment: Another question: What happens if the whole matrix $W$ is multiplied by constant $c$ (Instead of just one row). Then is there any relation between $P$ and $Q$? (simpler than $n$ times using Sherman-Morrison formula)

What happens to this infinite sum?