C# How to Rename file after File.Copy without using File.Move

Question: I'm Working on a module where I need to copy a file to FTP path using C#. From there FTP will start processing that file based on name and extension. My Problem is while copying a huge file to the path FTP Picked up that file for processing before copying process get completed. To overcome this issue I changed the file name and extension and done with the file copy.
Now I need to rename the file with Original name. Is there any way in C# to rename the file without using File.Move ?
Thanks.
Comment: Out of curiosity, why don't you want to use `File.Move`?
Comment: If you are working with a remote FTP site then look at this question http://stackoverflow.com/questions/35638532/renaming-file-with-ftpwebrequest
Comment: `File.Move` calls the WinAPI `MoveFile` function, which is about as low-level as you need to go. What's the issue with using it? *I'm a carpenter. Can I pound these nails into a board without using a hammer or nailgun?* Sure you can, but it's not going to be as easy or efficient.
Comment: @Steve, I *think* he's saying that he has a local directory that some FTP process checks for files to upload, and he doesn't want that process to start sending a file that's in the middle of being copied to the local FTP directory, so he wants to copy the file to that directory by a different name and switch the filename at the last minute so it's fully "there" before the FTP uploading process notices it.
Comment: @adv12 possible, hope for some clarifications
Comment: @adv12: Yes, that's exactly what's being asked, and File.Move will do it instantly if they're on the same volume (it just changes the file system info and doesn't actually move any data). You can't get any quicker than that, even with very large files.
Comment: Sounds like the process picking up the file, is picking up the file to early. Do you have any control over the pickup process? Here we often use "end of transmission files". In the sense that, a customer would upload their large file(s) to our servers, once done they upload the "end of transmission file", and our pickup process triggers on the arrival of the "end of transmission" file.
Comment: @Steve, Thanks for your reply, I'm not using FTPWebRequest instead moving the file to windows shared folder.
Comment: @adv12, Thanks for our reply. Yeah process picking up the huge file before the copying process get completed. Due to that it's breaking the system.
Answer: Usually you´ll have to use File.Move to accomplish this task. It is the easier approach.
If, for whatever reason you don´t want to use it, you can do it this way (you will have to reference Microsoft.VisualBasic):
<code>Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);
</code>
Comment: It is quite unclear. If OP confirm your theory i ll delete


Handling/Filtering bad/broken routes/links - Redirect to existing known route

Question: I have the following route:
http://somehost/Project/Page/5/Contactgfmsdiojfdui9m

I want that to be permanently redirected to:
http://somehost/Project/Page/5/Contact

How i can accomplish filtering bad routes that i don't want to support?
Comment: possible duplicate of [Asp.Net MVC 301 Redirects](http://stackoverflow.com/questions/4967542/asp-net-mvc-301-redirects)
Comment: I think you didn't understand my question .
Answer: Two options:
Url Rewrite (Documentation)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="ProjectPageContent_Redirect" stopProcessing="true">
                    <match url="^/Project/Page/(\d+)/Content.*" />
                    <action type="Redirect" url="/Project/Page/{R:1}/Content" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

RedirectPermanent from Controller
RedirectController.cs
public class RedirectController : Controller
{
    public ActionResult ProjectPageContent(Int32 id)
    {
        return RedirectPermanent(String.Format("/Project/Page/{0}/Content", id));
    }
}

RouteConfig.cs
routes.MapRoute(
    name: "ProjectPageContent_Redirect",
    url: "/Project/Page/{id}/Contact{*extra}",
    defaults: new { controller = "Redirect", action = "ProjectPageContent" }
);


DFS count isolated nodes for articulation points

Question: I have a graph and a starting node. I want to find how many nodes become isolated when I remove each node in the graph, for all nodes, using DFS.
For example, if I start on a fixed node 1, and remove node 2, how many isolated nodes I will have? and if I remove node 3?
I know I can just do DFS for all nodes(removing a different node each time), but doing so I will have to navigate the graph one time for each node, I want to solve it with just one run.
I have been told it has O(|V|*||A|), being |V|=number of edges, and |A|= number of nodes.
I've been playing with prenum and postnums, but with no success.
Comment: Please provide a concrete example.
Answer: Let N be the number of vertices and M be the number of edges. If you just want a O(NM) solution as you stated, you don't need to go any further than running a DFS for each vertex.
The complexity for each DFS is O(N+M) so the total complexity will be of O(N(N+M)) = O(N²+NM). Usually we have more edges than vertices, so NM grows much faster than N² and we can say that the complexity is of O(NM). Keep in mind, though, that if you physically delete the current vertex at each step your implementation will have a much worse complexity, because physically deleting a vertex means removing entries from a lot of adjacency lists, which is costly no matter how you represent the graph. There is an implementation trick to speed up the process: instead of physically deleting the current vertex before each DFS, just mark the vertex as deleted, and when you are going through the adjacency lists during the DFS just ignore the marked vertex.
However, i feel that you can solve this problem in O(N+M) using Tarjan's algorithm for finding articulation points. This algorithm will find every vertex that, when removed from the graph, splits the graph in more than one connected component (these vertices are called articulation points). It's easy to see that there won't be isolated vertices if you remove a vertex that is not an articulation point. However, if you remove an articulation point, you will split the graph in two parts G and G', where G is the connected component of the starting vertex, and G' is the rest of the graph. All vertices from G' are isolated because you can't reach them if you run a DFS from the starting vertex. I think that you can find the size of G' for each vertex deletion efficiently, maybe you can even do this while running Tarjan's. If i find a solution i can edit this answer later.
EDIT: i managed to solve the problem in O(N+M). I will give some hints so you can find the answer by yourself:

Every undirected graph can be decomposed in (not disjoint) sets of biconnected components: each biconnected component is a subset of the vertices of the graph where every vertex in this subset will remain connected even if you remove any vertex of the graph
Tarjan's O(N+M) algorithm to find bridges and articulation points can be altered in order to find the biconnected components, finding which vertices belong to each biconnected component, or which biconnected components contain each vertex
If you remove any vertex that is not an articulation point, answer for this vertex is obviously N-1
If you remove an articulation point, every vertex in the same biconnected component of the starting vertex will still be acessible, but you don't know about the other biconnected components. Don't worry, there is a way to find this efficiently
You can compress every graph G in a graph B of its biconnected components. The compression algorithm is simple: every biconnected component becomes a vertex in B, and you link biconnected components that share some articulation point. We can prove that the resulting graph B is a tree. You must use this tree somehow in order to solve the problem presented in step 4

Good luck!


Distribute objects vertically when viewport changes

Question: I've been sitting at this problem now for about 4h. Way to long I suppose. So here I am:
I would like to distribute div containers vertically as soon as the viewport exceeds a specific height. Here's a sketch of an example.

HTML:

CSS:
* {
    margin:0;
    padding:0
}
body {
    margin:0;
    text-align:center;
    background: no-repeat fixed center center #030303;
    allowtransparency:true
}
.bubu {
    background-color:#eee;
    position: absolute;
    height: 100%;
    width:500px;
    left: 50%;
    margin-left: -275px;
    /* width / 2 */
}
.center1 {
    background-color:red;
    position: relative;
    height: 10%;
    width:100%
}
.center2 {
    background-color:yellow;
    position: relative;
    height: 35%;
    width:100%
}
.center3 {
    background-color:red;
    position: relative;
    height: 10%;
    width:100%
}
.center4 {
    background-color:yellow;
    position: relative;
    height: 35%;
    width:100%
}
.center5 {
    background-color:red;
    position: relative;
    height: 10%;
    width:100%
}
.element {
    background-color:#123456;
    position: absolute;
    height: 250px;
    width:500px;
    top:50%;
    margin-top: -125px;
    /* width / 2 */
}

Since margin:auto 0; will not do the job (will convert to 0 in height) I tried all different kinds of solutions. This (jsfiddle) is the one that only came close to it.
What I did was basically to add five classes, three of them height:10%; and two of them containing my containers height:35%;
Everything surrounded by one container height:100%;
As you can see, every time the container expands (my example size) off 500px the center expands twice.
How on earth can I solve this??
Comment: This should be quite easy with Flexbox, if the [browser support](http://caniuse.com/flexbox) is acceptable. Otherwise, I would probably use JavaScript.
Comment: What kind of browser support are you looking for?  There are many ways to do this.  How about using some JavaScript or jQuery if needed?
Comment: Sorry folks I can't use a framework like jQuery since I'm working on low level devices and performance critical environment. We have implemented our own framework for every specific case :-/
Comment: flexbox did the job! Thanks @thirtydot for that!
Answer: I assume you want to do some responsive design.
So what about using bootstrap?
It has a very flexible Grid system and it works out of the box on the most devices.
Comment: Bootstrap's grid system doesn't really help with this specific problem.


Não consigo capturar o post pela webapi c#

Question: bom dia. Já estou tentando a alguns dias tentando capturar um POST feito no JavaScript pela webapi c# e o máximo que conseguir é a webapi me dizendo que o parâmetro esperado está NULL.
var objFornecedor = {
                ID_FORNECEDOR: 38,
                NOME: "cleverton teste",
                CNPJ: "546546546546",
                ENDERECO: "rua c",
                BAIRRO: "novo teste",
                CIDADE: "serrinha",
                SITUACAO: "1",
                DATA_CADASTRO: new Date(2015,02,02)
    }

    $.ajax({
                  contentType: 'application/json; charset=utf-8',
    data: objFornecedor,
          url: 'http://localhost:3190/servicowebapi/fornecedor/incluir',
      success: function(retorno)
        {
              alert('funcionou');..........

e aqui eis o códigos que recebe
  [HttpPost]
  [ActionName("incluir")]
  public void Post(FORNECEDOR objFornecedor)
  {
      ctx.FORNECEDOR.Add(objFornecedor);
      ctx.SaveChanges();
  }

me retorna esse erro.
An exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Valor não pode ser nulo.
ctx.FORNECEDOR.Add(objFornecedor);
objFornecedor está NULL
e aqui segue minha classe FORNECEDOR
public partial class FORNECEDOR
{
    public int ID_FORNECEDOR { get; set; }
    public string NOME { get; set; }
    public string CNPJ { get; set; }
    public string ENDERECO { get; set; }
    public string BAIRRO { get; set; }
    public string CIDADE { get; set; }
    public string SITUACAO { get; set; }
    public Nullable<System.DateTime> DATA_CADASTRO { get; set; }
}

Answer: Use o JSON.stringify:
$.ajax({
    type:'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(objFornecedor),
...

Comment: @Cleverton, seria legal por na pergunta que está utilizando Cordova. Fiz utilizando uma página ASP.Net e deu no mesmo que você. Se eu encontrar tempo, tento fazer com cordova.
Comment: já fiz de toda forma que vc imaginar, acabei de testar por uma página ASP.nET com o mesmo código para consumir e adivinha ?  o asp.net consome (jQuery), mas lá por dentro do plugin do cordova só consigo ler.
Comment: já adicionei todos os verbos no WebConfig POST, GET, PUT, DELETE, OPTIONS
Comment:
Answer: Tenta assim:
var objFornecedor = {
        ID_FORNECEDOR: 38,
        NOME: "cleverton teste",
        CNPJ: "546546546546",
        ENDERECO: "rua c",
        BAIRRO: "novo teste",
        CIDADE: "serrinha",
        SITUACAO: "1",
        DATA_CADASTRO: new Date(2015, 02, 02)
    };

    $.ajax({
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(objFornecedor),
        type: 'POST',
        url: 'http://localhost:3190/servicowebapi/fornecedor/incluir',
        success: function (retorno) {
            alert('funcionou');
        }
    });

Comment: XMLHttpRequest cannot load http://localhost:3190/servicowebapi/fornecedor/incluir?ID_FORNECEDOR=38&NOM…ATA_CADASTRO=Mon+Mar+02+2015+00%3A00%3A00+GMT-0300+(Hora+oficial+do+Brasil). Response for preflight has invalid HTTP status code 405
Comment: @Cleverton editei a resposta, tenta com esse código.
Comment: então, a solução temporária foi feita por meio de uma POG, fiz uma solicitação GET, passei pelos URL. não entendo pq usando o HttpPost não funciona.
Comment: Fiz um exemplo com o mesmo código acima e funcionou.
Comment: NÃO SEI o que acontece, se eu colocar o verbo HttpPost na webapi não funciona


How do jQuery Mobile widgets work?

Question: I am using jQuery Mobile to develop a mobile web app for the first time. It is easy to get jQuery Mobile started with just adding some data-* attributes. So far, it is good. However, I was always troubled with one question: How do jQuery Mobile widgets work with just add some data-* attributes instead of invoking the widget explicitly just like jQuery UI widget? When and where do they get invoked and then rendered as they look like? I've searched google all over but found nothing valuable. Anyone could help? Thanks in advance!
Answer: Well, it's a feature of jquery-mobile called auto-initialization. It scans the dom when the page is loaded and based on the attributes of the html elements, it automatically calls the invocation functions on each of the elements. It's pretty simple actually. You can read more about this behavior here: http://demos.jquerymobile.com/1.0/docs/api/globalconfig.html

How do jQuery Mobile widgets work?


Ionic: ScreenOrientation to Portrait

Question: I am developing an Ionic-App and I want to set the Screen Orientation to Portrait.
and I know I could set it with this:
<preference name="orientation" value="portrait" />

but this isn't working,
I found a cordova plugin called screen-orientation-plugin but this is not working too. Do you have any another solution for this? Or Can anyone explain me how these 2 methods are working correctly?
.config(function($ionicConfigProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {

      $scope.changeOriantationPortrait = function() {
          screen.lockOrientation('portrait');
      }
      changeOriantationPortrait();
    }

Comment: Are you saying the the orientation is set to landscape by default?
Comment: @MegaAppBear No, i mean i cant freeze the orientation to portrait
Comment: cordova version? OS where you tested?
Comment: cordova 5.3.3 and iOS 9
Answer: I have used this plugin for my project and it is worked perfectly
cordova plugin add net.yoik.cordova.plugins.screenorientation

Controller
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    $scope.changeOriantationLandspace = function() {
        screen.lockOrientation('landscape');
    }

    $scope.changeOriantationPortrait = function() {
        screen.lockOrientation('portrait');
    }
}

HTML
<button class="button button-full button-positive " ng-click="changeOriantationLandspace()">Change To Landspace Mode</button>

<button class="button button-full button-positive " ng-click="changeOriantationPortrait ()">Change To Portrait Mode</button>

Reference
Comment: Thank you Mushin, yeah i tried this too, but when i implement it into my code, the whole app doesnt work and in the console he says screen is not a function :/
Comment: the Problem is, that i am getting no error. The device Ready listener dont get fired, but when i commenting the methods out, the deviceready event gets fired.
Comment: added it in the question
Comment: Can You create a small demo for me?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96579/discussion-between-muhsin-and-bernhard-miehl).
Comment: Please open this link http://chat.stackoverflow.com/rooms/96579/discussion-between-muhsin-and-bernhard-miehl
Comment: Or come to skype (Skype Id:muhsin.k9)

Ionic: ScreenOrientation to Portrait


como mostrar o resultado de uma sql em  diferentes?

Question: Como faço para que os projetos pertencentes ao mesmo departamento fiquem na mesma section?

    $sql = "SELECT d.nome, p.titulo FROM projeto p, departamento d WHERE p.dpto_id=d.id ORDER BY d.nome, p.titulo";

    $dpto=null;
    foreach ($rows as $reg){

    $departamento=$reg["nome"];
        $titulo=$reg["titulo"];

        if($departamento!==$dpto){
    echo  "
";
        echo "
". $departamento . "
";
        echo "
". $titulo ."
";
      } elseif ($departamento===$dpto) {
        echo "
". $titulo ."
";
      }

        $dpto=$departamento;
     }

    //Resultdo final deveria ser assim

nome do departamento

lista de projetos

outro departamento

sua de projetos

Tentei assim, mas não consigo fechar a tag section.
Answer: Faz dessa forma:
$dpto=null;
foreach ($rows as $reg){

    $departamento=$reg["nome"];
    $titulo=$reg["titulo"];

    if($departamento!==$dpto){
echo  "
";
    echo "
". $departamento . "
";
    echo "
". $titulo ."
";
echo  "
";
  } elseif ($departamento===$dpto) {
echo  "
";
    echo "
". $titulo ."
";
echo  "
";
  }
    $dpto=$departamento;
 }

Comment: Não funcionou. Os projetos FV e DS pertencem ao Dpto1, mas ficaram fora da seção. O mesmo ocorreu com os projetos ABGO e GT do Dpto2.

section
h1 dto1 h1
XTZ
section

FV
DS

section
h1 dto2 h1
RT
section

ABGO
GT

section
h1 dto3 h1
YWZ
section

section
h1 dto4 h1
QWE
section
Comment: Eu atualizei o programa, tenta desse novo jeito
Answer: Você terá que ter um loop aninhado dentro de outro, algo do tipo:
foreach($departamentos as $departamento):
 $produtos = SQL ///SELECT * FROM PRODUTOS WHERE idDepartamento = $departamento->id // sua consulta aqui.
 foreach($produtos as $produto):
  echo $produto->nome."
";
 endforeach;
endforeach;

Desta forma você poderá selecionar todos os produtos em cada interação de departamento.


JAVASCRIPT Error exporting div to PDF

Question: I'm trying to export a div to pdf when I click the button, however I get a javascript function error that I can not solve, can anyone help me?
Image with error
JavaScript

HTML

         Cliente ID
        @Model.ID_Cliente

         Nome
        @Model.Nome

         Morada
        @Model.Morada

Comment: Possible duplicate of [jQuery 1.9 .live() is not a function](https://stackoverflow.com/questions/14354040/jquery-1-9-live-is-not-a-function)
Answer: live method is deprecated and probably removed in your jQuery version.
Try using on instead.
Comment: It worked when replacing live by on. However, I get an error saying Uncaught Invalid orientation: [object object]
Answer: Which version of jquery are you using? .live has been removed from version 1.9 on wards.
$(document).on("click", '#btnPrint', function () {
        // Setar o width da div no formato a4
        $("#renderPDF").width((a4[0] * 1.33333) - 80).css('max-width', 'none');

        // Aqui ele cria a imagem e cria o pdf
        html2canvas($('#renderPDF'), {
            onrendered: function (canvas) {
                var img = canvas.toDataURL("image/png", 1.0);
                var doc = new jsPDF({ unit: 'px', format: 'a4' });
                doc.addImage(img, 'JPEG', 20, 20);
                doc.save('NOME-DO-PDF.pdf');
                //Retorna ao CSS normal
                $('#renderPDF').width(cache_width);
            }
        });
    });

Comment: I'm using these scripts `
`
Comment: Since you are using a version newer than 1.9, live won't work. I have updated the code. You will have to use on.
Comment: It worked when replacing live by on. However, I get an error saying Uncaught Invalid orientation: [object object]
Comment: You are not using html2canvas correctly. Read the documentation and see if you can find the error

JAVASCRIPT Error exporting div to PDF


Problem on Poisson Process

Question: I am doing some problems related with the Poisson Process and i have a doubt on one of them. The problem is stated as follows:
A doctor works in an emergency room. The emergencies arrive according a Poisson Process with a rate of $\lambda =0.5$  emergencies per hour. The question is: When the first patient arrived, the doctor took care of him and spent 15 minutes. What is the probability that the doctor will find any patient waiting after finishing with the first one? And exactly with two patients waiting?
As the Poisson Process is memoryless, the time the doctor spent with the first patient does not affect the other ones. But im not sure on how to get the probabilities given the 15 minutes.
Would it be:
$P[N(0.25)>=2]$
$P[N(0.25)=3] = \frac{(0.5*0.25)^3  e^{-0.5 * 0.25}}{3!}$
Comment: Hint: Poisson processes are memoryless.
Comment: please add the `self-study` tag to your question and read the wiki for guidelines on posting questions related to homework
Comment: If the process is memoryless, then does it means that the solution would be to calculate the probability of having 2 or more arrivals?
Comment: Here it means that what will happen in the next 15 minutes has the same distribution as any other 15 minute increment, regardless of what has already happened.
Comment: Just updated the question, as 15min = .25 hours
Answer: The first question asks what the probability is that the doctor will find any patients waiting. One way to do this is to find the probability that he will find no patients waiting. In other words, what is the probability that the next interarrival time is greater than 15 minutes? Since you have a Poisson process, you know the distribution of interarrival times, and hence you can get $P[T_2 > 15]$, which is equivalent to $P[\mbox{no patients waiting}]$. Then, to get the probability of at least one patient waiting is trivial.
For the second part, you seem to be on the right track with the second formula. Remember that $N(t) - N(s) \sim Poisson(\lambda(t-s))$. Here, your $s$ is the time of the first arrival, and $t$ is fifteen minutes after this first arrival, and you're interested in if $N(t) - N(s) = 2$. The distribution of this relies on $\lambda$, which you know, and $t - s$ which you also know.

Problem on Poisson Process


Problema ao deixar container rolável usando Listview

Question: Olá, estou criando um feed e nesse feed estou usando Listview.builder, tenho alguns botões que servem como os filtros, porém quero que os botões de filtros rolem junto com as postagens. Já tentei envolver tudo dentro do ScrollView porém sem sucesso.
Aqui meu Feed
Segue o código do ListView.
 Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
final CollectionReference post =
    FirebaseFirestore.instance.collection('posts');
return Material(
  child: Column(
    children: [
      FilterButtons(size: size), //Os meus filtros
      Expanded(
          child: StreamBuilder(
        stream: post.snapshots(),
        builder: ((context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (streamSnapshot.hasData) {
            return ListView.builder(
                padding: EdgeInsets.zero,
                itemCount: streamSnapshot.data!.docs.length,
                itemBuilder: (context, index) {
                  final DocumentSnapshot documentSnapshot =
                      streamSnapshot.data!.docs[index];
                  return Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        child: Container(
                          color: Color.fromARGB(255, 176, 143, 229),
                          height: size.height * 0.25,
                        ),
                      ),
                    ],
                  );
                });
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        }),
      )),
    ],
  ),
);

}
Comment: Você pode tentar dois caminhos... **1)** Dentro do stream builder criar uma lista com os posts que deseja, e incluir no index 0, algum valor "vazio"para quando for construir a lista, você saber que no index 0 "vazio" você deverá retornar seu Widget de botões e nos demais casos a estrutura do post. **2)** É mais complexo, mas você pode adicionar um scrollController na sua lista e depois observar as mudanças no scroll para movimentar manualmente teu widget de botões.
Answer: Seguindo a primeira solução que foi apontada pelo Matheus nos comentários, você pode fazer um controle no seu ListView, e exibir o item dos botões de filtros como primeiro da lista.
Para isso, algumas modificações devem ser feitas:

Agora o número de elementos da sua ListView foi acrescido de um. Logo, adicione um item a mais à contagem para reservar um espaço para ele:

itemCount: streamSnapshot.data!.docs.length + 1, // Adicionado +1

No seu construtor de cada elemento, podemos verificar se o índice é 0, e se for, retornar a lista de filtros. Caso contrário, retorna-se o resto da lista. É preciso atentar-se que agora o índice 0 refere-se ao widget de botões, e o primeiro elemento da lista que vem do SnapShot agora é de índice 1. Ou seja, você deve utilizar index-1 nos lugares que usava index.

itemBuilder: (context, index) {
                  if (index == 0) { // O primeiro item da lista é o especificado por você.
                      return FilterButtons(size: size);
                  }
                  final DocumentSnapshot documentSnapshot =
                      streamSnapshot.data!.docs[index - 1]; // Lembre-se de utilizar index - 1 aonde for necessário.
                  return Column(
                    children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        child: Container(
                          color: Color.fromARGB(255, 176, 143, 229),
                          height: size.height * 0.25,
                        ),
                      ),
                    ],
                  );
                }


To show a certain endomorphism ring is an algebra

Question: Let $A$ be an algebra over a field $K$ of finite dimension. Let $M$ be a finitely generated $A$-module. My question is about the ring ${\rm End}_A(M)$ of $A$-endomorphisms of $M$. I want to show that it is a $K$-algebra.
To show that $K$ lies in the center of ${\rm End}_A(M)$, I look at the ring homomorphism $K\to {\rm End}_A(M): \alpha\mapsto \alpha 1_M$, where $1_M$ is the identity mapping on $M$. I can show that $\alpha1_M$ commutes with every $f\in {\rm End}_A(M)$. But is this map 1-1? How can I show that if $\alpha1_M=0$ then $\alpha=0$?
Answer: Hint: if $f\colon K\to R$ is a ring homomorphism (mapping $1$ to $1$) and $R$ is not a zero ring, then $f$ is one-to-one whenever $K$ is a field.


Desabilitar Textarea (com TinyMCE) ao carregar dado do mysql

Question: Para desabilitar um textarea com o tinyMCE eu usava o código
tinyMCE.get('id_textarea').getBody().setAttribute('contenteditable', false);

dentro de um script Javascript, com evento onclick de um button, e ocorria tudo bem.
O problema agora é o seguinte: tenho 5 páginas, cada página com 5 textareas, todos editáveis pelo tinyMCE, e com um botão "Salvar" para cada textarea. Na última página, inseri um botão submit "Enviar", o qual grava um "sim" no BD mysql, numa tabela com os textarea e com o campo "enviado" que recebe esse "sim". O que estou tentando fazer e não consigo, é, após clicar nesse botão submit "Enviar", que todos os textarea fiquem desabilitados para edição, através de uma consulta SQL ao campo "enviado", ou seja, após gravado o "sim", o usuário não consegue editar mais os textarea, nem naquele momento, nem depois ao reabrir as páginas com textarea.
Já inseri o script na tag , já tentei colocar o script num echo dentro do php, e nada adiantou para desabilitar, apenas grava o sim no BD. Segue o código do script e do php/html. Dentro da tag :
function enviartudo() {
  tinyMCE.get('id_textarea1').getBody().setAttribute('contenteditable', false);
  tinyMCE.get('id_textarea2').getBody().setAttribute('contenteditable', false);
}

PHP
Após um SELECT ao BD:
include_once('conexao.php');
$query = "SELECT..........";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
if ($row['enviado'] == 'sim') {
    echo '';
}

if (isset($_POST['enviar'])) {
    $query1 = "UPDATE tabela SET enviado = 'sim' ";
    $data1 = mysqli_query($dbc, $query1);
    mysqli_close($dbc);
 }

HTML

       TEXTAREA 1
       <textarea type="text" id="textarea1" name="textarea1" class="areatexto"
       maxlength="5000">
          <?php echo (isset($_POST['textarea1']) ? $_POST['textarea1'] :
          htmlspecialchars_decode(stripslashes($row['textarea1']))); ?>
       </textarea>
       <input type="submit" name="submit1-1" value="Salvar" class="btn_save_item"/>

       TEXTAREA 2
       <textarea type="text" id="textarea2" name="textarea2" class="areatexto" maxlength="8000">
          <?php echo (isset($_POST['textarea2']) ? $_POST['textarea2'] :
          htmlspecialchars_decode(stripslashes($row['textarea2']))); ?>
       </textarea>
       <input type="submit" name="submit1-2" value="Salvar" class="btn_save_item" />

      <input type="submit" name="enviar" value="Enviar" class="btn_save_item" />

Não coloquei todo o código das 5 páginas com os 5 textarea de cada uma, pois ficaria muito grande, porém o código é repetitivo, alterando apenas id/name das div, form, textarea, botões submit, entre outros.
Comment: `if ($row['enviado'] == 'sim') { $desabilitado = "disabled";` e nos textareas `>`
Comment: @LeoCaracciolo, já havia tentado isso, mas o tinymce não aceita o "disabled", nem o "readonly" no textarea. Se coloco readonly:1 no Setup do tinymce, todos os textarea já iniciam em readonly ao carregar, e não é isso o que desejo. De qq forma, valeu, mas o problema continua..
Comment: Pessoal, encontrei uma solução. Criei outro script do tinymce, porém alterando o nome do Selector e com outro skin (para alterar o background do textarea), além de inserir o readonly=1. Aí, no PHP, fiz um if/else, criando uma variável que define a classe do textarea. E no código HTML, no textarea, inseri uma classe com PHP: `class=""` . Vou por a solução abaixo..
Answer: Conforme comentei acima, após uma boa noite de sono encontrei uma solução.
Criei outro script do tinymce, porém alterei o nome do Selector e inseri o readonly=1, menubar=false e deixei só o preview na toolbar, tudo para não permitir mais qq edição. Criei tb outro skin (para alterar o background do textarea). No PHP, fiz um if/else, criando uma variável que define a classe dos textarea. E no código HTML, nos textarea, inseri uma classe com PHP. Seguem os códigos:
Script 1 do tinymce:
tinymce.init ({
        selector: '.areatexto',
        height: 200,
        skin: 'custom',
        theme: 'modern',
        resize: false,
        plugins: 'print charwordcount preview searchreplace autolink visualblocks visualchars image link media table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists textcolor imagetools contextmenu colorpicker textpattern',
        toolbar1: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat | table image | preview',});

Criei outro script do tinymce:
tinymce.init ({
        selector: '.areatexto2', //aplica o plugin em todos textarea com class="areatexto2"
        height: 200, //altura de cada textarea
        skin: 'custom2',
        theme: 'modern',
        readonly: 1,
        resize: false,
        plugins: 'preview',
        toolbar1: 'preview',
        menubar: false, });

Criei um if/else no PHP:
if ($row['enviado'] == 'sim') {
    $classTextarea = "areatexto2";
}
else {
     $classTextarea = "areatexto";
}
E no HTML:
<textarea type="text" id="xxxxxx" name="xxxxx" class="<?php echo $classTextarea; ?>" maxlength="5000">
Funciona perfeitamente, não permitindo mais a edição dos textarea (com class="areatexto2"), pois o readonly=1, além de retirar o menubar e todos plugins de edição.


Google Spreadsheet Pivot Table Range Update Using Scripts

Question: How do I edit the Data Range of a Pivot Table in A Google Docs Spreadsheet with a script?
Or...
Is it possible to use a named range for a Pivot Table range?
Comment: Possible duplicate of [Pivot table with Google Script](https://stackoverflow.com/questions/11326172/pivot-table-with-google-script)
Answer: Unfortunately, at this time (31 July 2012), I believe the answers are "you can't" and "no". :-(
The only workarounds I can suggest are: 1. use the QUERY spreadsheet function, which supports open-ended ranges that will accommodate growing data, to generate the table, or 2. use Google Apps Script itself to generate the table. Both of which require more effort than if you could just modify the source data ranges with script (like you can with Excel/VBA).  On the other hand, the general implementation of Pivot Tables in GSheets is still a bit buggy, so it's arguable that you might want to explore one of the other options for this reason.
Answer: I found a workaround that could help you, like I answered in the other Post:JavaScript Method to change PivotTable Data Range Google Docs Spreadsheet
Create a sheet dedicated to your data, row 1 = headers, all other rows = data.
Delete rows with no data.
If for example you use columns A through F, create a Pivot and use this range: SHEET_NAME!A:F
The pivot will "grow" to the new rows because the range is "all the data in the columns A to F".


Is it reasonable/possible to use pre-scores as predictors of change?

Question: In change analyses (of any variable, from pre to post) we usually controll for the pre-score, as it may affect the rate of change. However, what if I am especially interested in the effect of the pre score on the rate of change, like
Diff(post - pre) = a + b*pre.
What if I am especially interested in b? Is the model above reasonable or are there any problems with that?
In multilevel-analysis of longitudinal data there is a correlation coefficient for the relation between the initial level (intercept) and the rate of change (slope). Thats the information I need, but in an ordinary regression model.
Comment: Take a look at latent difference scores, which is a SEM technique. In that framework, you can predict the latent difference/change from T0 to T1 by levels of T0. See https://doi.org./10.1177/0265407517718387 and https://stats.stackexchange.com/questions/595777/multilevel-model-with-two-timepoints
Comment: As mentioned by @ErikRuzek, a latent difference score approach would be preferred because the observed difference (change) score variable typically contains a lot of measurement error variance (unreliability). This can lead to substantial bias in the estimated b coefficient. The latent change score approach corrects for error. See also: https://youtu.be/0QUuP2BoMlk
Comment: Why not do a multilevel analysis?
Comment: A problem is that the change score is necessarily correlated with the `pre` value. See [this page](https://stats.stackexchange.com/q/478310/28500) and [this page](https://stats.stackexchange.com/q/509452/28500), for example.
Answer: Here are some additional references for the latent change/latent difference score approach:
McArdle, J. J. (2009). Latent variable modeling of differences and changes with longitudinal data. Annual Review of Psychology, 60, 577-605.
Raykov, T. (1993). A structural equation model for measuring residualized change and discerning patterns of growth or decline. Applied Psychological Measurement, 17, 53-71.
Steyer, R., Eid, M., & Schwenkmezger, P. (1997). Modeling true intraindividual change: True change as a latent variable. Methods of Psychological Research - Online, 2, 21–33.
Steyer, R., Partchev, I., & Shanahan, M. (2000). Modeling true intra-individual change in structural equation models: The case of poverty and children's psychosocial adjustment. In T. D. Little, K. U. Schnabel & J. Baumert (Eds.), Modeling longitudinal and multiple-group data: Practical issues, applied approaches, and specific examples (pp. 109–126). Hillsdale, NJ: Erlbaum.


How light weighted Dexterity-base contenttype can be

Question: I'm trying to write a light weight content type that work similar to Facebook's post.

The whole content schema is just a text field. There's no title, description.
It must be Contentish and is managed by CMFCore: It must have an FTI, a portaltype so that we can create/browse content through standard method; it is catalog-aware.
They will have relation/reference within each others.
The number of objects is gonna be huge, say 10-100M.

The most similar things to this is the comment object (plone.app.discussion). While I've looked through the plone.app.discussion, I found the content implementation is really complicated, with too much low level base classes. In most of the parts, I either don't understand it at all or it can't be reused outside the comment use case, and have little referenced/sample value to me.
So I want to ask is how much overhead it will be if I go the high level framework path compare to the low level one that plone.app.discussion went through ?
Answer: I don't think p.a.discussion is right for you.
A Dexterity type may be fine, but you'll need to tune the performance. If performance is going to be an issue, it'll be because of the things that make types contentish (e.g. an FTI, the CMF base classes), so nothing will be lighter than Dexterity and meet your requirements, but you may want to think about whether you actually want to store everything in a relational database or something else instead. It shouldn't be strictly necessary, though.
Martin
Answer: Plone will not scale to 10 M items in its catalogue (the largest I've heard of is something like 400 k). I would suggest building your application with a light weight framework like Pyramid.
Comment: The ZODB is not the problem here. The problem is that Plone's portal_catalog becomes a single point of contention for every write to the database. Unfortunately all of Plone's navigation is built from the catalogue, which makes asynchronous catalogue updates difficult to achieve. This needs to be fixed, but is a long term project.
Comment: Where do you think the problem lie ?

ZODB can't scale big ?

the catalog is too large to fit on the client's memory ?

the catalog is poor implemented so that query over million objects take too much cpu ?


Knapsack problem - Find which items are taken

Question: I need to find every optimal solution for knapsack problem.
Here is my code
void knapSack(int W, int wt[], int val[], int n)
{
   int i, w;
   int K[W+1][n+1];
   for (w = 0; w <= W; w++)
   {
    for(i=0;i<=n;i++){
        if(i==0)
            K[w][i]=0;

        if(w<wt[i-1] && i!=0)
            K[w][i]=K[w][i-1];

        if(w>=wt[i-1] && i!=0)
            K[w][i]=max(K[w][i-1],K[w-wt[i-1]][i-1]+val[i-1]);

       }
   }

   i=n;
  int j=W;
   while(i,j>0){
    if(K[j][i]!=K[j][i-1]){
        cout<<"Item "<<i<<" is in the bag"<<endl;
        i=i-1;
        j=j-wt[i-1];
    }
    else
        i=i-1;
   }
}

Input data is:
4 6 //n W
2 1 //p1 w1
3 2 //p2 w2
3 4 //p3 w3
4 5 //p4 w4

And output should be like this:
1 4
2 3

The first part of my code which is packing the bag is working great, but the secound part where I try to find which items were taken is giving me answer: item 3, item 2, item 1 which is wrong because there is 2 solutions: you take item 1 and 4 or item 2 or 3. How can I fix this?
In the picture below there is table with table solution of packing
Comment: Not your problem, but `i,j>0` isn't doing what you think it's doing - in this case it's essentially the same as `j>0`. You probably wanted `i>0 && j>0`.
Comment: Move `i=i-1` one line down. With some [debugging](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/), you probably could've figured out that section of the code thinks the third item weighs 2, the second item 1 and the first item 0 (instead of 4,2,1), which would've indicated that you're looking at the wrong weight values.
Answer: I would use the same formula that you use to maximize the value to see which items picked i.e.
if (K[w][i] == K[w-wt[i-1]][i-1] + val[i-1])
then item i is picked else this is not picked and go to previous item i-1.
Also there could be more than 1 set of items which when picked can yield the maximum value.
In that case look for each such value in the array K[W][..] for the maximum value K[W][n] and traverse the array from that point to get the picked items.
Code is :
void knapSack(int W, int wt[], int val[], int n)
{
   int i, w;
   int K[W+1][n+1];
   for (w = 0; w <= W; w++)
   {
    for(i=0;i<=n;i++){
        if(i==0)
            K[w][i]=0;

        if(w<wt[i-1] && i!=0)
            K[w][i]=K[w][i-1];

        if(w>=wt[i-1] && i!=0)
            K[w][i]=max(K[w][i-1],K[w-wt[i-1]][i-1]+val[i-1]);

       }
   }

   cout << "\n" << "Maximum value obtained is : " << K[W][n] << "\n";
   int j;
   for ( j=1; j<=n; j++ ) {
     if (K[W][j] == K[W][n]) {
       int w = W;
       int i = j;
       while(i>0 && w>0){
          if (K[w][i] == K[w-wt[i-1]][i-1] + val[i-1]) {
            cout << "Item " << i << " is in the bag" << "\n";
            w = w - wt[i-1];
            i--;
          } else {
            i--;
          }
        }
      cout<< "\n";
     }
   }

}


Programmatically create a new node from an existing NID

Question: Essentially I want to take a node and duplicate it. Take a node ID and programmatically create a copy of the node.
I want to be able to edit the newly created node, and maintain the data on the old node.
Comment: I am aware of creating new nodes on the fly, and populating the values. example: http://timonweb.com/posts/how-to-programmatically-create-nodes-comments-and-taxonomies-in-drupal-7/ Just seeing if there was slicker way of going about it.
Answer: On entities, you can use is_new to signify a new entity to save, but you still need to unset nid (iirc), vid, and tnid manually. This saves unsetting log.
$new = clone $node;
$new->is_new = true;
unset($new->nid);
unset($new->vid);
unset($new->tnid);
node_save($new);

Interestingly, the node_clone module incorrectly sets the properties to null, which is significant for databases that support NULL and DEFAULT separately (e.g. PostgreSQL).
Answer: You may be happy with the replicate module which provides an API to do just that for any entity.
As stated in its README file (You'll find more in it) :
Very basic usage example:
/**
 * Replicate Basic test function.
 *
 * In this example we will suppose that there is a node with nid = 1 we want
 * to replicate.
 */
function replicate_test_function() {
  // Load a newly created node as an entity.
  $entity = array_shift(entity_load('node', array(1)));

  // Duplicate the entity and save the replica.
  replicate_entity('node', $entity);

  // You can use replicate_clone_entity() instead, alter the replica afterward
  // and manually save the entity, but if you want to implement a generic
  // code like adding ' [Replicate]' to the end of every replicated node title,
  // use the API hook hook_replicate_entity_ENTITY_TYPE().
}

Answer: You can load your node with node_load() and unset the nid and vid and then save the new node with node_save()
  $nid = 4;
  $node = node_load($nid);
  $new_node = $node;
  unset($new_node->nid);
  unset($new_node->vid);
  node_save($new_node);

Comment: @ThroneDigital and again a pleasure ;-) good luck in your projects


Any idea to get mobile identification in php program

Question: There is a vote module in my program.
Users could voting up /down use PC or moblie phones in login state .and we alse allow users voting in logout state.
So that we have to check users vote only once in logout state. Is there any Idea to do this with php?
And I think we must storage PC's ip/MAC or mobile's identification like phone number etc.
Thanks for u help.
Answer: There is a lot of informations that you can find in <code>$_SERVER</code> about the current user , for ip addresse it works for both mobile and pc it's not depending on the platform and you can find it in :
<code>$_SERVER["REMOTE_ADDR"];
</code>


Should I apply my treatment as a continuous gradient, or in blocks?

Question: I am designing an experiment, and am looking for advice on how to apply my treatment most efficiently.
I'll give an example to explain. My response is car efficiency - how many miles per gallon of fuel the car uses. I have two groups of cars - one from Factory A with a regular factory manager, and one from Factory X, which has a fuel efficiency expert as its manager. There are 20 cars from each factory.
Each factory also has a mixture of ingredients to produce different fuel with, and have produced slightly different fuels for each car. None of the cars have the exact same fuel, but I know the exact ingredients and amounts that have been used.
Finally, I will be testing the cars efficiencies while driving at different speeds, and here is where my main question lies. Should I use a continuous gradient of speeds, or should I use two blocks of speeds?
I have a few hypotheses I want to test:

Cars from Factory X are more efficient than cars from Factory A.
The mix of Fuel influences the efficiency of the car.
Efficiency increases with speed, but more so for cars from Factory X than cars from Factory A.

To test the effect of speed on efficiency I could drive each pair of cars (one from A, one from X) at a different speed, spread evenly between 20mph and 80mph. Alternatively, I could drive half of the cars at 20mph, and half at 80mph.  Bear in mind that I have no pre-experiment knowledge on how efficiency varies with speed, but I suspect it is not a linear relationship, probably more of a threshold change.
Which approach would be more powerful for testing my hypotheses?
Another question - I was hoping that a simple regression model would be able to answer most of my questions - something like this:
efficiency ~ Speed + Fuel + Factory

"Fuel" would potentially be a PCA of the fuel ingredients. Would any of the predictors need to be random, or nested effects, or interactions?
Many thanks
Comment: Is there some other factors you want to control? Like drivers? What about a paired experiment, you select pairs of cars, one from each fabric, and drive them at the same time, same conditions, same speed, once, then repeat, switch drivers, the same again? Then you could avoid the need of some specific regression model ...
Comment: Thanks. I've mentioned all of the relevant factors - "driver" is not one of them. I can pair cars from the two factories to have the same speed, but I can't control the "fuel" so that will always differ between the two cars.
Answer: This depends whether your goal is only to test the hypothesis you tested, or if you are also interested in estimating and criticizing your regression model. First a simple example: If you are interested in a simple regression model $y=\beta_0 + \beta_1 x+\epsilon$ with possible values for $x$ being the interval $[a, b]$, then the optimal design (at least for minimizing prediction variance, but probably also for other criteria), is to take half of observations at $x=a$ the other half at $x=b$.  But, that assumes you trust your model blindly, if the straight line model is wrong, maybe there is some curvature or other nonlinearities, you will not detect that from such a design! So it might be good to allow for a few interior points to allow for model criticism.
This in part answers your question:

Should I use a continuous gradient of speeds, or should I use two blocks of speeds?

With many different values for speed, you allow for nonlinearities and model criticism. You could use Optimal Design theory (in R, package AlgDesign, for an example see Some questions about AlgDesign for Fractional Factorial Design in R) to find good speed values, assuming some flexible model.
But, combine this with a paired design, run the experiment with pairs of matched cars from the two factories. That will also allow for test not depending on the regression model.


How do I fix the "The each() function is deprecated" error?

Question: I am using Drupal 7.6.0 on a server with PHP version 7.2.11.
I get this error message.

Deprecated function: The each() function is deprecated. This message will be suppressed on further calls in menu_set_active_trail() (line 2405 of C:\xampp\htdocs\portailcommerce\includes\menu.inc).

How can I fix it?
Comment: You can fix it by providing a patch to Drupal core and take part in the discussion to get it merged. Before it gets merged you could use your patch to get rid of the warning until then.
Comment: There is no need to provide a patch. Drupal 7 removed every usage of `each()` from PHP code since Drupal 7.61.
Answer: Just update Drupal 7 to latest version which, as I am writing this answer, is version 7.64. Drupal 7 doesn't use each() in PHP since November 7, 2018, as the CHANGELOG.txt file says. (See the last line of the part I quoted.)

Drupal 7.61, 2018-11-07

File upload validation functions and hook_file_validate() implementations are
  now always passed the correct file URI.
The default form cache expiration of 6 hours is now configurable (API
  addition: https://www.drupal.org/node/2857751).
Allowed callers of drupal_http_request() to optionally specify an explicit
  Host header.
Allowed the + character to appear in usernames.
PHP 7.2: Fixed Archive_Tar incompatibility.
PHP 7.2: Removed deprecated function each().

As long as you use at least Drupal 7.61, you will fix the error you shown, which (in your case) is caused from menu_set_active_trail(). (The code shown in the documentation page doesn't show any line using each() because the code has been updated to the latest Drupal 7 version.)
If you are using third-party modules, you could still see that error, but caused by other functions/methods. In that case, you need to update all the modules you are using on that site.
If this doesn't fix other The each() function is deprecated errors, you need to check the issue queue for every third-party module you are using, and verify there are patches for fixing that error.


Adding two separate ajax Post rquest results together

Question: I have two separate Ajax Post requests that i need to add together, they are both linking to a currency exchange feed, its basically two values that get converted from different currencies and then need to be added together after both being converted to one currency, ive gotten them both on the same currency no i just need to add the two results together to get a final total.
Here are the two requests
<code>    var dataString = "amount=" + entireTotal + "&from=" + from + "&to=" + to;
        //Lets Get the exchange rates from our total
     $.ajax({
       type: "POST",
       url: "http://fileserver/website/modules/mod_calculation/js/currency.php",
       data: dataString,
       success: function(data){
        $('#inputresult').show();
        //Put received response into result div
         $('#inputresult').html(data);
       }
     });

var dataString = "amount=" + amountGel + "&from=" + fromGel + "&to=" + toGel;
            $.ajax({
       type: "POST",
       url: "http://fileserver/website/modules/mod_calculation/js/currencygel.php",
       data:  dataString,
       success: function(data){
           $('#resultsgel').html(data);
         //Show results div
         $('#resultsgel').show();
        //Put received response into result div
       }
     });
</code>
any help at all will be much apreciated.. Thanks :)
Answer: <code>var request1 = $.ajax({ ... }),
    request2 = $.ajax({ ... });

$.when(request1, request2).then(function(response1, response2) { ... })
</code>
Further reading:

A good article about how to use promises in jQuery: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
And the official documentation pages.

Small abstract example similar to what you need (sorry, don't have enough time to create ajax requests there, but they behave exactly the same): http://jsfiddle.net/Y26zd/
Comment: @Dawid van der Hoven: well, now you see the structure of the retrieved data. It's javascript the very basics :-)
Comment: interesting approach, repped +1
Comment: Hey Thanks, 90% of the way there, It works, i Just need to now add the two Response values together? any idea... "601,150.9,success,[object Object]" that what im currently getting. I just need the numbers, that the value
Comment: @Dawid van der Hoven: we don't know what you return and what your current code is (that returns what you've shown)
Comment: well its giving me a success,[object Object], When all i need is the responseText?, Im sorry im new to AJAX. Thanks any way, ill Try and see if i can find the solution, and thanks @zerkims Your Awesome. Helped me alot thanks :)
Comment: @Dawid van der Hoven: what "it"? Show some code that does that. Open chrome developer tools or firebug and look what the server returns back to you
Comment: Well, im inserting the result this way $('#finaltotal').fadeIn("slow").html(response1 + response2); and then im also doing this console.log(response1, response2);... and it gives me this on the html (601,173.2,success,[object Object]R273,405.00,success,[object Object]) and on the console its giving me " ["601,173.2", "success", Object { readyState=4,  responseText="601,173.2",  status=200,  more...}]["R273,405.00", "success", Object { readyState=4,  responseText="R273,405.00",  status=200,  more...}] "


how to manipulate the keyboard in iphone

Question: I want to manipulate the keyboard in iphone .
basically want to create the action on the keyboard.
thanks advance
Answer: You mean, create additional, non-standard button on the keyboard?
Try this


Probability of reaching a threshold after several trials

Question: I was wondering if there wasn't some better way to get to the bottom of this question I had regarding the chances of reaching a certain threshold of guessing numbers correctly over a series of trials.  This isn't my specialty, so would appreciate answers that are like you were talking to a 5 year old or at least google-able :)
So say I have a game where I have to pick 10 out of 80 numbers and then 20 are drawn.  For each one of my Picks that is chosen as one of the 20 I get a black marble.
I need to know the odds that if I can get AT LEAST 20 black marbles in 5 games, picking 10 numbers each game.  Each game is discrete in that the picked numbers are replaced and the 20 numbers that are drawn are totally random
I can tell what the average amount of black marbles I will win per game (2.5) and therefore the average amount of black marbles I'll win in 5 games (12.5). I can do this because for a single game, hyper geometric distribution tells me the odds of each outcome of catches: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.  I can then multiply each of these by their probabilities and sum them to get the average amount I will win in that game
e.g. $(HYPGEOMDIST(0, 10, 20, 80) * 0) + (HYPGEOMDIST(1, 10, 20, 80) * 1)$, etc
Here's how I would do this by hand if I had to (this is the part I'd like to simplify / correct my assumptions on!!):
Find each permutation of black marbles (0-10) I could win for each of the 5 games without regard to order.
Filter each permutation so that if the set of 5 games does not sum to 20 it is discarded
For the remaining sets find and multiply the HYPGEOMDIST for each of the 5 games in each set, then sum every set
Please excuse me if this has been asked somewhere else, I am unfamiliar with the terminology in order to search well enough on this site.
Answer: You have correctly identified that your problem is one of convolution of hypergeometrics.
Your two simplest choices appear to be either:

Direct numerical convolution of the probability functions. This is not difficult and given the probability function is on a grid, it can even be done in Excel fairly easily.
You could perhaps try an approximation to the hypergeometric, such as perhaps a normal approximation; if we're not too far in the tail for the sum it should be reasonable.

So let's try them:
1. Direct convolution:
(Calculation details omitted - I did it in R using the convolve function, though it could be done with fft and its inverse or filter as well, but they're all a bit fiddly. In this case it's probably easier to just do it directly as a calculation on the vector of probabilities.)
This is what the probability function of the convolution looks like:

The probability of getting $\geq 20$ on that p.f. is 0.009385. This is 'exact' to the numerical accuracy of the convolution (which should be to more than the number of figures I quoted, so the quoted figures should be accurate).
Here's the same graph with the p.f. of the hypergeometric and the convolution of 5 of them computed in Excel, in this case by repeated use of the SUMPRODUCT function. The answers are of course the same:

2. Normal approximation. Since it turns out (as we see from 1.) that we're quite far out in the tail, this won't be very accurate. But let's go ahead and try it:
From Wikipedia
For a single set of 20 draws ($N=80, K=20, n=10$, and $k$ is the number of 'hits' (black marbles you get).
Your mean for $k$ is: $n {K\over N} = 10 \times 20/80 = 2.5$ as you stated.
Your variance for $k$ is: $n{K\over N}{(N-K)\over N}{N-n\over N-1}$ $= 2.5 \cdot \frac{3}{4} \cdot \frac{70}{79} = 1.6614$  (s.d. 1.289)
Hence $S=Y_1+Y_2+\ldots +Y_5 \quad \dot{\sim}\,\, N(12.5,2.8822^2)$
With continuity correction:
$P(S\geq 19.5) \approx P(Z\geq (19.5-12.5)/2.8822) = P(Z\geq 2.4287) = 0.0076$
The z-value cutoff itself here is enough to hint to us that the approximation may not be very accurate.
(While not terrible accurate, the uncorrected version is significantly less accurate in this case, having about half the required probability.)
Given that the numerical convolution isn't all that much harder than this inaccurate approximation, in this case, it's worth the additional effort.
---
An alternative approximation that is often used is the binomial approximation to the hypergeometric; the usual one would take $n=10$ and $p=0.25$. In this case, that's quite convenient because the convolution of them will also be binomial (with $n=50$ and $p=0.25$); however, it tends to be inaccurate when you sample more than about 5-10% of the population, and in this situation it's a lot more than that, so we would anticipate that it won't be very good. Further, the usual form overestimates the variance (since it ignores the 'without replacement' aspect). In this case it yields a probability about 50% too high.
However, as Brunk et al.$^{(1)}$ point out, since several of the hypergeometric parameters can be interchanged without changing the probabilities, there are actually four quite natural binomial approximations to the hypergeometric, and they discuss another reference that says the one with the smallest "n" for the binomial is generally the best approximation. Brunk et al. give a detailed analysis which broadly seems to back this simple advice up.
In their notation, the total population is $N$, there are $M$ items
in the population with the characteristic of interest and there are $n$
in the sample (i.e. my $K$ above is their $M$ and my $k$ is their $x$), then:
$$H(x;N,n,M) = \binom{M}{x}\binom{N-M}{n-x}/\binom{N}{n}\,,$$
where $0 \leq x \leq \min(M,n)$ and the usual binomial approximating
probability is
$$B(x;n,M/N) = \binom{n}{x}(M/N)^r\, (1-M/N)^{n-r}\,,$$
for $0 \leq x \leq n$.
Since in the hypergeometric, $n$ and $M$ can be interchanged, as can
the roles items-of-interest and items-not-of-interest,
$$H(x;N,n,M)=H(x;N,M,n)=H(n-x;N,N-M,n)=H(M-x;N,N-n,M)$$
leading to four binomial approximations to those probabilities:
$B(x;n,M/N)$
$B(x;M,n/N)$
$B(n-x;N-M,n/N)$
$B(M-x;N-n,M/N)$
In our situation, $N=80$, $M=20$ and $n=10$, so the four "sample sizes" are minimized by taking the first approximation, the one we already considered; this suggests we likely can't do better with the usual forms of binomial approximation.
--
An alternative possibility for a binomial approximation, since the probabilities are essentially zero near the maximum is to forget sticking to the given $n$ and instead choose $n$ and $p$ so as to approximately match the first two moments:
$np = 2.5$
$np(1-p)=1.6614$
Dividing the second equation by the first, $1-p = 0.66456$ or $p = 0.33544$, implying $n\approx 7.453$. If we seek to approximate the individual components of the convolution, the possibilities are to take $n = 7$ or $n=8$, with implied variances $1.607$ and $1.719$ (and of those we might anticipate $n=8$ to do slightly better since it gives more of a 'right tail'), but we could also consider rounding only to the nearest $0.2$ ($n=7.4$) so that we have integer $n$ once we have added the five components, yielding these approximations after the convolution:
(i) $n=35, p = 2.5/7$
(ii) $n=37, p = 2.5/7.4$
(iii) $n=40, p = 2.5/8$
> 1-pbinom(19,35,2.5/7)
[1] 0.007825608
> 1-pbinom(19,37,2.5/7.4)
[1] 0.008837474
> 1-pbinom(19,40,2.5/8)
[1] 0.01022883

With the smallest percentage error on the middle one, though the $n=8$ one is also "close". Nevertheless, the accuracy is not particularly good, though much better than our other approximations.
(1): Brunk, H. D., J. E. Holstein and F. Williams (1968),
A Comparison of Binomial Approximations to the Hypergeometric Distribution
The American Statistician, Vol. 22, No. 1 (Feb.), pp. 24-26


Able to play the right hand Presto on the first try?

Question: Usually I have to perfect a piece at Allegro and then slowly get it to Presto starting with single beats, and then merging every 2 groups of beats until I can play the whole piece Presto nonstop.
Well I was practicing Chopin's Grande Valse Brilliante for the first time today. I tried practicing it years before. I was in my second year of piano and I figured "I can do Chopin now because I am a fast learner". Well that turned against me and I wasn't able to do it. I clearly needed to learn a technique for fast piano playing.
About a year later and I am able to play notes very fast. But I still did not go after Presto pieces for years. It seemed intimidating. Finally I plucked up the courage and practiced the Solfeggio in C minor. That is when I realized the speed up to Presto had to be done differently than the previous speed up to Allegro.
And now today I am able to play the right hand of Grande Valse Brilliante for the most part correct at speed with only a few wrong note errors that are inevitably going to happen when you play super fast. It just exhausts my hand though to play that fast. I can feel the burn. The same thing happens when I do a continuous Alberti bass at Allegro.
But why am I able to play the right hand at Presto with no previous practice of that piece? Does it have to do with the fact that I have listened to Grande Valse Brilliante a lot and thus the notes and tempo have been ingrained into my memory and that I am playing my right hand that fast only because I have great memory of things I listen to?
My left hand isn't up to speed yet. With all those leaps I have to slow down my left hand for accuracy.
Answer: The simple fact is that some piano music fits our hands much better than other piano music.
When we play piano, we're repurposing our hands and fingers to do tasks that are slightly different than those for which they evolved. This means that, usually—especially when you're dealing with virtuosic music from the likes of Chopin, Liszt, etc.—it takes some time to get the music under our fingers. But every once in a while, something really terrific happens: we play something, and it almost seems like it was made for our hands.
I think that's all that's happening here, and I'll urge you not to overthink it. Some music fits our hands more naturally than others, but other (most?) music—like the leapy music you mentioned—doesn't, and thus it requires extra work.
I recommend you view the latter as the default position. Instead of becoming frustrated that all music doesn't come to you so easily, I recommend you just enjoy the few moments where it does come more easily!

With that said, I guess it might be possible to engineer your repertoire based on what music is easier for you. Look at the pieces that come more naturally; are there common traits in that music that aren't in the more difficult music? If so, perhaps you could use that to your advantage: if you need to learn a new piece quickly, try to find one similar to the "easier" pieces. Then again, if you want to continue improving the skills necessary for these "harder" pieces, then stray away from the easier ones.
Comment: could this have more to the practice and training the player has and less to do with hands? what I mean is there are times when i am practicing exercises or simpler songs that are working toward the skills i need to play something more complex and then amazingly i can just play the harder stuff. its almost as if practice and skill building has improved my playing ability.
Comment: @bk3o So you think that me having practiced the Solfeggio in C minor to where I can play it at Presto might be why I can play the right hand of Grande Valse Brilliante with no previous practice of that piece? That maybe I perfected my fast fingers technique needed for that piece by practicing the Solfeggio in C minor first.
Answer: There are several proper movements to play the piano and several improper ones.  All you need to to is find a teacher who knows both.  You could very well have all the proper movements down but one or two improper ones are hindering you.
The fact that you feel a burn or can't play as fast as you like implies you are doing something wrong (most likely not playing from the elbow).  Please keep in mind, nobody knows this so don't tell, MORE practice or slower metronomic practice is not what you need.  You need PROPER practice, not more.  Practice doesn't make perfect, perfect practice does. Five minutes of proper movement is far better than two hours of improper practice.  Far worse is that five minutes of improper movement gets hardwired into our brains and is there for forever.  So . . .
I would need to see and hear you play to diagnose but here are some of the most common technique hindering movements:  Crossing the thumb under the palm.  Flexing and abducting at the same time (most every pianist does this - virtuosos don't).  Twisting your wrist in ulnar or radial deviation which goes along with not re-aligning the forearm behind each finger. Playing from the flexors and not the weight of the arm (up/down).  Playing from the flexors and not the pronator or supinator (rotation).  Improper or no grouping. Trying to play with a "still and quiet hand."
There are many other movements you may be missing such as in/out to accommodate the fact every finger is a different length and, because the fulcrum of the key is lightest on the outside. In places you have to play in, you can add pronator and supinator motions or forward shifts.
Playing is a mechanical science and your arms must obey the laws of physics.  If you try to ignore them and beat the piano into submission, you will eventually lose.
If your body is out of alignment with itself, all your plaints will come to fruition.  Proper movement is the only cure.  Like a car that is out of alignment and eating up your tires.  Driving it more won't fix the problem.  Fixing the alignment will.
A friend poo-poos my training and sticks to his Russian training.  Well, he just developed thumb problems.  Survival of the fittest.
Comment: "Please keep in mind, nobody knows this so don't tell" You're posting a public answer on a public site. Everyone can see this answer.
Comment: Also what you claim as "nobody knows this" is pretty much common knowledge imo


php -f file.php?

Question: So anyways, I was talking to someone about PHP about deobfuscating PHP code and he said "Change the eval to echo and then run php -f file.php".
I understand what it means to change eval to echo (in the code), however, what does he mean by php -f file.php?
Answer: php -f file.php is a simple command to run the specific file.This is assume has nothing to do with deobfuscating PHP code
Answer: He means: "Run 'php -f <filename>' on the command line."
How that is supposed to deobfuscate anything, I haven't the slightest. It merely compiles and executes the php-script in the file.
Comment: Changing `eval` to `echo` is the part doing the deobfuscation.
Comment: It's one of those badly designed obfuscation scheme's where they `eval` some base64 encoded PHP code. He's made it `echo` instead of `eval`.
Comment: Obviously, but I still don't see the point. It doesn't deobfuscate anything. Sure, it can translate it from an unreadable mess to runnable code, but that result can still be obfuscated.
Answer: That means run the command php -f <file> from the command line.  However, I can't see how that would help in deobfuscating anything, because it would effectively just render the file to the command prompt.  The same as opening it up and looking at it.
Answer: As everyone pointed out this is actually running the php script on command line. On unix like systems you will need php-cli or similar named package. Do not that CLI version of PHP uses somewhat different php.ini settings and even have its own ini file. For example on my Debian Squeeze box, it is located in /etc/php5/cli

php -f file.php?


iniciante com duvida em código

Question: ola!
Comecei a estudar agora logica de programação, e estava fazendo um programa para  calcular o imc, só que por algum motivo quando uso a função parseInt na minha variável de peso e altura ele não faz o calculo certo.
segue o codigo:
<meta charset = "utf-8">

Answer: parsenInt() esta funcionando corretamente. Quando você passa um valor de ponto flutuante ex. "39.9" ou 39.9 ele é convertido para um valor inteiro 39, parseFloat() por sua vez converte para um valor de ponto flutuante ex. "39.9" será convertido para 39.9 ou 39 será convertido para 39.0.
Para corrigir o seu problema basta usar parseFloat() no lugar de parseInt().
https://www.w3schools.com/jsref/jsref_parsefloat.asp
Answer: O problema é que você está utilizando a função parseInt(string), que analisa um argumento string e retorna um inteiro, para analisar duas entrada que pertencem ao domínio dos números reais.
Se pegar por exemplo os meus dados cujo a altura == 1.86 e o peso == 85, o imc calculado com parseInt(string) seria imc == 85, pois parseInt(1.86) == 1 e o programa me recomendaria um médico.
Para resolver você deve usar parseFloat(string) que analisa um argumento string e retorna um número de ponto flutuante.
Então com os mesmos dados e a função parseFloat(string) meu índice de massa corporal é 24.5693143716 pois parseFloat(1.86) == 1.86.

function escrever(txt) {

    document.write( txt + "
");
}

alert("calculadora imc");

var nome = prompt("qual seu nome?");
var altura = parseFloat(prompt("qual sua altura?"));
var peso = parseFloat(prompt("qual o seu peso?"));
console.log("Peso :" + peso);
console.log("Altura :" + altura);
var calculaimc = (peso / (altura*altura));

escrever(nome + " o valor do seu imc é de: " + calculaimc);

if(calculaimc <= 18.5){
    escrever("seu imc esta abaixo do recomendado.");
}

if(calculaimc >= 18.6 && calculaimc <= 24.9){
    escrever("seu imc esta normal.");
}

if(calculaimc >= 25 && calculaimc <= 29.9){
    escrever(" seu imc indica sobrepeso.");
}

if(calculaimc >= 30 && calculaimc <= 39.9){
    escrever(" seu imc indica obesidade.");
}

if(calculaimc >= 40){
    escrever( "seu imc esta muito acima do recomendado.");
    alert("procure um medico");
}

iniciante com duvida em código


Unhandled SqlException in user code

Question: I'm trying to build a web form that can send information to a database via ASP.Net and Microsoft SQL Server Management Studio.

It says there's incorrect syntax near Table, which is the name of the table in the database I'd like to store the values.
If you need me to post more code for clarification, I'll do that. Does anyone know what could be wrong?
I appreciate any help you can give
Thanks
EDIT:
So I changed my table name to mynameTable  and I'm getting this error.  It says string or binary data would be truncated
Comment: If that is really your table name CHANGE it, but you will soon discover that this is not your only problem here. txtFName is a textbox right?
Comment: `Table` is a keyword in SQL. If that really is your table name, surround it with `[]`.
Comment: Yeah, I named all my text box id values like that.  Like txtFName, txtEmail etc..  Why is that wrong?
Answer: You have at least four issues; two of them cause your INSERT statement to fail (see bold headings below), and two are design flaws (see additional suggestions under each heading below). While I listed the design flaws as "additional suggestions" only, it's actually important to fix these, too.
1. TABLE is a SQL keyword.
TABLE is a SQL keyword. (And so is Table, since SQL syntax is case-insensitive.)
If you actually named your table Table, you need to "escape" the name by putting it in square brackets:
INSERT INTO [Table] …
--          ^     ^
--         add these!

Additional suggestion: Change the table's name so that it hints at what kind of data or facts are stored in the table. Consider that everyone knows that Table is a table. But it is not obvious that Table contains some kind of personal data; so call your table Customers, Employees, Hairdressers, etc. — or if there really isn't any more specific term, call it Persons.
2. You cannot concatenate a string and a TextBox.
It doesn't make sense to append a TextBox into a string:
"… VALUES ('" + txtFName + "', …"

It should be:
"… VALUES ('" + txtFName.Text + "', …"
//                      ^^^^^

Additional suggestion: You are basically dynamically creating a SQL statement using string concatenation. The way how you're doing it opens up the possibility of SQL injection attacks. (This is a kind of security hole; please research this if you don't know what it is!)
Please use parameterized queries instead:
var cmd = new SqlCommand("INSERT INTO Persons (FirstName, LastName, …) VALUES (@FirstName, @LastName, …)", connection);
cmd.Parameters.AddWithValue("@FirstName", txtFName.Text);
cmd.Parameters.AddWithValue("@LastName", txtLName.Text);
…

And your SQL injection security hole is gone. Also, you won't have to worry about correctly escaping quote characters (') that could have been entered by the user in the textboxes.
Comment: @DrewKennedy: I wholeheartedly agree! I was busy editing my answer while you posted this comment.
Comment: Thanks.  I should prolly name it something else.  I just put square brackets and it didn't work tho
Comment: Thanks stakx.  I'll incorporate your suggestions. Makes sense
Comment: You are doing the lord's work, sir.  Thank you so much! That was very helpful.  And yikes, I didn't realize I was vulnerable to injections :/   Thanks for the heads up
Comment: This is weird.  I followed your directions, and I was able to insert two records no problem.  Now I'm getting this error '{"String or binary data would be truncated.\r\nThe statement has been terminated."}'   I have no idea why
Comment: because one of your text columns is defined with a smaller capacity than the string's length you're trying to insert. E.g. you're inserting `"ABC"` (length 3) into a column defined as `VARCHAR(2)` (capacity 2; `"C"` will get truncated).
Answer: Table is a keyword. You should create a new name for your table.
Reference:
http://msdn.microsoft.com/en-us/library/ms189822%28v=sql.105%29.aspx
Answer: You are using a reserved keyword TABLE and the first thing to do is to change that name in something more comprehensible. If you cannot change that name then you should use the square brakets around that name.
But this is just the first problem. Then you have another one.
You try to create your sql command concatenating strings but you put a textbox object in the concatenation instead of the Text property of the textbox.
SqlCommand cmd = new SqlCommand("INSERT INTO [TABLE] VALUES('" + txtFName.Text + "',....

And this is still very wrong because this result in code open to SQL Injection, so what you really need to do is start using a parameterized query
SqlCommand cmd = new SqlCommand("INSERT INTO [TABLE] VALUES(@fname, @lname, ..... ");
cmd.Parameters.AddWithValue("@fname", txtFName.Text);
cmd.Parameters.AddWithValue("@lname", txtLName.Text);
... and so on for all the others fields ....

Comment: I followed the directions you guys gave me, and it worked for two records, and now I'm getting an error.   This is the error '{"String or binary data would be truncated.\r\nThe statement has been terminated."}'   Why is that?  It worked before, now all of the sudden I get this error..
Comment: It is simply a mismatch between the data length of your inputs and the data length allowed by your database fields. You should not pass more data than the database fields expect. Usually you could prevent this problem setting the MaxLength property on the user interface controls. IE _txtFName.MaxLength = _ has the FirstName field.
Comment: Thanks.  Yeah, I noticed last night.  I had varchar(10) for Credit cards, but when I put American Express, since it's more than 10 characters it didn't work.

Unhandled SqlException in user code


Exact 2 centres of symmetry

Question: I have to answer and prove the answer to the following question:

There exists figures in plane with exactly 2 centres of symmetry?

I know to show that closed figures have at most 1 centre of symmetry.
But I don't know to show that unclosed (opened) figures have at most 1 centre of symmetry, to complete the demonstration.
Thank you for any ideas.
Comment: It is not true that an arbitrary point set can have at most 1 center of symmetry (for instance, take the entire plane).  So it depends somewhat on what exactly a "figure" is defined to be.  Are there any restrictions?  For general figures it is very far from true that non-closed sets are open.
Comment: See also [this post](https://math.stackexchange.com/questions/1997741/centre-of-symmetry-of-a-bound-figure?rq=1).
Answer: Let $f,g\colon\Bbb R^2\to\Bbb R^2$ be non-identity symmetry maps of some figure $X$ with unique fixpoints $F_f$ and $F_g$, respectively. Then $h:=f\circ g\circ f^{-1}$ is a symmetry map of $X$ invariant and has unique fixpoint $F_h:=f(F_g)$. Now if $F_f\ne F_g$, then $F_h=F(f_g)\ne f(F_f)=F_f$ as well as $F_h=f(F_g)\ne F_g$ (because $f$ does not leave $F_g$ invariant), i.e., there are at least three centres of symmetry.
Upon closer inspection, one finds that the set of symmetry centres is infinite an unbounded in the situation above.

Exact 2 centres of symmetry


how to make a php crontab silent

Question: I set up a crontab in Cpanel to run every min. It's working great but I don't want an e-mail every min. I have a second cron tab that runs every day. I would like the responce of this tab. Is there a way to tell the crontab to be silent or only e-mail on error?
I have:
    *    *  *   *   * php /home/public_html/folder/file.php 2>&1

The last bit 2>&1 I added because i thought it would make it silent.
From the Cpanel Docs:

You can have cron send an email everytime it runs a command. If you do not want an email to be sent for an individual cron job you can redirect the command's output to /dev/null like this: mycommand >/dev/null 2>&1
Answer: use -q it means "quiet" and thus doesn't generate output
*    *  *   *   * php -q /home/public_html/folder/file.php

also, ask yourself why you want to run it every minute, that's a little excessive.
Comment: @xenoterracide what are some other options to check a database and sent out alerts on a realtime basis?
Comment: @bandnon 1 minute intervals aren't realtime anyways... but long running scripts that poll will do it, event driven programming might be good, when an alert is generated, send it.
Comment: It's a crontab that checks the status of buses in real time. The file is checking to see how many minutes the bus is away and if it's close alerts the user.
Comment: Also, `-q` did the trick.
Comment: If it needs to run once a minute, what's the problem with that?  Surely the developer knows why it needs to run so frequently...
Comment: @Tom generally cron may not be the right solution for things that need to run that often. But that's an opinion, and one that we enforce at work.
Answer: 2>&1 redirects the everything written to stderr to stdout
>/dev/null redirects stdout to /dev/null
cron will always email you anything sent to stdout or stderr unless redirected elsewhere.  Ideally, your PHP script should be rewritten to accept a --quiet flag that doesn't write a whole bunch of useless crap out to stdout, which you could then use in your cron job.
The lazy man's option is to put a wrapper script around your cron job that will stop it from emailing you unless your command exits non-zero.
Answer: The correct setup would be
>/dev/null

This makes the standard output be ignored and only emails you if there is an error
Your current setup doesn't handle the standard output therefore you get an email every time it runs.
Comment: You're assuming that errors are being printed to stderr rather than stdout.  This is not a safe assumption.
Comment: I see. I also see that curl has --silient but can I curl an php script?
Comment: @BandonRandon, you can curl URLs like http/https if this was your question.
Comment: @l1x yes that was my question. That would make it run just like loading it in the browser correct?
Comment: @BandonRandon yes, like http://yourdoma.in/folder/file.php
Comment: Okay, so that's another route to go. The accept answer seemed to be a simple solution.

how to make a php crontab silent


Dirac delta function in spherical cordinates

Question: I am studying Dirac Delta Function in Spherical Polar Cordinates. I found this expression
$$\delta\ ^3 (\vec r -\vec r_{o}) = \frac{ \delta\ (r -r_{o})\delta\  (θ -θ_{o})\delta\ (φ -φ_{o}  )}{r^2 \sin θ }$$
And then they have reduced it to
$$\delta\ ^3 (\vec r -\vec r_{o}) = \frac{ \delta\ (r -r_{o})\delta\  (θ -θ_{o}) }{2πr^2 \sin θ }$$
How do we get this reduced expression from the above expression? Please explain.
Comment: Compute $\int\limits_{r=0}^\infty \int\limits_{\theta=0}^{2 \pi} \delta(r-r_0) \delta(\theta - \theta_0) r\ dr\ d\theta$ and you'll get non-unity value.  Given you demand the integral = 1.0, these give you the scaling constants.
Answer: It is not true that two expressions are equal. Note that
$$\begin{align}
\int_0^{2\pi}f(r,\theta,\phi)\delta(\phi-\phi_0)\,d\phi&=f(r,\theta,\phi_0)\\\\
\int_0^{2\pi}\frac1{2\pi}f(r,\theta,\phi)\,d\phi&\ne f(r,\theta,\phi_0)
\end{align}$$
unless $f(r,\theta,\phi)$ is independent of $\phi$.
Comment: @dineshkatoch Please let me know how I can improve my answer.  I really want to give you the best answer I can.


request in java server has no query string

Question: I am trying to send an input from PHP server to Java server using "GET"
My request sent has no issues
Request and Response
Both the server are connected, I am receiving a response "null Please enter a number"
where null is an output for
out.println(inputdata);

My code
HTML

<meta charset="UTF-8">
<title>Cloud Computing</title>

<form action="url.php" method="get">
Input: <input type="text" name="inputdata" >

       <input align="center" type="submit">
</form>

PHP

 <meta charset="UTF-8">
  <title>PHP Test</title>

 <form action="url.php" method="get">
Input: <input type="text" name="inputdata" >

<input align="center" type="submit">
</form>

    <?php

        echo "Query for:";
        echo $_GET["inputdata"];
        //echo $_POST["inputdata"];
         $inputdata = $_GET["inputdata"];
         $url = "http://localhost:8080/CloudComputingProj/Cloudpi";

    $post_params_s = ["inputdata"=>$inputdata];

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt ( $ch, CURLOPT_POST          , TRUE ) ;
    curl_setopt ( $ch, CURLOPT_POSTFIELDS    , $post_params_s ) ;
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE ) ;
    curl_exec($curl);
    curl_close($curl);
?>

Java Server
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            System.out.println("Inside Service");

            System.out.println(request.getQueryString());
            if(request.getMethod().equals("GET")){
                doGet(request, response);
            }
        }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
           //   System.out.println(request.getParameterMap());     //Returns null
            InputStream requestBodyInput = request.getInputStream();
            String inputdata = request.getParameter("inputdata");
            System.out.println(inputdata);
            //response.getWriter().append(" \n Served at: ").append(request.getContextPath());
            response.setContentType("text/html");
             PrintWriter out = response.getWriter();
             //out.println("Hello World!");
             out.println(inputdata);
            // System.out.println(request.getQueryString());
             if (request.getParameter("inputdata") == null) {
                 out.println("Please enter a number");
             } else {
                 out.println("Hello "+request. getParameter("input")+"!");
             }

        }

I am not finding anything here for "request", none of the standard methods give me anything other than 'null' kindly help ! I am new to this.
Answer: You are checking a non exist input
if (request.getParameter("input") == null)
                          ^^^^^

Which I think that is should be as follows:
if (request.getParameter("inputdata") == null)

UPDATE
you are posting the request to curl, while you are checking for GET request type.
if(request.getMethod().equals("GET"))

you need either to check if the request is post and then get the POST request body or setting your curl to send a GET request with a simple query string.
Comment: Thank you Hassan for the quick reply.

That "input" is by mistake, it should be inputdata.   Nevertheless the request fails at service itself. It does not give me any Parameter or Query String.
Comment: Just did , thanks for noting.

Is there anything else you found fishy in the java server code?
Comment: In protected void service, the "request" I am getting is does not return anything other than request.getMethod()

For e.g.

  System.out.println(request.getQueryString());

gives me a 'null' where it should be giving me the query string i.e. the url of my php server with the input variables.

The doGet method is inconsequential if the request itself is received incomplete.

And neither getParameter() or getQueryString() works.
Comment: Please check the image named "Request and Response". Maybe you find something I don;t.
Comment: `request.getQueryString()` will read the query string of that url : `http://localhost:8080/CloudComputingProj/Cloudpi` not the url `localhost/url.php?inputdata=.....` , try to send the url as follows: `$url = "http://localhost:8080/CloudComputingProj/Cloudpi?inputdata=$inputdata";`
Answer: try to modify php code to $url = "http://localhost:8080/CloudComputingProj/Cloudpi?inputdata=".$inputdata
Also you can debug your java side by typing the get request in any browser http://localhost:8080/CloudComputingProj/Cloudpi?inputdata=your-encoded-param
Comment: This doesn't work as this is my Java server URL (Which I am calling from PHP)

The inputdata is being sent by the request as query string and parameter (Check Image).
Comment: @Pandeyji the request image you post is the request to the php server, not to java server.You can call you java server directly as I said. If your java server response correctly, then there is a bug in your php code.
Comment: Are you suggesting that I call my java server directly from the HTML instead of calling a php ?
Comment: @Pandeyji yes, for testing purpose.
Comment: Oh yes I get the inputdata now

Output:
Webpage: 2131 Hello null!

Java Console:
Inside Service
/CloudComputingProj
java.util.Collections$3@20d3e8f0
2131
2131
Comment: But again the request as seen in the image seems to be correct. I am not sure why is it behaving this way
Comment: Perfect it works !!
Thanks a lot ...being breaking my head on this for hours now :X


Why can't I change the value of a property of the styles object in React js , inside an event Listener after rendering

Question: I have a jsx file :
import React from "react";
import ReactDom from "react-dom";
const styles = {
  textAlign: "center",
  color: "black"
};
ReactDom.render(

Good {wish}

,
  document.querySelector("#root")
);
document.querySelector("h1").addEventListener("click",function(){
  styles.color="salmon";
  console.log(styles);
});

I cannot change the styles object on click, it remains the same, "styles.color" is still "black".
Why can't I modify the styles object ?
Comment: Direct DOM manipulation is *almost always* the wrong approach in React.  Create a component, store the styles in state, update state in a click event.  Overall it looks like you should be starting with some introductory tutorials on React.
Comment: Your component isn't changing when you update the "styles" because react doesn't know to rerender the component. To do so, you need to use the useState hook which means that when you update the state variable it triggers a rerender
Comment: Also I notice that you're trying to add event listeners to the dom elements themselves instead of using components which is strange because if you're using react you shouldn't have to touch the DOM at all, at the very least very rarely
Comment: I wasn't doing any DOM manipulation, I wanted to know how that scenario would turn out to be , I was just curious, Anyways thank you guys for the suggestions.
But still when I log the styles object, styles.color is not updated , is there a reasoning for it?
Answer: You really shouldn't be attempting to maniuplating the DOM when using react. It does that stuff for you!
Create a component
Mycomponent.jsx
import {useState} from 'react';
function myComponent(wish){
const [styles,updateStyles] = useState();

function doSomething()
{
// Change styles here
updateStyles(/*Whatever you're doing to styles*/)
}

return(

Good {wish}

)
}
export default myComponent;

and in your main component
main.js
import React from "react";
import ReactDom from "react-dom";
import MyComponent from './Mycomponent.jsx';
ReactDom.render(

    <MyComponent wish={/*String here*/}/>

,
  document.querySelector("#root")
);
});

I highly recommend when you're starting a new project to use create-react-app because it does all this boilerplate stuff for you so you can get straight into coding in react instead of setting it up yourself. Also I would recommend to familiarize yourself with the official react documentation.
Comment: Thank you for this, but could you explain why the styles object is not updated. When I log it , why isn't the color property being changed? particularly after using the render function.
Comment: What react does is creates a 'virtual DOM' that it keeps track of and whenever component state updates (you changing the styles variable) it compares the new 'virtual DOM' to the actual DOM and reconciles the two so that the UI matches the application state. Since you changed application state in a way that react doesn't know about (attaching an event listener to the DOM element instead of through react) it doesn't know that it should update your component. Does that help?
Comment: also, you declared styles as a const in your example
Comment: Even if I did change the styles.color property outside the event listener, the styles object doesnt change.
Comment: But styles is an object which is stored in the heap right? And it is not a primitive , so I can assign a new value to one of its existing properties right?
Comment: Regardless, react doesn't know about the change, therefore it doesn't update the DOM


Adicionar items Ionic

Question: Preciso que os valores mudem ao clicar nos botões + e -, como na imagem.
Peguei um exemplo no Plunker (http://plnkr.co/edit/V1GEsL5IooR8MROuiAoc?p=preview) e estou tentando adaptar ao que eu preciso, porém não estou tendo sucesso. Alguém poderia me dar umas dicas?
Segue oq tenho até agora:

    $scope.formData = [];

    $scope.products = [{
        'id': '1',
        name: 'Festa do Cabide'
    }, {
        'id': '2',
        name: 'Balada do Natal'
    }, {
        'id': '3',
        name: 'Almôndegas Radiotivas'
    }];

    $scope.changeQuantity = function (productId, quantity) {
        var newItem = true;
        angular.forEach($scope.formData, function (value, index) {
            console.log(value);
            console.log(index);
            if (value.product_id === productId) {
            //remove if quantity 0 or null
                if (quantity === 0 || quantity === null) {
                    $scope.formData.splice(index, 1);
                }else {
                    $scope.formData[index].quantity = quantity;
                }
                newItem = false;
            }
        });
        if (newItem) {
            $scope.formData.push({product_id: productId, quantity: quantity});
        }
    };

{{ formData }}

{{ product.name }}

              Quantity:

              <input type="number" ng-model="quantity" placeholder="product_{{product.id}}" value="" style="border: thin solid black">

Answer: Outro desenvolvedor me ajudou e resolveu da seguinte forma:

    $scope.ticketPlus = function(ticketIndex, itemIndex) {
        $scope.tickets[ticketIndex]['items'][itemIndex]['quantity'] ++;
        console.log($scope.tickets);
    }

    $scope.ticketMinus = function(ticketIndex, itemIndex) {
        if(!$scope.tickets[ticketIndex]['items'][itemIndex]['quantity'] == 0) {
            $scope.tickets[ticketIndex]['items'][itemIndex]['quantity'] --;
        }

    }

    <input type="number" ng-model="item.quantity" placeholder="0">

Adicionar items Ionic