Java 'for' loop with range

Question: I am working on a basic program (console).
The program should allow the user to enter in various marks, until the mark entered exceeds 100. At this point the program should display a histogram. Each star represents a student who achieved a module mark in the range shown.
This is an example of the output.
0 - 29 xxx
30 - 39   xxxxx
40 - 69   xxxxxxx
70 - 100  xxxx
20 students in total.
As the user enters each mark, there ought to be a counter that increases in value and print the total number of marks entered.
I want to make sure that the program is as efficient as possible but also understandable
Code
Working with @Dici on collabedit I have an amazing answer to my question:
public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int[] ranges  =  { 0,29,39,69,100 };
    int[] inRange = new int[ranges.length - 1];

    int mark;
    do {
        System.out.println("Enter Mark:");
        mark = sc.nextInt();
        for (int j=1 ; j<ranges.length ; j++)
           if (ranges[j-1] <= mark && mark <= ranges[j]) {
               inRange[j-1]++;
               break;
           }
    } while (mark <= 100);

    System.out.println(Arrays.toString(inRange));

    String s = "The number of students that have scored between %d and %d is: ";
    int k = 0;
    for (int i=0 ; i<ranges.length - 1 ; i++) {
      System.out.print(String.format(s,ranges[i] + k,ranges[i + 1]));
        for (int r = 0; r<inRange[i] ; r++)
            System.out.print("*");
        System.out.println();
        k = 1;
    }

    sc.close();

Thank you again for your amazing help!
Comment: You need to be much more specific. We aren't mind readers, concise and targeted questions are best. Are you asking about ranges for the marks for the student?
Comment: Ranges of what? Do you want to break the possible grade range into "buckets" (e.g. 0 - 29, 30 - 59, etc.) and keep a running count of the grades in each bucket?
Comment: Can you use Java 8 ?
Comment: @Dici I am using the Java 8 JDK
Comment: Your code doesn't make the slightest sense. Neither does your request to put ranges into it. Maybe you try to fix you code regarding whatever it is supposed to do *without* these mysterious ranges. Once it does something useful you may come back to the idea of putting ranges to it.
Comment: @Holger Well I am here to learn, that is why I posted this here. Comments like that aren't very helpful if you belittle my efforts. I more than understand that my approach is not correct and that it needs adjustment
Comment: @Niral Mehta: what approach? I see a bunch of random code that can't be said to have errors as it doesn't seem to have a goal that it could miss. Just go through your code and try to tell what each expression is supposed to do and why. Since you didn't tell what you actually want to do your code has to do it. But it fails to tell it as well.
Answer: As we did it together on Collabedit, here is a working code for your question :
public class Test {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int[] ranges  =  { 0,29,39,69,100 };
        int[] inRange = new int[ranges.length - 1];

        int mark;
        do {
            System.out.println("Enter Mark:");
            mark = sc.nextInt();
            for (int j=1 ; j<ranges.length ; j++)
               if (ranges[j-1] <= mark && mark <= ranges[j]) {
                   inRange[j-1]++;
                   break;
               }
        } while (mark <= 100);

        System.out.println(Arrays.toString(inRange));

        String s = "The number of students that have scored between %d and %d is : ";
        int k = 0;
        for (int i=0 ; i<ranges.length - 1 ; i++) {
          System.out.print(String.format(s,ranges[i] + k,ranges[i + 1]));
            for (int r = 0; r<inRange[i] ; r++)
                System.out.print("*");
            System.out.println();
            k = 1;
        }

        sc.close();
    }
}

Comment: I'm sorry, I can't quite understand this. Is this correct, this a list and through the list you've defined a range of 0 to 100 on the second line.

Then you've created both a maximum and minimum range value that can be altered only within the code. I'm not quite understanding the *i +29** on your fourth line. Could you explain the fifth line to me please?
Comment: Let's assume you have the input array `[3,25,17,88]`. What you want is to know how many items of this array are in each range you defined, is that right ?
Comment: Yeah that is right, so you would use the above code to sort the array into the appropriate range?
Comment: Each element of the list is a `Predicate` with a `test` method. `test(i)` returns `true` iff `min <= i <= max`. I guess you see how it can be useful
Comment: Thank you for explaining it to me, so if I wanted to store values ad have the list sort them can I use the scanner outside of the list?
Comment: You keep talking about sorting but that was not your original question. Plus, I don't understand the last part of your comment
Comment: I want to take each user input and fit it into a range. i.e 3 falls in to the range 0 - 29. Once the user input is added to the range it will then increment some kind of counter by 1 as it belongs there
Comment: Is it possible to private message you? This is what I want but it would be better for me to show you what I mean with a link to what I am being asked to do
Comment: Let's chat here, you don't have enough reputation for chatting on SO : http://collabedit.com/v2n8y
Answer: Quick suggestion: do not alter marksInsp inside the loop if that's your loop index.
Paulinho made the excellent suggestion of using the modulo operator. I'll extend that here to a map, since you didn't specify the upper mark limit:
public static void main(String[] args) {
    int currentMark, currentBucket;
    final int BUCKET_WIDTH = 30;
    Map<Integer, Integer> markRanges = new HashMap<Integer, Integer>();

    for(int i = 0; i < 101; i++) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Marks: ");
        currentMark = input.nextInt();
        currentBucket = currentMark % BUCKET_WIDTH;
        if(markRanges.containsKey(currentBucket)) {

            // There's already an entry for this bucket
            markRanges.put(currentBucket, markRanges.get(currentBucket) + 1);
        } else {

            // If there isn't, make a new entry
            markRanges.put(currentBucket, 1);
        }

        // Print out grade buckets
        for(Integer j : markRanges.keySet) {
            System.out.println(String.format("There are %d students with scores between %d and %d", markRanges.get(j), j, j.intValue() + BUCKET_WIDTH - 1));
        }
    }
}

Comment: At the end of your code it says that the variable is already defined in method main(java.lang.String[])
Comment: @NiralMehta yeah; fixed.
Answer: Okay. Now that makes sense. If you have a number
  int mark = 3;

You can use an if statement
 if(mark <= 10){

      //do this

 }else if(mark <= 20){

     //do this

  }

You can also use a switch statement, however personal preference leads me to almost always use if statements.
If you want "buckets" you could use
  ArrayList<String> marksForStudent = new ArrayList<>();

the documentation for that is here.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Or, alternatively and probably what you want is a hashmap. With the student's name or other unique identifier as the key and then a collection to contain their marks.
  HashMap<String, ArrayList<String>> gradesForStudents = new HashMap<>();

  gradesForStudents.put("Marc",Arrays.asList("99","98","100"));

Something like that.

Java 'for' loop with range


Get JSON page content with PhantomJS

Question: I would like to know how to parse JSON in phantomjs. Any page content is enclosed in html (
{JSON string}
). Is there an options to remove enclosing tags or asking for a different Content-Type as "application/json"? If not, what's the best way to parse it. Is it using jQuery after including with includeJS jQuery?
Answer: Since you are using PhantomJS which is built of the webkit browser you have access to the native JSON library. There is no need to use page.evaluate, you can just use the plainText property on the page object.
http://phantomjs.org/api/webpage/property/plain-text.html
var page = require('webpage').create();
page.open('http://somejsonpage.com', function () {
    var jsonSource = page.plainText;
    var resultObject = JSON.parse(jsonSource);
    phantom.exit();
});

Comment: Shameless plug: Checkout how to use a AWS Lambda to run your phantomjs scripts!
https://github.com/justengland/phantom-lambda-template
Answer: Here is what I did:
var obj = page.evaluate(function() {
    return eval('(' + document.body.innerText + ')');
}

Then the obj you got is the JSON object returned from that page.
Comment: the obj is null. This code is fine and logs JSON : page.open(encodeURI(url), function(status){
  if( status !== "success"){
    ...
  } else {
      console.log( page.content );
      phantom.exit(); } but not this one : page.open(encodeURI(url), function(status){  if( status !== "success"){ ... } else {
      var obj = page.evaluate(function() {
         return eval('(' + document.body.innerText + ')');
      });
      console.log(obj)
      phantom.exit(); page.evaluate is still mysterious! Shouldn't eval be discarded?
Answer: As already in the accepted answer, I would suggest using JSON.parse() for converting a JSON string into an object.
For example, your code could look like this:
var jsonObject = page.evaluate(function() {
  return JSON.parse(page.plainText);
});

Comment: To whomever downvoted, this is a valid approach. I know that jQuery might be a little overkill for JSON parsing, but please give me the courtesy of explaining your downvote. Thanks.
Comment: @CameronTinker why not use native javascript JSON.parse ?? Why include a library thats not required for this?
Comment: I have updated this answer to remove jQuery as a dependency.
Answer: If the json data contains html strings, they will be removed within the suggested page.plainText attribute.
Comment: I just tried it and it didn't remove html strings from json.

Get JSON page content with PhantomJS


Large scale pivot table in Python

Question: I have 100-300Go data under csv format(numerical + unicode text) and needs to do regular Pivot Table jobs on this. After googling/StackOverflow-ing, could not find satisfactory answer (only partial).
 Wondering which solution is the fastest for single machine  (64Go RAM):
1) Convert and Insert into PostGres and proces all in PostGres DB through SQL ?
   (or MySQL....)
2) Load csv in chunk in Pandas and process one by one manually ?
3) Load csv + convert to HDF and process the HDF by chunk ?
4) Other solution.
Answer: For working on a single machine, PostgreSQL may be the best fit from the 3 options you list.
To keep memory usage in check you can use partitioning and handle the data by chunks.
Comment: Any real experience on Pivot table on it ?
Comment: yeah, I've used those 3 tools to build pivot tables as well as olap cubes before. At the range of a few 100 Gb's postgreSQL works well as long as one partitions data so that it can work in memory and avoid using SWAP.
Comment: What if your pivot table has 2000 columns? How do you pivot using a relational database because the limit is 1024 columns for many of them
Comment: You should post that on a new question  @user798719
Answer: The questioner must have solve the problem , for others whom might land upon this question , my answer might help.
Try this solution (convert it as per your dataset) , I tried on 50-80 GB it worked adding numpy will improve the performance.
<code>import pandas as pd
from datetime import date
from datetime import datetime

print("1 Load rec =", datetime.now())
df6 = pd.read_csv('sampleDataframeFlux/sampleDataframeFlux.csv',low_memory=False, memory_map=True,engine='c',na_filter=False,index_col=False,usecols=["time", "Label","Server","value"])
print("shape",df6.shape)

print("2 Create dataframe =",datetime.now())
df6["Label"]=df6["Server"]+"|"+df6["Label"]
df6.drop(['Server'],axis=1,inplace=True)

print("3 Time trim =", datetime.now())
df6['time']=df6['time']//1000000000
print("shape",df6.shape)

print("4 Round Epoch to nearest multiple of 5 =", datetime.now())
df6['time']=5*round(df6['time']/5)
print("shape",df6.shape)

print("5 Pivot dataframe=", datetime.now())
df6=df6.pivot_table(index='time', columns=["Label"],values="value",fill_value=0)
print("shape",df6.shape)

print("6 Epoch to UTC =", datetime.now())
df6.index=pd.to_datetime(df6.index, unit='s')

print("7 Convert to type category to reduce memory =", datetime.now())
df6=df6.astype('category')
print("shape",df6.shape)

print("8 Start to write to a file  =", datetime.now())
df6.to_csv('file_11.csv', header=True, chunksize=500000)
print("9 Finish =", datetime.now())
</code>

Large scale pivot table in Python


object references an unsaved transient instance - save the transient instance before flushing

Question: Estou com o seguinte problema tenho três tabelas uma com o nome
Usuario      com as seguintes propriedades Id, Usuario, NomeUsuario e Senha
Pessoa       com as seguintes propriedades Id, Nome
Funcionario  com as seguintes propriedades Id, Cargo, Id_Usuario e Id_Pessoa
sendo que usuário uso para me logar ao sistema.
quando vou cadastrar o funcionário preciso passar para a tabela funcionário o id do usuario logado que já está salvo no bando de dados.
Estou recebendo o seguinte erro?

object references an unsaved transient instance - save the transient instance before flushing

Estou tendo salvar conforme o código abaixo:
    public void salvar() {
    FacesContext context = FacesContext.getCurrentInstance();
    try {

        //Salvar Insert Id do Objeto Usuário para a Tabela Funcionario Id_Usuario.
        this.funcionarioModel.setUsuarioModel(usuarioModel);

        //Salvar Insert Dados de Pessoa da Tabela Pessoa e o Id do Objeto Pessoa para Tabela Funcionario Id_Pessoa
        pessoaModel = this.pessoaController.salvar(this.pessoaModel);
        this.funcionarioModel.setPessoaModel(pessoaModel);
        this.pessoaModel = new PessoaModel();

        //Salvar Insert Dados Tabela Funcionario
        this.funcionarioController.salvar(this.funcionarioModel);
        this.funcionarioModel = new FuncionarioModel();

        context.addMessage(null, new FacesMessage("Funcionario salvo com sucesso!"));
    } catch (NegocioException e) {
        FacesMessage mensagem = new FacesMessage(e.getMessage());
        mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
        context.addMessage(null, mensagem);
    }
}

Edit
Oi Felipe , só mais uma duvida se vc poder me ajudar, seguido o raciocínio que vc entendeu bem. tenho a classe UsuarioRepository conforme abaixo;
package br.com.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import br.com.model.UsuarioModel;

public class UsuarioRepository implements Serializable {
    private static final long serialVersionUID = 1L;

    private EntityManager manager;

    @Inject
    public UsuarioRepository(EntityManager manager) {
        this.manager = manager;
    }

    public UsuarioModel porId(Long id) {
        return manager.find(UsuarioModel.class, id);
    }

    public List<UsuarioModel> todos() {
        TypedQuery<UsuarioModel> query = manager.createQuery("from UsuarioModel", UsuarioModel.class);
        return query.getResultList();
    }

    public UsuarioModel guardar(UsuarioModel usuario) {
        return this.manager.merge(usuario);
    }

    public void remover(UsuarioModel usuario) {
        this.manager.remove(usuario);
    }

    public UsuarioModel ValidaUsuario(String nomeUsuario,String senha){
        String Jpql = "Select u From UsuarioModel u Where u.nomeusuario = :usuario And u.senha = :senha";
        try {
            //Query que sera executada (Jpql)
            TypedQuery<UsuarioModel> query = manager.createQuery(Jpql, UsuarioModel.class);
            //Parâmetros da Query
            query.setParameter("usuario", nomeUsuario);
            query.setParameter("senha", senha);
            //Retorna o Usuario se For Localizado
            return query.getSingleResult();
        } catch (Exception e) {
            return null;
        }

    }

}

e classe UsuarioController conforme abaixo
package br.com.controller;

import java.io.Serializable;
import javax.inject.Inject;

import br.com.model.UsuarioModel;
import br.com.repository.UsuarioRepository;
import br.com.util.NegocioException;
import br.com.util.Transactional;

public class UsuarioController implements Serializable {
    private static final long serialVersionUID = 1L;

    @Inject
    private UsuarioRepository usuarioRepository;

    @Transactional
    public void salvar(UsuarioModel usuarioModel) throws NegocioException {
        if (usuarioModel.getNomeUsuario().isEmpty() ) {
            throw new NegocioException("Não é Possivel Salvar Funcionario sem Usuario");
        }
        this.usuarioRepository.guardar(usuarioModel);
    }

    @Transactional
    public void excluir(UsuarioModel usuarioModel) throws NegocioException {
        usuarioModel = this.usuarioRepository.porId(usuarioModel.getCodigo());
        if (usuarioModel.getNomeUsuario()!= null) {
            throw new NegocioException("Não é possível excluir um Funcionario sem Usuario");
        }
        this.usuarioRepository.remover(usuarioModel);
    }

}

que inicializa a EntityManager
com o metodo guardar
public UsuarioModel guardar(UsuarioModel usuario) {
    return this.manager.merge(usuario);
}

fiz conforme entendido na sua explicação
usuarioModel = this.usuarioController2.salvar(this.usuarioModel);
        this.funcionarioModel.setUsuarioModel(usuarioModel);

Mas ainda assim não consegui implementar o código. Caso vc possa me ajudar em mais essa.
segue o erro
 ADVERTÊNCIA: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
javax.el.ELException: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.apache.el.parser.AstValue.invoke(AstValue.java:260)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1206)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at org.jboss.weldx.persistence.EntityManager$96039635$Proxy$_$$_WeldClientProxy.merge(Unknown Source)
    at br.com.amarildo.repository.UsuarioRepository.guardar(UsuarioRepository.java:32)
    at br.com.amarildo.controller.UsuarioController.salvar(UsuarioController.java:51)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldSubclass.salvar$$super(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:49)
    at org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:77)
    at br.com.amarildo.util.TransactionInterceptor.invoke(TransactionInterceptor.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:74)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldSubclass.salvar(Unknown Source)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldClientProxy.salvar(Unknown Source)
    at br.com.amarildo.view.CadastroFuncionarioBean.salvar(CadastroFuncionarioBean.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    ... 34 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.jpa.event.internal.core.JpaMergeEventListener.saveWithGeneratedId(JpaMergeEventListener.java:73)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:271)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:251)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:189)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:85)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:876)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:858)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:863)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1196)
    ... 69 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'nomeusuario' cannot be null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
    at com.mysql.jdbc.Util.getInstance(Util.java:360)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:971)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2141)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2062)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 91 more

fev 17, 2017 3:19:48 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1206)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
    at org.jboss.weldx.persistence.EntityManager$96039635$Proxy$_$$_WeldClientProxy.merge(Unknown Source)
    at br.com.amarildo.repository.UsuarioRepository.guardar(UsuarioRepository.java:32)
    at br.com.amarildo.controller.UsuarioController.salvar(UsuarioController.java:51)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldSubclass.salvar$$super(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:49)
    at org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:77)
    at br.com.amarildo.util.TransactionInterceptor.invoke(TransactionInterceptor.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:74)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldSubclass.salvar(Unknown Source)
    at br.com.amarildo.controller.UsuarioController$Proxy$_$$_WeldClientProxy.salvar(Unknown Source)
    at br.com.amarildo.view.CadastroFuncionarioBean.salvar(CadastroFuncionarioBean.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.jpa.event.internal.core.JpaMergeEventListener.saveWithGeneratedId(JpaMergeEventListener.java:73)
    at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:271)
    at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:251)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:189)
    at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:85)
    at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:876)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:858)
    at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:863)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1196)
    ... 69 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'nomeusuario' cannot be null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
    at com.mysql.jdbc.Util.getInstance(Util.java:360)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:971)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2141)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2077)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2062)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 91 more

Comment: Sua edição é uma nova dúvida, é recomendável abrir uma nova pergunta. E por favor não adicione assinatura, não é permitido no site.
Comment: @JavaX_javaX Depois de você fazer a modificação o que ocorre? O mesmo erro? Algum erro diferente? É lançada alguma exceção? Caso sim, coloque o *stacktrace*?
Comment: vlw Felipe segue o erro abaxo
Comment: @JavaX_javaX Complementei minha resposta abaixo. Dê uma olhada!
Comment: **mais uma vez Obrigado Felipe vou tentar aqui grato**
Answer: A instância usuarioModel provavelmente está no estado detached, ou seja, o JPA não sabe quem ela é porque ela está fora do Persistence Context. No trecho:
//Salvar Insert Id do Objeto Usuário para a Tabela Funcionario Id_Usuario.
this.funcionarioModel.setUsuarioModel(usuarioModel);

Você apenas adiciona o usuarioModel ao seu funcionarioModel, mas não adiciona ao PersistenceContext.
De acordo com o padrão que você está seguindo no seu código, acredito que você deva ter um usuarioController. Caso tenha, verifique se ele possui algum método que adicione o usuarioModel ao Persistence Context, por exemplo, algum que faça uso do método merge do EntityManager. Assim, você poderia adicioná-lo ao Persistence Context e depois adicioná-lo ao funcionarioModel dessa forma:
this.usuarioModel = this.usuarioController.merge(this.usuarioModel);
this.funcionarioModel.setUsuarioModel(usuarioModel);

Edit:
O erro ocorre porque usuárioModel que você está executando o merge tem o campo nomeusuario igual a null. Para resolver isso, substitua a evocação do método salvar(UsuarioModel usuarioModel) da classe UsuarioController pela evocação de um método que chame o método find da classe EntityManager.
Pelo código que você colocou, você pode evocar o método porId da classe UsuarioRepository ou, caso queira manter está mesma estrutura de camadas, poderia implementar um método com essa funcionalidade na sua classe UsuarioController. Nesse caso você iria substituir isso:
usuarioModel = this.usuarioController2.salvar(this.usuarioModel);
this.funcionarioModel.setUsuarioModel(usuarioModel);

Por isso:
//O método porId da classe UsuarioController evocaria o metodo
//porId da classe UsuarioRepositoty que, por sua vez, evocaria
//o método find da classe EntityManager
usuarioModel = this.usuarioController2.porId(this.usuarioModel.getId());
this.funcionarioModel.setUsuarioModel(usuarioModel);

Comment: vlw Felipe a logica e essa mesmo, acho que entendi o que vc falo vou tentar. muito grato pela sua ajuda


split conjugacy class in $S_n$ into two equal size conjugacy classes in $A_n$

Question: Let $n>2$ and $\tau\in A_n$ and let $C=\{g\tau g^{-1}|g\in S_n\}$ be the conjugacy class of $\tau$ in $S_n$.
Suppose that there is no odd element $x\in S_n$ such that $\tau x=x\tau$.
Prove that $C$ is a  union of two disjoint conjugacy classes in $A_n$.
I managed to observe that if $\sigma_1\in S_n$ an even element and $\sigma_2\in S_n$ an odd element, then:
$\sigma_1\tau\sigma_1^{-1}\neq\sigma_2\tau\sigma_2^{-1}$ otherwise we get that the odd element $x=\sigma_2^{-1}\sigma_1$ commutes with $\tau$.
So, I got one conjugacy class to be the conjugacy class of $\tau$ in $A_n$, say $Q$. It is now clear that it contains all the elements in $C$ of the form $g\tau g^{-1}$ for $g$ even. But I couldn't prove that $C\setminus Q$ can be generated by a conjugacy class in $A_n$ and moreover the sizes equivalence $|Q|=|C\setminus Q|$.
Comment: Hint: Orbit stabiliser
Answer: Let $g_0\in S_n$ be a fixed odd permutation (for example, a transposition).
Then $C$ is the disjoint union of the conjugacy classes in $A_n$ of $\tau$ and $g_0\tau g_o^{-1}.$
First, let $g\tau g^{-1}\in C$. Then either $g\in A_n$, and $g\tau g^{-1}$ lies in the $A_n$-conjugacy class of $\tau$, or $g$ is odd and in this case, $g=g'g_0$ with $g'\in A_n$ and
$g\tau g^{-1}$ lies in the $A_n$-conjugacy class of $g_0\tau g_0^{-1}.$ (Indeed $g'=g g_0^{-1}$ is the product of two odd permutations, hence is even).
It remains to see that the two $A_n$-conjugacy classes are disjoint: assume that $g\tau g^{-1}= h (g_0 \tau g_0^{-1})h^{-1}$ with $g,h$ even. Then $g^{-1}hh_0$ commutes with $\tau$, but is odd, contradicting the assumption on $\tau.$
Comment: Yes it is right, but you didn't prove that the two classes are of equal size.
Comment: You can easily chek that, if $S$ is the stabilizer of $\tau$ for the action of conjugation by an element of $A_n$,  then $g_0Sg_0^{-1}$ is the stabilizer
 of $g_0\tau g_0^{-1}$ for the action of conjugation by an element of $A_n$. Since conjugation by an element is bijective, these stabilizers have same cardinality. But then the orbits of $\tau$ and $g_0\tau g_0^{-1}$, which are nothing but there conjugacy classes, have same cardinality .
Answer: $\newcommand{\Size}[1]{\left\lvert #1 \right\rvert}$Consider the more general situation where the finite group $G$ acts on the finite set $\Omega$, and $H$ is a subgroup of $G$ of index $2$.
Let us compare the orbit of $\alpha \in \Omega$ under $G$ and under $H$, using orbit-stabiliser. I write $\alpha^{G}, \alpha^{H}$ for the orbits, $G_{\alpha}, H_{\alpha}$ for the stabiliser.
$$
\Size{\alpha^{H}}
=
\Size{H : H_{\alpha}}
=
\Size{H : H \cap G_{\alpha}}
=
\Size{H G_{\alpha} : G_{\alpha}}
=
\frac{\Size{H G_{\alpha}}}{\Size{G}} \Size{G : G_{\alpha}}
=
\frac{\Size{H G_{\alpha}}}{\Size{G}} \Size{\alpha^{G}}.
$$
Now note that $H G_{\alpha}$ is a subgroup of $G$, as $H$ is normal in $G$, and that $H \le H G_{\alpha} \le G$,
so that
$$
\frac{\Size{H G_{\alpha}}}{\Size{G}}
=
\begin{cases}
1/2 & \text{if $G_{\alpha} \le H$}\\
1 & \text{if $G_{\alpha} \nleq H$}\\
\end{cases}
$$
Apply for $G = S_{n}$ and $H = A_{n}$ acting by conjugacy on $H$.
Comment: In general it won't be normal, so I am **not** using the 2nd isomorphism theorem, but the equality of indices holds true anyway.
Comment: I assume you use the second isomorphism theorem for $|{H : H \cap G_{\alpha}}|
=
|{H G_{\alpha} : G_{\alpha}}|$. How can you show that $G_{\alpha}$ is normal?


originate conference from python esl

Question: I want to setup a conference call, initiating from  an ESL program.
In my python script I call the first number :
freeswitchcon.api("originate","sofia/gateway/MySIP/91XXXXXXXXXX+" &conference(9099)"

then I call another number:
freeswitchcon.bgapi("originate","sofia/gateway/MySIP/91XXXXXXXXXX+" &conference(radioHealth_${strftime(%Y-%m-%d)}+flags{mute})"

My Dialplans are:
<extension name="conf_demo">
<condition field="destination_number" expression="^9099$">
<action application="conference" data="radioHealth_${strftime(%Y-%m-%d)}+flags{endconf}"/>
</condition>

<extension name="conf_demo">
<condition field="destination_number" expression="^9098$">
<action application="conference" data="radioHealth_${strftime(%Y-%m-%d)}+flags{mute}"/>
</condition>

I get a call on the first number, but not on the second number. Freeswitch logs are:
2016-04-18 05:37:26.417807 [NOTICE] switch_channel.c:1055 New Channel sofia/external/91XXXXXXXXXX [a22ea00c-0527-11e6-86df-415bf8be0d99]
2016-04-18 05:37:26.777867 [NOTICE] sofia.c:7539 Hangup sofia/external/91XXXXXXXXXX [CS_CONSUME_MEDIA] [CALL_REJECTED]
2016-04-18 05:37:26.777867 [NOTICE] switch_core_session.c:1641 Session 24 (sofia/external/91XXXXXXXXXX) Ended
2016-04-18 05:37:26.777867 [NOTICE] switch_core_session.c:1645 Close Channel sofia/external/91XXXXXXXXXX [CS_DESTROY]

Any guidance would be appreciated
Answer: I realise this is a couple of years late, but I noticed that you are calling the normal api in your first originate command:
freeswitchcon.api("originate","sofia/gateway/MySIP/91XXXXXXXXXX+" &conference(9099)"

This means that the first call will be initiated but then python will wait for that call to return (i.e. when it is hung up) before continuing.
If you use freeswitchcon.bgapi, as in your second call, then the call will be originated in the background and python  will not wait for the call to end before continuing.

originate conference from python esl


Appengine datastore Row count on an entity using GQL

Question: Is there a way to get total number of rows in a Google App Engine Datastore Table (Entity) using GQL ?
Answer: You can use count.  It is in the doc: https://developers.google.com/appengine/docs/python/datastore/gqlqueryclass?hl=nl#GqlQuery_count
Comment: Does this work from the Datastore Viewer GQL command ? I am looking for that. But this helps, nonetheless. Thanks !
Comment: NO, you cannot chain methods in the Datastore viewer


Integral Operator: Linear and Continuous

Question: I'm studying the following proposition:
An integral operator $Tf(y):= \int_Ak(x,y)f(x)dx$ is linear, and is continuous on the the following spaces:
$$  \sup_{x \in A, \>y\in B} |k(x,y)| < \infty \implies T:L^1(A) \rightarrow L^{\infty}(B) \tag1$$
$$ \int_B \sup_{x \in A} |k(x,y)|dy \lt \infty \implies T:L^1(A) \rightarrow L^1(B) \tag2 $$
Q1) In the proposition above when it says that: an integral operator $T$ is linear and, is continuous on the following spaces - what space is it referring to? normed space $L^\infty (B)$ in statement (1) ? normed space $L^1 (B)$ in statement (2)?
Q2) The implication arrows in statement (1) and (2) confuse me. What role does the left side of the implication arrow plays in the proposition? Would the proposition still be the same if the left side of the implication arrow is removed:
$$   T:L^1(A) \rightarrow L^{\infty}(B) \tag1$$
$$  T:L^1(A) \rightarrow L^1(B) \tag2 $$
After the proposition, the book that I used give an example: that Fourier Transform is an operator $F: L^1(\mathbb{R}) \rightarrow L^\infty (\mathbb{R})$
Given the above sentence, would it be correct to say that $Ff(y)$ is linear and continuous without given that e.g. (I guess:) $\sup_{x \in A, \>y\in B} |k(x,y)| < \infty$
Hope I'm being clear with my questions as I struggle to understand the proposition above. Thank you!
Comment: I wonder what this book is!
Answer: You have to show that if $\sup_{x \in A, y \in B}\vert k(x,y)< \infty$ the operator $T$ is a continous map from $L^1(A) \to L^\infty(B)$. More precisely you have to show the existence of a $C > 0$ such that for every $f \in L^1(A)$ the inequality
$$ \sup_{y \in B} \vert Tf(y) \vert \leq C \Vert f \Vert_{L^1(A)}$$
holds. To find such a $C$ you need the left side of the implication arrow.
Answer: The correct way of stating the proposition is the following:
1) $T$ is  a bounded operator from $L^{1}(A)$ to $L^{\infty}(B)$ if $sup_{x,y}|k(x,y)| <\infty$.
2). $T$ is  a bounded operator from $L^{1}(A)$ to $L^{1}(B)$ if $\int_B \sup_x|k(x,y)|dy <\infty$.
The language used in the book is not a standard one and it has caused unnecessary confusion in your mind.
Yes it is correct to say that FT is a bounded operator from $L^{1}(\mathbb R)$ to $L^{\infty}(\mathbb R)$.


Calculate distance in 3D space

Question: Imagine I want to determine the distance between points 0,0,0 and 1,2,3.
How is this calculated?
Comment: How would you do it in two dimensions?
Comment: No idea. For some reason they don't learn us that at school…
Answer: By using the the Pythagorean theorem twice, you can show that $d((0,0,0),(1,2,3))=\sqrt{\left(\sqrt{1^2+2^2}\right)^2+3^2}=\sqrt{1^2+2^2+3^2}$.
In general, if you have two points $(x_1, \ldots, x_n)$ and $(y_1, \ldots, y_n)$ in $\mathbb{R}^n$, you can use the Pythagorean theorem $n-1$ times to show that the distance between them is
$$\sqrt{\displaystyle\sum_{i=1}^n (x_i -y_i)^2}$$
Comment: @user3019105 We use induction, together with the fact that all the coordinate axes are orthogonal to each other. So the way the z-axis is orthogonal to the xy-plane (and hence to any line that has constant z-coordinate) generalizes. Or rather, that is how we define the geometry of higher dimensional space.
Comment: A starting point might be [this article on Wikipedia](https://en.wikipedia.org/wiki/Euclidean_distance).
Comment: How can we prove the last formula? I find it difficult to imagine a n-dimensional space geometrically when $n > 3$...
Comment: Thank you, where can I find some theory and examples about this  topic?
Comment: @user3019105 unfortunately, I don't know any references that talk about this in elementary terms, explaining why things are like they are. This is a basic example of a metric space (the Euclidean metric), and the metric is induced by a norm ($\ell^2$ norm), and that norm comes from an inner product, so this is an example in a lot of places, and I can give you references for generalizations, but I don't think they are what you are looking for.
Comment: Whatever you have, if you could share it, I will be thankful and take a look!
Answer: Here is an illustration:

You want to find $d$, where $d^2 = h^2 + z^2$, and $h^2 = x^2 + y^2$. So
$d^2 = (x^2 + y^2) + z^2$, and therefore $d = \sqrt{x^2 + y^2 + z^2}$
Answer: It's Pythagorean theorem, just like with 2D space.
$||[0, 0, 0]-[1, 2, 3]|| = \sqrt{(0-1)^2+(0-2)^2+(0-3)^2} = \sqrt{1+4+9} = \sqrt{14}$
Answer: The distance between two points in three dimensions is given by:
        Given two points: point $a = (x_0, y_0, z_0)$; point $b = (x_1, y_1, z_1)$
        The distance is (in units):
         $$d = \sqrt{(x_1-x_0)^2 + (y_1-y_0)^2 + (z_1 - z_0)^2}$$
        For your given points: point $a = (0,0,0)$; point $b = (1,2,3)$
        Using substitution:
               $$d = \sqrt{(1-0)^2+(2-0)^2+(3-0)^2}$$
               $$d = \sqrt{(1 + 4 + 9)}$$
               $$d = \sqrt{(14)}$$
               $$d = 3.7$$
        Note: if one point, point a, is the origin $$(0,0,0)$$ then
              the equation reduces to d = $\sqrt{(x^2 + y^2 + z^2)}$
Comment: Does d equal exactly `3.7`? I get `3.7416573867739413` doing the calculation in Python.
Comment: For some basic information about writing math at this site see e.g.
[here](//meta.math.stackexchange.com/q/5020),
[here](//meta.stackexchange.com/a/70559),
[here](//meta.math.stackexchange.com/q/1773) and
[here](/help/notation).
Comment: Thanks, this is by far the clearest answer for us non-mathematicians. I needed that extra bit of hand holding.

Calculate distance in 3D space


How to perform a basic full rank factorization?

Question: What is the general process for performing full rank factorization on a matrix?
For example, if I am given $$A = \begin{bmatrix}
2 & 1\\
 4& 2\\
6 &3
\end{bmatrix}$$
What operations do I perform on this matrix, to get the following solution?
$$=\begin{bmatrix}
1\\2
\\3
\end{bmatrix}\begin{bmatrix}
2 &1
\end{bmatrix}=BC$$
I ask, because if I am given a different $A$ matrix, where the factorization isn't so obvious, I would like to know the best method to achieve full-rank factorization!
Comment: Consult https://en.wikipedia.org/wiki/Rank_factorization#Construction
Comment: Fixed, sorry about that.
Answer:
Find a basis for the row space
Write the rows as linear combinations of basis elements

or

Find a basis for the column space
Write the columns as linear combinations of basis elements


Limit calculation, justification for use of l'Hospital's rule

Question: Determine the limit
$$\lim_{x\to 0} x\int_x^1\frac{\cos t}{t^2}\mathrm{d}t $$
I would use the l'Hospital's rule, but for that I need to be able to justify that the integral tends to $\infty$. Not concerned with the calculation itself, rather need to justify the use of l'Hospital's rule.
Calculating out the series looks to be very tedious, no doubt it will answer the question, but is there a faster way?
Comment: The integrand is bigger than $(\cos 1) / t^2$. Now, take out the constant from the integral and see that it is divergent.
Comment: If you really want to use L'Hospital's rule you just need to write the $x$ as $1/(1/x)$ so that the denominator has $1/x \to \infty$ as $x \to 0^{+}$. The LHR only requires the denominator to tend to $\infty$. There is no need to worry about numerator.
Answer: Hint. You may observe that, as $x \to0$,
$$
x\int_x^1\frac{\cos t}{t^2}\mathrm{d}t=x (1-x)\times \frac{\int_x^1\frac{\cos t}{t^2}\mathrm{d}t}{1-x}\sim x (1-x)\times \left(-\frac{\cos x}{x^2}\right)
$$ and you may conclude easily.
We have used

$$
\frac{f(x)-f(a)}{x-a}\to f'(a)
$$

with $f'(x)=-\dfrac{\cos x}{x^2}$ and $a=1$.
Answer: $$\cos(t)=1+o(1)\implies \frac{\cos(t)}{t^2}=\frac{1}{t^2}+o\left(\frac{1}{t^2}\right)\implies \frac{\cos(t)}{t^2}\sim_0\frac{1}{t^2} \implies \int_x^1\frac{\cos(t)}{t^2}\mathrm d t=+\infty.$$
Therefore $$\lim_{x\to 0}\int_x^1 \frac{\cos(t)}{t^2}\mathrm d t=\lim_{x\to 0}\frac{\int_x^1 \frac{\cos(t)}{t^2}\mathrm d t}{\frac{1}{x}}\underset{Hospital}{=}...=1.$$
The fact that you can use l'Hospital is because you have an indetermination of the type $\frac{\infty }{\infty }$.
Comment: $f=o(g)$ at $x=a$ if $\lim_{a}\frac{f}{g}=0$.
Comment: Yes, I understand why I can use l'H, the o-notation bit is a tad confusing, haven't used it that much. $o(1)$ means that $t$ is increasing faster than $1$?
Comment: Ah, okay, now it makes sense, thanks.
Answer: You may avoid De l'Hopital by noticing that $\frac{\cos t}{t^2} = \frac{1}{t^2}-\frac{2\sin^2(t/2)}{t^2}$, where the last part is a continuous and bounded function on $(0,1]$, hence, by exploiting $\int\frac{dt}{t^2}=-\frac{1}{t}$:
$$ \int_{x}^{1}\frac{\cos t}{t^2}\,dt = -1+\frac{1}{x}-C+O(x) $$
(where $C=\int_{0}^{1}\frac{2\sin^2(t/2)}{t^2}\,dt$) and that clearly implies:
$$ \lim_{x\to 0}x\cdot\int_{x}^{1}\frac{\cos t}{t^2}\,dt = \color{red}{1}.$$
Comment: this one is way simpler. +1


Characteristic function problem

Question: Suppose $X_1$ and $X_2$ are independent random variables and suppose also that $X_1$      and $X_1-X_2$ are independent. Show that
$$\mathbb{P}_{X_1}[X_1=c]=1$$
for some constant $c$.
What I get so far is that $\phi(t)\phi(-t)=1$. Then I have problems transforming $\phi(-t)$ to the form of $\phi(t)$. From there, we can get $f(x)$ by integrating $\phi(t)$, but I am not sure I was thinking correctly.
Comment: Please add the `self-study` tag and review its [tag wiki](http://stats.stackexchange.com/tags/self-study/info), modifying your question as necessary.
Comment: Are you assuming that $X_1$ and $X_2$ have the _same_ distribution?
Answer: Hint: Unless you are specifically asked to give a
proof via characteristic functions, consider
instead that if $X_1$ and $X_1-X_2$ are independent, then
they are also uncorrelated (that is, their covariance is $0$). Thus, from
the bilinearity of the covariance function and the knowledge that
$\operatorname{cov}(X,X) = \operatorname{var}(X)$, we have that
$$\operatorname{cov}(X_1, X_1-X_2)
= \operatorname{cov}(X_1,X_1) - \operatorname{cov}(X_1,X_2) =
\operatorname{var}(X_1) - 0 = \operatorname{var}(X_1) = 0.$$
So, what can we say about $X_1$ from this result?

Edit: added in response to @whuber's comment.
I don't have a complete answer when $X$ and $Y$ do not
have a variance and so cannot be said to have a covariance,
but the following is an attempt in that direction
Suppose that $X$ and $Y$ are random variables and
$a$ is a real number such that either $P\{X = a\} > 0$
or $X$ admits of a density at $a$, and this density is continuous
and positive at $X = a$.  Then, consider the following.

The conditional distribution of $X-Y$ given that
$X=a$ is the same as the conditional distribution of $a-Y$ given
that $X = a$.
In the special case that $X$ and $Y$ are independent (and thus
so are $a-Y$ and $X$ independent
random variables) the conditional distribution of
$a-Y$ given $X = a$ is the same as the unconditional
distribution of $a-Y$.
From 1. and 2. we have that for independent random
variables $X$ and $Y$, the conditional distribution of
$X-Y$ given that $X=a$ is the same as the unconditional
distribution of $a-Y$.  This unconditional distribution depends on
the value of $a$
On the other hand, if $X$ and $Z$ are independent random
variables, then the conditional distribution of $Z$ given
that $X=a$ is the same as the unconditional distribution
of $Z$, and this unconditional distribution in no way depends
of what $a$ is.
In the problem at hand, $X=X_1$ and $Y = X_2$ are independent
random variables and thus from 3. we have
that the conditional distribution of
$X_1-X_2$ given that $X_1 = a$ is the same as the unconditional
distribution of $a-X_2$. This distribution depends on the value of $a$;
different choices of $a$ result in different distributions.
On the other hand, with $X=X_1$ and $Z = X_1-X_2$ being given
to be independent random variables, 4. tells us that the
conditional distribution of $Z = X_1-X_2$ given $X_1=a$ does not
depend on the value of $a$ at all!

$X_1$ cannot admit of a continuous density since then we would have
more than one $a$ and thus (as per 5.), different conditional distributions
for $X_1-X_2$ in violation of 6. For the same reason, $X_1$ cannot
take on two or more values with positive probability. In short,
the only way that 5. and 6. can peacefully co-exist is when
$X_1$ takes on only one value $a$ with probability $1$.
Comment: It's a good hint (+1). I wonder how one would proceed when it is not assumed the variables have variances.
Answer: The question is on the right track.  Since such a problem evidently is intended to help one understand and work with characteristic functions, I will include many of the details that might otherwise be omitted from the solution.

For any random variable $Z$, then, and a real number $t$, let us write
$$\phi_Z(t) = \mathbb{E}(e^{i t Z})$$
for the characteristic function (cf) of $Z$.  For future reference, note that
$$|\phi_Z(t)| \le \mathbb{E}(|e^{i t Z}|) = \mathbb{E}(1) = 1.$$
It is well known--and easily shown by expanding the exponential into its Taylor series at $0$--that when $\phi_Z$ is differentiable at the origin, its derivatives (divided by suitable powers of $i$) are the moments of $Z$.  Regardless, $\phi_Z$ will be continuous at $0$ (essentially because its behavior there reflects the tails of the distribution of $Z$, which necessarily approach asymptotic values and therefore don't change $\phi_Z(t)$ much for very small $|t|$).
When two variables $(Z_1,Z_2)$ are independent, the characteristic function of a linear combination $\alpha_1 Z_1 + \alpha_2 Z_2$ is neatly related to the cfs of the variables themselves via
$$\eqalign{\phi_{\alpha_1Z_1+\alpha_2Z_2}(t)&=\mathbb{E}\left(e^{i t (\alpha_1Z_1+\alpha_2Z_2)}\right)=\mathbb{E}\left(e^{i t \alpha_1Z_1}e^{i t \alpha_2Z_2}\right)=\mathbb{E}\left(e^{i t \alpha_1Z_1}\right)\mathbb{E}\left(e^{i t \alpha_2Z_2}\right) \\
&=\phi_{Z_1}(\alpha_1 t)\phi_{Z_2}(\alpha_2 t).
}$$
The penultimate equality required independence of the random variables $e^{it\alpha_iZ_i}$, but that is assured by the independence of the $Z_i$.
Assuming $X$ and $Y$ are independent and that $X$ and $X-Y$ are independent, apply this result to a linear combination of $X$ and $X-Y$, say $\alpha X + \beta (X-Y)$, computing it in two ways, using both independence assumptions:
$$\eqalign{\phi_X((\alpha+\beta)t)\phi_Y(-\beta t) &= \phi_{(\alpha+\beta)X-\beta Y}(t)=\phi_{\alpha X+\beta(X-Y)}(t)=\phi_X(\alpha t)\phi_{X-Y}(\beta t) \\
&=\phi_X(\alpha t)\phi_X(\beta t)\phi_Y(-\beta t).
}$$
This was the key move.  The desired conclusion follows directly, but some care is needed in the analysis.
The tricky part is that we cannot just divide both sides by $\phi_Y(-\beta t)$, because for many values of $t$ it could be zero.  However, since $\phi_Y(0)=\mathbb{E}(1)=1$ and $\phi_Y$ is continuous at $0$, then for any real $\beta$, $\phi_Y(-\beta t)$ must be nonzero in a neighborhood of zero.  Within this neighborhood (which expands as  $|\beta|$ decreases) we may cancel the common $\phi_Y(-\beta t)$ terms appearing at both ends of the preceding series of equations, yielding
$$\phi_X((\alpha+\beta)t) = \phi_X(\alpha t)\phi_X(\beta t).$$
(Setting $\alpha=-\beta=1$ gives $1=\phi_X(0)=\phi_X(t)\phi_X(-t)$, which is the partial result reported in the question.)
Another way to express this is to take logarithms.  For any real number $\gamma$ define the cumulant generating function (cgf) as
$$\psi(\gamma) = \log(\phi_X(\gamma)).$$
Since $\phi_X$ is continuous and positive near $0$, $\psi$ is continuous near $0$.  Consider the special case $t=1$ and assume both $|\alpha|$ and $|\beta|$ are small enough that they and $|\alpha+\beta|$ lie in the neighborhood of values $t$ where $\phi_Y(-\beta t)$ is nonzero.  It is immediate that
$$\psi(\alpha+\beta) = \psi(\alpha) + \psi(\beta);\ \psi(0) = 0.$$
It is easy to show that the only such functions are the linear ones.  Thus, there must exist a number $\gamma$ for which
$$\psi(t) = \gamma t$$
for all sufficiently small $t$.  Equivalently, in this neighborhood
$$\phi_X(t) = e^{\gamma t}.$$
Since $|\phi_X(t)| \le 1$ for (sufficiently small) positive and negative values of $t$, $\gamma$ must be a purely imaginary number.  Writing it as $\gamma = i c$ for a real number $c$ yields
$$\phi_X(t) = e^{i c t}.$$
Since this is differentiable at the origin, we can now obtain all the moments of $X$.  In particular,
$$\mu_1=\mathbb{E}(X) = \frac{1}{i}\frac{d}{d t} e^{i c t} \vert_{t=0} = c$$
and
$$\mu_2=\mathbb{E}(X^2) = \frac{1}{i^2}\frac{d^2}{d t^2} e^{i c t} \vert_{t=0} = c^2.$$
Therefore the variance of $X$ is
$$\text{Var}(X) = \mu_2 - \mu_1^2 = 0$$
and the desired result follows immediately: $X$ must be almost everywhere a constant (equal to the value of $c$ that emerged in the analysis).
Comment: @Dilip Thanks for the correction; I will fix that. I had indeed observed that $|\phi(t)|=1$ but was unable to find a simple way to exploit it.  This troubles me--it would seem one ought to be able to deduce from this that $\phi(t)=\exp(ic t)$.  That's certainly possible by appealing to theorems about the decay of $\phi$ at infinity, but I am wondering whether there is a quick elementary way to make this argument.
Comment: I would appeal to the head of $\phi$. If for nonzero $ t $, $|\phi (t)| = 1$, then $ X $ is discrete with period $2\pi/t $ (Jensen's inequality). So, then if the infimum of all such positive $ t $ is zero, the "period" becomes infinite, i. e., $ X $ is constant almost surely. That is the intuition. The details are only marginally more difficult.
Comment: Very educational indeed!  A couple of minor things. Where you say "$\alpha=\beta=1$" I think you meant to say that $\alpha=-\beta=1$.  Also, a characteristic function is essentially a Fourier transform, and Fourier transforms of real functions have the property that $\phi(-t) = [\phi(t)]^*$ and so from $1=\phi(0) = \phi(t)\phi(-t)$ we can immediately deduce that $|\phi(t)|=1$.

Characteristic function problem


Adding a minimal key to a BCNF decomposition

Question: If I will add a minimal key to a given BCNF decomposition can it be no more a BCNF decomposition?
Formally, say I have F (group of functional dependencies), schema R and it's BCNF decomposition {R1,R2,R3,R4} and I will add another group R5 to the decomposition which is a minimal key of schema R.
Will the new decomposition  {R1,R2,R3,R4,R5} be still a BCNF decomposition of R?
Answer: Every minimal key is in BCNF since projection of F+ on it contains only trivial functional dependencies. As observed, e.g., by Koehler, any dependency preserving BCNF decomposition can be made into lossless by adding a table representing a minimal key. The resulting decomposition is still dependency preserving.
Henning Köhler: Finding Faithful Boyce-Codd Normal Form Decompositions. AAIM 2006: 102-113


Using drupal login system for another platform

Question: I want to create another site that uses the drupal user login / registration system so that it is integrated with my drupal site. This would allow current users to use this other service without having to register again.
Can someone let me know if this is possible? Sharing login cookie / registration / user validation...etc.
I am using drupal 7.
Answer: The Services module provides an HTTP REST API for authentication (amongst other things). So it should be easily usable to let a remote/separated site re-use your Drupal web site user authentication. The following code comes from its documentation and illustrate how to use it for user authentication. The returned user object will contain the session name and id to use in future REST request if more data from the Drupal are needed (for instance to retrieve user profile or content).
<code>// REST Server URL
$request_url = 'http://your-drupal/rest_server_endpoint/user/login';

// User data
$user_data = array(
  'username' => 'user_name',
  'password' => 'user_password',
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}
</code>


Microsoft Edge passando caracteres estranhos em chamada AJAX

Question: Tenho uma chamada Ajax em um sistema Web, aonde você especifica uma data de demissão, e demite um funcionário naquela data:

data é o parâmetro que vem pela chamada Ajax. Quando eu testo no Chrome ou em qualquer outro navegador, funciona perfeitamente. Porém meu cliente usa o Edge, e quando fui testar nele, esse Datetime.Parse falha com System.FormatException.
Vejam os testes que fiz:

01/01/2019 -> Essa data eu copiei do debugger quando fiz a chamada pelo Chrome, depois colei nesse site. O output foi:

01/01/2019 - Este é o valor que vem no debugger quando faço o teste via Microsoft Edge. Veja o output do mesmo site:

Se você selecionar as datas que coloquei aí e colar no mesmo site, poderão ver o mesmo resultado. Apesar de as datas parecerem idênticas, aparentemente há caracteres estranhos escondidos na que o Edge passa na chamada Ajax!
O que está acontecendo? Como posso resolver?
Comment: @downvoter pode se pronunciar sobre o motivo do downvote?
Answer: Este é um comportamento conhecido.
Edge inclui, na sua cadeia de tratamento de dados, um parser que identifica o formato de data de acordo com o padrão ECMA-402 e inclui caracteres especiais como LTR e RTL.
Este não é um comportamento padrão entre browsers.
Você precisará incluir na sua cadeia de avaliação um parser que elimine o conteúdo de marcação direcional.


Erro ao criar tabelas com chaves estrangeiras

Question: Ao correr o script abaixo ocorre o erro:

Cannot add foreign key constraint

ao criar as últimas duas tabelas.
create database Cinema;
use Cinema;

create table Filme (
    id_filmes int primary key auto_increment not null,
    nome_BR varchar (45) not null,
    nome_EN varchar (45) not null,
    anoLanccamento int not null,
    sinopse varchar (45) not null,
    fk_id_diretor int,
    fk_id_genero int,
    constraint foreign key (fk_id_diretor) references diretor (id_diretor),
    constraint foreign key (fk_id_genero) references genero (id_genero)
)engine = InnoDB;

create table Funcionario (
    id_funcionario  int primary key auto_increment,
    nome varchar (45) not null,
    carteiraTrabalho int not null,
    dataContratacao date not null,
    salario float not null
)engine = InnoDB;

create table diretor (
    id_diretor int primary key auto_increment,
    nome varchar (45) not null
)engine = InnoDB;

create table genero (
id_genero int primary key auto_increment,
nome varchar (45) not null
)engine = InnoDB;

create table funcao (
    id_funcao int primary key auto_increment,
    nome varchar (45) not null
)engine = InnoDB;

create table horario (
    id_horario int primary key auto_increment,
    hora time not null
)engine = InnoDB;

create table sala (
    id_sala int primary key auto_increment,
    nome varchar (45) not null,
    capacidade int
)engine = InnoDB;

create table premiacao (
    id_premiacao int primary key auto_increment,
    nome varchar (45) not null,
ano int
)engine = InnoDB;

create table horario_trabalho_funcionario(
    fk_id_horario int,
    fk_id_funcionario int,
    fk_id_funcao int ,
    constraint foreign key (fk_id_horario) references horario (id_horario),
    constraint foreign key (fk_id_funcionario) references funcionario (id_funcionario),
    constraint foreign key (fk_id_funcao) references  funcao (id_funcao)
) engine = InnoDB;

create table filmes_exibido_sala (
    fk_id_filmes int,
    fk_id_sala int,
    fk_id_horario int,
    constraint foreign key (fk_id_filmes) references filme (id_filme),
    constraint foreign key (fk_id_sala) references sala (id_sala),
    constraint foreign key (fk_id_horario) references  horario (id_horario)
)engine = InnoDB ;

create table filmes_has_premiacao (
    fk_id_filmes int primary key auto_increment,
    fk_id_premiacao int,
    ganhouBOOL varchar (45),
    constraint foreign key (fk_id_filmes) references filme (id_filme),
    constraint foreign key (fk_id_premiacao) references premiacao (id_premiacao)
)engine = InnoDB;

Comment: tente especificar mais o seu problema e identar o código para que fique mais fácil para a comunidade entender e assim tentar te ajudar =)
Answer: Tem dois erros no seu script.
Primeiro, crie as tabelas sem chaves estrangeiras primeiro. Da forma como está, ao tentar criar a tabela Filme vai falhar dado que as tabelas director e genero ainda não existem.
Segundo, na sua tabela Filme chamou id_filmes à chave primária. No entanto, nas tabelas que se referem a Filme usou id_filme como chave primária da tabela estrangeira (isto é, tem um s a mais).
O seu script actualizado (e a funcionar no SQLFiddle):
create table funcao (
    id_funcao int primary key auto_increment,
    nome varchar (45) not null
)engine = InnoDB;

create table horario (
    id_horario int primary key auto_increment,
    hora time not null
)engine = InnoDB;

create table sala (
    id_sala int primary key auto_increment,
    nome varchar (45) not null,
    capacidade int
)engine = InnoDB;

create table premiacao (
    id_premiacao int primary key auto_increment,
    nome varchar (45) not null,
ano int
)engine = InnoDB;

create table Funcionario (
    id_funcionario  int primary key auto_increment,
    nome varchar (45) not null,
    carteiraTrabalho int not null,
    dataContratacao date not null,
    salario float not null
)engine = InnoDB;

create table diretor (
    id_diretor int primary key auto_increment,
    nome varchar (45) not null
)engine = InnoDB;

create table genero (
id_genero int primary key auto_increment,
nome varchar (45) not null
)engine = InnoDB;

create table Filme (
    id_filme int primary key auto_increment not null,
    nome_BR varchar (45) not null,
    nome_EN varchar (45) not null,
    anoLanccamento int not null,
    sinopse varchar (45) not null,
    fk_id_diretor int,
    fk_id_genero int,
    constraint foreign key (fk_id_diretor) references diretor (id_diretor),
    constraint foreign key (fk_id_genero) references genero (id_genero)
)engine = InnoDB;

create table horario_trabalho_funcionario(
    fk_id_horario int,
    fk_id_funcionario int,
    fk_id_funcao int ,
    constraint foreign key (fk_id_horario) references horario (id_horario),
    constraint foreign key (fk_id_funcionario) references funcionario (id_funcionario),
    constraint foreign key (fk_id_funcao) references  funcao (id_funcao)
) engine = InnoDB;

create table filmes_has_premiacao (
    fk_id_filmes int primary key auto_increment,
    fk_id_premiacao int,
    ganhouBOOL varchar (45),
    constraint foreign key (fk_id_filmes) references filme (id_filme),
    constraint foreign key (fk_id_premiacao) references premiacao (id_premiacao)
)engine = InnoDB;

create table filmes_exibido_sala (
    fk_id_filmes int,
    fk_id_sala int,
    fk_id_horario int,
    constraint foreign key (fk_id_filmes) references filme (id_filme),
    constraint foreign key (fk_id_sala) references sala (id_sala),
    constraint foreign key (fk_id_horario) references  horario (id_horario)
)engine = InnoDB ;


Limit of $\left(x^{3} - 1\right)\left(x^{2} - 1\right)^{1/3} \over 5\ln\left(x\right)$ when $x\to1^{+}$

Question: I am searching a way to solve an equation with the asymptotic method; we can't use the hopital nor sostitution, but we must find a way to solve it using just significant limitations and basic properties of limits.

$\displaystyle{\left(x^{3} - 1\right)\left(x^{2} - 1\right)^{1/3} \over 5\ln\left(x\right)}$.
The limit of this functon as it approches to  $1^{+}$.

Thanks a lot for the help, I would appreciate to understand not just the result ( that I know ) but you could make it. Thanks.
Comment: Why the restriction $x\to 0^+?$
Comment: The restriction is for ${x\to 1^+}$ , and I just wrote the exercise. But it changes the sign I think
Comment: Sorry, I meant $1^+.$ The limit  is $0$ for $x\to 1.$
Answer: With $x >1$
$$\tag{1}\frac{(x^3-1)(x^2-1)^{1/3}}{5 \ln x} = \frac{(x-1)^{4/3}}{\ln x}\frac{(x^2+x+1)(x+1)^{1/3}}{5}$$
Using the well-known inequality
$$\frac{x-1}{x} < \ln x < x-1,$$
we see that
$$(x-1)^{1/3} < \frac{(x-1)^{4/3}}{\ln x} < x(x-1)^{1/3}.$$
By the squeeze principle,
$$\lim_{x \to +1}\frac{(x-1)^{4/3}}{\ln x} = 0.$$
Hence, the limit of the LHS of (1) is $0$ since the second factor on the RHS converges to a finite limit.
Comment: Yes, I did that, but after? I don't know what to do with (x-1)^4/3 and (x+1)!
Comment: Use squeeze theorem after bounding $(x-1)^{4/3}/\ln x$
Comment: What do you think the limit will be given those bounds?
Answer: Note $x^3-1=(x-1)(x^2 + x + 1).$ Also, because $\ln '(1) = 1,$ $\lim_{x\to 1} (\ln x)/(x-1) = 1.$ So we have, as $x\to 1,$
$$\frac{x-1}{\ln x}\cdot\frac{(x^2+x+1)(x-1)^{1/3}}{5} \to 1\cdot \frac{3\cdot 0^{1/3}}{5} = 0.$$


AngularJS with SignalR $scope variable issue

Question: I'm new with AngularJS and SignalR but I've ran into an issue that I just haven't been able to resolve or find other similar postings that might help me.  Sorry that this became fairly lengthy but I wanted to supply as much information as possible.
I'm trying to create a fairly simple SPA in which the page will have three basic areas.  A Lobby (like a sign in area), then an Admin section and a User section.  So based on how they sign in, they would be displayed either the Admin section or the User section. (Which all this works fine for me)
Between the Admin section and User sections I have a chat area so messages can be sent back and forth between the Admin and any users connected in.  But on the specific page, I get the display for the message that was entered, but it will 'not' display any messages coming from the other users (or Admin).  I can see in the console that the message is received by the other page and it's added to the messages array but it acts like there are two messages array so it's not combining the messages into the same array to be displayed.  I'll show this below after the code segments.
Both of these chat areas are displaying the same messages array as:
User chat area:

            {{msg.message}}

    <input ng-model="newMemberMessage" class="form-control input-sm pull-left" style="width: 80%" type="text" />
    <button ng-click="sendMemberMessage()" class="pull-right btn btn-primary btn-sm">Send</button>

Admin chat area:

            {{msg.message}}

    <input ng-model="newAdminMessage" class="form-control input-sm pull-left" style="width: 80%" type="text" />
    <button ng-click="sendAdminMessage()" class="pull-right btn btn-primary btn-sm">Send</button>

I have the following ChatHub method created:
    public void SendMessage(SendData data)
    {
        Clients.Group(data.roomNumber, Context.ConnectionId).newBroadcastMessage(data.name + ": " + data.message);
    }

In my controller I have a variable defined as:
$scope.messages = [];

I then have the following directives declared:
$scope.sendMemberMessage = function () {
    chat.server.sendMessage({ name: $scope.name, message: $scope.newMemberMessage, roomNumber: $scope.roomNumber });
    displayMessage("You: " + $scope.newMemberMessage);
    $scope.newMemberMessage = "";
};

$scope.sendAdminMessage = function () {
    chat.server.sendMessage({ name: $scope.name, message: $scope.newAdminMessage, roomNumber: $scope.adminRoomNumber });
    displayMessage("You: " + $scope.newAdminMessage);
    $scope.newAdminMessage = "";
};

chat.client.newBroadcastMessage = onNewBroadcastMessage;

function onNewBroadcastMessage(message) {
    displayMessage(message);
    $scope.$apply();        //Required to update the scope digest bindings.
    console.log(message);
};

function displayMessage(message) {
    $scope.messages.unshift({ message: message });
    console.log("Added new member message to messages.  Current Messages: ");
    for (var i = 0; i < $scope.messages.length ; i++) {
        console.log($scope.messages[i]);
    }
};

When I run my application I'm opening the form in a Chrome window and in a Firefox window to make sure they are running independent of each other.
This is what I get displayed in the consol when I enter a couple messages in my Admin screen running in the Chrome window:
[08:44:28 GMT-0500 (Central Daylight Time)] SignalR: Invoking chat.SendMessage jquery.signalR-2.1.2.js:81
Added new member message to messages.  Current Messages:                       mainCtrl.js:293
Object {message: "You: Admin Test 1"}                                          mainCtrl.js:295
[08:44:28 GMT-0500 (Central Daylight Time)] SignalR: Invoked chat.SendMessage  jquery.signalR-2.1.2.js:81
[08:45:06 GMT-0500 (Central Daylight Time)] SignalR: Invoking chat.SendMessage jquery.signalR-2.1.2.js:81
Added new member message to messages.  Current Messages:                       mainCtrl.js:293
Object {message: "You: Admin Test 2"}                                          mainCtrl.js:295
Object {message: "You: Admin Test 1", $$hashKey: "004"}                        mainCtrl.js:295
[08:45:06 GMT-0500 (Central Daylight Time)] SignalR: Invoked chat.SendMessage  jquery.signalR-2.1.2.js:81

The messages above show up in the Admin chat panel correctly.
The following is displayed in the console of the Firefox but neither of these show up in the Users chat panel:
"[08:44:28 GMT-0500 (Central Standard Time)] SignalR: Triggering client hub event 'newBroadcastMessage' on hub 'chat'." jquery.signalR-2.1.2.js:81
"Added new member message to messages.  Current Messages: "      mainCtrl.js:293
Object { message: "Admin: Admin Test 1" }                        mainCtrl.js:295
"Admin: Admin Test 1"                                            mainCtrl.js:278
"[08:45:06 GMT-0500 (Central Standard Time)] SignalR: Triggering client hub event 'newBroadcastMessage' on hub 'chat'." jquery.signalR-2.1.2.js:81
"Added new member message to messages.  Current Messages: "      mainCtrl.js:293
Object { message: "Admin: Admin Test 2" }                        mainCtrl.js:295
Object { message: "Admin: Admin Test 1" }                        mainCtrl.js:295
"Admin: Admin Test 2"                                            mainCtrl.js:278

Now if I enter a chat message on my users screen in Firefox, the Firefox console shows:
"[09:04:38 GMT-0500 (Central Standard Time)] SignalR: Invoking chat.SendMessage" jquery.signalR-2.1.2.js:81
"Added new member message to messages.  Current Messages: " mainCtrl.js:293
Object { message: "You: User Test 1", $$hashKey: "004" } mainCtrl.js:295
"[09:04:38 GMT-0500 (Central Standard Time)] SignalR: Invoked chat.SendMessage" jquery.signalR-2.1.2.js:81

The entered text shows up fine on the Firefox users chat display.
And the following is displayed on the Chrome console but does not display in the Chrome chat panel.  (The chat panel still displays the previous Admin chat messages.)
[09:04:38 GMT-0500 (Central Daylight Time)] SignalR: Triggering client hub event 'newBroadcastMessage' on hub 'chat'. jquery.signalR-2.1.2.js:81
Added new member message to messages.  Current Messages:  mainCtrl.js:293
Object {message: "Mike: User Test 1"} mainCtrl.js:295
Mike: User Test 1 mainCtrl.js:278

That listing of the messages array, 'should' have the previous chat messages still in the array.
So I can't figure out what I've done wrong or why the chat displays are not displaying the chat messages from the other persons.  I've got an original sample chat application where I've put two chat windows on it using the same variable and model names in both chat panels and it works fine.  So I know this logic should work but I can't figure out what I've done wrong with this main application preventing the chat messages to be displayed in the other windows.
Can anyone give me any help on this?
Answer: After a lot of pains taking trial and error, I tried using the original example chat program that I was basing my application off of.  With that program working I applied my new program to it piece by piece.  After I finally got down to piecing in sections of the Admin part into it I finally found my problem.  There was a  tag in my Admin section that had an old line of code in it that was setting the ng-controller on it which was the same ng-controller on the main  at the top of the page.  As soon as I removed that second ng-controller setting the chat started working properly again.  I'm assuming that the second ng-controller setting was creating a second $scope so that is why I was seeing my messages array as being duplicated even though the display of my messages array was not within this second ng-controller tag.  At least now I can finally continue on with my project.


Integrate $\int \frac{dx}{(x^2+1)^2}$

Question:
$$\int \frac{dx}{(x^2+1)^2}$$

How should I approach this? Is there a general approach when the degree of the denominator>>numerator in this case $x^4>>1$?
Comment: There is a general approach for all rational fractions. https://en.wikipedia.org/wiki/Partial_fraction_decomposition
Comment: @gbox see [here](http://math.stackexchange.com/a/1658414/203577) someone asked  the same today
Comment: $$\int\frac1{(x^2+1)^2}\,dx = \int\frac{1+x^2-x^2}{(x^2+1)^2}\,dx = \int\frac1{x^2+1}\,dx - \int x\frac{x}{(x^2+1)^2}\,dx$$$$ = \int\frac1{x^2+1}\,dx +\frac12\int x\,d\frac1{x^2+1} = \int\frac1{x^2+1}\,dx +\frac12 \frac x{x^2+1} - \frac12\int\frac1{x^2+1}\,dx$$$$= \frac12\frac x{x^2+1} + \frac12\arctan x + const $$
Answer: Apply Integral Substitution:
$\color{green}{x=\tan \left(u\right)\quad \:dx=\frac{1}{\cos ^2\left(u\right)}du}$
$$=\int \frac{\sec ^2\left(u\right)}{\left(\tan ^2\left(u\right)+1\right)^2}du=\int \frac{\sec ^2\left(u\right)}{\left(\sec ^2\left(u\right)\right)^2}du=\int \cos ^2\left(u\right)du=\int \frac{1+\cos \left(2u\right)}{2}du$$
Now it's easy...
Answer: Here you can split the integrand into a sum of rational functions of the form $$\frac{1}{(x^2+1)^2}=\frac{a}{i+x}+\frac{b}{-i+x}+\frac{p}{(i+x)^2}+\frac{q}{(-i+x)^2},$$ determine the constants $a,\,b,\,p,\,q$ and then integrate.

Integrate $\int \frac{dx}{(x^2+1)^2}$


Python "for loop" looping time limit

Question: how to set a time limit for "for loop"?
say I would like the looping each 200mms
for data in online_database:
    looping time  = 200 mms
    print(data)

Thanks!
Comment: Set a variable with the time at before the loop. Inside the loop, check the difference between the current time and the start time. If it's more than 200ms, break out of the loop with a `break` statement.
Comment: The module "time" provides "time" or "time_ns" and "sleep" for this.
Comment: What exactly is supposed to be limited? Is `online_database` an iterator whose `__next__` method could take more than 200 ms?
Answer: import time

t_sleep = 0.2

for x in range(10):
    print(x)
    time.sleep(t_sleep)

this code would sleep for 0.2 secs for every iteration
Answer: Maybe something like this could help
import time

for i in YourSequence:

    current_millis = round(time.monotonic() * 1000)
    max_milis = (current_millis + 200) #200 is for the time difference

    while round(time.monotonic() * 1000) < max_milis:
          #----Your code------

Additionally, if your program is large, you could add these lines to periodically keep an eye out if your program has crossed the max time limit
if round(time.monotonic() * 1000) > max_milis:
       break

Something like this
import time

for i in a:

    current_millis = round(time.monotonic() * 1000)
    max_milis = (current_millis  + 200)

    while round(time.monotonic() * 1000) < max_milis:

        #Your Codes......

        if round(time.monotonic() * 1000) > max_milis:
              break

        #Your Codes......

        if round(time.monotonic() * 1000) > max_milis:
             break

        #Your Codes......
        break

Answer: You can use default_timer from the timeit module to find how much time has passed:
from timeit import default_timer

start_time = default_timer()
looping_time = 0.2

for data in online_database:
    print(data)
    end_time = default_timer()
    if end_time - start_time > looping_time:
         break

Note: default_timer() returns an amount of seconds from a fixed point in time. It is exclusively used for timing things.
Documentation: timeit.default_timer

Python "for loop" looping time limit


Patching Exchange mailbox server without potential data loss

Question: I have what I think is a quick easy question.  I'd like to apply a service pack to my exchange 2007 mailbox server.  I don't have a CCR setup, so its a pretty standard configuration.  We do have it running on VMware and I plan on snapshotting it before the service pack is applied.
My question is, can certain aspects of exchange be disabled so that outlook can't connect to the mailbox server before I snapshot/update the server?  I'd like to avoid any data loss if it can be done.  For example, one idea I had was disabling the mailbox databases and then patching the server.  However, I don't know if that can be done.
Another idea I had was patching the exchange server while the network is disconnected, but once again, I don't know if that would work either.
Answer: You've got a couple of options.

Do a full backup of all Mailbox Databases and start the upgrade ASAP after the backup (store this off the server you're upgrading!).
Stop (but don't disable) the Microsoft Exchage Information Store service, snapshot your machine and start the upgrade.

Of those options, the second will give you a consistent snapshot of your .edb files if you're doing a VM level snapshot. If you leave the Information Store service stopped and kick off the upgrade, that should effectively give you what you want.
I'd also leave the network connected when installing the Service Pack because IIRC some CRL checks are made, and these can take a long time to timeout if the network isn't connected, causing you an unnecessary delay during the upgrade.
The only thing I'd recommend is do it during "off" time, so an evening or preferably a weekend, just so you have some breathing space if anything goes wonky.
Comment: Ok, so to be clear, there's no other way you can think of to mitigate any data loss?  So piggy backing off what you said, for me an ideal situation would be pre-disabling the services and preventing them from starting automatically, this way the data is in a consistent state when I snap shot the server **and** when i start the patching so no new mail has been submitted outlook side after the snapshot until i confirm everything is ok.  My concern is if something does bomb in the patching and I have to roll the snapshot back.  I just want to make sure there's no way for outlook to connect.
Comment: I will be disabling the CAS / HT severs, so nothing to worry about on that end, just for the staff that happen to be directly connected (via VPN)
Comment: @EricC.Singer I actually slightly misinterpreted your original question, so I just made a quick update. Basically, yes if you pre-stop (I wouldn't disable) the services you should achieve what you want.
Comment: So just to clarify, can I not only stop the information store service, but also disable it (to prevent an auto start)?  If so, that sounds perfect.  This way once i kown the patches applied, I can fire up the stores.  if the stores don't fire up, then it's not the end of the world as i can roll back to the snapshot.
Comment: I don't know this for sure, but I imagine the Service Pack will not be happy if you disabled a critical service like the Information Store. It will automatically try to start services as soon as it's done, and if one is disabled I'm not sure how it will react to that. If you snapshot the machine while the services are stopped you should be OK, since if you need to revert to that snapshot they will still be stopped.
Comment: sorry, I just saw your comment about not disabling?  Tell you what, I'll find out for sure in two weeks if it can be disabled.  Eaither way, I'll mark this as the answer, but I'll repost if it can be disabled without issue.  IMO, while a small risk off hours, we should still be able to do this without any chance of data loss.  I'd rather have users not be able to do something for a minute, then do work and lose it.
Comment: Oh, and I guess with exchange 2010, this could be done (regardless of DAG's) since everything goes through the CAG anyway.
Comment: Yes, in Exchange 2010 I guess you could stop the Client Access services for the same effect. The chances of an upgrade totally trashing your mailbox databases are incredibly slim, but by no means impossible. I'd always have a full backup available as well, for extra peace of mind.
Answer: Steps to safely Patch your Exchange server without potential data loss:
Step 1: Download CUs
Step 2: Put Exchange Server in Maintenance Mode
Step 3: Prepare for CU
Step 4: Install RSAT-ADDs Feature
Step 5: Prepare Schema, AD, and Domains
Step 6: Install CU via Unattended Setup or GUI
Step 7: Remove Server from Maintenance Mode
Step 8: Install Pending SUs
Refer this link for more information.


Sublime Text ler arquivo less com a sintaxe do CSS

Question: Alguém sabe como fazer o Sublime Text abrir arquivo less e reconhecer a sintaxe dele.
Quando eu abro o arquivo .less, aperto crt+shift+P e escolho Set Sintax: CSS, mas tenho que fazer isso toda a vez.
Alguém sabe como implantar permanente no Sublime Text 3?
Answer: A sintaxe do css é diferente da do less, o que você pode e na verdade, o certo a se  fazer é instalar o PackageControl (já deveria vir incorporado ao sublime xD) e instalar o less package.


How to store second dropdown value in database

Question: function YOUR_FUNCTION_THAT_DISPLAYS_FORM(&$form, &$form_state) {
  $query_state=db_select('state', 's');
  $query_state->fields('s',array('State_code','State_name'));
  $query_state->orderBy('State_name','ASC');
  $state_results = $query_state->execute();

  $options_state = array();

  // Using fetchAll() you can iterate through a result set.
  while ($state_record = $state_results->fetchAll()) {
    // You want state code as key, not state name as key.
    $options_state[$state_record->State_code]=t($state_record->State_name);
  }

  // State form element.
  $form['state1']= array(
    '#type' => 'select',
    '#title' => t('State'),
    '#options' =>$options_state,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => '_ajaxfunction',
      'wrapper' => 'divaroundseconddropdown'
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  // City wrapper form element.
  $form['city_element_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

// AJAX callback function.
function _ajaxfunction(&$form, &$form_state) {
  $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

  $query_city=db_select('city', 'c');
  $query_city->fields('c',array('District_Code','District_Name','State_Code'));
  $query_city->condition('State_Code', $key, '=');

  $query_city->orderBy('District_Name','ASC');
  $city_results = $query_city->execute();
  $options_city = array();

  while ($city_record = $city_results->fetchAll()) {
    // This is correct.
    $options_city[$city_record->District_Code]=t($city_record->District_Name);
  }

  // Render city setting.
  $form['city_element_wrapper']['city']= array(
    '#type' => 'select',
    '#title' => t('District'),
    '#options' => $options_city,
    '#required' => TRUE,
  );

  return $form['city_element_wrapper'];
}

I have tried to get city value like this 'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'], but error is coming like

Notice: Undefined index: city_element_wrapper in
  form_test_custom_form_submit()

How to solve it?
function form_test_custom_form_submit($form, $form_state) {
  $prog_id =1;

  db_insert('tot_prog')->fields(array('state1' => $form_state['values']['state1'],
'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],) // i have metioned like this,  is correct???? but its shows error, how to get the select city value???
        ->execute();
 drupal_set_message("successfully saved Settings");
}

Answer: Your error:

Notice: Undefined index: city_element_wrapper in
  form_test_custom_form_submit()

means that index city_element_wrapper is missing in $form_state variable. Do this:
function form_test_custom_form_submit($form, &$form_state) {
  $prog_id =1;

  db_insert('tot_prog')
    ->fields(array(
              'state1' => $form_state['values']['state1'],
              'city_element_wrapper' => $form_state['values']['city_element_wrapper']['city'],
            ) )
    ->execute();

  drupal_set_message("successfully saved Settings");
}

Always take the reference of $form variables if you want to fetch values from the variables or update the values of the variable. For more details about PHP reference read this.