Filling a list with a variety of matrices which are samples from a matrix

Question: I'm wanting to fill a list with many different matrices which are created by selecting a variety of different samples from an original matrix. Then repeat this process 10 times. I managed to do it (after much fighting/painful learning process). I would be so grateful if someone could point me in the right direction to get rid of my redundant code and improve the functions I'm using (maybe even get rid of the loops which I gather are rather frowned upon).
My problem hinged on getting the different sized matrices out of the loop.
Here's the code I used, one day I aspire to write R code that is not ugly:
##defining a matrix called allmat
allmat <- matrix(rnorm(100), nrow=50, ncol=2)

##sampling different sizes of the allmat matrix from 0.1*allmat to 10*allmat
for(i in seq(0,9,by=1)) {
  for(j in seq(0.1,10,by=0.05)) {
    nam <- paste("powermatrix_",j,"_",i,sep="")
    assign(nam, allmat[sample(nrow(allmat),replace=T,size=j*nrow(allmat)),])
  }
}

##then using apropos to pick out the names of the matrices from file
##eventually converting matrix list into a list to then use lapply
matrixlist <- data.frame(apropos("powermatrix_"), stringsAsFactors = FALSE)

##then rather horribly trying somehow to get my dataframe into a
## list which eventually I do below (but although inelegant this bit is
## not crucial)

colnames(matrixlist) <- "col1"
matrixlist_split <- strsplit(matrixlist$col1, "_")
library("plyr")
df <- ldply(matrixlist_split)
colnames(df) <- c("V1", "V2", "V3")
vector_sample <- as.numeric(df$V2)
mynewdf <- cbind(vector_matrices,vector_sample)

##creating the list before lapply
mylist <- as.list(mget(mynewdf$col1))

##then with the list I can use lapply (but there has to be a much
## much better way!)

Comment: Does `OUT <- sapply(seq(0.1,10,by=0.05),function(y){sapply(1:10,function(x){allmat[sample(nrow(allmat),replace=T,size=0.1*nrow(allmat)),]}, simplify = F, USE.NAMES = T)}, simplify = F, USE.NAMES = T)` work?
Comment: We need `vector_matrices`.
Answer: Many thanks for all your input. This is now working much better with the following two lines. I didn't know you could seq_along or seq with lapply. These two in combination are very helpful.
this vector changes the size and repititions of the matrix sampled
seq_vector    <- c(rep(seq(0.1,1,by=0.1),each=10))

this samples the matrix for all of the sizes and repeats defined by the sequence vector
myotherlist   <- lapply(seq(seq_vector), function(x)   allmat[sample(1:nrow(allmat), replace=T, size=x*nrow(allmat)),])


csvHelper sort dynamic data

Question: Can anyone help me to understand how we can sort data in csvHelper before we write to string object? I am trying with Key but it is not working in case when there is dynamic data.
        string source = "James,Anthony,Mary\n,10,\n21,,212";

        using var reader = new StringReader(source);
        using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
        var records =  csvReader.GetRecords<dynamic>().ToList();

        var orderedRecords = records.OrderBy(r => r.Key);

        using (var writer = new StringWriter())
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(orderedRecords);

            Console.WriteLine( writer.ToString());
        }

I am getting following exception.
CsvHelper.WriterException: 'An unexpected error occurred.
  IWriter state:
  Row: 1
  Index: 0
  HeaderRecord:
  1
  '

The expected output I am looking for is,
   Anthony,James,Mary //--> Header Sorted Alphabetically
   ,10,               //--> First Row Sorted as per Header
   21,,212            //--> Second Row Sorted As Per Header

I appreciate your help on this.
Comment: Your CSV source looks not correct. What is your definition of dynamic data?
Comment: @Maytham I am getting this as a string from API. The `source` has the sample string in the code
Comment: You need to find a way to unifying your input data so your code gets correct CSV format
Answer: After updating the question.
You need to use James, Antony or Mary instead of 'Key' to sort data and the code works:
var source = $"James,Anthony,Mary\n,10,\n21,,212";

using var reader = new StringReader(source);
using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csvReader.GetRecords<dynamic>().ToList();

var orderedRecords = records.OrderBy(r => r.James);

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(orderedRecords);

    Console.WriteLine(writer.ToString());
}

P.S. It's very dangerous when you use dynamic to read data, usually we use stable data table.
Comment: @Aqdas, To get the output result, you can use Linq:
```source.Split('\n').Select(line => line.Any(element => char.IsDigit(element)) ? line.Split(',').ToArray() : line.Split(',').OrderBy(word => word).ToArray())
```
Comment: @Busuev, I think there was some confusion. I have updated my question and added expected output.
Comment: Thanks, But its not sorted alphabetically. How I can do that?
Comment: and what If the source has `ADAM` in header. So I appreciate assistance on sorting it alphabetically.

csvHelper sort dynamic data


making a ordered pair from a two tables in mathematica

Question: I had to recreate a youtube video that shows eight points moving in a straight lines but makes a circle rolling on the edges. I eventually made the program but I'm trying to generalize it so I can make it with different shapes. I used the code I had before but I am having trouble making an ordered pair that will work with the code. Every time I compile I get an error saying the points have to be ordered pairs but I can't figure out how to make the two tables ordered pairs.
p = 8; (*Number of points*)
\[Phi] = \[Pi]/p; (*Phase Shift*)
n = 1; \ (*Some integer*)
nump = 8; (* Number of points*)
total = nump - 1;  (* Shift number of points by -1*)

w[t_] := t^n; (* Random angular frequency*)
\[Theta][q_] = \[Phi]*q;
A1[q_] := Cos[\[Theta][q]];
A2[q_] := Sin[\[Theta][q]];
x[t_] = A1[q]*Cos[w[t] + \[Theta][q]];
y[t_] = A2[q]*Cos[w[t] + \[Theta][q]];
x1t = Table[ A1[q]*Cos[w[t] + \[Theta][q]], {q, 0, total}];
y1t = Table[ A2[q]*Cos[w[t] + \[Theta][q]], {q, 0, total}];

(*mylist = Transpose[List[x1t,y1t]]*)
mylist = Flatten[{x1t, y1t}, {2}]

pcircle =
ParametricPlot[{Transpose[List[x1t, y1t]], {Cos[t], Sin[t]}}, {t, 0,
2 \[Pi]}, PlotLegends -> "Expressions"]
Animate[Show[pcircle,
Graphics[{PointSize[Large], Black,
Point[Dynamic[{Flatten[{x1t, y1t}, {2}]}]]}]], {t, 0, 2 \[Pi],
AppearanceElements -> None}]

Answer: you have a scoping problem, the animation iterator t is not the same as the global t in x1t,y1t.  This works:
Animate[Show[pcircle,
  Graphics[{PointSize[Large], Black,
    Point[Dynamic[{Flatten[{x1t,y1t}/. t -> ta, {2}]}]]}]], {ta, 0, 2 \[Pi],
  AppearanceElements -> None}]

you could also fix this by making x1t explicitly a function of t
x1t[t_] = ...

then using x1t[t] everywhere.


Issue running energyplus using eppy idf.run()

Question: I'm having a problem running the following chunk of code in Jupyter Notebook:
i=[0,1,2,3]
from eppy.runner import run_functions
for i in i:
    OA.Economizer_Control_Type = ECT[i]
    idf1.saveas('C:/Users/mdahdolan/Dropbox/Work and Studies/Economizer
    Study/Python/1A_Small_Office.idf')
    print(OA.Economizer_Control_Type)
idf1.run(verbose='v')

and I'm getting this error:
om/bEI6B.jpg
Answer: You have issues with the path in the function saveas(), check that the route is available, exists and you can reach it without privileges ;)
Comment: The saveas() function is not related to the idf.run() function, each time I try to use idf.run() I get that error, otherwise, the saveas() function is doing exactly what it should, which is overwriting the previous idf file.


Jquery modal not working second time

Question: I am developing one application using codeigniter. In this application got a problem that modal window is not opening second time.
In detail .
I have form(view) which contains two select box and search button. User will select the options then click on search button it will  display a paginated result . I am using ajax to get the result. The pagination is also based on ajax. On this table result user can edit or update any of the records. Here comes the issue. I am displaying the update form inside a modal window. Inside that modal window I have to do some jquery validations. For that I am including jquery library. The moment when I hit on the edit button for the first time, the modal window is showing and second time it is throwing an error
Uncaught TypeError: Object [object Object] has no method 'modal'

If I removed the jquery library from the modal window then it is working fine.
The code which I am using on this is
My first view

Modal form in the same page.

    <button type="button" class="close" data-dismiss="modal">×</button>

Update Schedule

    Close
    Save changes

please tell what is the issue with this. How can I include the jquery library inside the modal window.
Comment: OK but than you should use the `noConflict` mode to avoid object conflict of either version; see this http://stackoverflow.com/q/1566595
Comment: Why are you loading two different instances of jQuery on the same page?
Comment: @Vishal sorry I am novice in jquery. please tell me which two instance you are talking about.
Comment: ``
`` -  I guess both will load jQuery to your site.. try removing one of those.
Comment: thanks . I am using both versions of jquery in my application
Answer: I see a minor issue with misplaced braces, not sure if it can cause this issue: you need to replace :
        });
        }
    });
  });

with :
        });
    });
});

at the end of the script.

Jquery modal not working second time


Flask-SQLAlchemy queries

Question: I am having issues with a seemingly simple sqlalchemy query using Flask.
I have a table called Links and within that table there are columns called 'id', 'author_id', 'link', and 'group'. My models.py looks like this:
class Links(db.Model):

__tablename__='links'

id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
link = db.Column(db.String, unique=False, nullable=True)
group = db.Column(db.String, unique=False, nullable=False)

def __init__(self, author_id=None, link=None, group=None):
    self.author_id = author_id
    self.link = link
    self.group = group

def __repr__(self):
    return'<Link %r>' %(self.link)

I would like to return the values of all groups associated with the user that is logged into the application. Here is my views.py file:
 @app.route('/members/', methods=['GET','POST'])
@login_required
def members():
    error=None
    form = PostLink(request.form, csrf_enabled = False)
    uid = session['user_id']
    link = "NULL"
    groups = Links.query.filter_by(author_id=uid).all()

    if request.method=='POST':
        if form.validate_on_submit():
            new_group = Links(
                       uid,
                       form.group.data,
                       link,
                       )
            try:
                   db.session.add(new_group)
                   db.session.commit()
                   flash("You have created a group!")
            except IntegrityError:
                    error = 'That group did not work, maybe it already exists?'
            else:
             flash_errors(form)
    return render_template('members.html', form=form, error=error, link = link, groups=groups)

And my 'members.html':
{% extends "base.html" %}

{% block content %}

Add New Group: {{ form.group }}

  <input id="link" type="hidden" name="link" value= {{ link }}/>

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

</form>

{% for group in groups %}

{{ group }}

{% endfor %}

{% endblock %}

Currently this is just returning a list of links and groups in an odd format:
<Link u'link2'>

<Link u'linky'>

<Link u'linkymaybe'>

<Link u'madeit'>

<Link u'BLAH'>

So the core of my question is how do I build a query using SQLAlchemy to display all groups associated with the logged in user (uid = session['user_id']) I am pretty new to Flask and this problem is becoming an issue as I have tried a number of filter_by and filter statements with no luck at all.
Thank you in advance!
Answer: It is displaying correctly the object "Link" returned by the query.
You need to format it in the template.
Thisi is link {{ group.link }} from author #{{ group.author_id }} in group named {{ group.group }}

Maybe you've chosen a bad name "group" when cycling on results in the template. It should be called link.
Comment: Thank you! This worked great. One more question. How can I filter the output to show no duplicate groups?
Answer: In the template, you can show the group name using {{ link.group }} instead of {{ link }}. The query is returning the whole object.

Flask-SQLAlchemy queries


Applying a mathematical function to a list of factors in python

Question: I have a function that returns a list of the factors of a number "n":
def factors(n):
    i = 2
    factlist = []
    while i <= n:
        if n% i == 0:
            factlist.append(i)
        i = i + 1
    return factlist

Now I'm trying to create a function that counts how many times a factor is a factor of n. I have a function called "howManyTimesDivides" that returns this:
def howManyTimesDivides(n, d):
    i = 0
    while n%d==0:
        n /= 2
        i += 1
    return i

Now, I'm trying to combine these two, but I cannot seem to apply the howManyTimesDivides function to a list "a = factors(n)". Here's what I have:
from collections import Counter
def factorCounts(n):
    a = factors(n)
    map(howManyTimesDivides(n,a), a)
    return dict(Counter(divides))

Any insights?
Answer: You could use a list comprehension:
def factorCounts(n):
    a = factors(n)
    b = [howManyTimesDivides(n, i) for i in a]
    return b

print(factorCounts(20))

Output:
[2, 1, 3, 2, 1]


How to split a string if there is no common delimiter

Question: I have a text file named headers.txt containing several FASTA inputs. I have to break apart the header for each of them into individual columns containing the ID, sequence name, node number, sequence length and sequencing type. Each of them should be in their own separate column in the same data frame.
They are written out as follows (headers.txt)
NZ_MCQZ01000071.1:2282-2767 Klebsiella pneumoniae strain TR196 Scaffold45_1, whole genome shotgun sequence

RYOH01000117.1:3-590 Klebsiella pneumoniae strain 16WZ-131 NODE_117_length_2026_cov_233.332478, whole genome shotgun sequence

RYOJ01000145.1:3-857 Klebsiella pneumoniae strain 16WZ-128 NODE_145_length_2293_cov_224.091606, whole genome shotgun sequence

NZ_CABWRH010000049.1:1707-2128 Klebsiella pneumoniae strain SRRSH43 isolate SRRSH43, whole genome shotgun sequence

RYQS01000239.1:1916-2698 Klebsiella pneumoniae strain 16HN-12 NODE_239_length_2763_cov_7.539092, whole genome shotgun sequence

Information on header based on last sequence
ID: RYQS01000239.1:1916-2698

sequence name: Klebsiella pneumoniae strain 16HN-12

node number: NODE_239

sequence length: length_2763_cov_7.539092

sequencing type: whole genome shotgun sequence

My problem is that these .txt files can contain hundreds of FASTA inputs such as these with some containing the necessary information and some do not (for example some state the length and some do not), such as the example sequence headers given above. Thus, the column should still be generated but left open if the necessary data is not found.
I have tried using strsplit, however i can't find a delimiter that works for all of them and this is as far as I have gotten
library("Biostrings")

fastaFile <- readDNAStringSet("~/ex1/headers.txt")
seq_name = names(fastaFile)
df <- data.frame(seq_name)

library(stringr)
df[c('ID', 'Sequence name','Sequence length','Node number','Sequencing type')] <- str_split_fixed(df$seq_name, ' ', 5)

df <- df[c('ID', 'Sequencing name', 'Sequence length','Node number','Sequencing type')]

The data frame should look like this

ID
Sequence name
Node number
Sequence length
Sequencing type

RYQS01000239.1:1916-2698
Klebsiella pneumoniae strain 16HN-12
NODE_239
length_2763_cov_7.539092
whole genome shotgun sequence
Answer: You could use a kind of look-behind to the colon plus some text until the space. Since (?<=:\w+-\w+) won't work because of varying length, we may use \K which resets the match at this point. The other regex are straightforward.
readLines('headers.txt') |>
  {\(.) .[. != '']}() |>
  strsplit(':\\w+-\\w+\\K\\s|\\sNODE_|_length_|_cov_|,\\s', perl=TRUE) |>
  {\(.) lapply(., `length<-`, max(lengths(.)))}() |>
  lapply(\(x) {g <- grepl('genome', x);if (any(g)) {x[length(x)] <- x[g]; x[g] <- NA};x}) |>
  do.call(what='rbind.data.frame') |>
  type.convert(as.is=TRUE) |>
  setNames(c('ID', 'name', 'node', 'length', 'cov', 'type'))
#                               ID                                                 name node length        cov                          type
# 1    NZ_MCQZ01000071.1:2282-2767      Klebsiella pneumoniae strain TR196 Scaffold45_1   NA     NA         NA whole genome shotgun sequence
# 2           RYOH01000117.1:3-590                Klebsiella pneumoniae strain 16WZ-131  117   2026 233.332478                          <NA>
# 3           RYOJ01000145.1:3-857                Klebsiella pneumoniae strain 16WZ-128  145   2293 224.091606                          <NA>
# 4 NZ_CABWRH010000049.1:1707-2128 Klebsiella pneumoniae strain SRRSH43 isolate SRRSH43   NA     NA         NA whole genome shotgun sequence
# 5       RYQS01000239.1:1916-2698                 Klebsiella pneumoniae strain 16HN-12  239   2763   7.539092                          <NA>

See the demo.
Note: R >= 4.1 used.


Limite entre jornada - SQL Server 2008

Question: Boa tarde,
gostaria de fazer uma SQL para controlar o limite da última batida do ponto dos funcionários com a primeira do outro dia, filtrando a quantidade de vezes que o cálculo deu menos que 11 horas por exemplo.
Tenho os dados abaixo, então por exemplo, pegaria o valor da última batida do dia 22 menos a primeira do dia 23 e se a diferença for menor que 11 horas o valor aparece, e assim por diante, em datas seguidas, se a diferença entre datas for maior que 1 ele ignora o cálculo.
CHAPA       DATA        BATIDA

005770    | 22/04/2015  | 07:17

005770    | 22/04/2015  | 11:39

005770    | 22/04/2015  | 13:02

005770    | 22/04/2015  | 20:23

005770    | 23/04/2015  | 07:21

005770    | 23/04/2015  | 12:59

005770    | 23/04/2015  | 16:56

005770    | 24/04/2015  | 07:31

005770    | 24/04/2015  | 11:35

005770    | 24/04/2015  | 13:00

005770    | 24/04/2015  | 17:33

Comment: Rafael, você quer saber a diferença de tempo entre uma batida e outra?
Comment: boa tarde Felipe, exato, a diferença entre a ultima batida de uma data por exemplo a do dia 22 e a primeira do dia 23. preciso filtrar os funcionários que tiveram menos de 11 horas de descanso entre os dias.
Answer: Calcular a diferença entre as duas datas de forma fiável não é muito fácil, mas podes fazer o seguinte:
;with cte as (

  select chapa,
         data,
         min(cast(data as datetime) + cast(batida as datetime)) primeira_batida,
         max(cast(data as datetime) + cast(batida as datetime)) ultima_batida,
         row_number() over (partition by chapa order by data) rn
  from tbl_registos
  group by chapa, data

)
select c1.chapa,
       c1.data,
       c1.ultima_batida,
       c2.data,
       c2.primeira_batida,
       convert(varchar(3), datediff(mi, c1.ultima_batida, c2.primeira_batida) / 60) + ':' +
          right('0' + convert(varchar(2), datediff(mi, c1.ultima_batida, c2.primeira_batida) % 60), 2) diferenca_horas
from   cte c1
inner join cte c2
   on c2.chapa = c1.chapa
  and c2.rn = c1.rn + 1
where convert(varchar(3), datediff(mi, c1.ultima_batida, c2.primeira_batida) /60) + ':' +
          right('0' + convert(varchar(2),datediff(mi, c1.ultima_batida, c2.primeira_batida) % 60), 2)
          < '11:00'

Para a uma tabela com os seguintes dados
CHAPA       DATA        BATIDA
005770    | 22/04/2015  | 07:17
005770    | 22/04/2015  | 11:39
005770    | 22/04/2015  | 13:02
005770    | 22/04/2015  | 20:23
005770    | 23/04/2015  | 07:21
005770    | 23/04/2015  | 12:59
005770    | 23/04/2015  | 16:56
005770    | 24/04/2015  | 07:31
005770    | 24/04/2015  | 11:35
005770    | 24/04/2015  | 13:00
005770    | 24/04/2015  | 17:33

Este sera o output:
chapa     | data        | ultima_batida | data         | primeira_batida | diferenca_horas
005770    | 2015-04-22  | 20:23:00      | 2015-04-23   | 07:21:00        | 10:58

Podes verificar o SQLFiddle.
Isto irá devolver os funcionários que tiverem menos de 11:00 de diferença entre a hora de saída e a hora de entrada (em dois dias consecutivos). Repara que se a diferença for 11:01 eles não serão mostrados. Penso que seja isto que queres. Se precisares de alguma explicação, ou ajuste na query, avisa!
Comment: Bruno, deu certo. muito obrigado pela força

Limite entre jornada - SQL Server 2008


Jquery An Input value change according to another field

Question: Right now, when one field change, the other field change accordingly.
What i want to do is originally the 2nd field  has some prefilled input from database, and when the 1st input field was fill in by the user, i want to keep the data from database plus adding the text input by the user after the database data.
The problem currently is when new input was enter, the original data retrieved from the db disappear. Any solution?/ Many thanks

addEvent(document.getElementById('name'), 'keyup', function () {
   document.getElementById('url').value = this.value.replace(' ');
});

function addEvent(ele, evnt, funct) {
  if (ele.addEventListener) // W3C
    return ele.addEventListener(evnt,funct,false);
  else if (ele.attachEvent)  // IE
    return ele.attachEvent("on"+evnt,funct);
}
<form>
    <input type="text" id="name" />
    <input type="text" id="url" />
</form>
Answer: Try this:

var oldValue = document.getElementById('url').value;
addEvent(document.getElementById('name'), 'keyup', function () {
   document.getElementById('url').value = oldValue + this.value.replace(' ');
});

function addEvent(ele, evnt, funct) {
  if (ele.addEventListener) // W3C
    return ele.addEventListener(evnt,funct,false);
  else if (ele.attachEvent)  // IE
    return ele.attachEvent("on"+evnt,funct);
}
<form>
    <input type="text" id="name" />
    <input type="text" id="url" value="www." />
</form>

here www. is already filled in second textbox, what ever you type in first texbox will append to the text in second textbox.
Comment: Note that if you hit space, it sometimes write undefined
Comment: Thank you so much.It works. What if the 1st field isn't from user, it's a field know as nextdate, it automatically displays a date according to the startdate user select. So can the 1st textbox append to the 2nd textbox automatically as well? Thanks in advance
Comment: Work around is required for that
Answer: Why dont you keep it simple ,since you have tagged it in jQuery ,here's my answer:

if(typeof set =="undefined"){
var set = $("#url").val();
}
$("#name").on('keyup',function(){

$("#url").val(set+$(this).val());

});

<form>
    <input type="text" id="name" />
    <input type="text" id="url" value="asdas"/>
</form>


How can I delete data from my array with the key value?

Question: I am trying to delete all the data from within a specific key in my array, but cant work out why my code isn't working. I have used print_r to check the code works and I can see that the correct value is being printed for each array when I click the 'remove' button, but it isn't removing the data from the key.
My current array looks like this:
Array
(
    [0] => Array
        (
            [0] => S30813-Q100-X303
            [1] => 5
            [2] => Refurbished
        )

    [1] => Array
        (
            [0] => JX-1T1-LTU
            [1] => 8
            [2] => New
        )

)

I am outputting the data to a table with:
        for ($row = 0; $row < $totalcount; $row++) {
        echo "
";
        for ($col = 0; $col < 3; $col++) {
            echo "".$contents[$row][$col]."	";

            }
        for ($col = 0; $col < 1; $col++) {

            $del = $row;
            echo "<form action='' method='post'><input type='text' name='del' value=".$row."></input><input type='submit' name='deletepart' value='Remove'></input></form>	";
        }
        echo "
";
        }

Front-end:

My php to unset the array key (and where I am guessing the problem lies) is:
<?php

    if (isset($_POST['deletepart'])) {
        $value_to_delete = $_POST['del'];
        $value_to_delete = $key;

        unset($_SESSION['arr'][$key]);
        $_SESSION["arr"] = array_values($_SESSION["arr"]);
    }

?>

Any help on where I am going wrong here would be very much appreciated!
Comment: You are overwriting the value for `$value_to_delete` in `$value_to_delete=$key` replace it with `$key = $value_to_delete`
Comment: where is `$key` data comes?
Comment: @AbdullahRazzaki ...That has done it! Thanks
Answer: try this
write $key = $value_to_delete; instead of $value_to_delete = $key
<?php

    if (isset($_POST['deletepart'])) {
        $value_to_delete = $_POST['del'];
        //$value_to_delete = $key; //instead of this use
         $key = $value_to_delete;

        unset($_SESSION['arr'][$key]);
        $_SESSION["arr"] = array_values($_SESSION["arr"]);
    }

?>

Comment: or use `unset($_SESSION['arr'][$_POST['del']]);`


Out of tune and Buzzing

Question: I recently replaced the nut and saddle and put new strings on my acoustic. My guitar does not play in tune, even after I know I've turned it correctly. Some chords sound in tune while others don't.
Frank
Comment: Need a pic of what you've done.
Comment: Hi Frank - the reason pictures would be essential here is that it sounds like you have altered the scale length of the guitar, or in some way messed up the intonation.
Answer: A new nut and saddle are essentially new boundary conditions for the string.  Assuming that they are placed correctly on the guitar (pics please) my guess would be that they are no adjusted yet.  The nut grooves may not be low enough and that forces you to press a little harder and will cause the strings to bend out of tune.  This is just a guess.  How much work did you do after the replacement to tweak everything else into proper adjustment?  For example the truss rod may need a tweak.

Out of tune and Buzzing


How can I tell if it is an object or an array?

Question: I want to know the type of the variable put in the function. So, I used typeof and like this:
randomFunctionName: function(obj){
    switch(typeof obj){
        case "object":
           //Something
        case "text":
            //Something else
    }
}

But the problem is, I can't tell if obj is an array or an object, since
typeof [] === "object"  //true
typeof {} === "object"  //true

So, how I can I separate them? Is there any difference between them?
Comment: Search terms were `determine object or array`
Comment: I think this is a common advanced topic, such as here: http://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array
Comment: Another example is http://stackoverflow.com/questions/6844981/distinguish-between-array-and-hash-in-javascript-with-typeof
Comment: Or here: http://stackoverflow.com/questions/5336090/is-this-an-acceptable-way-to-determine-if-an-object-is-an-array-in-javascript
Comment: How can you find those links? I searched for a few times and what I found is `nothing` related.
Comment: Well, looks like I am not so good at searching stuffs.
Answer: An array is an object.  You can test if an object is an array as follows:
Object.prototype.toString.apply(value) === '[object Array]';

You can wrap this up into a function as follows:
function isArray(a)
{
    return Object.prototype.toString.apply(a) === '[object Array]';
}

Comment: Is `[object Array]` the same in every browser?
Comment: Yes, this will work for any browser that is ECMAScript compliant, which should be all browsers.
Answer: check the constructor:
[].constructor == Array  //true
{}.constructor == Object  //true

Comment: `{}.constructor` --> `SyntaxError: Unexpected token .`
Comment: I see the image but I don't get the error in chrome(the image looks like chrome)
Comment: I am using Chrome 20.0.1115.1  Do you think it is a bug of Chrome or did I do something wrong?
Comment: The latest version I can get (winXP) is 18.0.1025.162 m and i don't get any  error. chrome19 is BETA and chrome20 is dev, so I don't have do care about them because they don't have to be stable.
Comment: I am actually using the dev channel, but I don't think that will affect JavaScript?
Answer: Since ECMAScript 5 you can use the native method:
Array.isArray( maybeArray );

If compatibility is of concern you can use Underscore.js or jQuery:
_.isArray( maybeArray ); // will use the native method if available
$.isArray( maybeArray );

This kind of utility is also present in AngularJS.
Answer: This is pretty simple. Try something like
var to = {}.toString;
alert(to.call([])); //[object Array]
alert(to.call({})); //[object Object]


show that symmetric and anti-symmetric matrices are eigenvectors for linear map

Question: Consider the linear map
$$L:Mat_{nxn}(\mathbb{R})\rightarrow Mat_{nxn}(\mathbb{R}),\\
M\mapsto 4M-7M^T$$
a) Prove that any symmetric or anti-symmetric matrix is an eigenvector for $L$.
b) Is $L$ diagonalizable? Justify.
Solution:
Let $M$ be symmetric ($M=M^T$), then $L(M)=4M-7M^T=4M-7M=-3M=(-3)M$ where $-3$ is an eigenvalue an $M$ the eigenvector.
The same for $M$ anti-symmetric ($M=-M^T)$. Does this prove a)?
Comment: @AUDLIQWD  It is **not** okay to render your question meaningless, after three users answered your question.
Comment: you have changed your solution after my answer !!
Answer: An operator $T: V \to V$ is diagonalizable if $V$ is spanned by the eigenvectors of $T$.
Once you have the all symmetric and anti-symmetric matrices are eigenvectors, the next step is to see if all of $\text{Mat}_{n\times n}$ is spanned by those matrices. Now observe that any matrix $A$ can be written as the sum of a symmetric and anti-symmetric matrix as follows:
$$A = \frac{A - A^T}{2} + \frac{A+A^T}{2}  $$
Therefore, your operator is diagonalizable.
Answer: Remark: You have to investigate the linear operator $L$ !

Let $M \ne 0$ be symmetric, then

$$L(M)=4M-7M=-3M,$$
hence $-3$ is an eigenvalue of $L$ and $M$ an corresponding eigenvector.

Let $M \ne 0$ be anti-symmetric, then

$$L(M)=4M+7M=11M,$$
hence $11$ is an eigenvalue of $L$ and $M$ an corresponding eigenvector.
Comment: Just a curiosity! Does L have any eigen value other than 11 and-3?? And what is the AM of these two eigen values?(AM= Arithmetic Multiplicity)
Answer: As a quirky alternative for part b, you could show that for every $n\times n$-matrix $M$ you have
\begin{eqnarray*}
L^2(M)&=&L(4M-7M^{\top})\\
&=&4(4M-7M^{\top})-7(4M-7M^{\top})^{\top}\\
&=&65M-56M^{\top},
\end{eqnarray*}
from which it follows that
$$L^2(M)-8L(M)-33M=0,$$
and so the minimal polynomial of $L$ divides
$$X^2-8X-33=(X-11)(X+3).$$
Comment: Great answer! Still my curiosity is about the multiplicities of the eigen values. Of course AM=GM but is there anyway of finding AM?
Comment: Eigen value-3 has AM=(n^2 +n)/2 and eigen value 11 (n^2 +n)/2