If the second derivatives $f_{xx}$ and $f_{yy}$ exist, does $f_{xy}$ exist?

Question: If the second derivative with respect to to $x$ exists ($f_{xx}$) and the second derivative with respect to $y$ ($f_{yy}$), does it follow that $f_{xy}$ exists?
Comment: Do you want the derivative to exist over the whole domain or just at a point?
Comment: Just one pointt
Comment: Try to adapt the example given at your other question.
Answer: The general answer is

Yes, if the second derivatives  $\:f_{xx} $ and $ \:f_{yy}$  are continuous, and
No (not necessarily), if $\:f_{xx} $ and $ \:f_{yy}$ are discontinuous.

For your specific case some clarification is required.
If by saying "second derivatives $\:f_{xx} $ and $ \:f_{yy}$ exist at a point $P$"  you mean that the corresponding right and left limits exist and are equal, i.e. for a point $P = (x,y)$
$$
\lim\limits_{\Delta x \to 0} \dfrac{f_x(x + \Delta x,y) - f_x(x , y)}{\Delta x} =
\lim\limits_{\Delta x \to 0} \dfrac{f_x(x,y) - f_x(x - \Delta x, y)}{\Delta x}
\tag{1a}
$$
and
$$
\lim\limits_{\Delta y \to 0} \dfrac{f_y(x,y + \Delta y) - f_y(x , y)}{\Delta y} =
\lim\limits_{\Delta y \to 0} \dfrac{f_y(x,y) - f_y(x, y - \Delta y)}{\Delta y},
\tag{1b}
$$
then YES, $\ f_{xy}$ exists, as conditions $ \eqref{1a}$ and $ \eqref{1b} $ imply that $f_{xx}$ and $f_{yy}$ are continuous at $P$.

Proving first case is not difficult. One write something like

For any function $f: \mathbb{R}^2 \to \mathbb{R}$ with continuous second partial derivatives at a point $P = (x,y)$ we have $f_{xy} = f_{yx}$  (Schwartz-Clairaut theorem). That means that the order in which you differentiate with respect to different variables does not matter. The existence and continuity of $f_{yy}$ implies that you can differentiate function $f$ at least once w.r.t. $y$ and preserve continuity. Similarly, we conclude that we can differentiate $f$ at least once w.r.t. $x$ and preserve continuity. These two operations are independent, so the result of applying both of them to $f$ will still be continuous, i.e. the corresponding right and left limits exist and are equal. That means that $f_{xy}$ exists and is continuous at the point $P$.

As for the second case, we can provide a counterexample. For instance, assume $P = (0,0)$ and consider function
$$
f(x) = \begin{cases}
\dfrac{xy(x^2-y^2)}{x^2+y^2} & \text{for } \ (x,y) \neq P,\\
(0,0) & \text{for } \ (x,y) = P.
\end{cases}
$$
Clearly $f$ is continuous at $P=(0,0)$, but its second partial derivatives are not.


How can I use onchange attribute with symfony 1.4

Question: I'am using symfony 1.4 with propel orm. I have 3 tables such as countries, states and counties. I want to use the onchange attribute to avoid overload and pass over unrelated records. How can I use onchange attribute in form classes.
Answer: Why use it in the form class and not in you view (and use it with ajax) when rendering the field? That assuming you are not doing an echo $form and you are echoing each field (label, error, field). If you do an echo $form, you might need to write it in the form class (imo this belongs in the view, not in the class, but that's another problem). Just use the array attributes parameter with you are defining the widget. Something like:
$this->widgetSchema['state'] = new sfWidgetFormDoctrineChoice(array(blabla), array('onchange' => 'someJsFunction'));

If you want to also restrict the choices, then, in the form classes (for example to only populate a select with the US states when US has been selected in the country selectbox), send the  context to the form as an option:
in your actions:
$this->form = new whateverForm(array(), array('context' => $this->getContext()));
in your form do something like:
$context = $this->getOption('context');

if (!$context instanceOf sfContext) throw new sfException('whateverForm needs the context.. bla bla');

$taintedValues = $context->getRequest($this->getName());
$country = $taintedValues['country'];`

That will get you the current submited country to display the states only for that country.
Same thing with the counties.


error parsing 'Gemfile', unexpected <<,

Question: I started a new rails project yesterday and everything worked fine.  When I tried to run rails server or bundle install.

[!] There was an error parsing Gemfile: syntax error, unexpected <<,
  expecting end-of-input - <<<<<<< HEAD   ^. Bundler cannot continue.
#  from /home/jhyatt/code/portfolio/Gemfile:10  #
  -------------------------------------------  #  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
  <<<<<< 5.1.3'

Gemfile:
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
<<<<<< 5.1.3'
=======
gem 'rails', '~> 5.1.1'
>>>>>>> 7eea851168152eafdda270b0524cef1d563dc203
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

<<<<<< 3.3.6'

=======
>>>>>>> 7eea851168152eafdda270b0524cef1d563dc203
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Comment: It looks like you need to remove your merge-conflict markers.
Answer: Clean your Gemfile, removing the merge conflicts and try again. Also verify the Rails version you need:
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

gem 'rails', '~> 5.1.3'
gem 'sqlite3'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'bootstrap-sass', '~> 3.3.6'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Comment: Thank you Sebastian. Im new to this and looked everywhere and wasnt find anything that worked. Thanks again!

error parsing 'Gemfile', unexpected <<,


How to import font in PhpStorm

Question: I am making HTML Emailer. The content of the emailer is of Raleway font. that's why I want to import Google's Raleway fonts in PhpStorm.
How can I do so?
Any help would be great.
Comment: Why do you want to import it? To use it as font for your code? Or in a project? What language is your project? Please be clear in your question. **PS:** don't use it as font for your programming, you probably want a *monospace* font for that.
Comment: Still it isn't clear to me. An HTML emailer. How do you want to use the font? Must the user see the font in the received email? Are you using an email library? How are the emails generated?
Comment: i have edited question
Comment: `font-family: 'Raleway', sans-serif.`i have written this syntax to use my contents' font as Raleway . yes.. user must see the fonts which i have given in my HTML Email. and I am not using any email library. as Outlook doesn't support any third party library.
Comment: I still do not understand what do you mean by "importing" here. 1) It's a font from Google Fonts services 2) You just doing HTML/CSS .. so what's the problem here? Just follow instructions from Google Fonts and use it. 3) *"as Outlook doesn't support any third party library."* Same here -- what this supposed to mean?
Answer: There is no need to add fonts to the IntelliJ IDE directly. You should install the font to your OS.

For Ubuntu:

Download the font (e.g. .otf),
Unzip it,
and then install by double-clicking on the font file and push 'install' btn,
or alternatively: put your fonts in /usr/share/fonts/opentype and update the fonts cache with sudo fc-cache -f -v

For the Windows:

Open the Windows Control Panel.
Select Appearance and Personalization.
At the bottom, select Fonts. ...
To add a font, simply drag the font file into the font window.
To remove fonts, just right click the chosen font and select Delete.
Click Yes when prompted.

Go to the PhpStorm (or whatever IntelliJ) Settings -> Fonts, and remove a tick from the 'Show only monospaced fonts' checkbox.

Then you'll see a full list of fonts of your system in the dropdown below.
If there is no your installed font, you should restart your IDE and repeat the 3-rd step.
Enjoy ;)

How to import font in PhpStorm


Validação de campo único em formulário no Asp.Net MVC

Question: Estou desenvolvendo uma aplicação que gerencia inscrições em cursos, e no meu formulário de cadastro tenho o campo CPF, e gostaria de saber como eu faço para deixar esse campo único, ou seja, barrar o usuário de fazer outro cadastro com o mesmo CPF. Se o CPF já existir na tabela, o sistema deve barrar esse CPF existente e o usuário terá que informar outro CPF caso ele queira fazer um novo cadastro.
Answer: Implemente um Attribute de CPF:
namespace MeuProjeto.Attributes
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class CPFAttribute : ValidationAttribute
    {
        private MeuProjetoContext context = new MeuProjetoContext();

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) return null;

            int soma = 0, resto = 0;
            string digito;
            int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
            int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };

            string CPF = value.ToString().Replace(".", "").Replace("-", "");

            if (CPF.Length != 11)
                return new ValidationResult("CPF Inválido.");

            if (Convert.ToUInt64(CPF) % 11111111111 == 0)
                return new ValidationResult("CPF Inválido.");

            if (validationContext.ObjectInstance.GetType() == typeof(Pessoa))
            {
                var model = (Pessoa)validationContext.ObjectInstance;

                if (context.Pessoas.Any(p => (p.Cpf == CPF) && (p.PessoaID != model.PessoaID)))
                {
                    var message = FormatErrorMessage("CPF já está cadastrado.");
                    return new ValidationResult(message);
                }
            }

            string tempCpf = CPF.Substring(0, 9);

            for (int i = 0; i < 9; i++)
                soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i];

            resto = soma % 11;
            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = resto.ToString();
            tempCpf = tempCpf + digito;
            soma = 0;

            for (int i = 0; i < 10; i++)
                soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];

            resto = soma % 11;

            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;

            digito = digito + resto.ToString();

            if (CPF.EndsWith(digito))
                return null;
            else
                return new ValidationResult("CPF Inválido.");
        }

        public override string FormatErrorMessage(string name)
        {
            return name;
        }
    }
}

Use no seu Model:
[CPF]
public String Cpf { get; set; }

A validação é feita pelo ASP.NET MVC.
Answer: Utilize na Controller um metodo que busca o cpf e também um metodo que verifica se o CPF é valido no mesmo método
 private void ValidaCpf(Aluno aluno)
    {

        if (aluno.cpf != null)
        {
            Aluno duplicatealuno = db.Alunos
            .Where(d => d.cpf == aluno.cpf)
            .FirstOrDefault();
            //verifica se o Cpf ´´e igual ao existente e verifica se o id é diferente do aluno cadastrado com o CPF
            if (duplicatealuno != null && duplicatealuno.cpf == aluno.cpf && duplicatealuno.id != aluno.id)
            {
                string errorMessage = String.Format(
                "CPF já cadastrado no sistema");
                //defina qual campo irá receber a mensagem e a mensagem
                ModelState.AddModelError("cpf", errorMessage);
            }

            if (!CpfValido(aluno.cpf))
            {
                string errorMessage = String.Format(
              "CPF inválido");
                ModelState.AddModelError("aluno.cpf", errorMessage);
            }
        }
    }

     #region Helpers
    public bool CpfValido(string cpf)
    {
        int[] multiplicador1 = new int[9] { 10, 9, 8, 7, 6, 5, 4, 3, 2 };
        int[] multiplicador2 = new int[10] { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };
        string tempCpf;
        string digito;
        int soma;
        int resto;
        cpf = cpf.Trim();
        cpf = cpf.Replace(".", "").Replace("-", "");
        if (cpf.Length != 11)
            return false;
        tempCpf = cpf.Substring(0, 9);
        soma = 0;

        for (int i = 0; i < 9; i++)
            soma += int.Parse(tempCpf[i].ToString()) * multiplicador1[i];
        resto = soma % 11;
        if (resto < 2)
            resto = 0;
        else
            resto = 11 - resto;
        digito = resto.ToString();
        tempCpf = tempCpf + digito;
        soma = 0;
        for (int i = 0; i < 10; i++)
            soma += int.Parse(tempCpf[i].ToString()) * multiplicador2[i];
        resto = soma % 11;
        if (resto < 2)
            resto = 0;
        else
            resto = 11 - resto;
        digito = digito + resto.ToString();
        return cpf.EndsWith(digito);
    }

    #endregion

E antes de salvar utilize o método
ValidaCpf(aluno);
 //Caso o cpf exista ele ira mostrar a mensagem
        if (ModelState.IsValid)
        {}

Você pode adicionar na model a definição de campo unico, não tenho certeza se funciona em todos caso ou se esse é seu caso.
[Display(Name = "CPF")]
    [Required(ErrorMessage = "Por favor, preencher o campo CPF.")]
    [Index("INDEX_CPF2", IsUnique = true)]
    [StringLength(14)]
    public string cpf { get; set; }

Comment: O problema desta forma é que ela é executada antes do ciclo normal de validação do MVC, podendo até ser considerada um anti-padrão.


Windows 7 versus 8 Access CNAME'd Share

Question: Here's a situation that came up yesterday: we have a share on a machine we have to access using an alias (CNAME). The machine is running Windows Server 2012 R2, and services Windows 7 and 8 clients.
Windows 7 clients have no issues opening the share \SHARECNAME or \IP.AD.DR.ESS
Windows 8 clients can only open the share by \IP.AD.DR.ESS
What worked eventually was to create SPN records for the CNAME to point to the HOSTNAME (setspn -S HOST/CNAME HOSTNAME, etc.) and suddenly the share was usable.
The HOSTNAME machine did log an error:
"The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server HOSTNAME$. The target name used was cifs/CNAME." for which I haven't found that much information, but did point me in the direction of setting the proper SPN records.
What I'm trying to understand is why the difference in client experience?
Thank you.
Answer: Not exactly sure, but did you happen to set the DisableStrictNameChecking registry setting?
http://www.md3v.com/enable-windows-server-smb-2-0-alias-cname
The IP vs CName along with the SPN is obviously indicating that Kerberos is involved.  Perhaps it's the SMB 3.0 encryption that's showing itself.  This would only be on a Server2012 to Win8 connection, but that's one of the major differences between SMB 2 and SMB 3.  I don't believe that encryption on the shares is enabled by default, but by moving to SMB 3, the protocol might be requiring a Kerberos authentication.
http://blogs.technet.com/b/josebda/archive/2013/10/02/windows-server-2012-r2-which-version-of-the-smb-protocol-smb-1-0-smb-2-0-smb-2-1-smb-3-0-or-smb-3-02-you-are-using.aspx
Comment: @christopher-g-lewis SMB2 and above don't need DisableStrictNameChecking to be set in order to access file shares using an alias. This is only applicable to SMB1. If the server and all clients are SMB2+ capable then this step isn't necessary. Info on this is hard to find on Google, but the "More Information" section in this KB explains - https://support.microsoft.com/en-us/kb/281308
Answer: We had a similar issue with a new NetApp. All W10/2012 clients were not able to access the CNAME share, but W7/2008R2 clients were able to do so. We didn't have to create the CNAME SPN. What we did is remove all SPNs for the CNAME that showed up with setspn -l cname.
NOTE: We had the CNAME as AD computer account as well and it stayed there after.

Windows 7 versus 8 Access CNAME'd Share


Spring @Transactional not starting a transaction

Question: I have a multi-module Maven project with the following structure:
project
  |
   -- data
       |
        -- DepartmentRepository.java
  |
   -- domain
       |
        -- Department.java
  |
   -- service
       |
        -- DepartmentService.java
       |
        -- DepartmentServiceImpl.java
  |
   -- web
       |
        -- DepartmentController.java

The project uses Spring 4.1.4, Spring Data JPA 1.7.2 and Maven 3.1.0.  The following classes are included:
@Entity class Department {}

interface DepartmentRepository extends JpaRepository<Department, Long> {}

interface DepartmentService {
  List<Department> getAll();
}

@Service
@Transactional(readOnly = true)
class DepartmentServiceImpl implements DepartmentService {
  @Autowired
  private DepartmentRepository departmentRepository;

  @Transactional
  public List<Department> getAll() {
    return departmentRepository.findAll();
  }
}

I was hoping that as soon as the code enters DepartmentServiceImpl.getAll, a transaction would have been started.  However, I am finding that this is not the case.  No transaction is started.  I have checked this by examining TransactionSynchronizationManager.isActualTransactionActive() inside this method, which prints false.  I have also checked by putting break points in TransactionAspectSupport.invokeWithinTransaction.  However, as soon as departmentRepository.findAll is invoked, a transaction is correctly started (since SimpleJpaRepository, the class which provides an implementation of the JPA repository interface is also annotated with @Transactional).
A complete sample application demonstrating the problem is available on Github.
Answer: I noticed your annotation-driven mode is set to aspectj
<transaction:annotation-driven mode="aspectj"/>

but you don't seem to have load-time-weaver defined anywhere in your context.
That may or may not be the issue as I only took a quick look. Also, I don't see why you would need aspectj vs the default proxy mode with what you have, so you might be fine just removing the mode="aspectj" altogether and default to proxy.
Comment: I changed `` to `` in the sample application to get the transactions to work.


How can I get Database name, Size, Table name, Objects, Indexes, Check Constraints, Foreign keys in a single query

Question: I am looking for a query to get all the details as mentioned in Subject. I am sure there should be one developed with the same requirement.
Comment: The answer depends on your database engine, which you didn't provide.
Comment: What database do you mean? This thing is different in different databases?
Comment: Thanks for the response. I have an Oracle database with 50 tables. I need a resultset with columns as mentioned in the subject. hope that clarifies the query
Comment: Yes, now it is clear. But one thing. Does your user(schema) has SELECT_ANY_DICTIONARY privilege? Or are you able to SELECT * FROM DBA_OBJECTS for example?
Comment: I mean, do you want the single query for current schema or any schema?
Comment: Additionally, you did not describe a form of the result. It is possible to make plain table or hirerchical result (using CONNECT BY clause)
Answer: <code>select user schema,'1.FIELDS' obj, null name, c.TABLE_NAME,c.COLUMN_ID col_order,c.COLUMN_NAME,
c.DATA_TYPE,c.DATA_LENGTH,c.DATA_PRECISION,c.DATA_SCALE,c.NULLABLE,null condition
from user_tab_columns c
union all
select user,'2.INDEX '||uniqueness,index_name,table_name,i.column_position, i.column_name,null,
null,null,null,null,null
from user_ind_columns i inner join user_indexes using(table_name,index_name)
union all
select user,'3.CONSTR', constraint_name, table_name, csc.position, csc.column_name,null,null,
null,null,null,cs.search_condition
from user_constraints cs inner join user_cons_columns csc using (table_name,constraint_name)
where constraint_type='C'
union all
select user,'4.FK', constraint_name, table_name, csc.position, csc.column_name||'->'||r_constraint_name,
null,null,null,null,null,cs.search_condition
from user_constraints cs inner join user_cons_columns csc using (table_name,constraint_name)
where constraint_type='R'
order by  4, 2, 3, 5
</code>
This will show information regarding to all tables in the curren schema. For each table it shows 1) fields 2) indexes 3) constraints 4) foreign keys


Linear Algebra dependent Eigenvectors Proof

Question: Problem statement:
Let $n \ge 2 $ be an integer.  Suppose that A is an $n \times n$ matrix and that $\lambda_1$, $\lambda_2$ are eigenvalues of A with corresponding eigenvectors $v_1$, $v_2$ respectively.  Prove that if $v_1$, $v_2$ are linearly dependent then $\lambda_1 = \lambda_2$.

I have an intuition as to why this is true, but am having difficulty formalizing a proof.  What I have doesn't seem tight enough.

If $v_1$ and $v_2$ are linearly dependent then $v_1$ lies in the span of $v_2$.  If two eigenvectors lie in the span of one another then only one of them is required in order to form a basis of the eigenspace.
All eigenvalues correspond to a single $n\times 1$ eigenvector or a set of $n\times 1$ linearly independent vectors.
Since $v_1$ and $v_2$ are linearly dependent, we know that there can only be one eigenvalue that corresponds to the single eigenvector.
Thus $\lambda_1$ must equal $\lambda_2$.

Any thoughts or criticism are welcome.
Thanks
Answer: You know that $$Av_1=\lambda_1v_1\\Av_2=\lambda_2v_2$$
If $v_1,v_2$ are linearly dependent, then $v_1=\mu v_2$ for some scalar $\mu$. Putting this in the first equation,
$$A(\mu v_2) = \lambda_1(\mu v_2) \implies Av_2 = \lambda_1 v_2$$
This gives $\lambda_1=\lambda_2$ as desired.
I think your idea is on the right track, but putting it in the above way gives more clarity.


Is Mootools' $$ a synonym of jQuery's $?

Question: I consider jQuery's $ function very handy. I know MooTools returns an Elements instance, but as a selector are there specific differences? Can you select whatever node on the Dom tree?
Comment: Yes, its basically the same. MooTools `document.getElements()` would be maybe a closer match but for the purpose of selecting nodes in the DOM tree they both do the job.
Answer: Mootools started with both functions $ and $$, then they removed the first one (they keep an alias, so you can also use $) in favor of document.id; $$ can be used exactly as the jQuery version. The main difference between the jQuery $ and the Mootools $$ is that the jQuery version will query the DOM using document.querySelector, while the Mootools version will query the DOM and instances of Mootools classes. To query classes, the class must have the method toElement implemented, and the method must return a reference to the DOM element.
You can learn more on elements and element selection, the dollar and dollars functions in the official Mootools website.


Apis are not working on old Android devices (Android 7 or less) in React Native using axios but working in new devices

Question: I used 'axios' library to fetch the data. It is working perfect on new Android devices (Android 9 & 10) but on old devices (Android 7 or less) it always gives Network Error like this: [ Error: Network Error] it seems like the devices could not establish a connection with the https URL.
This question is duplicate of this link below I am also getting this error can anyone help out.
Fix APIs connection problem with old Android OS (Android 7 or less) in React Native using axios

const SERVER_URL = 'https://*****.com/****';

export const getCities = () => async dispatch => {
  let res = await axios.get(`${SERVER_URL}/GetCityList`);
  res = parser.parse(res.data).ArrayOfMCity.mCity;
  if (res && !res.length) {
    res = [res];
  }
  const dropdownCities = [];
  res.forEach(r => {
    dropdownCities.push({label: r.CityName, value: r.CityID});
  });
  dispatch({
    type: GET_CITY,
    payload: {
      cities: res ? res : [],
      dropdownCities,
    },
  });
};
Comment: Hey, did you try the solutions on the link you shared? Make sure you rebuild the APK after - React native can get a bit funky so do it in Android Studio to make sure. We'd need to see your code and end point if these solutions don't work
Comment: Yeah I have tried the solution given in that link but it didn't worked. The thing is it is working perfectly in new android devices but not in old ones.
Answer: Well I got the solution I have tried other api other than my api and it is working perfectly. So I found out that I am having a certificate issue in android old devices. The certificate is not working in old devices from version 7.1 and older.
Here is the link which says that many websites will stop working in older android devices from 1st September 2021
https://www.androidpolice.com/2020/11/07/many-websites-will-stop-working-on-older-android-versions-in-2021/


How can I generate paging links from the URL when using mod_rewrite changes the URL

Question: First of all I am in DESPERATE need of help here PLEASE I will most likely start a bounty as soon as SO lets me.
I have a pretty large site (social network) MANY PAGES, I am currently doing a complete re-write to build it better then I did 2 years ago.  1 thing I have decided to change is the URLs on my site, there were like this http://example.com/?p=page-identifier-name  and sometimes http://example.com/?p=page-identifier-name&page=2&user=343433 you get the point with ultiple items in the URL, I am now switching to use mod_rewrite, I have actually done it, I have the whole site changed to using it but I have 1 huge problem,
My paging function, I LOVE it, it makes really nice paging like this prev 1 2 - 34 35 36 37 - 189 190 next or similar and work pretty well however now that I have switch to using mod-rewrite, obviously my URLs are different now which breaks my pager, I have tried a few things with no luck yet on making it work correctly again, that is why I have provied the full code to the paging below so if you care to help me you can easily drop it into a page and see how it works yourself.
The paging code currently looks for all keys and values in the URL for $_GET it then basicly itterates through all them since some pages have more then others on my site, it then re-build the proper URL with the correct page number and spits it out on the screen for my pager.  So something like www.example.com/?p=mail.inbox is now www.example.com/mail/inbox, if enough items are on the page though then it will show as www.example.com/?p=mail.inbox&page=12 now  www.example.com/?mail/inbox/page/12 another page might have more then just the p=page to show and page=page number some pages also have user_id's and sort by and just differetn things, now I wouldn't mind having somethings just appended to the pretty url but things like page number I would like to show how I want it to  show, I have all the mod_rewrite and regex working I just need help to make my pager code generate the correct links.  Since all pages are processed through the index.php file the page showing is never deeper then the root folder but the it would be nice maybe if I could trick it into thinking it is when it have a pretty url that makes it look like it is in a different folder.  example.com/mail/inbox is really in the root level index and not 2 folders deep,  tried using something like
$selfurl = $_SERVER["REQUEST_URI"].'/page/'. $pagenumber;

If I was on this page www.example.com/mail/inbox then this would make a paging link look like this www.example.com/mail/inbox/page/12 however if I were to click that link, then the new paging links would look like this www.example.com/mail/inbox/page/12/page/34 so obviously that is not the solution, I am really stuck here and if I can not find a solution then I will have to quit using regex and have some really crappy paging, I would really appreciate anyone who can try to help me, I don't see a soltion but surely there has to be one.
<?PHP

class Paging
{

    /*////////////////////////////////////////////////////////////////////////
    * Paging Function
    * //paging(10000, 50, 4); //number of results / items per page / number of page links in center
    * // paging(10000, 50); //or
    */ ///////////////////////////////////////////////////////////////////////
    public static function show_paging($total_results, $items_per_page, $adjacents = 3)
    {
        //$total_results = $reccnt;
        //$items_per_page = $pagesize;
        // adjacements will determinine how many paging links are in the middle of the outer paging

        if ($total_results > $items_per_page) {
            // build our link URLs
            $url_string = "?";
            foreach ($_GET as $k => $v) {
                if ($k != "page") { // <-- the key you don't want, ie "page"
                    if ($url_string != "?") {
                        $url_string .= "&"; // Prepend ampersands nicely
                    }
                    $url_string .= $k . "=" . $v;
                }
            }
            $selfurl = $url_string . '&page=';
            $page = $_GET['page'];
            if ($page) {
                $start = ($page - 1) * $items_per_page;
            }
            else {
                $start = 0;
            }
            if ($page == 0) {
                $page = 1; //if no page var is given, default to 1.
            }
            $prev = $page - 1; //previous page is page - 1
            $next = $page + 1; //next page is page + 1
            $lastpage = ceil($total_results / $items_per_page); //lastpage is = total_results/ items per page, rounded up.
            $lpm1 = $lastpage - 1; //last page minus 1
            /*
            * Now we apply our rules and draw the pagination object.
            * We're actually saving the code to a variable in case we want to draw it more than once.
            */
            $pagination = "";
            if ($lastpage > 1) {
                $pagination .= '

';
                //previous button
                if ($page > 1) {
                    $pagination .= 'prev';
                }
                //pages
                if ($lastpage < 7 + ($adjacents * 2)) { //not enough pages to bother breaking it up{
                    for ($counter = 1; $counter <= $lastpage; $counter++) {
                        if ($counter == $page) {
                            $pagination .= '' . $counter . '';
                        }
                        else {
                            $pagination .= '' . $counter . '';
                        }
                    }
                }
                else {
                    if ($lastpage > 5 + ($adjacents * 2)) { //enough pages to hide some{
                        //close to beginning; only hide later pages
                        if ($page < 1 + ($adjacents * 2)) {
                            for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) {
                                if ($counter == $page) {
                                    $pagination .= '' . $counter . '';
                                }
                                else {
                                    $pagination .= '' . $counter . '';
                                }
                            }
                            $pagination .= '…';
                            $pagination .= '' . $lpm1 . '';
                            $pagination .= '' . $lastpage . '';
                            //in middle; hide some front and some back
                        }
                        else {
                            if ($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
                                $pagination .= '1';
                                $pagination .= '2';
                                $pagination .= '…';
                                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) {
                                    if ($counter == $page) {
                                        $pagination .= '' . $counter . '';
                                    }
                                    else {
                                        $pagination .= '' . $counter . '';
                                    }
                                }
                                $pagination .= '…';
                                $pagination .= '' . $lpm1 . '';
                                $pagination .= '' . $lastpage . '';
                                //close to end; only hide early pages
                            }
                            else {
                                $pagination .= '1';
                                $pagination .= '2';
                                $pagination .= '…';
                                for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) {
                                    if ($counter == $page) {
                                        $pagination .= '' . $counter . '';
                                    }
                                    else {
                                        $pagination .= '' . $counter . '';
                                    }
                                }
                            }
                        }
                    }
                }
                //next button
                if ($page < $counter - 1) {
                    $pagination .= 'next';
                }
                else {
                    $pagination .= 'next';
                    $pagination .= '

';
                }
            }
            echo '
';
            echo '
';
            echo $pagination;
            echo '

';
        }
    }

    // converts page number to a start position number for MySQL query
    public static function page2db($page, $items_per_page)
    {
        if ($page) {
            $start = ($page - 1) * $items_per_page;
        }
        else {
            $start = 0;
        }
        return $start;
    }

}

?>

To use
<?PHP
//to use the paging functions i do something like this
$pagesize = 10;
$start = Paging::page2db($_GET['page'], $pagesize); //page number and items perpage

//the show the pager links
Paging::show_paging($total_count, $pagesize, 4);

?>

UPDATE
I need to figure out a way to get the value from URLs like this and only have the part minus the domain name, so
http://example.com/mail/inbox would only return /mail/inbox this should work on and number of directories and should not return valus like ?var1=something that are on it, so it should only return the folders that are added onto
a domain the catch is these folders are not real folders, they are created with mod_rewrite in the URL
http://example.com/mail/inbox
http://example.com/forums/category
http://example.com/users/online
http://example.com/users/online/friends
I am trying to fix a PHP paging code that is messed up now that I use mod-rewrite, the links it prints to the screen are incorrect because it rebuilds the URL based on the $_GET values, this doesnt work anymore as the names in the URLs do not match the $_GET values
SO if a URL is http://example.com/users/online or http://example.com/users/online/page/22 then I need to rebuld it into a variabe as http://example.com**/users/online/ then my paging code can add on it's page part if needed to.
Answer: First of all, you don´t have to change anything, if the regex in the mod-rewrite is good, it will not touch your http://domain.com/?p=page-identifier-name&page=2&user=343433 url, it will only process the urls where folders are found (folders as in /bla/bla/etc/). So even without your new paging function, everything should work exactly as before with both the old and the new urls.
Apart from that I would always recommend to build your url from scratch, adding the necessary elements as needed so that you always know how the url will / can look and design your mod-rewrite regex accordingly.
So, at the start of the page, get all variables (page, page number, sub-page, etc.) and use these elements to build every url.
Edit: Ok, it seems your pagination is very apart from the rest of the url so a dirty solution would be to search the url you already have for the page-[0-9] part and replace the number or add that part if it is not found. I wouldn´t really recommend it, but it seems possible.
Comment: The problem is that theory does not work if it did then I wouldn't be trying to get it to work, I mean sure I can keep my old generated paging links and they will load the page but if I go to a URl **domain.com/mail/inbox/page/2** and click on the paging link for page 3 it then loads **domain.com?p=mail.inbox&page=3** instead of **domain.com/mail/inbox/page/3** Everybody just assumes that it still works without modifying the PHP and it DOES need to be modified otherwise I get that problem
Comment: Thanks for realizing I have a problem someone actually downvoted my and voted to close this as if I dreamed this up.  As you say you would not recommend it, do you have a method you would recommend? I need to get it working but also has to be good performance so If I need to re-write code then thats what needs to be done but I really don't even see where to start since the URL's get changed
Comment: Like I said, I would always build the url from the ground up. If you use a separate pagination class perhaps that would mean adding the elements of the url as input for the function. And yes, downvotes without comments suck :(
Comment: By the way, I guess there's no harm either in searching the url for a page number and replace it with the new one (or add it if not found...), it just doesn't feel right :-)
Comment: thanks for the tips, I updated the bottom part of my post with an idea I have if I can't find a better one, this would be a lot easiar I think if the directories were real instead of fake ones made by mod-rewrite
Answer: It seems the best method that I have found is to pass into the paging function, the URL of the page I am on using
$pagingurl = 'http://localhost/mail/inbox/';
Paging::show_paging($total_count, 3, $pagingurl, 4);

This seesm liek the best solution for allowing me to use my mod-rewrite URLs
Comment: Yes this is how i go about it
Comment: http://stackoverflow.com/questions/1469067/need-help-with-my-pager-php-function-now-that-i-use-mod-rewrite/1469807#1469807
Answer is in this question


Redirect module does not allow redirection for existing node's path alias

Question: I installed fresh Drupal 8 and after that the Redirect module with proper settings. After adding the redirect rule for a path alias it does not work but it saves data properly into the database.
But it works if I add internal path like node/{id}. In this case it works for internal path as well as path alias.
I just wanted to redirect it on the basis of path alias only. Is it possible to add only path alias for the redirection?
Answer: I just ran into this also.  You may want to look at https://www.drupal.org/project/url_redirect to see if it fits your needs.


Implicit function theorem for level set

Question: Given level set show gradient is zero if function continuously differentiable.
I was asked to show if $\{(x,y)||x|=|y|\}$ is level set of continuously differentiable function $F(x,y)$ by implicit function theorem $\nabla F(0,0)=0$.
So if set is level set then $F(x,\pm x)=c$ for some constant $c$. Hint says assume $\nabla F(0,0)$ is not equal to zero and contradiction.
I know the theorem says if $O$ is open subset of $\mathbb{R}^2$ and $F$ is continuous differentiable, if $(x_0,y_0)$ is point in $O$ with $F(x_0,y_0)=0$ and $Df_y(x_0,y_0) \neq 0$ there is positive number $r$ and continuously differentiable function $g: I \rightarrow \mathbb{R}$ with $f(x,g(x))=0$ for all x in $I$, but don't know if that is correct implicit function theorem it called Dini theorem. How to start this?
I don't know if gradient not zero, one of partials is not zero. So if $\frac{\partial F}{\partial x}(0,0) \neq 0$. Then how to achieve contradiction? Or would be $F(0,0)=c \neq 0$?
Should I define function $g(x,y)=|x|-|y|$ then if gradient not zero, then both $Dg_x(0,0)$ and $Dg_y(0,0)$ not equal $0$?
Answer: 1. The condition $F(x,\pm x)=c$ gives the partial derivatives in the diagonal directions: they are both zero, so the gradient is zero as well.
More formally, consider $G(u,v)=F(u+v,u-v)$,
show that $D_uG(0,0)=D_vG(0,0)=0$,
notice that $\nabla G = A \nabla F$ for some matrix $A$,
and conclude.
2. The proof by contradiction, with the implicit function theorem, is less straightforward.
Let us assume $\nabla F(0,0) \neq 0$.
Then either $D_xF(0,0) \neq 0$ or $D_yF(0,0)\neq0$.
Without loss of generality, we can assume $D_x F(0,0) \neq 0$.
But then, the level set, in a neighbourhood of $(0,0)$, is the graph of a function $x \mapsto g(x)$. But it is not the graph of any function. Contradiction.
Comment: So that is all I need to say since $\frac{\partial F}{\partial x}(0,0)=0$ and $\frac{\partial F}{\partial x}(0,0)=0$ since we are differentiating a constant, then gradient is zero?
Comment: Yes: you can differential $G(u,0)=F(u,u)=c$ wrt $u$.
More directly, you could also differentiate $F(x,x)=c$ and $F(x,-x)=c$ wrt $x$:
you get a system of equations with $D_xF(0,0)$  and $D_yF(0,0)$ as unknowns.
Comment: why is $g(x)$ not the graph of any function? because $|y|=|x|$ is not function?
Comment: Yes: each (non-zero) $x$ should have two images, $x$ and $-x$.

Implicit function theorem for level set


Swimming pace - where should I be and what should I do?

Question: I started training for triathlons 3 years ago and have completed one Olympic distance race each year (in addition to 2-3 half-Marathons per year). I train year-round because it helps me stay in shape. I don't train for races and I mainly compete against myself, but doing a race helps me push my limits. I spend most of my training time with running because it gives me the best workout and I can do it in the winter, but I do enjoy riding and open-water swimming as soon as I can get out. I am in the pond from late April through late October. I am having knee trouble right now and stopped running. As a result, I swim more than in previous years and I pay more attention to how I am doing in the water.
When I began with triathlon training at the age of 48, I initially struggled with finding a freestyle rhythm. I kept switching back to breast stroke. My breathing technique improved quickly, though, and I can now do 2400 meter freestyle swims in open water comfortably without stopping because I have to catch my breath or I swallowed water.
I usually start with a 3-2-3-2 breathing pattern but can sustain a 3-3 pattern as well if I pace myself a little. I can switch between patterns as needed. I pay attention to my form, try to be streamlined, stretch my arm forward, pull back strongly all the way, minimize body roll, look down and keep my neck relaxed. I really feel comfortable in the water at all times. I have books about swimming techniques for triathletes and I seem to be doing everything they say.
But - no matter what I try, I can't swim faster than about 2:30/100m, which appears fast to me but is abysmally slow in comparison and puts me into the bottom 5% in the swim in every race. My biking and running is more middle-of-the-road, so this is not a general physical limitation of my body. Clearly, I must be doing something wrong in the water.
Based on other forum posts, it appears that most people who start out swimming struggle with breathing or fear or other "minor" barriers. Once they overcome this, they can swim a competitive pace. In my case, I don't experience the typical beginner's problems. I am just slow, and I can't find much direct advice that would help me figure out why.
I realize that I could take lessons, do laps in a controlled environment (pool), etc. I am concerned that I will end up spending time and money on a trainer and pool lessons that may not help me because I am swimming already at the ceiling of my abilities. I am not ready for this.
On the other hand, I am so much slower than where I think I should be (at least 20% to 30%) that there must be an obvious cause. I am not just looking to fine-tune my form.
What should I do?
Comment: Get a coach. We can't tell you what's wrong with your swimming, but they will be able to.
Comment: Look for a Masters swim program in your area - they often have a good-sized triathlete contingent. As @PhilipKendall says, a coach is a good idea, and really the only way to observe and diagnose issues. Swimming laps may allow you to focus on speed without needing to navigate.
Answer: I used Triathlete Magazine's Essential Week-by-Week Training Guide: Plans, Scheduling Tips, and Workout Goals for Triathletes of All Levels.  The author maintained that developing speed in the swim portion for triathletes comes from improving technique.  Most triathletes begin triathlons after becoming competent runners or cyclists first.  Very few begin triathlons already being a competent swimmer.  He was saying (nicely) newer triathletes could stand to learn how to swim better.
Lessons with a coach/swim instructor will improve your technique.  Then you can gain muscle memory in a controlled environment, that is, a pool.
Answer: If you didn't swim competitively as a youth, you likely need to start from the beginning to build a technically correct stroke.  Because water is so much more dense than air, drag from the water is the main thing keeping people slow when trying to swim fast.  Without seeing your stroke I wouldn't hazard to coach you other than to say it is very likely your technique that is holding you back, not your strength or fitness.  I would recommend getting someone to video you in the pool them compare what you see to some Olympic level talent, only from a stroke mechanics standpoint.  I would bet every aspect of your mechanics from simple body position on to the fine points of your catch, pull, breathing, kicking, etc. needs improvement.
If you do a YouTube search on "swimming freestyle progression", you will see lots of instructional videos with specific drills to help you improve.  The answer recommending getting coaching is absolutely correct, but seeing yourself on video will help you come to the same conclusion.  It's very difficult to swim correctly without an external set of eyes to evaluate you and give feedback.
Answer: OK, even if triathletes who have not been swimmers are notoriously crappy at swimming, and even if you are almost 50, there's no reason you shouldn't be able to do a sub 2'00" per 100. My suspicion is that it mostly has to do with technique, although cycling and running will leave you lacking in upper body strength too.
The advice you got in the comments is good: find a local masters team, or a triathlon club with a good swim coach. Also, definitely train more in the pool to gain speed and correct technique. Open water swimming is too different from pool swimming to really be able to give the same benefits.
The most common technique flaw in non-swimmers trying to swim is lifting the head. As you lift the head ever so slightly you make your legs sink. That increases drag a lot, since drag depends on the cross-section area you present to the water. That's probably why "total immersion" is so popular with triathletes ans swim-runners.
Another technique flaw you might have gained by not swimming enough pool swimming is lack of reach and finish, and lack of rotation, either as a consequence or cause of the former. In a wetsuit it is easy to swim too flat, not rotating properly, and as a consequence not reaching far enough to catch the water. And when you don't reach, you automatically don't finish, missing the last part of the stroke that would have given the most speed. To gain this technique you require strong core muscles and lats, delts and pecs, so don't cheat out on some gym exercising in addition to the running and cycling.
And good luck!


Check memoryless property of a Markov chain

Question: I suspect that a series of observed sequences are a Markov chain...
$$X=\left(\begin{array}{c c c c c c c}
A& C& D&D  & B & A &C\\
B& A& A&C & A&D &A\\
\vdots&\vdots&\vdots&\vdots&\vdots&\vdots&\vdots\\
B& C& A&D & A & B & E\\
    \end{array}\right)$$
However how could I check that they indeed respect the memoryless property of $$P(X_i=x_i|X_j=x_j)?$$
Or at the very least prove that they are Markov in nature? Note these are empirically observed sequences.  Any thoughts?
EDIT
Just to add, the aim is to compare a predicted set of sequence from the observed ones.  So we'd appreciate comments on as to how best to compare these.
First Order Transition matrix $$M_{ij}=\displaystyle \frac{x_ij}{\sum^mx_{ik}}$$ where m=A..E states
$$
M=\left(\begin{array}{c c c c c c c}
    0.1834&    0.3077 &   0.0769&    0.1479  &  0.2840\\
    0.4697&    0.1136 &   0.0076 &   0.2500  &  0.1591\\
    0.1827&    0.2404&    0.2212 &   0.1923 &   0.1635\\
    0.2378 &   0.1818&   0.0629&    0.3357 &   0.1818\\
    0.2458 &   0.1788&    0.1173 &   0.1788  &  0.2793\end{array}\right)$$
Eigenvalues of M
$$E =\left(\begin{array}{c c c c c c c}
   1.0000    &              0       &           0    &              0   &               0 \\
        0   &         -0.2283    &              0  &                0    &              0 \\
        0        &          0      &       0.1344   &               0  &                0\\
        0     &             0    &              0   &          0.1136 - 0.0430i &       0   \\
        0   &               0     &             0  &                0  &           0.1136 + 0.0430i\\
    \end{array}\right)$$
Eigenvectors of M
$$V =\left(\begin{array}{c c c c c c c}
   0.4472&            -0.5852    &        -0.4219   &         -0.2343 - 0.0421i & -0.2343 + 0.0421i\\
   0.4472  &           0.7838   &         -0.4211  &          -0.4479 - 0.2723i & -0.4479 + 0.2723i\\
   0.4472  &          -0.2006  &           0.3725 &            0.6323  &           0.6323          \\
   0.4472  &          -0.0010     &        0.7089      &       0.2123 - 0.0908i &  0.2123 + 0.0908i\\
   0.4472   &          0.0540    &         0.0589    &         0.2546 + 0.3881i  & 0.2546 - 0.3881i\\
    \end{array}\right)$$
Comment: Possible duplicate: http://stats.stackexchange.com/questions/29490/test-for-markov-property-in-a-time-series
Comment: The linear regression was an example to strengthen the point of my argument. I.e. that you might not need to test Markov property directly, you only need to fit some modem which assumes Markov property and then check for model validity.
Comment: I vaguely remember I have seen somewhere a hypothesis test for H0={Markov} vs H1={Markov order 2}. This could help.
Comment: The columns contains the series, and the rows the elements of the sequences? What is the observed number of rows and columns?
Comment: @mpiktas The rows represent the independent observed sequences of transitions through states A-D.  There are some 400 sequences... Bear in mind that the sequences observed are not all of the same length. In fact the above matrix in many cases is augmented by zeros.  Thank you for the link by the way.  It seems that there is still considerable room for work in the this field.  Do you have any further thoughts? Regards,
Comment: If the sequences are not the same, we can assume that they come from different Markov processes, then you must check each series individually. I thought maybe there is a possibility of pooling data.
Comment: Concerning further thoughts, is it really necessary for you to check the Markov property? Maybe you just use a model for which Markov property is essential? Then use the model and check for discrepancies. I think you can draw parallels with linear regression. There is no test that there is a specific linear relationship in your data. That is why residual diagnostics is so important, they help you to see whether model is useful approximation or not.
Comment: Your comment is appreciated. I wonder if the Levenshtein http://en.wikipedia.org/wiki/Levenshtein_distance difference between strings is a possible way of comparing the groups.  So it's really an indirect way of proving that the Markov properties hold in the observed series... somehow this seems a bit precarious though and may not hold water.
Comment: I'm not sure how you'd use linear regression in our case, could you elaborate as to what parameters you'd be comparing?
Comment: I see exactly what you mean now. If you pop that onto an answer I'll give it a tick. Regards,
Answer: Markov property might be hard to test directly. But it might be enough to fit a model which assumes Markov property and then test whether the model holds. It may turn out that the fitted model is a good approximation which is useful for you in practice, and you need not to be concerned whether Markov property really holds or not.
The parallel can be drawn to the linear regression. The usual practice is not to test whether linearity holds, but whether linear model is a useful approximation.
Comment: This seems like the best option in reality, only I cannot actually compare a linear model to any actual experimental data. Or did you have something else in mind?
Answer: To concretize the suggestion of the previous reply, you first want to estimate the Markov probabilities - assuming it's Markov. See the reply here Estimating Markov Chain Probabilities
You should get a 4 x 4 matrix based on the proportion of transitions from state A to A, A to B, etc. Call this matrix $M$. $M^2$ should then be the two-step transition matrix: A to A in 2 steps, and so on. You can then test if your observed 2 step transition matrix is similar to $M^2$.
Since you have a lot of data for the number of states, you could estimate $M$ from one half of the data and test $M^2$ using the other half - you are testing observed frequencies against theoretical probabilities of a multinomial. That should give you an idea of how far off you are.
Another possibility would be to see if the basic state proportions: proportion time spent in A, time spent in B, matches the eigenvector of the unit eigenvalue of M. If your series has reached some sort of steady state, the proportion of time in each state should tend to that limit.
Comment: Do it the same way you did M, only instead of looking at nearest neighbour transitions, (say, sequences AB), look at pairs that are 2 apart. So, if a subject goes ACB, that counts towards your AB transition count. So does ABB. Create a matrix where item in row i, column j contains the i to j transitions. Then divide by the column totals. You want the columns to sum to 1. Under the Markov property, this matrix should be close to $M^2$
Comment: There's a bit to take in there.I have calculated the Transition matrix $M$, but I'm not sure how you'd calculate the $M^2$ empirically. Could you clarify that point?  Regards,
Comment: Also, the latter comment is very interesting, although I don't have the time spent in each state of my observed sequences. I only have the total time for each row. So that may limit the applicability of that method.  What are your thoughts?
Comment: RE: equilibrium. I was assuming that the transitions occur at set moments - say every second, you transition from current state to next state. You could take the frequency of A, B, C, and D states near the ends of the sequences, or across sequences to estimate the limit behaviour.
Comment: In R, if you do eigen(M), you should get the eigenvalues and eigenvectors of M. One eigenvalue will be 1. The corresponding eigenvector should be proportional to your steady state proportions .... if Markov.
Comment: When you say $M^2$ should be 'close' to $M^2' from the observed data, what exactly do you mean by 'close'? A ranksum test shows me that the H0 hypothesis cannot be rejected at the 5% level. Would you use a different test? If you could could just clarify that a little further we'll be able to  wrap up the bounty.
Answer: I wonder if the following would give a valid Pearson $\chi^2$ test for proportions as follows.

Estimate the one-step transition probabilities -- you've done that.
Obtain the two-step model probabilities:
$$
\hat p_{U,V} = {\rm Prob}[X_{i+2}=U|X_i=V] = \sum_{W\in\{A,B,C,D\}} {\rm Prob}[X_{i+2}=U|X_{i+1}=W]{\rm Prob}[X_{i+1}=W|X_i=V]
$$
Obtain the two-step empirical probabilities $$\tilde p_{U,V} = \frac{\sum_i \# X_i = V, X_{i+2} = U}{\sum_i \# X_i = V}$$
Form Pearson test statistic $$T_V = \# \{X_i = V\} \sum_U \frac{(\hat p_{U,V} - \tilde p_{U,V})^2}{\hat p_{U,V}}, \quad T=T_A + T_B + T_C + T_D$$

It is tempting for me to think that each $T_U \sim \chi^2_3$, so that the total $T\sim \chi^2_{12}$. However, I am not entirely sure of that, and would appreciate your thoughts on this. I am not likewise not co sertain about whether one needs to be paranoid about independence, and would want to split the sample in halves to estimate $\hat p$ and $\bar p$.
Comment: Don't the probabilities have to have a normal distribution with mean 0 and variance=1 for this to hold? I'd be very interested to know what anyone thinks here.
Comment: That's what the terms in the sum are supposed to be, asymptotically with large counts.
Answer: I think placida and mpiktas have both given very thoughtful and excellent approaches.
I am answering because I just want to add that one could construct a test to see if $P(X_i=x|X_{i-1}=y)$ is different from $P(X_i=x|X_{i-1}=y \text{ and } X_{i-2}=z)$.
I would pick values for $x$, $y$ and $z$ for which there are a large number of cases where the transition from $z$ to $y$ to $x$ occurs.  Compute sample estimates for both probabilities.  Then test for difference in proportions. The difficult aspect of this is to get the variances of the two estimates under the null hypothesis that say the proportions are equal and the chain is stationary and Markov.  In that case under the null hypothesis if we just look at all 2 stage transitions and compare them to their corresponding three stage transitions but only include outcomes where these sets of paired outcomes are separate by at least 2 time points then the sequence of joint outcomes where success is defined as a $z$ to $y$ to $x$ transition and all other two stage transitions to $x$ as failures represent a set of independent Bernoulli trials under the null hypothesis.  The same would work for defining all $y$ to $x$ transitions as successes and other one stage transitions to $x$ as failures.
Then the test statistic would be the difference between these estimated proportions.  The complication to the standard comparison of the Bernoulli sequences is that they are correlated.  But you could do a bootstrap test of binomial proportions in this case.
The other possibility is to construct a two by two table of the two stage and three stage paired outcomes where $0$ is failure and $1$ is success and the cell frequencies are counts for the pairs $(0,0)$, $(0,1)$, $(1,0)$ and $(1,1)$ where the first component is the two stage outcome and the second is the corresponding three stage outcome.  You can then apply McNemar's test to the table.
Comment: I see what you are referring to here although I'm finding the first paragraph very terse however. For example "Compute sample estimates[...], then test for difference in proportions". What do you mean by sample estimates?  Surely there would be no variance in $$P(X_i|X_{i-1}=y)$$ or am I misunderstanding your train of thought?
Comment: @user1134241 You mentioned "empirically observed", I assumed that you have data from this stochastic sequence. If you want to estimate P(X$_i$=x|X$_i$$_-$$_1$=y) for each index i-1 where X$_i$$_-$$_1$=y, count the number of times X$_i$ = x and divide it by the number of times X$_i$$_-$$_1$ = y (regardless of what X$_i$ equals). That is an estimate because the observed finite sequence is just a sample of a portion of a sequence of the stochastic process.
Comment: In your last paragraph, let me ask what constitute a success and exactly? In the case where you say a two-step transition: are you saying $i\rightarrow j\rightarrow i$ and a 3-step would be $i\rightarrow j\rightarrow k\rightarrow i$?
Answer: Beyond Markov Property (MP), a further property is Time
Homogeneity (TH): $X_t$ can be Markov but with its transition matrix
$\mathbf{P}(t)$ depending on time $t$. E.g., it may depend on
the weekday at $t$ if observations are daily, and then a dependence
$X_t$ on $X_{t-7}$ conditional on $X_{t-1}$ may be diagnosed if TH
is unduly assumed.
Assuming TH holds, a possible check for MP is testing that $X_t$ is independent
from $X_{t-2}$ conditional on $X_{t-1}$, as Michael Chernick and StasK
suggested.  This can be done by using a test for contingency table.
We can build the $n$ contingency tables of $X_t$ and $X_{t-2}$
conditional on $\{X_{t-1} = x_j\}$ for the $n$ possible values $x_j$,
and test for independence. This can also be done using $X_{t-\ell}$
with $\ell > 1$ in place of $X_{t-2}$.
In R, contingency tables or arrays are easily
produced thanks to the factor facility and the functions apply,
sweep. The idea above can also be exploited graphically. Packages ggplot2 or lattice easily provide conditional plots to compare conditional
distributions $p(X_t \vert X_{t-1}=x_j, X_{t-2} = x_i)$.  For instance
setting $i$ as row index and $j$ as column index in trellis should under MP lead to similar
distributions within a column.
The chap. 5 of the book The statistical analysis of stochastic  processes in time by J.K Lindsey contains other ideas for checking assumptions.

[## simulates a MC with transition matrix in 'trans', starting from 'ini'
simMC <- function(trans, ini = 1, N) {
  X <- rep(NA, N)
  Pcum <- t(apply(trans, 1, cumsum))
  X[1] <- ini
  for (t in 2:N) {
    U <- runif(1)
    X[t] <- findInterval(U, Pcum[X[t-1], ]) + 1
  }
  X
}
set.seed(1234)
## transition matrix
P <- matrix(c(0.1, 0.1, 0.1, 0.7,
              0.1, 0.1, 0.6, 0.2,
              0.1, 0.3, 0.2, 0.4,
              0.2, 0.2, 0.3, 0.3),
            nrow = 4, ncol = 4, byrow = TRUE)
N <- 2000
X <- simMC(trans = P, ini = 1, N = N)
## it is better to work with factors
X <- as.factor(X)
levels(X) <- LETTERS[1:4]
## table transitions and normalize each row
Phat <- table(X[1:(N-1)], X[2:N])
Phat <- sweep(x = Phat, MARGIN = 1, STATS = apply(Phat, 1, sum), FUN = "/")
## explicit dimnames
dimnames(Phat) <- lapply(list("X(t-1)=" ,"X(t)="),
                         paste, sep = "", levels(as.factor(X)))
## transition 3-fold contingency array
P3 <- table(X[1:(N-2)], X[2:(N-1)], X[3:N])
dimnames(P3) <- lapply(list("X(t-2)=", "X(t-1)=" ,"X(t)="),
                       paste, sep = "", levels(as.factor(X)))
## apply ONE indendence test
fisher.test(P3[ , 1, ], simulate.p.value = TRUE)
## plot conditional distr.
library(lattice)
X3 <- data.frame(X = X[3:N], lag1X =  X[2:(N-1)], lag2X = X[1:(N-2)])
histogram( ~ X | lag1X + lag2X, data = X3, col = "SteelBlue3")

]
Answer: You could bin the data into evenly spaced intervals, then compute the unbiased sample variances of subsets $\{X_{n+1}:X_n=x_1,X_{n-k}=x_2\}$. By the law of total variance, $$\mathrm{Var}[E(X_{n+1}|X_n,X_{n-k})|X_n] = \mathrm{Var}[X_{n+1}|X_n]-E(\mathrm{Var}[X_{n+1}|X_n])$$
The LHS, if it is almost zero, provides evidence that the transition probabilities do not depend on $X_{n-k}$, though it is clearly a weaker statement: e.g., let $X_{n+1}\sim N(X_n,X_{n-1})$. Taking the expected value of both sides of the above equation, the RHS can be computed from the sample variances (i.e., replacing expected values with averages). If the expected value of the variance is zero then the variance is 0 almost always.


Can you show that $\bar{X}$ is a consistent estimator for $\lambda$ using Tchebysheff's inequality?

Question: This question was taken from a practice exam in my statistics course.
Given a random sample $X_1, X_2, ... X_n$ from a Poisson distribution with mean $\lambda$, can you show that $\bar{X}$ is consistent for $\lambda$?
We are told to use Tchebysheff's inequality. Which is: $Pr(|X-\mu| \geq k\sigma) \le \frac{1}{k^2}$
Also, as far as I know, consistency of an estimator is the property that as we increase the sample size of $\bar{X}$, our estimator should return values closer and closer to the actual value we want to estimate.
So the first thing I did was find the variance for $\bar{X}$ as follows:
$Var(\bar{X})=Var(\frac{\sum(X_i)}{n})=\frac{1}{n^2}Var(\sum(X_i))=\frac{\lambda}{n}$
I notice that as $n \rightarrow \infty $ the variance decreases to $0$, but how does this help me?
Now I guess we can use Tchebysheff's inequality where we need $Pr(|\bar{X}-\lambda| \geq \epsilon) = 0$ and that is where I get stuck...
Any help is appreciated.
Comment: I've updated my question again.
Comment: Please add the `self-study` tag and read its [tag wiki](http://stats.stackexchange.com/tags/self-study/info),modifying your question as asked there (e.g. identify your specific problem). "I can't do it, show me how" is not adequate.
Comment: You haven't yet dealt with what *consistency* is. See steps 1 and 2 below - you haven't mentioned what it is you need to show to demonstrate consistency. (You also didn't write down the general form of Chebyshev - i.e. step 3 - before substituting details from this specific problem into it, so if you made a mistake there you would make it difficult for people to point out where you went wrong.) Please do steps 1, 2 and 3 properly, so that hints that relate parts of what you write can be offered. It appears such skipping over of essential steps is leading you into difficulty in the first place.
Comment: $E(\bar X)\to\lambda$ and $V(\bar X)\to 0$ as $n\to\infty$ is a sufficient condition for $\bar X$ to be a consistent estimator of $\lambda$.
Answer: Edit: Since it seems the point didn't get across, I'm going to fill in a few more details; it's been a while, so maybe I can venture a little more.
Start with definitions.
step 1: give a definition of consistency
Like this one from wikipedia's Consistent estimator article:

Suppose ${p_θ: θ ∈ Θ}$ is a family of distributions (the parametric model), and $X^θ = {X_1, X_2, \ldots : X_i ~ p_θ}$ is an infinite sample from the distribution $p_θ$. Let ${ T_n(X^θ) }$ be a sequence of estimators for some parameter $g(θ)$. Usually $T_n$ will be based on the first $n$ observations of a sample. Then this sequence ${T_n}$ is said to be (weakly) consistent if
$\underset{n\to\infty}{\operatorname{plim}}\;T_n(X^{\theta}) = g(\theta),\ \ \text{for all}\ \theta\in\Theta$

step 2: Note (hopefully!) that it relies on convergence in probability, so give a definition for that in turn (wikipedia article on Convergence of random variables).

A sequence ${X_n}$ of random variables converges in probability towards the random variable $X$ if for all $ε > 0$
$\lim_{n\to\infty}\Pr\big(|X_n-X| \geq \varepsilon\big) = 0.$

step 3: Then write Chebyshev's inequality down:

Let $X$ (integrable) be a random variable with finite expected value μ and finite non-zero variance σ2. Then for any real number $k > 0$,
$\Pr(|X-\mu|\geq k\sigma) \leq \frac{1}{k^2}.$

(wikipedia article on Chebyshev's inequality)
step 4: now look at the rather strong similarity between two expressions in (2) and (3).
Does that not give you a huge clue about a way to approach this?

So let's start
From Chebyshev:
$Pr(|\bar{X}-\lambda| \geq k\lambda/n) \le \frac{1}{k^2}$ (you worked out all the parts of this but never actually wrote it down in your question. I can't fathom why you wouldn't)
Let $\epsilon=k\lambda/n$ (that's the obvious step from the "huge clue" you were supposed to see by comparing the two things I said to write down ... one had an $\epsilon$ where the other had a $k\lambda/n$ ... if you'd written them both down, as I'd been suggesting, I expect it would have been obvious as soon as you compared them).
So now, the only thing that's really left is to show that for any $\epsilon$, as $n\to\infty$, the RHS goes to 0.


Accounting Student taking Master in Stat, need your help regarding taking subjects

Question: I had a Bachelor in Accounting and now I'm doing a Masters in Statistics.
This is my first semester and I have to Choose at least 3 out of 6 offered subjects for this semester. These subjects Are:

Mathematics for Statistics
Applied Modeling
Regression Analysis
Bayesian Statistics
Categorical Data Analysis
Survival Analysis

I'm going to take Math for sure as I believe its the base to understand the other courses. The problem is that I'm not sure what are the other 2 subjects that I should take. The reason behind this doubt is that my background in math is still not solid. So, I'm trying to know which two of these courses are the least dependent on math.
Comment: Ask around locally. Look for statements of prerequisites. Unless you name your institution people can only guess how they're taught.
Comment: Most of the math for statistics courses is "real analysis", so I would suggest looking for maths courses of this kind.
Answer: Basically all these subjects can be taught in a more or less mathematical way- in a way with more proofs or with a more practical intuitive way. You should look at the Curriculum of your university and/or ask professors/TAs.

Mathematics for Statistics

As you are pretty new to quantitative subjects you should go for this one. It is a good idea. It probably includes some real analyses and some matrix algebra. Most data analysis is based on concepts of linear algebra (e.g. inverse, pseudo-inverse, transpose of a matrix)

Applied Modeling

This one might be interesting for you as you have a finance background and modelling is often used in quantitative finance. There you have many stochastic processes, e.g. Marcov Processes.

Regression Analysis

Regression analysis is the basis for supervised machine learning and forecasting. Especially in business/economics it is still the most widespread quantitative area. You should really take this course. If you have deeply understood the idea behind regression it might be easier for you to understand other Supervised ML algorithms particularly classification.

Bayesian Statistics

Sounds more theoretical. It might give you a more theoretical view on "Applied modelling". So if you are really interested in random processes, e.g. MCMC, it might be a good one to choose.

Categorical Data Analysis

Might be a specific case of regression analysis for count data. You should better take the basic "regression Analysis" course. Here they might teach you some models like Poisson and Negative Binomial regressions which are rather less used in the industry except of insurances.

Survival Analysis

Might be a specific case of regression analysis for count data. You should better take the basic "regression Analysis" course. Here they might teach you some models like Kaplan Meier and Hazard functions which are rather less used in the industry except of insurances.
Final words:
It might be better to talk to former students, TAs or Professors at your university like @NickCox stated. It might also be good to show the course descriptions to someone who is proficient in the area. However based on the names of the course I would take Mathematics for Statistics and Regression Analysis and one topic you are interested in. Applied Modelling might be a good choice.
Comment: Thank you all guys and special thank to you Mr.Fredi. I really appreciated your effort to answer my question and helping me.


How to configure SpamAssassin to set Atlassian JIRA notifigations to white list?

Question: I have problem Atlassian JIRA email notifications. These notifications come to deleted by SpamAssassin some reason.
So I need to know how to confirgure SpamAssassin to but these notications to whitelist.
I configured firstname.lastname@example.com email to whitelist but that does not help or I just confirgured this wrong.
I tested now my JIRA and all emails that is sent from address email@example.com to firstname.lastname@example.com is deleted with SpamAssassin and emails that is sent from email@example.com to email@example.com come to not deleted with SpamAssassin. This occurs only JIRA but not other Atlassian products like FishEye or Crucible, etc.
Can anyone help me on this issue?
Here is smtp result:
root@alm:~# postconf | grep smtpd_recipient_restrictions
postconf: warning: /etc/postfix/main.cf: unused parameter:    virtual_overquota_bounce=yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
postconf: warning: /etc/postfix/main.cf: unused parameter:    virtual_maildir_limit_message="The user you are trying to reach is over quota."
postconf: warning: /etc/postfix/main.cf: unused parameter: virtual_maildir_extended=yes
postconf: warning: /etc/postfix/main.cf: unused parameter: virtual_mailbox_limit_override=yes

Comment: What are the SA logs for these mails?
Comment: Where do I can find SA Logs on Ubutnu 14.04 LTS?
Answer: I would do it this way.
create a rule
header LOCAL_JIRA From =~ /example\.com/i
score LOCAL_JIRA  -100

Where example.com is your specific instance name, you can also do full emails like
header LOCAL_JIRA From =~ /jira-emailer\@example\.com/i

For Postfix whitelist, follow this guide
Comment: I tested this now and this does not help!
Comment: Can you post your header results? what is the email system (MTA)
Comment: header LOCAL_JIRA From =~ /alm\@i4ware\.fi/i
score LOCAL_JIRA  -100

allow_user_rules on
Comment: https://www.howtoforge.com/virtual-users-and-domains-with-postfix-courier-mysql-and-squirrelmail-ubuntu-14.04-lts
Comment: what are the results of postconf | grep smtpd_recipient_restrictions
Comment: I added these to my original question.
Comment: Did you run spamassassin --lint
Comment: No.. I try if it helps
Comment: spamassassin --lint did not help.
Comment: I tested now my JIRA and all emails that is sent from address email@example.com to email@example.com is deleted with SpamAssassin and emails that is sent from email@example.com to email@example.com come to not deleted with SpamAssassin. This occurs only JIRA but not other Atlassian products like FishEye or Crucible, etc.
Comment: full headers or get a consultant.


Benefit of processing multiple entities at once?

Question: I am about to port renderkit to Drupal 8.
The D7 version contains an interface EntityDisplayInterface, which builds render arrays from entities.
In the D7 version, this contains one method buildEntities($entity_type, $entities); which allows to process multiple entities at once. The idea here was that this could speed up performance.
For D8, I wonder if this is still relevant. E.g. it seems that D8 views really renders each entity separately. And even though there is EntityViewBuilder::viewMultiple(), this really does most of its processing within the foreach(), so separate per entity.
So.. should I drop the buildEntities() method in D8, and only leave buildEntity()?
Comment: Performance reasons aside, I would keep the API the same if possible so as to not confuse your userbase. :)
Comment: This is already a lost cause because the signature of those methods will inevitably change, as $entities parameter will be type-hinted with EntityInterface, and $entity_type parameter will be dropped at least for ::buildEntity().
Comment: Also I don't know who my userbase is, or how many.. https://www.drupal.org/node/2900827
Comment: oh ok. hmm sorry I dunno intimate details on entity rendering in d8. Ah, by userbase I ment the ~750 downloads of your module.
Comment: Just saying, I found \Drupal\Core\Entity\Display\EntityViewDisplayInterface, which looks similar to my EntityDisplayInterface, except that it has this verbose parent interface. EntityViewDisplayInterface::buildMultiple() seems to be optimized for processing multiple entities at once.
Answer: buildMultiple() exists, but it was done before we introduced render caching to entities and with that, lazy entity rendering/building. Now we don't really need multiple processing.
See https://www.drupal.org/node/2843565 for a discussion about that and the conclusion that we don't really need buildMultiple() anymore.
The idea is that if we render a page with 20 articles, then rendering them all separately is slightly slower on the first request. However, if you save one of those articles, or create a new one, then when accessing that page again, only one needs to be rendered (again), the others can be returned from the cache.
Whether or not a multiple API makes sense for you depends on how it will be called, if you expect it to be called on multiple entities, then can make sense, if not, then probably not.
Comment: Both. See https://md-systems.github.io/drupal-8-caching/#/render-caching and down.
Comment: renderkit EntityDisplayInterface objects can be called in various ways. Some of them multiple, some of them single.
E.g. https://drupal.org/project/entdisp has a Views row plugin, a Views field plugin, an entityreference formatter plugin, and then there is https://drupal.org/project/entdispfieldui. But the entire API would get simpler if it only supports single entity.
Comment: Which exactly is cached? The building of the render array, or the rendering of the render array to html? Or both? I attended Fabian's session but forgot :)


number of elements of basis of subspaces

Question: May I ask if my proof is correct for the following?
Let $V$ be a vector space and dim(V) = n, and let $W$ be a subspace of $V$ and dim (W) = n-1. If $U$ is a subspace of $V$ such that $U \not\subset$ W show that $dim (W \cap U) = dim (U) - 1.$
Proof. Since $dim (W) = n-1,$ then $ n-1 < dim (U) \leq n.$ We should have $dim (V) = dim (U)$. Hence, $U = V$ So,
\begin{align*}
 dim (W \cap U) = dim (W \cap V) = dim (W) = n-1.
\end{align*}
Comment: In some texts, the formula
$$
\dim(U \cap W) = \dim(U) + \dim(W) - \dim(U + W)
$$
is given. Perhaps it would be sufficient to go straight to this formula.
Comment: What do you mean by "Note that since $U$ is not contained in $W,$ it must be the case that $\alpha_n$ is in the basis of $U$"?
Comment: We have no reason to believe that $U$ is a one-dimensional subspace, so if you are trying to say that the singleton $\{\alpha_n\}$ is necessarily a basis of $U$, then this is incorrect.
Comment: I mean.. the vector that is in the basis of $V$ which is not in the basis of $W$ should be in the basis of $U$.. I am not really sure if this is correct...
Comment: will do that.. thank you!
Answer: As I point out in the comments, your proof is not correct.
Hint: Let $k = \dim(W \cap U)$ and $d = \dim(U)$. Let $\{\alpha_1,\dots,\alpha_k\}$ be a basis of $W \cap U$. Note that this set can be extended both to a basis $\{\alpha_1,\dots,\alpha_k,\dots,\alpha_{n-1}\}$ of $W$ and a basis $\{\alpha_1,\dots,\alpha_k,\beta_{k+1},\dots,\beta_d\}$ of $U$.
Answer: We are given that
(i) the vector space $V$ has dimension $n$,
and also that
(ii) $U$ and $W$ are subspaces of $V$ such that $\dim W = n-1$ and $U \not\subset W$.
As $U \not\subset W$, so either $W \subsetneqq U$ or $W \not\subset U$.
Case 1. Suppose that $W \subsetneqq U$. Then $W$ is a proper subspace of $U$ and thus we have
$$
n-1 = \dim W < \dim U \leq \dim V = n
$$
from which it follows that $\dim U = n$, and so we must have $U = V$. Then the subspace $U+W$ of $V$ must equal $U=V$ also. Therefore we obtain
$$
\dim V = \dim (U+W) = \dim U + \dim V - \dim (U \cap W) = \dim V + \dim W - \dim (U \cap W),
$$
which implies that
$$
\dim (U \cap W) = \dim W = n-1 = \dim U - 1.
$$
Case 2. Suppose that $W \not\subset U$. Thus we have $U \not\subset W$ and $W \not\subset U$. So the subspace $U+W$ of $V$ satisfies
$$
U+W \supset U \cup W \supsetneqq W,
$$
which implies that
$$
n= \dim V \geq \dim (U+W) > \dim W = n-1,
$$
and hence
$$
\dim (U+W) = n,
$$
from which it follows that
$$
U+W = V.
$$
Therefore
\begin{align}
 \dim (U \cap W) &= \dim U + \dim W - \dim (U+W) \\
&= \dim U + (n-1) - n \\
&= \dim U - 1,
\end{align}
as required.
Hope this helps.


What does 'op' exactly mean in an submit button?

Question: In the form_state['values']['op'] = t('Save');
What does 'op' exactly mean and do ?
Answer: I'm pretty sure it's shorthand for the word operation.
It doesn't 'do' anything as such, it's the name assigned to all submit inputs so that the form processor can identify which button has been pressed (and perhaps fire off different submit handlers based on that).
And it looks like it's gone in Drupal 8 (in favour of $form_state['triggering_element']), so enjoy it while you can :)
Comment: Nope, not gone anywhere. That issue is not closed yet after almost 8 years. And the users who use browser translation feature to translate pages (and forms) can't submit forms. Unbelievable.
Answer: As of 2024, the best way to access the 'operation' in a form is to use $form_state->getFormObject()->getOperation().
See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityForm.php/function/EntityForm%3A%3AgetOperation/10


Proof that interval $]0,1[$ is an open set

Question: I have this question in my set of exercises of real analysis:

prove that the interval $]0,1[$ is an open set.

The definition says

the set $A\subset \mathbb{R}^m$ is open if for all $a \in A$, $\exists \delta \gt 0$ such that $B[a; \delta] \subset A$.

Although I get the intuition of this definition somehow, I don't really know how to prove the statement mathematically. In particular, I don't know how to choose my $\delta$.
Any tips are welcomed.
Thank you in advance.
Comment: The basi hint is: take a point and try to find a ball centered on it and contained in the set. I know it may sound basic, but I promise if you follow the hint you will be able to solve the problem.
Comment: Hint: Try to prove that the complement of $]0,1[$ is closed
Comment: Thanks guys for the help.
Answer: If $a\in A$, take $\delta=\min\{a,1-a\}$ (that is, $\delta$ is the smallest between the distances from $a$ to $0$ and to $1$). Then $(a-\delta,a+\delta)\subset(0,1)$.
Comment: @MatthieuRousseau To formally proof that last inclusion: suppose $x \in (a-\delta, a+\delta)$. So $x > a-\delta$ and as $\delta \le a$, we know $a-\delta \ge 0$ and so $x > a-\delta  \ge 0$ hence $x >0$; also $\delta \le 1-a$ so $a+\delta \le 1$ and $x < a+\delta \le 1$ implies $x < 1$. Just to show we don't rely on a "picture".
Answer: For $a \in (0,1)$ set $$\delta = \frac12(1-|2a-1|)$$
Then $B(a, \delta) = (a-\delta, a+\delta) \subseteq (0,1)$. Indeed,
$$a-\delta = a-\frac12(1-|2a-1|) = \left(a-\frac12\right) + \left|a-\frac12\right| \ge 0$$
$$a+\delta = a+\frac12(1-|2a-1|) = \left(a+\frac12\right) - \left|a-\frac12\right| \le \left(a+\frac12\right) - \left(a-\frac12\right) =1 $$


Practicing electric guitar using a Boss Katana, what can I use for playing backing tracks?

Question: I've been practicing electric guitar using a Katana for the past few months, I was considering playing over a track, but not sure how to do it.
I don't think the Katana can play anything other than what I connect to it, as in a laptop through USB, quick google searches seems to indicate that, but correct me if I'm wrong.
I do have some decent headphones, Sennheiser HD600, but I don't have speakers, could I maybe hook them up to a laptop and set the volume appropriately so I can hear the Katana plus the headphones backing track? does that make sense or what do you guys normally use for this?.
Thanks.
Comment: Can you update your question with the specific model of amplifier and a link to the appropriate page at Boss/Roland with the specs?  This may have a very simple answer.
Comment: Welcome! Perhaps I'm being dense, but: "I don't think the Katana can play anything other than what I connect to it"—how could it possibly play something without a connection? If you mean, for example, could you store data within the amp somehow, no, pretty sure it's just an amp. Though 2) could you specify which Katana model? It might have different inputs. And do you have any other speaker of respectable size of any kind? I'm wondering why the track can't just play out loud, without headphones, without interacting with the amp.
Comment: I meant, that I can't for example connect it a USB to the laptop and play a backing track plus my guitar.
Comment: Also, it looks to me like most Katana models have an "aux in" stereo mini jack. If you can connect a CD player or other device via analog stereo plug, you should be able to mix it with your guitar and output both.
Comment: No, I dont have any decent speaker, so before buying one I was curious what's a good method.
Comment: I just got the Artist mkII and you can do like we did in the old days and play along with your CD player blasting. What I did do is I got a Boss js-10 eBand and this thing is sick. If I had one of those back when I was just starting out I'd probably been a world class guitarist. The are an amazing learning tool and fun as hell. It comes with effects and it has backing tracks pre loaded but you can go to the boss eBand site and download tones and sounds others have downloaded. Also you can also. Download your favorite songs to learn
Answer: The Katana series has an aux input on the back panel of the amp. This will accept any sound source with a stereo mini jack or or mini jack adapter. There is no independent volume control for the aux input so you will have to use the master volume and the guitar channel volume to get the right balance.
The USB connection is only for sending audio from the amp to a computer for recording. It does not accept audio from a computer to play through the amp.
Here is a link to the manual: https://static.roland.com/assets/media/pdf/KTN-Mk2_eng02_W.pdf
Pages 6 and 7 have the info relevant to your question, look at items 20 and 21 below:
Comment: So, basically, connect mini trs jack from headphone socket on computer to port 21?


drupal notification for content type

Question: I have a requirement to allow users to subscribe content type. When a new node of the subscribed content type is created, notification mail must be sent. I tried notify module but it only allows to subscribe while registration.
Is there any solution for unsigned users to subscribe a content type?
Comment: create a rule for sending mail on node publish.
Comment: "i have requirement to allow users to content type" -To do what with that content type? Would you care to edit it a bit? Or do you want me to do it?
Comment: @Mołot i have requirement to allow users to subscribe content type
Comment: For unsigned users it will be hard - Drupal keeps all user-related data in tables related to, well, users. Unregistered users are one user to the system (uid 0). Probably you will need to use some code from one of the newsletter modules and some from Notify to make this work the way you want it.
Comment: Try this module

https://drupal.org/project/simplenews_content_selection
Answer: I'd try to create a rule that's fired when new content is added and when a user is subscribed to it (check this with a condition). Use the 'Send email' action to send an email to the subscribed users.

drupal notification for content type


Convert String to List - c#

Question: I have a list as a single string like - "['2','4','5','1']" and length of this is 17 as each char is counted.
Now I want to parse it into list object like - ['2','4','5','1'] whose length will be 4 as the number of elements in a list.
How can I do this in C#?
Can it be done without doing basic string operations? If yes then how?
Comment: `list = Newtonsoft.Json.JsonConvert.DeserializeObject>("['2','4','5','1']");`
Comment: Or `var result = str.Split(',','[',']').Where(s => !string.IsNullOrEmpty(s)).ToList();`
Comment: what do you mean by "basic string-operations"? Could you please elaborate on what you want to achieve and in particular what you´ve tried already? We´re not here to do the thinking for you. You have to think yourself. However we can help you, if you have a specific problem or when you´re stuck.
Comment: @SᴇM `StringSplitOptions.RemoveEmptyEntries` - don't know if there's a difference in performance, but I'd rather use the option.
Comment: @Fildor Agreed, in that case - `var result = str.Split(new[] { ',','[',']' }, StringSplitOptions.RemoveEmptyEntries);`
Comment: @Fabio I am really tempted to try and benchmark your solution against the others. I kind of like it and think it fits better the _"without doing basic string operations"_ ... why not make it an answer?
Comment: @SᴇM Splitting the string really worked for me. Its the simplest way to do this. Thanks!
Answer:
Without basing string operations

Your string value looks like valid JSON array.
using Newtonsoft.Json;

var list = JsonConvert.DeserializeObject<List<char>>("['2','4','5','1']");

// => ['2','4','5','1']

If you need output as integers set output type to be list of integers and JSON serializer will convert it to integers.
var list = JsonConvert.DeserializeObject<List<int>>("['2','4','5','1']");

// => [2, 4, 5, 1]

Converting to integers will handle negative values as well ;)
var list = JsonConvert.DeserializeObject<List<int>>("['-2','4','-5','1']");

// => [-2, 4, -5, 1]

Comment: Nice idea [@Fabio](https://stackoverflow.com/users/1565525/fabio) !
Answer: You can try regular expressions and Linq in order to Match all the integers and turn them (ToList()) into List<int>:
using System.Linq;
using System.Text.RegularExpressions;

...

string str = "['2','4','5','1']";

var result = Regex
  .Matches(str, @"\-?[0-9]+")              // \-? for negative numbers
  .Cast<Match>()
  .Select(match => int.Parse(match.Value)) // int.Parse if you want int, not string
  .ToList();

Answer: Try to Split by , and then use Regex to get only digits:
var str = "['2','4','5','1']".Split(new char[] {',' })
    .Select(s => Regex.Match(s, @"\d+").Value);

Or thanks to @Fildor :
var str = Regex.Matches("['2','4','5','1']", @"\d+").Cast<Match>()
    .Select(s=> s.Value);

Comment: If you regex match anyway, why split first?

Convert String to List - c#


Periodic points of topologically conjugated functions in dynamical systems?

Question: I'm working on a homework problem which seems obvious, but I am having a hard time proving/completing. The problem can be stated as follows:
Let $f,g:$ $\mathbb R$ $\rightarrow$ $\mathbb R$ be $\mathcal C^1$ functions and suppose they are topologically conjugated by a diffeomorphism $h$. Let $x_0$ be a periodic point of period $n$ of $f$. Prove that $y_0=h(x_0)$ is a periodic point of period $n$ of $g$, and that $(f^n)'(x_0)=(g^n)'(h(x_0))$
The first part seems pretty obvious from the definition of topological conjugacy - it preserves all the dynamics, so the periodic point is preserved as well. Anything beyond this seems to be lost on me, and I can't figure out how to start the second part.
Answer: Since you have $h(f^n) = g^n(h)$, just differentiate and use the chain rule:
$$(h(f^n))' = (g^n(h))'$$
$$h'(f^n)\cdot(f^n)' = (g^n)'(h)\cdot h'$$
Evaluating at $x_0$, and recalling that $f^n(x_0)=x_0$ and $g^n(h(x_0))=h(x_0)$,
$$h'(\;\underbrace{f^n(x_0)}_{x_0}\;)\cdot(f^n)'(x_0) = (g^n)'(h(x_0))\cdot h'(x_0)$$
$$\require{cancel}\cancel{h'(x_0)}\cdot(f^n)'(x_0) = (g^n)'(h(x_0))\cdot \cancel{h'(x_0)}$$
Cancelling $h'(x_0)$ (since it isn't zero),
$$\boxed{(f^n)'(x_0) = (g^n)'(h(x_0))}$$
as desired.
Comment: Well, you have to prove to yourself that it's true. You can write (abbreviating composition) $f = h^{-1}gh$, so just note that $f^n = (h^{-1}gh)(h^{-1}gh)\cdots(h^{-1}gh)$ and all of the "interior" $h^{-1}h$ are identity, leaving $f^n = h^{-1}g^nh$. This gives what you want, right?
Comment: Ah. I didn't know you could make that first claim about conjugates. I thought the conjugacy only applied to the functions, not their iterates. Thanks for clearing that up.
Comment: No of course this is true. As soon as you wrote it, it hit me.


Suppose k is an integer such that $6k + 1$, $12k + 1$, $18k + 1$ are primes. Show that $n = (6k + 1)(12k + 1)(18k + 1)$ is a Carmichael number.

Question: Suppose k is an integer such that $6k + 1$, $12k + 1$, $18k + 1$ are
primes. Show that $n = (6k + 1)(12k + 1)(18k + 1)$
is a Carmichael number.
This is a question on a past exam that I find difficulty to answer. Can anyone help?
Answer: Let $6k+1=p, 12k+1=q, 18k+1=r$, so $n=pqr$. Consider $a$ s.t. $(a, n)=1$. Note that $n-1=1296k^3+396k^2+36k$  is divisible by $6k=p-1, 12k=q-1, 18k=r-1$. Then $a^{n-1} \equiv (a^{p-1})^{\frac{n-1}{p-1}} \equiv 1 \pmod{p}$ and similarly $a^{n-1} \equiv 1 \pmod{q}$, $a^{n-1} \equiv 1 \pmod{r}$ so $a^{n-1} \equiv 1 \pmod{n}$. Thus $n$  is a Carmichael number.


Model Matrices Incompatible - Error in update in Biglm package in R

Question: I'm running through a large dataset chunk by chunk, updating a list of linear models as I go using the biglm function. The issue occurs when a particular chunk does not contain all the factors that I have in my linear model, and I get this error:
Error in update.biglm(model, new) : model matrices incompatible

The description of update.biglm mentions that factor levels must be the same across all chunks. I could probably come up with a workaround to avoid this, but there must be a better way. This pdf, on the 'biglm' page, mentions that "Factors must have their full set of levels
specified (not necessarily present in the data chunk)". So I think there is some way to specify all the possible levels so that I can update a model with not all the factors present, but I can't figure out how to do it.
Here's an example piece of code to illustrate my problem:
df = data.frame(a = rnorm(12),b = as.factor(rep(1:4,each = 3)),c = rep(0:1,6))
model = biglm(a~b+c,data = df

df.new = data.frame(a = rnorm(6),b = as.factor(rep(1:2,each = 3)),c =rep(0:1, 3))
model.new = update(model,df.new)

Thanks for any advice you have.
Answer: I came across this problem also.  Are the variables in your large data frame specified as factors before breaking them into chunks?  Also, is the data set formatted as a data frame?
large_df <- as.data.frame(large_data_set) # just to make sure it's a df.
large_df$factor.vars <- as.factor(large_df$factor.vars)

If this is the case, then all of the factor levels should be preserved in the factor variables even after breaking the data frame into chunks.  This will ensure that biglm creates the proper design matrix from the first call, and that all subsequent updates will be compatible.
If you have different data frames from the start, (as you illustrate in your example), perhaps you should merge them into one before breaking down into chunks.  Continuing from your example:
df.large <- rbind(df,df.new)
chunk1 <- df.large[1:12,]
chunk2 <- df.large[13:18,]

model <- biglm(a~b+c,data = chunk1)
model.new <- update(model,chunk2)   # this is now compatible