Where and how to place apple-touch-icon in TYPO3 app

Question: I'm getting the following error in the backend:
Core: Exception handler (WEB): Uncaught TYPO3 Exception: #1518472189: The requested page does not exist |
TYPO3\CMS\Core\Error\Http\PageNotFoundException thrown in file /var/www/vhosts/my-doma.in/typo3/sysext/frontend/Classes/Controller/ErrorController.php in line 80.
Requested URL: https://my-doma.in/apple-touch-icon-120x120.png

To place an apple icon one apparently should add:
<link rel="apple-touch-icon" href="/path/to/apple-touch-icon.png">

somewhere, as seen here: https://stackoverflow.com/a/21144916/4120196
But given a TYPO3 (v9.5) application - Where and how should I to add this?
Comment: It can be in the page's template, extension's template, or even generated by TypoScript. We can not know that as you didn't give us any details. Please fix your question or it will be closed and/or downvoated.
Comment: What can you not know? I'm the one that doesn't know stuff here, that's why I'm asking :D One good solution is enough for me I don't need to know all of them. But I need a real example or a link to one. I don't know how to generate this with TypoScript.
Comment: You mention some TS part, which even didn't show us :) I'd like to know a way to read data from any computer in the net, but I don't sorry ;)
Comment: I guess you were distracted from my main question by my `shortcutIcon` sentence - I removed it now for a clearer question.
Comment: What I meant was that you mentioned that you used some TypoScript which causes the problem, but didn't show us the code, without which it was hard to know what's wrong. As I assume you found the solution, so that's good for you ;)
Answer: I found a way after stumbling on the headerData property - added this to my TypoScript root template:
page.headerData {
       1 = TEXT
       1.value = <link rel="apple-touch-icon" href="fileadmin/path_to_icons/apple-touch-icon.png">
}

And I found this answer when it comes to Android as well.
My android browser seemed to be happy already with the apple icon though.


multi dimensional php associative array

Question: I have this PHP code
      $RTPerDate['revenue'][$DateGroupped['date']] += $telco['revenue'];
      $RTPerDate['traffics'][$DateGroupped['date']] += $telco['traffics'];

Which produce this array
Array(
[revenue] => Array
    (
        [2015-10-01] => 166600
        [2015-10-02] => 578300
    )
[traffics] => Array
    (
        [2015-10-01] => 167
        [2015-10-02] => 576
    )

I want to make the array looks like this
Array(
[0] => Array
    (
        [revenue] => 166600
        [traffics] => 167
        [date] => 2015-10-01
    )
[1] => Array
    (
        [revenue] => 578300
        [traffics] => 576
        [date] => 2015-10-02
    )

Any help is appreciated. Thanks
Answer: EDIT
Do you perhaps mean you want it indexed by date?
$RTPerDate[$DateGroupped['date']]['revenue'] += $telco['revenue'];
$RTPerDate[$DateGroupped['date']]['traffics'] += $telco['traffics'];

Array(
[2015-10-01] => Array
    (
        [revenue] => 166600
        [traffics] => 578300
    )
[2015-10-02] => Array
    (
        [revenue] => 167
        [traffics] => 576
    )

Initial Answer
Something like this?
$RTPerDate[0]['revenue'] += $telco['revenue'];
$RTPerDate[0]['traffics'] += $telco['traffics'];
$RTPerDate[0]['date'] = $DateGroupped['date'];

$RTPerDate[1]['revenue'] += $telco['revenue'];
$RTPerDate[1]['traffics'] += $telco['traffics'];
$RTPerDate[1]['date'] = $DateGroupped['date'];

Comment: Thanks but not that one. Your solution will break the date group. The script is sum the revenue on each date so it is assumed that there are some revenue on the same date
Comment: I have made the array look the way you asked. Can you give more information on how it works and the intended functionality of the program? Put it in the description and show examples if possible.
Answer: Thanks all, I did small modification so the code like this
$RTPerDate[$DateGroupped['date']]['revenue'] += $telco['TheRevenue'];
$RTPerDate[$DateGroupped['date']]['traffics'] += $telco['TheTraffics'];
$RTPerDate[$DateGroupped['date']]['date'] = $DateGroupped['date'];

And so the array becomes like this
Array (
[2015-10-02] => Array
    (
        [revenue] => 578300
        [traffics] => 576
        [date] => 2015-10-02
    )

[2015-10-03] => Array
    (
        [revenue] => 12825
        [traffics] => 13
        [date] => 2015-10-03
    )
)

Comment: "[date] => 2015-10-03" is redundant, its already stored as the index to itself. Excluding that, the result is exactly my answer. Please mark a correct answer.
Answer: Try this
$field['revenue'][$DateGroupped['date']] += $telco['revenue'];
$field['traffics'][$DateGroupped['date']] += $telco['traffics'];

$RTPerDate[]['revenue'] = $field['revenue'][$DateGroupped['date']];
$RTPerDate[]['traffics'] = $field['traffics'][$DateGroupped['date']];
$RTPerDate[]['date'] = $DateGroupped['date'];

var_dump($RTPerDate) to view formatted arrays.
Comment: it returns the same result as the previous one

multi dimensional php associative array


Como importar dados do ACCESS para MYSQL

Question: Tenho um db ACCESS com muitas tabelas e muitos dados registrados, preciso importar essas tables para meu novo dbem MYSQL. algúem sabe uma forma ? ou um tutorial pra seguir ?
Estou usando o MySQL-Front e o phpMyAdmin para fazer o gerenciamento.
Comment: Tenta esse programa http://www.bullzip.com/products/a2m/info.php
Comment: Funcionou perfeito @HugoLeonardo . Abraços.
Comment: Posso postar como resposta?
Comment: Opa, manda ver.
Answer: Usa o Access to MySQL. Neste link tem um tutorial (em inglês) sobre como utilizar: bullzip.com/products/a2m/info.php.
Answer: Utilize esse Software Acess To MySQL
Introduction
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
>  Wizard interface.
>     Transfer data directly from one server to another.
>     Create a dump file.
>     Select tables to transfer.
>     Select fields to transfer.
>     Transfer password protected databases.
>     Supports both shared security and user-level security.
>     Optional transfer of indexes.
>     Optional transfer of records.
>     Optional transfer of default values in field definitions.
>     Identifies and transfers auto number field types.
>     Command line interface.
>     Easy install, uninstall and upgrade.


integration of functions using greatest integer function

Question: Integrate the function $[sin(x)]$ where $[x]$ represent integral part of  $x$ from lower limit $0$ to upper limit  $(2n-1)\pi$......  now my problem I have seen that it is  symmetric about  odd $\pi/2$  but I am not able to form a definite pattern by drawing the graphs also please can anyone explain that how to deal with this
Comment: Please learn how to typeset the formulas with LaTeX.
Comment: Is $[-0.5] = 0$ or $[-0.5] = -1$? The latter is standard (it behaves nicer since it doesn't make $0$ or negative numbers special in any way but treats all numbers equally), but it's good to be clear.
Comment: @Arthur: the "truncate towards zero" definition would make the question fairly easy :)
Answer: The sine is positive for arguments in the even half-periods ($[2n\pi,(2n+1)\pi]$) and negative otherwise, so that the integer part is $0$ and $-1$ respectively. (The points where the sine is $1$ have zero measure and can be ignored.)
So your integral is $-\pi(n-1)$.


Why are the codes generated by $G$ and $[I_k \mid A]$ equivalent?

Question: I am using the monomial equivalence definition for the equivalence of linear codes, so two codes $C, C'$ are called equivalent if there is a monomial matrix $M$ such that $ C'=CM=\{cM : c \in C\}$.
Now I am trying to understand why for every $[n,k]$ code $C$ with some $k \times n$ generator matrix $G$ there exists an equivalent code $C'$ generated by $[I_k \mid A]$ where $I_k$ is the identity matrix and $A$ an $k \times (n-k)$ matrix.
I know that the matrix $[I_k \mid A]$ can be derived from $G$ by way of Gaussian elimination. This is done by multiplying elementary matrices to $G$. Now two types (those giving row-switching and row-multiplying operations) of elementary matrices are also monomial. But row-addition elementary matrices are not. If the linear codes generated by $[I_k \mid A]$  and $G$ are indeed monomially equivalent, then there must exist monomial matrices such that the rows of $G$ multiplied to these monomial matrices give the rows of $[I_k \mid A]$.
So I have some questions: How does is that possible if there are non-monomial row-addition elementary matrices involved? Perhaps it is possible to write the elementary matrices as a product of monomial matrices (I do not think so)? How do I prove the existence of monomial matrices fulfilling the above property?
Any help would be very much appreciated.
edit:
I now learned that Gaussian elimination is not always enough to obtain one matrix from another.
But in short, my question still is:
Van Lint says: It is well known from linear algebra that every linear code is equivalent to a code with generator matrix in standard form. Could anyone elaborate the reasoning in this statement?
Comment: That is true, I must have misunderstood something then. But how can I reason that the Codes generated by $[I_k\mid A]$ and $G$ are monomially equivalent? There then are even more operations involved, I am not sure if they can be even performed by monomial matrices.
Answer: I'll assume here that the alphabet $\ \Sigma\ $ of your codes is a field.
Note that $\ M\ $ is an $\ n\times n\ $ matrix which operates on the columns of $\ G\ $.  If $\ E\ $ is a $\ k\times k\ $ elementary matrix, the codes $\ \big\{x^TG\,\big|\,x\in\Sigma^k\big\}\ $ and $\ \big\{x^TEG\,\big|\,x\in\Sigma^k\big\}\ $ are not merely equivalent, but identical:
$$
\big\{x^TG\,\big|\,x\in\Sigma^k\big\}= \big\{x^TEG\,\big|\,x\in\Sigma^k\big\}
$$
because $\ E\ $ is invertible.  For the result you're asking about to hold, the rowspace of $\ G\ $ must have dimension $\ k\ $—i.e. it cannot have any redundant rows.  Since its column space must also have dimension $\ k\ $ then among its $\ n\ $ columns there must exist $\ k\ $ that are linearly  independent. Let $\ M\ $ be a permutation (and hence monomial) matrix such that $\ GM \ $ has $\ k\ $ linearly independent columns shuffled to the first $\ k\ $ positions.  There must now exist an invertible $\ k\times k\ $ matrix $\ V\ $ such that $\ VGM=\big[I_k\,\big|\,A\big]\ $ for some $\   k\times(n-k)\ $ matrix $\ A\ $.
Now if $\ C'\ $ and $\ C\ $ are the codes generated by $\ VGM=\big[I_k\,\big|\,A\big]\ $ and $\ G\ $, respectively, then $\ C'=CM\ $, and therefore $\ C'\ $ and $\ C\ $ are equivalent.
Comment: This was very helpful and enlightened some essential linear algebra I had long forgotten. Thank you!
Answer: Notice that in the definition of equivalence, you are multiplying the monomial matrix with the code C, not just with its generating matrix G.
Indeed, the key to the answer is that a linear code is identified with a linear subspace (such as C), not with a basis of that subspace (the rows G). The matrix G gives one particular basis, but all linear combinations of rows of G are codewords too! Rows of G can always be added "for free" simply because the code is linear.
Comment: Thank you, I completely missed that point! I assume this answers my question in conjunction with Morgan Rodgers's above comment, as permuting columns can also be done by monomial matrices.


Infinitely nested radical problem?

Question: I became interested in this nested radical from another question and thought I would have a go at trying to come up with a formula for it. It is $$G(0)=\sqrt{1+\sqrt{2+\sqrt{4+\sqrt{8+\cdots}}}}.$$ This can be written as a recurrence relation when evaluated at $x=0$: $$G(x)^2=2^x+G(x+1).$$ Due to Ramanujan, we know that for some function $F(x)$ such that $$F(x)^2=ax+(a+n)^2+xF(x+n)$$ we have $$F(x)=a+n+x.$$ We can put $G(x)$ and $F(x)$ into equatable forms by making $x=1, n=1, a=\frac{\sqrt{13}-3}{2}.$ Summing these and correcting for $G(0)$ we should have $$G(0)=\sqrt{1+\frac{\sqrt{13}-3}{2}+1+1}=\sqrt{\frac{\sqrt{13}+3}{2}}.$$ this gives $1.817354021023971.$ However the correct value for $G(0)$ is around $1.78316580926410.$ What is the error in my reasoning?
Comment: This is [OEIS A$257576$](http://oeis.org/A257576).
Answer: Your mistake was assuming that $F(x)$ and $G(x)$ are the same for any $x$ simply because they are the same for $x=1$:
$$G(1)=\sqrt{2^1+F(1+1)}=\sqrt{2+F(2)} \\
F(1)=\sqrt{\left(\frac{\sqrt{13}-3}{2}\right)(1)+\left(\left(\frac{\sqrt{13}-3}{2}\right)+1\right)^2+(1)F(1+1)}=\sqrt{2+F(2)}$$
But look at $x=2$:
$$G(2)=\sqrt{2^2+F(2+1)}=\sqrt{4+F(3)} \\
F(2)=\sqrt{\left(\frac{\sqrt{13}-3}{2}\right)(2)+\left(\left(\frac{\sqrt{13}-3}{2}\right)+1\right)^2+(2)F(2+1)} \approx \sqrt{2.3028+2F(3)}$$
So if you replace $G(x+1)$ with $F(x+1)$ in your definition of $G$ (as you did to solve), then $G(0)$ actually looks like this when expanded:
$$G(0)=\sqrt{\frac{\sqrt{13}+3}{2}} \approx\sqrt{1+\sqrt{2+\sqrt{2.3028+2\sqrt{2.6055+\dots}}}}$$
Comment: Okay. I see how it goes awry at $x\ne1$ but I really only care about it at the point where $x=1$. It seems to me that my case at that point should still hold, right? I then easily convert $G(1)$ to $G(0)$. I still don't see what's wrong.
Comment: I'm sorry if this confused you.  I just edited my answer for a mistake in the recurrence relation.  I changed the $F(x+1)$ to $G(x+1)$.
Comment: The recurrence relation $G(x)^2=2^x+G(x+1)$ is indeed equivalent to your original nested radical expression when evaluated at $x=0$. But this is *not* the case for relation $G(x)^2=2^x+F(x+1)$. These are not equivalent beyond the second layer, as I showed in my answer. The issue is that you assumed you had put $G(x)$ and $F(x)$ into equitable forms when you had not.

Infinitely nested radical problem?


CSS not applied to content loaded via AJAX in IE7

Question: I'm having a problem with IE7 specifically.  I have a tabbed content area and each tab's content is being loaded via AJAX.  This works fine in FF and Chrome but IE7 renders the AJAX loaded content incorrectly. Its as though some of the CSS styles aren't being applied only after the AJAX call.
The JS:
<code>// Set up the AJAX object parameters
var tabOptions = {
    type: 'GET',
    cache: false,
    url: '/wp-content/themes/iview/ajax/latest-posts.php',
    dataType: 'text',
    error: function(xhr, textStatus, errorThrown, XMLHttpRequest) {
        $('<p>Sorry, your request could not be completed at the moment due to ' + errorThrown + ' </p>')
            .appendTo('#tabbed-content')
    },
    success: function(html, textStatus) {
        $('#tabbed-content').find('#loader')
                            .remove()
                            .end()
                            .find('.jspPane')
                            .append(html);
    }
}
</code>
Comment: Which styles don't seem to be applied? Perhaps those particular styles are not very compatible with IE7?
Answer: There might be two elements with the same id. Make sure that the content of #tabbed-content doesn't have an element with an already used id.
Comment: Turns out I needed to load the latest HTML5 shiv for IE8 and below (currently using modernizr)

Thanks for your help


Forest Fire simulation in Octave or Matlab

Question: In this page https://courses.cit.cornell.edu/bionb441/CA/forest.m
I found a code named "Forest Fire"
I am trying to figure out how this code works for educational purposes.
Here are the rules:
Cells can be in 3 different states. State=0 is empty, state=1 is burning and state=2 is forest.
If one or more of the 4 neighbors of a cell is burning and it is forest (state=2) then the new state is burning (state=1).
A cell which is burning (state=1) becomes empty (state=0).
There is a low probablity (0.000005) of a forest cell (state=2) starting to burn on its own (from lightning).
There is a low probability (say, 0.01) of an empty cell becoming forest to simulate growth.
what it is not very clear how it works is...
sum = (veg(1:n,[n 1:n-1])==1) + (veg(1:n,[2:n 1])==1) + ...
       (veg([n 1:n-1], 1:n)==1) + (veg([2:n 1],1:n)==1) ;

veg = 2*(veg==2) - ((veg==2) & (sum> 0 | (rand(n,n)< Plightning))) + ...
     2*((veg==0) & rand(n,n)< Pgrowth) ;

There is no problem in running the code, it just I am confused what are these vectors (sum and veg). Especially what makes (veg(1:n,[n 1:n-1])==1).
What I see is that, both are matrixes and veg is the data of the plot (matriz with 0's 1's and 2's).
I really appreciate any help you can provide.
Comment: What is the problem/error that you have got? Please update.
Answer: Binary comparison operators on a matrix and a scalar return the matrix of elements of that binary comparison with the scalar and the corresponding element of the original matrix.
sum is a matrix in which each cell contains the number of adjacent cells in the corresponding matrix veg that are on fire (==1).
(veg(1:n,[n 1:n-1])==1) is a matrix of logical 1s and 0s (I don't know if the data type is static or dynamic) in which each cell equals 1 when the cell to the left of the corresponding one in veg is on fire (==1).
Answer: https://courses.cit.cornell.edu/bionb441/CA/
Look at the URL, go back up the tree to see the source.
The rule:
Cells can be in 3 different states. State=0 is empty, state=1 is burning and state=2 is forest.
If one or more of the 4 neighbors if a cell is burning and it is forest (state=2) then the new state is burning (state=1).
There is a low probablity (say 0.000005) of a forest cell (state=2) starting to burn on its own (from lightning).
A cell which is burning (state=1) becomes empty (state=0).
There is a low probability (say, 0.01) of an empty cell becoming forest to simulate growth.
The array is considered to be toroidly connected, so that fire which burns to left side will start fires on the right. The top and bottom are similarly connected.
The update code:
sum = (veg(1:n,[n 1:n-1])==1) + (veg(1:n,[2:n 1])==1) + ...
       (veg([n 1:n-1], 1:n)==1) + (veg([2:n 1],1:n)==1) ;

veg = ...
     2*(veg==2) - ((veg==2) & (sum> 0 | (rand(n,n)< Plightning))) + ...
     2*((veg==0) & rand(n,n)< Pgrowth) ;

Note that the toroidal connection is implemented by the ordering of subscripts.


Android:how to set tag with spinner item

Question: Is it possible to set tag with spinner item.I want to set my bean object as tag with each spinner item is it possible?
Answer: May this help you:
Create your Own CustomAdapter as shown Below and add tag in getView() Method of that..
CustomAdapter:
public class MySpinnerAdapter extends BaseAdapter  {

    private Activity context;

    public MySpinnerAdapter (Activity context){
        this.context=context;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RelativeLayout item= (RelativeLayout)context.getLayoutInflater().inflate(R.layout.<your spinner item layout name>, null);

      //set your data to layout components

      item.setTag(<your tag object>);

        return item;
    }
}

Comment: is this the only way?can't we do this with array adapter
Comment: @Agr1909 its customAdapter buddy.. like we customise the array adapter according to our requirement..
Answer: Use Custom Adapter And set the view.setTag(yourObject);


How to properly write a Win32 application using boost::asio to communicate over serial connection

Question: I'm developing a Windows application that has to communicate (both input and output) with an Arduino through its serial port. I'm using boost::asio for portability reasons and I want to keep using it. What happens is that the first time I run my application it works perfectly, but if I run it a second time, no data comes from the Arduino anymore and the application stucks on the read operation. The only way to recover is to unplug and replug the Arduino USB cable from the computer.
This behavior is Windows-specific. The same code works perfectly on Linux.
The compiler is Visual Studio 2017 Community Edition.
Here is an example code to reproduce the issue:
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <vector>

int main() {
  boost::asio::serial_port port(ioctx, "COM3"); // "/dev/ttyACM0" on Linux

  port.set_option(boost::asio::serial_port::baud_rate(9600));
  port.set_option(boost::asio::serial_port::character_size(8));
  port.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one));
  port.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none));
  port.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none));
  char c = 'e';
  auto const s = boost::asio::write(port, boost::asio::buffer(&c, 1));
  std::cout << "sent " << s << " bytes" << std::endl;
  boost::asio::streambuf response;
  boost::asio::read_until(port, response, "\r\n");
  std::istream response_stream(&response);
  std::string line;
  std::getline(response_stream, line);
  std::cout << line << std::endl;

  port.close(); // last-ditch effort to get it working
}

Here is an Arduino sketch (got from the Arduino website):
int incomingByte = 0;   // for incoming serial data

void setup() {
  Serial.begin(9600);   // opens serial port, sets data rate to 9600bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
  }
}

Is there a way to restore the correct state of the connection? Am I missing something?
Answer: After having learned a couple of things, here is the solution:

Arduino uses its USB communication for both burning the sketch and performing data transmission back and forth the PC. The boot sequence foresees that for 2 seconds (for new Arduino versions and standard boot loader) the communication towards the boot loader is active. After that time, the sketch is executed.
Windows API allows to set all connection parameters at once via the SetCommState function and to retrieve them in a similar fashion with the GetCommState one. That is the method the set_option function uses to set the parameters, but it happens that calling GetCommState-SetCommState multiple times in a row slows down the process a lot (maybe by resetting the Arduino multiple times).

I ended writing the following function:
    #include <Windows.h>
    #include <chrono>

    void init_arduino(boost::asio::serial_port& port, std::chrono::milliseconds const& sleep = 2000)
    {
      DCB dcbSerialParams = { 0 };
      GetCommState(port.native_handle(), &dcbSerialParams);
      // this is the optimal way to set the whole serial port configuration
      // just in one shot.
      dcbSerialParams.BaudRate = CBR_9600;
      dcbSerialParams.ByteSize = 8;
      dcbSerialParams.StopBits = ONESTOPBIT;
      dcbSerialParams.Parity = NOPARITY;
      //Setting the DTR to Control_Enable ensures that the Arduino is properly
      //reset upon establishing a connection
      dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;
      SetCommState(port.native_handle(), &dcbSerialParams);
      PurgeComm(port.native_handle(), PURGE_RXCLEAR | PURGE_TXCLEAR);

      // Wait for Arduino to boot the sketch
      Sleep(sleep.count());
    }

and using it to replace the port.set_option( lines in the question example.
I also set the flow control to DTR_CONTROL_ENABLE instead of the original none in order to reset the Arduino upon connection.
Answer: USB serial adaptors can have device driver bugs and hardware problems. The fact that you have to unplug and plug the device to get it working again is indicative of a device driver bug.

Look for an updated driver. It will probably a Prolific or FTDI chipset, make sure you get the driver from the chip maker. See Prolific or FTDI
If it is a flow control related hardware problem you can wire together the DTR, DSR and CD pins, and wire together the RTS and CTS pins on the RS-232 connector on the USB adaptor. I have seen USB adaptors where this is necessary, despite setting no flow control in software.
Comment: Thank you for posting, I was just in the process of answering by myself to the question. Indeed, bugs occur but in this case it was neither a driver nor a hardware one. The Arduino was working perfectly under Linux as well as on Windows with the Arduino IDE serial monitor.


Regression/classification models and dummy variables

Question: I want to build regression model (linear and logit) but one of my independent variables is categorical variable with levels "Gym", "School", "Hospital", "Others". How to incorporate this variables in my model (in R)? Should I convert this variable to dummy variables ("School_dummy", "Hospital_dummy" and "Gym_dummy", without "Others_dummy") or there is another solution? And what if I omit "Gym_dummy" instead of "Others_dummy"? Is it okay or the model is harder to interpret? Because then I want to use step procedure based on AIC criterion in order to choose the most important variables, so it is possible that I end for example only with "Hospital_dummy" in my final model.
Comment: We have many posts on here explaining the issues with stepwise regression.
Answer: If the package you are using accepts categorical factors you should use them as such.
If not, then the option (one-hot-encoding) you mentioned is indeed suitable. If you leave a minimally reproducible example of your code I might be able to help further.
Answer: Assuming you're using the base R lm/glm functions:
If you createthe dummy variables yourself, the step process will treat them as separate variables, so you may get some of them removed while the others remain in the model.
You can also feed them into the model as categorical and R will do the dummification for you. When executing step, either the variable stays or is removed altogether, but you won't run into the problem of having only some of the dummy variables in the final model.


how a module is installed?

Question: I was successfully able to install the Nivo_Slider.
But I want to have proper understanding on how module installations work.
My question is:
Why doesn't the simple module installation of Nivo_slider do the job?
Why do I manually have to copy and paste something (look at the first step from here? Isn't that the whole purpose of module installation? Some other modules just get installed by copy and pasting the tar.gz file.
Answer: The Nivo Slider module relies on libraries that have a different license from the module itself. To work around this aspect, the Nivo libraries are distributed apart from the module. Consider this explanation from the licensing page at Drupal.org:

10. Can I write a "bridge module" to interface between Drupal and another system or library?
That depends on the other system.
It is possible to distribute a module that communicates with a 3rd party system over HTTP, XML-RPC, SOAP, or some other wire protocol, that leaves the 3rd party system unaffected.Examples of such systems include Flickr, Mollom, or certain legacy systems.
It is possible to distribute a module that integrates with a 3rd party PHP or JavaScript library, as long as the library is under either a GPL or GPL-compatible license. Examples of compatible licenses include BSD/MIT-style "permissive" licenses or the Lesser General Public License (LGPL). The Free Software Foundation maintains a list of popular GPL-compatible licenses.
It is not possible to distribute a module that integrates a non-GPL compatible library with Drupal, because it would be a derivative work of both Drupal and that other library and would therefore violate either the GPL or the license of the other library. Please be aware that includes some open source licenses that are incompatible with the GPL for one reason or another, such as the PHP license used for most PEAR packages.
If you wish to contribute a bridge module to a Drupal Git repository, please do not check in the 3rd party library itself. Doing so creates a fork of that 3rd party library, which makes it more difficult to maintain and only serves to waste disk space. Instead, provide detailed instructions for users to download and install that 3rd party library for use with your module. If you believe that your module is a special case where it really does need to be included in a Git repository, usually only because you need to make substantial modifications to it in order for it to work, please file an issue with in the Licensing Working Group issue queue first to discuss it.
Comment: Drupal modules use one license, other libraries use different licences, some of which aren't compatible with Drupal's license. These libraries can't be included with the modules that use them, they have to be sourced and installed separately. Does that clear it up @asma22?
Comment: Do you mean this issue is only for Nivo-slider and no other module requires the same configuration? If so then yes its not a Drupal specific issue, but if some other modules are like this which I think teh quote you provided is saying such, then its a Drupal issue and a developer needs to know whats going on for installations...
Comment: Can you elaborate on this "libraries that have a different license from the module itself."
Comment: @Clive
Yes... completely

how a module is installed?


Why $\sum^{\infty}_{n=1}\frac{\sin[n]}{n}=\frac{1}{2}(\pi-1)$?

Question:
Possible Duplicate:
Proving that the sequence $F_{n}(x)=\sum\limits_{k=1}^{n} \frac{\sin{kx}}{k}$ is boundedly convergent on $\mathbb{R}$

From Stewart, we cannot find a calculus 2 easy way to prove this:
$$\sum^{\infty}_{n=1}\frac{\sin[n]}{n}=\frac{1}{2}(\pi-1)$$
Comment: Also look here http://math.stackexchange.com/questions/161960/sum-inequality-sum-k-1n-frac-sin-kk-le-pi-1/183471#183471
Comment: What's $[n]$ suppose to be? perhaps the question has a typo?
Comment: Kerry just means $\sin(n)$
Comment: @BabakSorouh: But floor of a natural would be quite redundant.
Comment: Yeah floor or $n$ is just $n$, but this may just be it because sum of $\sin(n)/n$ is $1/2(\pi-1)$
Comment: This is not a duplicate. I need a proof acceptable at calculus 2 student's level.
Answer: $\sum\limits^{\infty}_{n=1}\dfrac{\sin{n\theta}}{n}$ is the Fourier series for  $f(\theta)=\dfrac{\pi-\theta}{2}, \;\; 0<\theta<2\pi,$ and converges uniformly on every closed interval $[\alpha, \beta], \;\; 0<\alpha<\beta<2\pi$ by Dirichlet's test.


Why does extending scalars from $R$ to $S$ preserve isomorphism?

Question: I am looking at a proof and there is a step I don't understand well. Sorry if this post seems disorganized, but I'm not sure how to ask this question in any other way.
Statement: Let $R$ be a commutative ring with unity. Let $M\cong \oplus_{x\in X}R$ and $N\cong \oplus_{y\in Y}R$ as $R$-modules. Then $M\cong N \Rightarrow |X|=|Y|$.
Proof: Let $P$ be a maximal ideal of $R$. Define $k:=R/P$. Then $k$ is a field and an $R$-algebra. We see that:
$$M\otimes_R k \\ \cong (\oplus_{x\in X}R)\otimes_R k\\ \cong \oplus_{x\in X} (R\otimes_R k) \\ \cong \oplus_{x\in X}k.$$
Similarly, $N\otimes_R k \cong ... \cong \oplus_{y\in Y}k$.
But $M\otimes_R k$ and $N\otimes_R k$ are $k$-modules, and $M\otimes_R k\cong N\otimes_R k$. Since $k$ is a field, they are vector spaces. Since two vector spaces being isomorphic implies that their bases have the same cardinality, we have that $|X|=|Y|$.
My question(s):
Why can we assert that $M\cong N$ as $R$-modules means that $M\otimes_R k\cong N\otimes_R k$ as $k$-modules? Does this work for a general $R$-algebra $S$? That is, if $M\cong N$ as $R$-modules, is it the case that $M\otimes_R S\cong N\otimes_R S$ as $S$-modules?
Comment: If an $R$-linear map $f:M\to N$ is an isomorphism of $R$-modules and $S$ is an $R$-algebra, then the $S$-linear map $\mathrm{id}_S\otimes f:S\otimes_RM\to S\otimes_RN$ is an isomorphism of $S$-modules. You should check this: if you know what the terms mean, then there is really no difficulty apart from coming up with the correct statement.
Answer: What you are describing is an instance of a much more general situation, which in my opinion is worth knowing, so I will try to elaborate:
What makes this work is the fact that the assignment $M\mapsto M\otimes_R k$ is a functor. What this means is the following:
A functor from the category of $R$-modules $_R\operatorname{Mod}$ (although not entirely accurate, you can think of this as the "set" of $R$-modules, and between each two $R$-modules you have the set of $R$-module homomorphisms between them) to the category of $S$-modules $_S\operatorname{Mod}$ is an assignment $F:_R\operatorname{Mod}\to_S\operatorname{Mod}$ such that

For every $R$-module $M$ there is an associated $S$-module $FM$
For every $R$-module homomorphism $f:M\to N$ there is an $S$-module homomorphism $Ff:FM\to FN$.
For every $R$-module $M$ we have $F\operatorname{id}_M=\operatorname{id}_{FM}$.
For any two $R$-module homomorphisms $f:M\to N$ and $g:N\to P$ we have $F(g\circ f)=Fg\circ Ff$.

This is a very general notion, and almost every construction you encounter in algebra is in some sense a functor.
Now what is very nice about functors is that they preserve isomorphism. That is, if you have isomorphic $R$-modules $M\cong N$, then you get isomorphic $S$-modules $FM\cong FN$. Indeed, $M\cong N$ means that we have mutually inverse $R$-module homomorphisms $f:M\to N$ and $g:N\to M$ (i.e. $g\circ f=\operatorname{id}_M$ and $f\circ g=\operatorname{id}_N$). By 3. and 4., we then obtain that the $S$-module homomorphisms $Ff:FM\to FN$ and $Fg:FN\to FM$ are also mutually inverse (i.e. $Fg\circ Ff=\operatorname{id}_{FM}$ and $Ff\circ Fg=\operatorname{id}_{FN}$). That is, $FM$ and $FN$ are isomorphic.
Now what you should check is that $M\mapsto M\otimes_R k$ is indeed a functor. More concretely, given a map $f:M\to N$ you should construct a $k$-module homomorphism $f\otimes_R k:M\otimes_R k\to M\otimes_R k$, such that 3. and 4. are satisfied. Once you have this, everything is automatic.
Comment: @iateawalrus A very nice introduction which covers a good part of the category theory one encounters in "everyday maths" is Leinsters 'Basic Category Theory'. You can find it here: https://arxiv.org/pdf/1612.09375.pdf
Comment: Clear, comprehensive answer. Is there a good book to do more readings on this? I am not extremely familiar with category theory.
Answer: Really the isomorphism $f\colon M\longrightarrow N$ that you serve to affirm that $M\cong N$, it serves to give the isomorphismom from $S\otimes_R M$ to $S\otimes N$.  Simply because the estension of scalars, is a functor from $R$-Mod to $S$-Mod. So you have a funtor given by $F(M)=S\otimes_RM$ and $F(f)=1_R\otimes f$. Since $F$ is a funtor it sends isomorphisms into isomorphisms.


How to Calculate Expected Value While Accounting for Historical Skill Level

Question: Let's say there is a skill based contest that has 1,000 people competing in it.  No one player can manipulate another players outcome.  You competed in this contest type 10,000 times and your historical average is that you finish in the top 40%.
How would you calculate the "expected value" of competing in this contest if the parameters were as follows:
1st through 300th place receive a prize amount of \$10.  The cost to enter the contest is $5.
I know the way to calculate the expected value without taking into account the fact that you historically finish in the top 40% would be: (30% chance of winning X \$10 prize) + (70% chance of losing X -\$5 loss) = -$0.05 expected value
However, how do you calculate the expected value of this contest when taking into account that you historically finish in the top 40% because of your skill level?
Comment: Isn't the without-expectation $30\%\cdot\,\$10+100\%\cdot\,-\$5=-\$2$, since you always pay $\$5$ to participate?
Answer: I'd reason that the skill is normally distributed among participants. And apparently, I am in the upper tail, making up 40%.
So after the contest is over, then I'd expect my results to be among the 400 best.
The question is then, what is the probability of being among the 300 best?
Without any more information, I'd estimate that probability at a fair 75%.
Therefore I'd calculate the expected winnings as $75\%\cdot\,\$10+100\%\cdot\,-\$5=\$2,50$.


any PHP or Ruby library to convert Tranditional Chinese to Simplified Chinese or vice versa?

Question: Is there any PHP or Ruby library to convert Tranditional Chinese to Simplified Chinese or vice versa (Big5  <--> GB)?  The iconv library won't do it, as it merely converts the encoding, but the glyph stays the same.
Answer: Try this class for PHP - http://www.phpclasses.org/browse/package/3130.html
Answer: You might get some leverage with 1.9

Encoding.constants.grep /gb/i
    => [:GB18030, :GBK, :GB1988, :GB12345]
Encoding.constants.grep /big5/i
    => [:Big5, :BIG5, :Big5_HKSCS, :BIG5_HKSCS, :Big5_UAO, :BIG5_UAO]

so it's something like
How can I convert a string from windows-1252 to utf-8 in Ruby?
original = File.open('name', 'r:original_encoding').read
original.force_encoding('new_encoding')
Though I've never tried it.


Finding the nth derivative of a function using standard forms

Question: $Y = \cos x \cos2x \cos3x$.
 How to find $Y_n$ ?
We can use some standard forms like $Y_n$ for $Y=\cos(ax+b)$ ; $Y_n = a^n \cos[n(\pi/2)+(ax+b)]$ , wherever applicable.
Answer: Hint:
Use Werner's formula
$2\cos A\cos B=\cos(A-B)+\cos(A+B)$
to find summands of the form $\cos(ax+b)$
Comment: Can you please elaborate
Comment: $$2\cos x\cos2x=\cos(2x-x)+\cos(2x+x)$$  and $$2\cos3x(2\cos x\cos2x)=2\cos3x\cos x+2\cos^23x=\cos(3x-x)+\cos(3x+x)+1+\cos(2\cdot3x)=?$$
Comment: I done it by myself  Thanks BTW ✌
Comment: @AyushBhardwaj, Nice to hear that
Answer: $$Y(x)=\cos (x) \cos (2 x) \cos (3 x)=\frac{1}{4} (1+\cos (2 x)+\cos (4 x)+\cos (6 x))$$
$Y_1(x)=\frac{1}{4} (-2 \sin (2 x)-4 \sin (4 x)-6 \sin (6 x))$
$Y_2(x)=\frac{1}{4} (-4 \cos (2 x)-16 \cos (4 x)-36 \cos (6 x))$
$Y_3(x)=\frac{1}{4} (8 \sin (2 x)+64 \sin (4 x)+216 \sin (6 x))$
$Y_4(x)=\frac{1}{4} (16 \cos (2 x)+256 \cos (4 x)+1296 \cos (6 x))$
$\ldots\ldots\ldots\ldots\ldots\ldots$
$Y_{4k+1}=\frac{1}{4} ((-2)^{4k+1} \sin (2 x)+(-4)^{4k+1} \sin (4 x)+(-6)^{4k+1} \sin (6 x))$
$Y_{4k+2}=\frac{1}{4} (-2^{4k+2} \cos (2 x)-4^{4k+2} \cos (4 x)-6^{4k+2} \cos (6 x))$
$Y_{4k+3}=\frac{1}{4} (2^{4k+3} \sin (2 x)+4^{4k+3} \sin (4 x)+6^{4k+3}\sin (6 x))$
$Y_{4k+4}=\frac{1}{4} (2^{4k+4} \cos (2 x)+4^{4k+4} \cos (4 x)+6^{4k+4}\cos (6 x))$
Hope this is useful


Function to convert GridView and Repeater in a JSON string

Question: I need a JavaScript function which will take the ASP.NET Repeater as input. The function must then parse through the object and return the data in the rows of the object as JSON.
Then, I can send the JSON back to the server to be interpreted/parsed and saved to the DB.
Comment: Your question isnt making much sense to me. You want to convert a server control to json, or the data that the controls are bound to?
Comment: Please edit your question to make it more explanatory.
Answer: your best bet is probably traversing the elements rendered by the Repeater and gathering the values into a javascript object. when you have that you can use json2's stringify() or jquery's serialize() or something similar to produce a json representation.


The fixed point of homeomorphism on the circle

Question: Let $f$ be a homeomorphism on the circle $S^1$ which preserve the orientation, if the set of fixed points of $f$ is infinite, does it imply $f=id$?
Comment: Did you mean homeomorphism (with an 'e')?
Comment: True is you also assume that f has finite order.
Comment: @studiosus could you explain it?
Answer: No. Fix one hemisphere of the circle and then in the other hemisphere apply a non-identity endpoint-preserving homeomorphism to the interval. The fixed hemisphere is an infinite subset but the homeomorphism on the circle is constructed to be non-identity.
Answer: No. Here is a counterexample. Parameterize $S^1$ by $\gamma: [-1,1] \to S^1$. Let $f: [-1,1] \to [-1,1]$ be defined by
$$
f(x) = \begin{cases}
x & \text{if } x \leq 0 \\
x^2 & \text{if } x \gt 0
\end{cases}
$$
The function $f$ is a homeomorphism from $[-1,1]$ to itself that has $[-1,0] \cup \{1\}$ as its set of fixed points. The parametrization $\gamma$ then lifts this to $S^1$.
Answer: As you requested:
Lemma. Suppose that $f$ is a homeomorphism of finite order of the circle which has at least 3 fixed points. Then $f=id$, the identity map.
Proof. Let $x, y, z$ be distinct fixed points of $f$. I will identify $S^1$ with the 1-point compactification of the real line (using the stereographic projection). Choose this identification in such a way that $x$ is identified with $\infty$ and $y$ is identified with $0$. Since $f(0)=0, f(z)=z$, it follows that $f$ has to be strictly increasing as a homeomorphism of the real line. Therefore, $f|R$ belongs to the group $Homeo_+(R)$. The latter is left-orderable (see my answer here). It is immediate that every left-orderable group is torsion-free: If $g>1$ then
$$g^2>g>1,$$
....
$$
g^n>g^{n-1}>...>g>1.$$
Hence, $g^n\ne 1$ for every $n>0$. Therefore, in our case, $f=1$, the identity homeomorphsm. qed
Note that this lemma is a special case of a more general theorem on fixed-point sets of order $p$ homeomorphisms of homology spheres (given by the so called Smith Theory). Here $p$ is prime. Such fixed point sets are $p$-homology manifolds and, in addition, $p$-homology spheres. For instance, it follows from the Smith Theory that if $f: S^n\to S^n$ is a periodic homeomorphism then either $f=id$ or the fixed point set of $f$ has empty interior. Another example: if $f: S^2\to S^2$ is a homeomorphism of finite order, $f\ne id$, then the fixed-point set of $f$ is either a topological circle, or empty or a pair of distinct points. Same for $f: S^3\to S^3$, except you also have to allow a topological sphere as the fixed point set.


Determine region of integration for homework problem

Question: For my Calc III homework problem, I am unsure how to determine the region of integration.
The problem is fairly simple.
$$
\text{Find the volume of the solid bounded by the planes }x = 0\text{, }y = 0\text{, }z = 0\text{, and }x + y + z = 7\text{.}
$$
Thinking this through, volume is easy especially because it is a solid. We can start with the following:
$$
\int\int\int_{D} xyz\:dA
$$
Just each of the sides multiplied together, all that's left is determining the region. Here's where I'm getting stuck.
I know I need to solve the plane for each variable and solve them all out systematically until I only have numbers for my outmost region, but I'm getting something wrong and I'm not sure if it's just a lapse in my algebraic knowledge or a lapse in understanding about the region itself.
First solving for x, for our innermost integral:
$$
x = 7 - y - z
$$
Then solving for y, for our second innermost integral:
$$
y = 7 - z - x\\
\text{Let's our previously solved x in to eliminate a variable}\\
y = 7 - z - (7 - y - z)\\
y = 7 - 7 - z + z + y\\
y = y \text{ (Clearly, I have failed to grasp something important.)}
$$
I can't use y = y for my bounds because this doesn't actually tell me what $a$ and $b$ are. What am I missing?
Answer: Our height is in $z = 7-x-y$, thus in a similar manner what KfSsOc suggested we may write the volume $V$ as:
$\begin{align}
V =\int_0^7 \int_0^{7-x} (7-x-y) \hspace{.1cm} dy \hspace{.05cm} dx
\end{align} $
Essentially thinking we take our function of $z$, integrate it from the origin to its bound in $y$ (the line $y=7-x$), then we integrate the resulting function in $x$ from its numerical endpoints, and obtain our volume. A picture might help making the limits for integration more clear if you're having trouble.
Comment: Thanks for taking the time to explain this. It was invaluable and also gave me the right answer (which is also helpful)
Answer: hint:$$ V = \displaystyle \int_{0}^7 \int_{0}^{7-z} \int_{0}^{7-y-z} 1dxdydz$$


Ordenação decrescente em Lista Duplamente Encadeada Circular em C

Question: To precisando de uma ajudinha aqui com Lista Circular Duplamente Encadeada para resolver um problema maior. Preciso fazer uma função que já insira meus elementos em ordem decrescente. Meu código até funciona com entradas que só necessitam ser invertidas.Ex: 1 2 3 4 5 6, que sai 6 5 4 3 2 1. O problema são com entradas do tipo 6 3 9 8 ... Onde acham que está o problema?
struct elemento{
  int altura;
  struct elemento *anterior;
  struct elemento *proximo;
 };
 typedef struct elemento Item;

typedef struct{
    int tamanhoLista;
    Item *primeiro;
    Item *ultimo;
}LCD_DE;

    void Inserir(LCD_DE *l){
    Item *novo = (Item*)malloc(sizeof(Item));

    scanf("%d",&novo->altura);

    if(l->tamanhoLista == 0){
        l->primeiro = novo;
        l->ultimo = novo;
        novo->anterior = novo;
        novo->proximo =  novo;
    }
    else{
        if(novo->altura >= l->primeiro->altura){  //antes do primeiro
            l->primeiro->anterior = novo;
            l->ultimo->proximo = novo;
            novo->anterior = l->ultimo;
            novo->proximo = l->primeiro;
            l->primeiro = novo;
        }
        else if(novo->altura < l->ultimo->proximo->altura){ //depois do ultimo
            l->ultimo->proximo = novo;
            l->primeiro->anterior = novo;
            novo->anterior = l->ultimo;
            novo->proximo = l->primeiro;
            l->ultimo = novo;
        }
        else{
            Item *i,*j,*k,*aux;
            for(i=l->primeiro;i!=l->primeiro;i=i->proximo){
                for(j=l->primeiro->proximo;j!=l->primeiro;j=j->proximo){
                    k=j->proximo;
                    if(novo->altura >= j->altura){
                        i->proximo = novo;
                        novo->anterior = i;
                        j->anterior = novo;
                        novo->proximo = j;
                    }
                    else if(novo->altura < j->altura){
                            j->proximo = novo;
                            novo->anterior = j;
                            k->anterior = novo;
                            novo->anterior = k;
                    }
                }

            }
        }
    }
     l->tamanhoLista++;
}

Answer: Acho complicado ficar achando esse tipo de problema com ponteiros, preferi criar um novo exemplo.
#include <stdlib.h>
#include <stdio.h>

typedef struct Item
{
   int height;
   struct Item* prev;
   struct Item* next;
} Item;

typedef struct
{
   int size;
   Item* first;
   Item* last;
} List;

static void insert(List *list, int height)
{
   printf("* ===\n");

   Item *newItem = (Item*)malloc(sizeof(Item));
   newItem->height = height;

   if (list->size == 0)
   {
      printf("* inserindo elemento %d em lista vazia\n", height);
      list->first = newItem;
      list->last = newItem;
      newItem->prev = newItem;
      newItem->next = newItem;
      list->size = 1;
      return;
   }

   if (height > list->first->height)
   {
      printf("* inserindo elemento %d antes do primeiro\n", height);
      list->first->prev = newItem;
      list->last->next = newItem;
      newItem->prev = list->last;
      newItem->next = list->first;
      list->first = newItem;
      list->size++;
      return;
   }

   if (height < list->last->height)
   {
      printf("* inserindo elemento %d depois do ultimo\n", height);
      list->last->next = newItem;
      list->first->prev = newItem;
      newItem->prev = list->last;
      newItem->next = list->first;
      list->last = newItem;
      list->size++;
      return;
   }

   printf("* inserindo elemento %d intermediario\n", height);
   Item* item = list->first;
   for (int i = 0; i < list->size; i++)
   {
      if (item->height < height)
         break;
      item = item->next;
   }

   item->prev->next = newItem;

   newItem->prev = item->prev;
   newItem->next = item;

   item->prev = newItem;

   list->size++;
}

static void print(List* list)
{
   printf("* ---\n");
   printf("* tamanho da lista: %d\n", list->size);
   Item* item = list->first;
   for (int i = 0; i < list->size; i++)
   {
      printf("* list[%d] = %d\n", i, item->height);
      item = item->next;
   }
}

int main(void)
{
   List list = { 0 };
   print(&list);

   insert(&list, 7);  // primeiro elemento
   print(&list);

   insert(&list, 2); // antes do primeiro elemento
   print(&list);

   insert(&list, 13); // depois do ultimo elemento
   print(&list);

   insert(&list, 9);  // elemento intermediario
   print(&list);
}

Veja em http://ideone.com/p0xSYt
Comment: Muuuuuito obrigada José, mesmo, a sacada do "item->prev->next = newItem" foi genial, nem pensei nesse nível de apontamento pra resolver o problema.Valeu mesmo :)


Can I Wire two cables together to get two inputs into one output

Question: My question is simple: If I open up a guitar cable, or use the jacks from a guitar/pedal (I have a few lying around) and connect the hot outputs and grounds together, could I connect that to another cable, therefore get a 2 inputs connected to one output? I have a loop pedal that does this, but I want 3 inputs to one output in total.
My idea is this:
<code>=======cable 1 hot====(to hot output) == == == cable 2 hot == == ==
-------cable 1 gnd----(to gnd output) -- -- -- cable 2 gnd -- -- --
</code>
(sorry for bad diagram; markdown is mean >:0 )
Comment: It might be better to ask this on the electronics stack exchange.  I am slightly puzzled whether you are connecting two outputs together or two inputs.  I would certainly not connect two outputs together.  I would not suggest doing either unless you know what you are doing.
Comment: No. Get a mixer to do this.
Comment: btw, stack exchange doesn't use HTML, it uses Markdown. There's a quick guide at the top of the question/answer space when you're editing, or a full guide here - https://meta.stackoverflow.com/editing-help
Comment: they are similar, but okay; I will edit
Answer: Edit: there seems to be some confusion here.
Based on the description in the question, I'm assuming you have two devices that output a line-level signal, and you want to connect those to a device that only has one input available.
If this is the case: don't wire the cables together directly. This may damage your devices: the output voltage from one device ends up in the output stage of the other device, which isn't designed to handle that.
There are several ways to do this safely:

use a switch, to connect one output at a time to the input. Simple, but requires you to turn down the output volume because a simple switch isn't guaranteed to make the switch silently.
use a mixer.
use a passive summing mixer. In its simplest form, this is just two resistors wired into the cable. This will result in a 6 dB signal loss.

<code>  INPUT 1 -------\/\/\/\---+
            ---+   R1  10K   +------------ OUTPUT
               |             |       +----
    INPUT 2 -------\/\/\/\---+       |
            ---+   R2  10K           |
               |           (shields) |
               +---------------------+
</code>

The other way round: splitting the output of one device to feed 2 devices, is described in danmcb's answer.
Comment: This as exact as an answer can be.
Comment: Where is the confusion? "could ... get (a) 2 inputs connected to one output?  ... I want 3 inputs to one output in total."  The OP is perhaps not a native English speaker, but this is completely clear in what is being asked. Also - in 30 years as an electronics and audio engineer, I have *never* heard of line outputs (as in mixer/FX pedal line out) being damaged by being connected together. They invariably have resistors to protect them, and even the op amps that generally driver them could handle this without. This is a myth.
Answer: It absolutely depends on the type of output.
What you want to do is called "distributing" the output to a number of inputs. Some types of output are actually designed to be distributed, some are not. Some can, but only with a bit of care and technical consideration.
(To know how and how many you need to know a bit of electronics, there is something called "impedance matching". I am going to try to not get into that.)
Some examples:

A "line level output" from a mixer (like the MIX outputs or an insert send point) can be distributed to a reasonable number of outputs in parallel (i.e. hot to hot, gnd to gnd ...) - how many is "reasonable" depends on impedances but 3 or 4 should be no problem.
A microphone or guitar output generally cannot be distributed - they are not designed to be. You should first amplify the signal through an appropriate pre-amp which has a line level output, and distribute that instead.
The speaker out from an amplifier is not line level - it is "hotter" (i.e. more volts and also ability to supply current). You can connect an amp to more than one speaker - but with care. Consideration must be given to the impedances of the speaker, the rating of the amp, and parallel/series configuration.
A headphone output can sometimes drive more than one pair of headphones - but again with some care about impedances, and the results may be unsatisfactory as the headphones may differ a lot in volume, and there would usually be no means of adjusting them individually.

So - the answer to your question is - "it depends". Your case sounds like case 2, so what you propose is not recommended.
Comment: why is this the accepted answer? Its informative but doesn't actually answer the question that was asked. Hobbes' response is about connecting multiple inputs to one output and this covers the inverse.
Comment: @Legorhin No, connecting multiple inputs to one output is the same as connecting one output to multiple inputs, i.e. distributing a signal.
Comment: @Legorhin I misclicked
Answer: You can use a passive "AB Y" pedal to accomplish this.  It's probably more common to want to split one source to two destinations, but you can also operate them in the opposite way.
Overall though, a (small) mixer is probably a better  solution in that it will give you the ability to control the sources independently.


John has 13 balls less than Peter, and they have 31 balls between them. How many has each of them?

Question: Word problem involving use if symbols
Comment: The usual approach is to set some variables (one for John, one for Peter), then write out the given information algebraically, using those variables, and solve.  In this case, of course, trial and error would also work just fine.
Comment: Welcome to MathSE.  Please edit your question to show what you have attempted and explain where you are stuck so that you receives responses that address the specific difficulties you are encountering.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: Denote by $J$ the amount of balls John has; in the same manner, denote by $P$ the amount of balls Peter has. If $J$ (John) has $13$ balls less than $P$ (Peter), it would follow then that $J=P-13$, i.e. $13=P-J$. You are also given the information that both $J$ and $P$ have $31$ balls between them; this is to say, $J+P=31$. To compare, $$\begin{align} P-J &= 13 \\ P+J &= 31\end{align}$$ Now what things would imply were you to subtract $13$ from $31$?
Comment: @Yemi Are you saying you are unable to solve the puzzle? Or are you asking how to "solve it mathematically"?
Comment: or just (2p-13)=31; 2p=44; p=22; p-13=9; 22+9=31;
Answer: Well if John has 13 balls less than Peter, then if $J$ is John's balls and $P$ is Peter's, we get
$J=P-13$
But then the total balls are $31$, that is $J+P=31$
We then make the substitution from the first line so:
$(P-13)+P=31$


Is it possible to have a bounded continuous function f:(a,b) to R such that the derivative of f tends to infinite as we approach b?

Question: CLAIM:Is not possible to have a bounded differentiable function f:[a,b) to R such that it's derivative  tends to infinite as we approach b. Is the claim correct? How can i prove it? I tried the following proof.Suppose for a contradiction that the claim is wrong. Then such a function f exist. Then i can define a function F[a.b] to R such that F=f in [a,b) but F(b)=limit f(x) as x tends to b. Then F is still differentiable (due to continuoity) and so is derivative at b should be defined so it's not infinite. Contradiction since derivative of F at b is same as derivative of f as x tends to b(due to continuity).
Comment: $\sqrt{x}$ can be easily adapted.
Comment: cheers...i should have thought it:D. But what is wrong with the proof?
Answer: Hint: Look at $\sqrt{1-x}$ over a suitable interval.
Comment: cheers.. but what is wrong with the proof?
Comment: You are assuming that (left) derivatives are continuous. That is false.
Answer: Hint: Look at $f(x)=\sin\frac1{b-x}$. For this $\lim_{x\to b}f'(x)$ does not exist at all, not even as divergence to $\infty$.
Answer: The upper half of a circle is bounded, continuous, and has a tangent line of every possible slope (including $-\infty$ and $\infty$).


How to find a Google API key in file?

Question: I have been given a Google API key that is allegedly being used in one of our company's sites.  However, I cannot confirm which one.
Besides using the "Find in Files" feature in Notepad++, and literally searching each folder on the server, is there a simpler way to confirm which site is using a Google API key?
I cannot search the entire drive because it will freeze everything up.
Comment: This has nothing to do with any of the tags you put in. I even think it is off-topic to ask "how do I find a string in a file on the server" on SO.
Comment: Only legit way would be to "grep the whole drive".
Comment: Is that why you downvoted me?
Answer: Download the projects from the server
1 - Try to search for google api call instead of key.
Open the project using IDE ( neatbeans or phpstorm )
Run a search for a (googleapis URL) with a little patient you cant spot where the api call is fired
2 - check package manager ex: package.json / bower.json / composer.json
if the application is using google sdk check the configuration required for the sdk and you will be able to find the key location if you follow the documentation
3 - ask for the google account used and get the key.
Comment: Thank you for your assistance.  I will attempt everything you suggested.

How to find a Google API key in file?


Multiple packages in java project and jar files

Question: I am trying to build java client for rabbitmq.
I have my source folder as A.mq.client.
Also I have a libs folder where I have my rabbitmq jar files. These jars have been added to build path. Everything works OK in Eclipse.
Then I export the entire project in eclipse as jar. jar contents are .classpath, libs folder and my package folder + rest of stuffs.
Now I am getting exception :
java.lang.ClassNotFoundException: com.rabbitmq.client.Consumer
com.rabbitmq.client.Consumer is in lib jars.
I am running jar using java -cp rabbit.jar A.mq.client.Worker where I want to invoke main method of worker class in my package and Worker is accessing jar packages.
Answer: As far as I know, you can't generally package jar files inside of another jar file.  Typically, you would have to expand all the various dependent jars prior to packaging up your final jar.  If you've ever used Maven, this is what the maven-shade-plugin helps to automate.
See the answer in this question for more information.
Answer: The CLASSPATH lists places, where the classes are found - either in a directory or in a jar, but not

directories of directories
directories of jars
jars of directories
jars of jars


iOS - Best practice to save Images locally - NSCache vs Save in Document Directory

Question: I'm developing an app that similar to Instagram feed (tableviews with cells that contain images and some labels).
For all the data I'm getting from the database, I'm using Data Task (because it doesn't take much to receive them), but for the images (which their url's I get with the Data request), I need to save locally for future use (improve user experience).
My logic is the following:
Save in NSCache or in Document Directory, the images inside folder with the date they been downloaded(create it once and append all other images if needed) (I'm deleting every folder which is not from the recent 7 days), and then for the TableView, just load if from there, so the tableview will scroll smoothly and won't load the url directly from its delegate method.
So where is the better place to store them according to my needs, NSCache or Document Directory.
Looking forward to hearing your suggestions, Thank you!
Comment: @HaiFengKao I prefer pure swift , no third party libraries . I can start build solution myself , im just looking for the correct path . Any more suggestions mate?
Comment: [SDWebImage](https://github.com/rs/SDWebImage)  might solve your problem. It caches image in the disk. NSCache might not be a good choice, because it will be emptied automatically when the system is low on memory.
Comment: @HaiFengKao maybe evolve this two together? for the time he have download it store it inside NSCache , and before the image "dismiss" he will store it locally for future use?
Comment: you can definitely do that.
Comment: @HaiFengKao , you think it could be efficient method?
Comment: It depends on the size of the images. If the size is normal(~1024x768), the performance should not be a problem.
Comment: @HaiFengKao , you have a skype maybe? It would be a great project to do :)
Comment: @HaiFengKao Two things: First, I agree with your recommendation to use something like SDWebImage. [AFNetworking](https://github.com/AFNetworking/AFNetworking) also has a nice `UIImageView` category, much like SDWebImage. But, second, it is no longer the case that `NSCache` is automatically purged on memory pressure. It _should,_ but doesn't. Both SDWebImage and AFNetworking manually register for `UIApplicationDidReceiveMemoryWarningNotification` and purge the cache manually, as should anyone who uses `NSCache`.
Comment: @JackkyWhite Thanks, but I have too many projects.
Comment: @Rob Thanks for the info. Indeed iOS 7 changes the behavior  of NSCache.
Answer: NSCache and persistent storage serve largely different purposes. NSCache holds the item in memory and is used for optimal performance. But it takes up memory (RAM) and you really should make sure that if you use NSCache that you respond to memory warnings and purge the NSCache in those cases. And when the app terminates, the NSCache is lost.
Using persistent storage cache (generally the Caches folder) is used for a different purpose, saving you from needing to re-retrieve the asset via some network request, but not holding the resource in memory. This makes it a great cache mechanism across sessions of running the app or in situations where you may have encountered memory pressure, purged the NSCache, but didn't want to re-retrieve the asset from the network.
Note that I mention the Caches folder for persistent storage, whereas you seemed to presume that one would use Documents folder, but there are two considerations:

Apple is getting more particular about apps only using Documents folder for user data that cannot be easily recreated, and using Caches folder for data that is easily re-retrieved. See File System Basics for more information.
Starting with iOS 11, you should only store user visible documents in the Documents folder (see WWDC 2017 Fall video, iOS Storage Best Practices). Even if you had internally used files that were not easily reconstructed, unless the intent was to eventually expose the user to them, you'd use the Application Support directory, not the Documents folder.

Bottom line, one would generally use the Caches folder for a persistent storage based cache.
Note, we'll often use a two-tier cache mechanism. Cache the resource to both NSCache and the Caches folder. Then, when you go to retrieve a resource, first check NSCache (really fast), if not there, check persistent storage, and if not there, re-retrieve the asset from the network.
Having said all of that, to make it even more complicated, there is a third type of cache, that provided by NSURLCache (i.e. responses for network requests are transparently cached by NSURLSession and NSURLConnection). This cache is dictated by poorly documented rules (e.g. it won't cache any single item whose size exceeds 5% of the total cache size) and is subject to the HTTP headers provided by the network response. This cache, though, operates largely transparently to you and provides both memory and persistent storage caches. Often you can enjoy NSURLCache caching behavior with absolutely no intervention on your part. It's seamless (when it works).
Comment: @SharadChauhan - Yes, I am. In your case, either the app was just suspended and not actually terminated or it's finding content in the [`NSURLCache`](https://developer.apple.com/documentation/foundation/urlcache).
Comment: Well at the end i have managed to come up with a "okay" efficiency soltuin , tell me what you think ::: DataTask that gets the future cells ID'S -> Check if the ID's exist in the presonal DB(Havent figured out if using NSDirectory or Core Data) -> If exist -> load the images,text etc' locally -> If not exists -> Download it -> Save it locally -> Load it locally....... No use of NSCache , only the CacheDirectory , will it decrease preference?
Comment: @Rob You write "...if you use NSCache that you respond to memory warnings and purge the NSCache in those cases." Isn't that done automatically by the system, which is the actual purpose of `NSCache`?
Comment: Thanks you again for awesome answer , so just to make thing a lil big more simple - You don't recommend use Document Directory , You do recommend use a mechanism the NSCache and hos folder in the follow order : CASE 1 : check in NSCache , case 2 : Check in Cache directory , CASE 3 : download again , Follow up questions : 1) There is a limit in the Cache directory? 2) When i download it online , i immediately store it inside both CASE 1 and CASE 2? or i wait for NSCache to remove it and than append it to the Cache folder? 3) I save the images as files inside the Cache folder? Thanks!!!!!!!!!!!
Comment: The limit in the cache folder is total available persistent storage (though you might want to be a good citizen and constrain that if you're app is likely to need extraordinary amounts of storage). Personally I would always cache to persistent storage and re caching to NSCache immediately when your download, if you are doing lazy loading, yes; if doing eager loading, then probably not. And, yes, when saving to persistent storage, I'd probably write it as a file, though NSURLCache uses SQLite.
Comment: @Rob do you think there is a way of getting the object from NSCache without making cache as static variable?
Comment: @anishparajuli - Sure, the cache doesn't care if it's a `static` or not. You just want it to persist throughout its useful lifespan. It's completely up to you how you accomplish that.
Comment: but if i create a cache as var cache = NSCache() and setObject next time i get the value as nil  with the cache?and if i want the object in anothe viewcontroller surely there is no way of getting the object..so i tried making that cache as static and it works ok now?
Comment: If you want two view controllers to share a cache, you can either pursue a singleton pattern or you can store it somewhere that persists (such as app delegate or (not good) a global), or you can instantiate it and pass it around.
Comment: Hi, I have a big doubt on this line `And when the app terminates, the NSCache is lost.`, are you sure about this ? As I am using `NSCache` in my Image downloading class and when I open the app again, Images are there even if there is no internet, so I have this doubt.


NSClient++: Invalid return code -1073741502

Question: I got a problem with NSClient++ (version 0.3.8.76).
I set up an external script handler, and it was working.
But since some time it returns this, everytime i run the check:
No output available from command (cmd /c echo scripts\scriptname.ps1; exit($lastexitcode) | powershell.exe -command -).

It just stopped working in the middle of the night, without any interaction.
A look in the NSClient++ Logs reveals:
error:modules\CheckExternalScripts\CheckExternalScripts.cpp:188: The command (cmd) returned an invalid return code: -1073741502

Since then, this happens to every script i try to run. Nothing seems to work anymore.
Restarting the NSClient Service doesn't help, but when i run nsclient with the /test flag, it's working as intended.
Rebooting is difficult, as this machine has some productive services running.
The NSC.ini seems to be ok, since no changes were made since it was working, and the same configuration is also used on different hosts and working. Also nsclient++.exe /test works as it should.
I appreciate any help or hints on how to fix this problem. tia!
Answer: If it stops working it sounds like a socket issue which is most likely fixed in 0.4.1/0.4.2
All in all 0.3.8 is very very old and an upgrade will fix many issues (including timeout issues and broken pipe issues, etc etc).
Comment: sorry for the late response. yes, an upgrade of nsclient fixed that issue.


Custom Checkbox without label

Question: I have an a element that acts like a toggle button :

var container = document.getElementsByClassName("favorite");

for (var i = 0; i < container.length; i++) {
  //For each element in the container array, add an onclick event.
  container[i].onclick = function(event) {
    this.classList.toggle('selected');
  }
}
body {
  background-color: #04246A;
}
.container {
    position: relative;
    width: 204px;
    max-width: 204px;
    height: 82px;
    max-height: 82px;
    padding: 24px;
    background: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    box-sizing: border-box;
    color: black;
  list-style: none;
   border: 2px solid black;
}

.container .favorite {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 40px;
    height: 40px;
    display: flex;
    border-radius: 50%;
    cursor: pointer;
}

.container .favorite:hover {
  background: #D9DEEA;
}

.container .favorite::after {
    z-index: 2;
    position: relative;
    margin: auto;
    height: 20px;
    content: url("https://img.icons8.com/ios/16/000000/star.png");
}

.container .favorite.selected::after {
    content: url("https://img.icons8.com/ios-filled/16/000000/star.png");
}

.container dl {
    margin: 0;
}

.container dl dt {
    display: block;
    font-size: 12px;
    color: #6B7790;
}
.container dl dd {
    margin: 0;
    font-weight: normal;
    color: #04246A;
}

Ref

XXX123

I want to transform it to a checkbox, but the solutions I find are for a checkbox with a label, I only want to use the checkbox in my html without the label or some additional div, this is what I tried :

body {
  background-color: #04246A;
}
.container {
position: relative;
width: 204px;
max-width: 204px;
height: 82px;
max-height: 82px;
padding: 24px;
background: #fff;
display: flex;
flex-direction: column;
justify-content: space-between;
box-sizing: border-box;
color: black;
  list-style: none;
   border: 2px solid black;
}

 input[type="checkbox"]{
   height: 20px;
   width: 20px;
   position: absolute;
   opacity: 1;
   margin: auto;
   height: 20px;
   cursor: pointer;
   top: 10px;
  right: 10px;
}

input[type="checkbox"]::after{
  content: url("https://img.icons8.com/ios/16/000000/star.png");
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 50%;
  margin: auto;
  height: 20px;
  width: 20px;
  pointer-events: none;
}

input[type="checkbox"]:checked:after {
  content: url("https://img.icons8.com/ios-filled/16/000000/star.png");

}
input[type="checkbox"]:hover:after{
  background: #D9DEEA;
}

.container dl {
margin: 0;
}

.container dl dt {
display: block;
font-size: 12px;
color: #6B7790;
}
.container dl dd {
margin: 0;
font-weight: normal;
color: #04246A;
}

  <input type="checkbox" />

Ref

XXX123

Which doesn't look good.
How can I fix this ? and thanks in advance.
Answer: You can add appearance:none to remove to checkbox appearance and set fixed height/width to checkbox and :after, changing :after to flex allows you to center the background.

body {
  background-color: #04246A;
}
.container {
position: relative;
width: 204px;
max-width: 204px;
height: 82px;
max-height: 82px;
padding: 24px;
background: #fff;
display: flex;
flex-direction: column;
justify-content: space-between;
box-sizing: border-box;
color: black;
  list-style: none;
   border: 2px solid black;
}

 input[type="checkbox"]{
   height: 40px;
   width: 40px;
   position: absolute;
   opacity: 1;
   margin: auto;
   cursor: pointer;
   top: 10px;
   right: 10px;
   appearance: none;
   outline: none;
}

input[type="checkbox"]::after{
  content: url("https://img.icons8.com/ios/16/000000/star.png");
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 50%;
  margin: auto;
  height: 40px;
  width: 40px;
  pointer-events: none;
  display: flex;
  justify-content: center;
  align-items: center;
}

input[type="checkbox"]:checked:after {
  content: url("https://img.icons8.com/ios-filled/16/000000/star.png");

}
input[type="checkbox"]:hover:after{
  background: #D9DEEA;
}

.container dl {
margin: 0;
}

.container dl dt {
display: block;
font-size: 12px;
color: #6B7790;
}
.container dl dd {
margin: 0;
font-weight: normal;
color: #04246A;
}

  <input type="checkbox" />

Ref

XXX123

Comment: Thanks, you are a life saver :D, actually I have something else, I want when I hover on the icon to give an effect like the circle is growing.
Comment: Add a keyframe or transition to :after on hover and you will be good to go.

Custom Checkbox without label


Doubling Trumpet and Trombone

Question: I have been playing the trumpet for two years now. I decided on May of the current year to buy a Trombone and play the Trombone as well.
I was getting a really nice tone on the Trumpet but now, for the past month it's very hard for me to get to some high notes that I was already getting with no effort. It's very rare nowadays if I get a nice clean tone on the Trumpet and I am practicing even more.
Is it realated to trying to play two brass instruments? I usually practice the Trumpet in the morning and in the afternoon and the Trombone afterwards.
Comment: It's more than likely your embouchure has suffered a little, as it's rather different for trombone than trumpet. If you stick to just trumpet for a while, I'd be surprised if it didn't improve. James Morrison appears to have solved the problem - he plays just about all the brass family of instruments - damned well - and can swap around quickly. Maybe ask him - I think he's an educator, too.
Comment: Are you taking lessons for both? You're at risk for destroying both your trumpet embouchure and 'bone embouchure if you don't.
Answer: When you say your trumpet range is suffering, what range are we talking? Double C's or G above the staff?
When I was working on cruise ships, I bought a trombone and my range improved. I thought about the extra blood flow and how it was helping me. I imagined I was getting better and I did.
Playing the trumpet is 20% technique and 80% attitude. You have to be confident and positive. Thinkong that you may "destroy your embouchure" is just bad advice. Noticing a negative change and doing something different to get that "happy feeling" again is a much more positive way to look at things. Stay away from all negative thought and negative people.
Answer: It is common to experience what seem like setbacks even when playing just one instrument.
Often thiis merely means that an early easier-but-more-limited habit, such as crushing the lips with mouthpiece pressure for high notes, is being replaced by a more-versatile improved new technique, such as developing balanced muscle tone throughout the lips.
Each improvement will progress from being awkwardly unfamiliar to eventually being another dependable habit to progress beyond, again with a temporary setback.
Switching between trumpet and trombone is a perfect time to learn
more about the huge role that your vocal tract plays on any wind instrument.
I consider my euphonium and trombone to be only the visible halves of the whole instruments.
If you haven't already, try alternating between playing some high notes and just singing them.
If you can whistle, try that too.
Singing and whistling train your mouth, tongue and throat to resonate each note just as much as your horn does.
Then pretend that you are singing, or whistling, while playing.
You will likely not only hit high notes with less effort,
on both instruments, but also realize that you can more deliberately
color your tone
with sweetness, mystery, punch, swing, twang, and plain old brass razz,
along with other moods and special effects.
Answer: You might have to become more conscious of your embouchure, modifing it for each instrument rather than just 'slap it on and blow'.   Certainly be sure you're not relying on pressure for the high notes.

Doubling Trumpet and Trombone


simple jQuery toggle to $("html, body").css({"overflow": "hidden"}); when opened and then switch to "scroll" when closed

Question: The toggle works as you would expect -- and is powered by attaching a class to an element set to open. As you could probably tell below:
The problem is.. and you can probably tell from my attempts, is I have three elements that open and close the toggle on click .isilnk '.isi__wrapper' and .isi__expander I am simply trying to set it that when and if the element is expanded or toggle open. eg. if ($(".isi").hasClass("isi--show-isi")) { simply set overflow: hidden to html, body and when it is closed or not open or doesn't have class above, then simply set html, body { overflow: scroll; }.
None of my attempts below allowed for this to work with both open and close, only one or the other. So, currently it works when the element is toggled open, but when it's closed, the html, body overflow does not go back to scroll and the user cannot navigate the site.
$(document).ready(function(){

    $('.isilnk').on('click', function(){
        $('.isi').addClass('isi--show-isi');
        $("html, body").css({"overflow": "hidden"});
    });

    if ($(".isi").hasClass("isi--show-isi")) {
      $("isi__wrapper").css("overflow","scroll");
      $("html, body").css({"overflow": "scroll"});
    }
    else {
      $("html, body").css({"overflow": "scroll"});
    }
    $('.isi__expander').click(function() {
       $("html, body").css({"overflow": "hidden"});
    });

    $('.isi__wrapper').click(function() {
        $("html, body").css({"overflow": "scroll"});
    }
});

Comment: could you post html as well ?
Comment: Also, a portion of your code isn't inside the click event function.  i.e. `if ($(".isi").hasClass("isi--show-isi"))` will always execute the `else` statement because it runs once: on document ready.
Comment: Changing that doesn't have a different result..
Answer: As a guess:
$(document).ready(function(){

    $('.isilnk').on('click', function(){
        $('.isi').toggleClass('isi--show-isi');
        $("html, body").css({"overflow": "hidden"});
        setCSS();
    });

    $('.isi__expander').click(function() {
      ('.isi').addClass('isi--show-isi');
      setCSS();
    });

    $('.isi__wrapper').click(function() {
      ('.isi').removeClass('isi--show-isi');
      setCSS();
    }
});

function setCSS() {
    if ($(".isi").hasClass("isi--show-isi")) {
      $("isi__wrapper").css("overflow","scroll");
      $("html, body").css({"overflow": "scroll"});
    }
    else {
      $("html, body").css({"overflow": "scroll"});
    }
}

Comment: Thank you this does not run for me at all for some reason.
Comment: Can you add your html to the question?


How to set index page with path function in django 2.0?

Question: Django 2.0 has introduced new path function in django.urls. So I m using path function to set my index page but as far as I know it doesn't accept regular expression.I have tried couple of options as follows
path('/',views.index,name='index'),

and
path('/index',views.index,name='index'),

but it gives 404 page not found.
So my question is how to set index page site using path function?
Comment: Leading slashes are probably the issue. You should see a warning when you do that if you're running the server interactively.
Comment: You can still use regular expressions with `re_path()`, which is a drop-in replacement for `url()`. However, in this case `path()` is probably the better way, yes.
Answer: To create index using path you can use blank string with quotes to set index page of your project as shown below.
path('',views.index,name='index')

Comment: there is no security vulnerability for this?
Comment: @Ben I don't think so.


Permutation function on $\mathbb{Z}_p$

Question: I'm curious about whether the function $\varphi:\mathbb{Z}_p\to\mathbb{Z}_p$ such that $\varphi(x)=x^3$ defines a permutation iff $p=5\pmod{6}$ (for $p\geq5$ of course). I have some evidence about it but it seems harder than I expected, I hope I'm not missing something important. Thanks.
Answer: Since $x^3=0$ if and only if $x=0$, the question boils down to determining for which $p$ the map $x\mapsto x^3$ is an automorphism of $(\mathbb{Z}/p\mathbb{Z})^{\times}$.
And because $(\mathbb{Z}/p\mathbb{Z})^{\times}$ is a cyclic group of order $p-1$, $x\mapsto x^3$ is an automorphism if and only if $p-1$ and $3$ are coprime. Finally, if $p\geq 5$ is prime then either $p\equiv 1$ (mod $6$) or $p\equiv 5$ (mod $6$), and so $x\mapsto x^3$ is an automorphism precisely when $p\equiv 5$ (mod $6$).
Comment: If $3$ divides $p-1$ then $(\mathbb{Z}/p\mathbb{Z})^{\times}$ has an element $x$ of order $3$, so $x\neq 1$ and $x^3=1$. On the other hand, if $3$ and $p-1$ are coprime then there are integers $r$ and $s$ such that $3r+(p-1)s=1$, and so if $x^3=1$ then $x=x^{3r+(p-1)s}=x^{3r}x^{(p-1)s}=1$. So in this case $x\mapsto x^3$ is injective, hence also surjective.
Comment: Why does $\varphi$ is an automorphism if and only if $p−1$ and $3$ are coprime?

Permutation function on $\mathbb{Z}_p$


Excel formular multiple sheets between dates

Question: I am struggling with a formular in excel to show the totals of rows across multiple sheets based on dates. Here is an example
Sheet 1
No of Days: Today - 2
Name  ¦  Total

Abc   ¦  6

Def   ¦  8

Sheet 2
Name ¦ 15/03/2024 ¦ 16/03/2024 ¦ 17/03/2024

Abc  ¦    7       ¦    3       ¦    8

Def  ¦    4       ¦    1       ¦    2

Sheet 3 - 53 (With the date increasing by 1 day at a time, 7 days on each sheet)
Name ¦ 18/03/2024 ¦ 19/03/2024 ¦ 20/03/2024

Abc  ¦    1       ¦    2       ¦    3

Def  ¦    5       ¦    0       ¦    3

So I basically need the sum of all sheets where the date is less than Today – 2
I hope that makes sense.
I cant see a way of filtering the results by date
Comment: Should not the total be `6` for `Abc` and `8` for `Def`? (`Today` being the 20th and `Today - 2` being the 18th)
Comment: Is there a compelling reason that you need to put those data in separate sheets?
Comment: Just for ease of use really, if I cant do it across multiple sheets I will have to add them all to one
Comment: sorry yes you are correct, I will edit
Comment: Less than today minus 2 is less than 18th equals `0` for both. Do you mean the sum of today up to 2 days back (smaller than or equal to today and larger than *(and equal to?)* today minus 2 days?) also your sample shows 1 sheet of 4 columns, while the point is the use of multiple sheets and a date range to be included/excluded. Should you not adapt your samples to your problem?
Comment: Sample updated, I need the Sum across the sheets for the date range. for example today - 2 would give me the Sum of 18/03/2024 , 19/03/2024 & 20/03/2024
Comment: I see. If you data is in one sheet, filtering columns by date is really easy. but if your data is in multiple sheets, then this problem just becomes much more complicated.
Answer: I think you can use FILTER and BYROW if you are open to put your data in one sheet:
Assuming below data is in range A1:G3:

Name
15/3/2024
16/3/2024
17/3/2024
18/3/2024
19/3/2024
20/3/2024

Abc
7
3
8
1
2
3

Def
4
1
2
5
0
3

Below formula should give you the desired results:
=BYROW(FILTER(B2:G3,(B1:G1>=DATE(2024,3,18))*(B1:G1<=DATE(2024,3,20)),""),LAMBDA(x,SUM(x)))

Here is the formula break down:

FILTER() filters out columns with Date >= 2024-03-18, and <= 2024-03-20.

=FILTER(B2:G3,(B1:G1>=DATE(2024,3,18))*(B1:G1<=DATE(2024,3,20)),"")

2.BYROW() sums the filtered out columns by row.
=BYROW(filteredData,LAMBDA(x,SUM(x)))

If it is absolutely necessary to keep your data in separate sheets, you can consider using INDIRECT and HSTACK to consolidate you data in separate sheets into one table, like below:
=HSTACK(INDIRECT("Sheet1!A1:G3"), INDIRECT("Sheet2!A1:G3"))

Alternatively,
If your columns are always arranged from the earliest date to the latest date, you don't even need FILTER, you can just use TAKE to get the last three columns and sum them by row:
=BYROW(TAKE(B2:G3,,-3),LAMBDA(x, SUM(x)))


Is it possible to track inventory and update item quanities in database for purchases made with Paypal?

Question: I know Java, but am no expert. I use JSP pages and Java Servlets for my site, with a Mysql database.
For a site that is selling products, I want to use Paypal payment buttons. Specifically the "Add to Cart" and "View Cart" buttons so the site can have a shopping cart feel.
I want to keep track of inventory, so when a purchase is made, meaning the payment has actually been submitted through Paypal and was successful, the database is then updated for each item purchased. I don't want to accept payment(s) for an item that is no longer available. So inventory tracking in this case is important.
Is it possible to interact somehow with Paypal and accomplish this task? I need some advice on how to do this.
Answer: Yes, you can use IPN (instant payment notification).
Everything you need is here https://www.paypal.com/ipn with examples.
Just simply update the inventory after the purchase is made and if it is down to zero, disable the payment button. The problem is very straightforward and all you have to do is go over the IPN documentation.
Comment: I visited the https://www.paypal.com/ipn page, and unfortunately, only one link out of the three on that page, actually work. I've been running into this problem frequently on paypal's site with other pages. I will look into the PDF file (the only like that works) in awhile. I can't get to the Code samples though, and I'll bet those would've come in handy for me too...
Comment: You should check if there is a problem with your provider. I have just checked again and had no problem accessing paypal.com site.
Comment: I tried to access the pages in IE 8, and had no problem accessing the pages that weren't showing up before. I recently downloaded Firefox 4...and its been nothing but trouble! Firefox 4 is the reason I've been having problems with pages on Paypal...


Botton webform change bootstrap class

Question: Maybe someone knows why when you change the name of the button, its class changes from btn-primary to btn-default. btn-primary only if there is a submit in the button name (Without spaces before or after).
Comment: Because that's how the bootstrap theme is coded. There's a preprocess function which checks the button label and applies a class based on it.
Comment: In includes/common.inc (`_bootstrap_colorize_button()`)
Comment: Where exactly is this function implemented?
Answer: Thank you so much for Clive help. As it turned out, the _bootstrap_colorize_button function is responsible for choosing which class will be assigned depending on the label. To add a new word to this function, you need to implement hook_bootstrap_colorize_text_alter().
My code.
<code>function myTheme_bootstrap_colorize_text_alter(array &$texts){
  $texts['contains'][t('Register')] = 'primary';
}
</code>
Instead of t ('Register'), you need the word and assign the bootstrap class you need.

Botton webform change bootstrap class


How can I programmatically replace a string on the front page?

Question: I create a custom module which replaces some string on the front page. For nodes, it work correctly, but it doesn't work on the front page. I wrote this code.
function my_module_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
    $generateBlock = NULL;
    $block_manager = \Drupal::service('plugin.manager.block');
    $block_config = [];
    $block_plugin = $block_manager->createInstance('id_block', $block_config);
    $block_build = $block_plugin->build();
    $block_content = render($block_build);

    $block = \Drupal\block_content\Entity\BlockContent::load(4);
    $render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
    $body = $render['body'][0]['#text'];
    $newContent = str_replace('---*block*---', $block_content, $body);
    // I don't know how render the new modified content from $newContent.
    return $variables;
  }
}

I need modify the content with a new string in $newContent, but I cannot save this content to variables. My content is not modified.
Comment: Can you tell us your use case? I doubt that doing this in preprocess_page is the best place to do it, but you haven't told us what your goal is.
Comment: Welcome to Drupal Answers! There is also no need to render a block in `hook_preprocess_page()`, which is probably the wrong place to do it, since Drupal core already renders blocks of its own. If you need to alter a block, there is a hook for that.
Comment: My use case is - that user create block in administration. This block content is with special string  ---*blok*---  - this string is saying where in block user wish generate content from another block 'id_block'

So I need find this string on front page and replace it with my render block. It work correctly in preprocess_node, but not in preprocess_page because I cannot save content - this not work $variables['page']['content']['kontakt'] = $mynewcontent
Answer: Have you considered using the Custom Token and Token Filter modules together?
There's also this brief tutorial on implementing your own custom tokens:
https://codimth.com/blog/web/drupal/how-create-custom-token-drupal-8-9
And here is Token Filter's Readme:
https://git.drupalcode.org/project/token_filter/-/blob/8.x-1.x/README.txt
Comment: Thanks. Custom token was good solution. I created it, and now is much better than before :)


How to play large intervals written for left hand in a Piano with normal sized hand?

Question:
The lower-note seems to be impossibly hard to play. How do I play that?
Is there a specific technique for this? Have Classical Pieces contained these kinds of intervals and how have these kinds of intervals been played by Pianists (now or back then)?
UPDATE:
Here is last part of 23 measure, the last note is not tied with the first of 24th.
Comment: You need to play the low Gb a fraction before the bar and hold it with the sostenuto pedal.
Comment: Darn, what piece is this? You're right, I doubt any human has that hand range - but is there a pedal marking notated earlier in the piece that this picture misses?
Comment: The question refers to a PIANO of course
Comment: No, it isn't. It is Juliet's dream by Abel Korzeniowski, get directly from the composer.
Answer: This is definitely possible, even with smaller hands, though the execution might be tricky depending on the speed of the passage.
Play the first Db in the middle line and the Bb whole note above with the 1st and 3rd finger of your right hand while playing the low Gb with the 5th finger of your left. (ignore the top Bb, as it is tied to the note in the previous measure and should not be played again)
Jump your left hand up to play the second note of the middle line (C) with the 1st finger of your left hand (holding the low Gb with the sustain pedal). At the same time, replace the right 3rd finger on Bb with the right 1st finger (keeping the note held down).
Play the next note in the middle line with the left 2nd finger (crossing over the 1st finger) and the top Gb with the right 3rd or 4th. Figure out the remaining fingering from there.
Hope that made some sense! Swapping fingers on a key without releasing it will take some practice. It might help to practice each hand separately for a bit.
EDIT:
In response to your update, the solution is simple: just play the bottom Gb with the 1st toe of your left foot.
Joking aside (but seriously, that would be totally awesome!), I do not see any way to play this precisely as written, given that the top note is not tied. That said, piano scores with impossible intervals are not unheard of and the standard technique is, in fact, to play the bottom note just before the rest, catching it with the pedal (as others have suggested). With some practice this can be done quickly enough to almost be imperceptible.
Below is an example from Schubert's Impromptu Op. 90, No 3 of how this is often notated. (Fun fact: In the original score, Schubert just left it as is and let the pianist try to figure it out. The rolled chord notation was added in later by editors since it was impossible to play as written for most pianists. Go figure!).
Comment: Thank you for your comment, but the upper note is not tied, I added more details, could you take a look at it again?
Comment: @WojciechS. Updated my answer :)
Answer: The video shows how someone plays this piece!
As Old Brixtonian says, you have to play the Gb in the l.h. just in advance of the 16th notes:
Answer: If the top note is tied and not slurred, you could hit the first 16th note with your right thumb.
The movement required by both hands after that is possibly uncomfortable but worth a try...
Comment: ...Or find a different piece to play! Is that top note tied, or is it a slur..?
Comment: @Tim Good call, updated. And of course good advice about choosing another piece. Or simply adapt this one depending on where it's to be used!


Nested List Operations By Index

Question: I have a nested list, each element within the nested list is a group of 4.  I want to perform arithmetic on each element in the list but am unsure how to access them.
my_nested_list = [[1, 0, 0, 3], [7, 2, 2, 3], [1, 3, 4, 3]]

for i in my_nested_list:
    for num in i:
        if num[0] == 7:
            num[1] = num[1] * num[1]

How could I square the second number of the nested list if the first number of the nested list == 7?  I thought the code I have above would work but it is not.  Any ideas?
The output I am expecting is for the 2 to become 4.
my_nested_list = [[1, 0, 0, 3], [7, 4, 2, 3], [1, 3, 4, 3]]

Comment: `my_listed_list` is a list of lists of ints. You have `for i in my_nested_list`, so `i` is a list of ints. You have `for num in i`, so `num` is an int. What is `num[0]` supposed to be?
Comment: just updated the output I am expecting.
Comment: @oppressionslayer Three are wrong, one replaces the outer loop with an index-loop, and one appallingly pops+inserts. student's answer is the only one not bad.
Answer: You can iterate through list in nested list for which you may only need to check first element instead of iterating inner list. May be you could try following:
my_nested_list = [[1, 0, 0, 3], [7, 2, 2, 3], [1, 3, 4, 3]]

for num in my_nested_list:
    if num[0] == 7: # for each list only need to compare first element
        num[1] = num[1] * num[1]
print(my_nested_list)

Output:
[[1, 0, 0, 3], [7, 4, 2, 3], [1, 3, 4, 3]]

Answer: my_nested_list = [[1, 0, 0, 3], [7, 1, 2, 3], [1, 3, 4, 3]]

for i in my_nested_list:
  for j in 3: # you have 3 lists
    if my_nested_list[j][i] == 1:
      my_nested_list[j][i+1]**2

Nested List Operations By Index


Is $\frac{A}{2}$ defined, when $A$ is a matrix?

Question: Given $A$ is a matrix, can I write something like $A = \frac{A}{2} + \frac{A}{2}$ ? Because I remember that it's not allowed to divide matrices
Comment: It makes sense because $\frac{1}{2}$ is a real not a matrix
Comment: It's fine since $A=(a_{ij})_{ij}$ and $\frac{A}{2}=\left(\frac{a_{ij}}{2}\right)_{ij}$
Comment: You are not allowed to divide *by* matrices.  However, you can *divide* a matrix by a *scalar* (a number).
Answer: Here, $\frac{A}{2}$ means $\frac{1}{2}A$ which makes sense as it is simply multiplying a matrix by a scalar.
Answer: You are right, dividing matrices is problematic, since the multiplication is neither commutative nor do all matrices have multiplicative inverses. However, dividing by a non-zero scalar $\lambda$ can be defined as $\frac{A}{\lambda} = \frac{1}{\lambda} A$, where now scalar multiplication is defined by multiplying each of the entries of $A$ with $\frac{1}{\lambda}$, effectively dividing all entries of $A$ by $\lambda$.


Concerning bijections between intervals of real numbers.

Question: To construct a bijection between, say, $A = (0,1) \subset \mathbb{R}$ and $B = [0,1] \subset \mathbb{R}$, the following function is often used:
$$ f(a) =
\begin{cases}
0,  & \text{if $a = \frac{1}{2}$} \\
1, & \text{if $a= \frac{1}{3}$} \\
\frac{1}{n-2}, & \text{if $a = \frac{1}{n}$, for $n \ge 4$}
\end{cases}$$
where $a \in A$, and $b \in B$.
But, what about all of the irrationals in $A$ and $B$? Clearly, $f$ only accounts for rational numbers, does it not? Perhaps it's trivial, as one could simply add the case that $f(a) = a$ if $a \in \mathbb{R} \setminus \mathbb{Q}$ (although, I'm not sure if that's actually even well-defined); but since this bijection is often presented without any qualification, I assume I'm missing something obvious here...
Comment: That is exactly what is going on, that it maps irrationals to themselves *and also maps all rationals not of the form $\frac{1}{n}$ to themselves*.  Wherever you copied it from just forgot to mention how $f$ acts on numbers not of the form $\frac{1}{n}$ for any $n$
Comment: Related: [how to define a bijection between $(0,1)$ and $(0,1]$](https://math.stackexchange.com/questions/160738/how-to-define-a-bijection-between-0-1-and-0-1?rq=1).
Answer: As you suggest, making $f$ the identity on the irrationals will do just fine. You also have to define $f$ on the rationals whose numerator is greater than $1$. Easy question: what do you suggest there?
This is perfectly well defined. It's even continuous at most points.
Comment: Oh, right. Yes, similarly the identity map would work for all real numbers of the form $\frac{p}{q}$ where $p > 1$ and $q > 0$ are relatively prime integers (i.e., the rational numbers reduced to their lowest terms).