text:
Q: How to know the probability of having 0 or 1 object on a series of samples? I am facing a probability problem : I have a certain volume $Vtot$ of water, in which I have $n$ particles. I am aiming at sampling 0 or 1 (no more) particle in every drop (of a volume $Vdrop$).
So I want to know the probability of getting 0 or 1 particle per drop and then estimate which dilution I have to do in order to have best results (P>0.95).
I tried a combinatorics approach but I cannot get through with it since every time I would sample more than 1 particle, chances to get 0 next time would rise, and vice versa
Well, any help would be much appreciated, it is certainly a simple problem but I just might have the wrong approach.

A: Lets assume that there are many more particles in your volume ($N_p$)than your desired sample size, $n$, so that the number of particles you sample do not affect the subsequent sampling to a significant extent and your sample volume is small compared to the total volume, (i.e, $N_p >> n$ and $V_{tot}>>nV_{drop}$. In that case, you can model the number of particles in your drop $N_d$ as a poisson random variable, with rate parameter $\lambda = \frac{N_p}{V_{tot}}V_{drop}$. Then you can calculate P($N_d=1$) and P($N_d=0$) using this poisson.
Now, if the above assumptoins are not true, then for each drop, we can still model it as a poisson, but the rate parameter will change each sample. The first drop will be modeled the same way, but subseuqent drops will require you to make a branch for each possibility: E.g., P($N_{d1}=0$) [branch 1] and P($N_{d1}=1$) [branch 2]. For each of sbusequent sample,  you will need to do this again, but the number of branches will grow such that if you plan to take $n$ samples, you will have $2^n$ branches at the final stage. Not an appealing calculation (although it can be easily programmed into R or some other language that supports intermediate math functions).


text:
Q: Grub Splash screen on Boot I want to enable the nice splash screen on GRUB boot menu. I have Ubuntu 11.04, running on a nVidia graphics card. Please help. I'm new to Linux.
edit
I want to set a background image when GRUB shows a list of available OS. I have Ubuntu 11.04. I've changed colour through grub.cfg in /boot/grub but can't set an image as background in the list.

A: I haven't tested it on my own, but the Grub Customizer seems to be able to do what you want. It's a nice GUI application where you can easily manage the Grub settings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating pgfplots I am using LaTeX in MacOsx Lion. My current version of pgfplots is 1.4.1 which I want to upgrade to 1.7. I really do not know how to install version 1.7. Any help?

A: Assuming you are employing the latest TeXlive (MacTeX is built on TeXlive, right?) or similar (MikTeX on windows) it is just a matter of updating with the update tools supplied (see @Pouya answer about TeX-live). However, it could be argued that you needed a more general, switchable solution.
Here is what I do:
I generate some local folder which is named out-of-live/tex. Within that folder you can put a regular TDS structure to comply with regular TeX installations.
In there I put pgfplots and (also pgf as that is typically required to be the lastest CVS version as well).
So I do a local installation of those packages, and others if I like, just there. In general I use CVS and git to be able to update them to the newest state, at any time (thereby going past the TeX-distribution).
Then the folder structure becomes:
.../out-of-live/tex/
                    pgf/
                    pgfplots/

Now, you simply need to edit your texmf.cnf file to add this out-of-live to the search path for sources.
Locate your file by: kpsewhich texmf.cnf.
Then edit that file and find the line referring to TEXMFHOME.
Then do this:
TEXMFHOME = {../out-of-live}
% or if it already contains ~/texmf do
TEXMFHOME = {~/texmf,../out-of-live}

TeXlive will automatically assume that that folder contains a TDS compliant directory structure, hence it will look for sources in tex, documentations in doc, etc.
Remember that TEXMFHOME will be searched before the regular installation path.
Also note, that typically by default, TeXlive adds the folder ~/texmf to the search path as well (so you could just place folders pgf and pgfplots in ~/texmf/tex, but the above is a more general picture).

A: Mac distribution of LaTeX comes with a little GUI tool called Tex Live Utility that allows you to upgrade packages. You can find it in your Application folder side by side tex editors. Another method is to use terminal command tlmgr in this fashion:
tlmgr update <packagename>

or for updating everything:
tlmgr update --all

To use tlmgr you might need sudo access.
Edit:
Probably you will be prompted to update tlmgr itself. To do so, try
tlmgr update --self


text:
Q: Downloading - get a callback when received all the request headers I use ion library for downloading files in my app. I want to read the response headers, check a particular header and either cancel or continue the download. Of course I can execute the HEAD query, check the header, and then execute the GET query. But I want to execute only one request.
Is there a way to get a callback when received all the headers, handle them and either continue or cancel the download?

A: Use the onHeaders callback.
.onHeaders(...)

https://github.com/koush/ion/blob/master/ion/src/com/koushikdutta/ion/builder/RequestBuilder.java#L186

A: I found another solution. Maybe it's better?
Ion.getDefault(<Context>).getHttpClient().insertMiddleware(new SimpleMiddleware()
{
    @Override
    public void onHeadersReceived(OnHeadersReceivedDataOnRequestSentData data)
    {
        super.onHeadersReceived(data);
    }
});


text:
Q: update json file using servlet In a java web app, i want to update the json file with the data which is received at server.
The json file already  exists in Web Pages\json\cards.json  as:
[
{
   "name": "Dhruvam Gupta",
   "job_title":"Android Developer",
   "email":"dhruvamprashant@gmail.com",
   "phone":"9839262655"
}
]

First i read the JsonArray from cards.json as follows which is successfully done because
System.out.println(array) gives the previous and appended data as:
[
{"name":"Dhruvam Gupta","job_title":"Android Developer","email":"dhruvamprashant@gmail.com","phone":"9839262655"},
{"email":"gabor.orosz@me.com","phone":"+36 30 610 6976","name":"Orosz Gábor","job_title":"Android Developer"}]

I have read the data as:
ServletContext context  = getServletContext();

    InputStream is = context.getResourceAsStream("/json/cards.json");
    InputStreamReader isr = new InputStreamReader(is);
    JsonReader jsr = new JsonReader(isr);
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(jsr);
    JsonArray array = element.getAsJsonArray();

    JsonElement ele = parser.parse(card);

    array.add(ele);
    System.out.println(array);

But when i try to write the array to json file then the exception is thrown as: \json\cards.json (The system cannot find the path specified).
 try {

        FileOutputStream fw = new FileOutputStream(new File("/json/cards.json"));

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fw));

        bw.write(array.getAsString());

        bw.close();

        fw.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }

So i want to know how can i update the data successfully.
I think the problem is in opening OutputStream from servlet to cards.json file.
Plz help me to rectify the problem.

A: First, read this, including the linked tutorial and blogpost.
Second, the path in context.getResourceAsStream("/json/cards.json") is relative to the deployment directory of your web application OR classpath (i.e. it is possible to load the resources from e.g. JAR files in WEB-INF/lib this way). But new File("/json/cards.json") uses absolute path on your file system, i.e. the paths are not the same.


text:
Q: Grunt error task "default" not found When trying to run grunt, I get an error message:
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.

I have already found several posts on this topic, and in each of them the problem was a missing comma. But in my case I have no idea what's wrong, I think I didn't miss any comma (btw, this content was copy/pasted from the internet).
module.exports = (grunt) => {
    grunt.initConfig({
        execute: {
            target: {
                src: ['server.js']
            }
        },
        watch: {
            scripts: {
                files: ['server.js'],
                tasks: ['execute'],
            },
        }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-execute');
};

What could be the problem?

A: You didn't registered the default task. Add this after the last loadNpmTask
grunt.registerTask('default', ['execute']);

The second parameter is what you want to be executed from the config, you can put there more tasks.
Or you can run run existing task by providing the name as parameter in cli.
grunt execute
With you config you can use execute and watch. See https://gruntjs.com/api/grunt.task for more information.

A: If you run grunt in your terminal it is going to search for a "default" task, so you have to register a task to be executed with Grunt defining it with the grunt.registerTask method, with a first parameter which is the name of your task, and a second parameter which is an array of subtasks that it will run.
In your case, the code could be something like that:
...
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask("default", ["execute", "watch"]);
...

In this way the "default" task will run rispectively the "execute" and the "watch" commands.
However here you can find the documentation to create tasks with Grunt.
Hope it was helpful.


text:
Q: How do I make a call with VoiceResponse? Twilio I want to make a call using VoiceResponse for all the info on how the call should work, but I can't seem to find how to generate a URI for the call to use (because it requires phone number, phone number, URI in the Call.creator method)
                StringBuilder messageB = new StringBuilder();
                for(int i = 2; i < input.split(" ").length; i++) {
                    messageB.append(" " + input.split(" ")[i]);
                }

                Say say = new Say.Builder(messageB.toString().replace(" ", "%20")).voice(Say.Voice.POLLY_JUSTIN).build();
                Record recording = new Record.Builder().build();
                Pause pause = new Pause.Builder().length(3).build();
                TwiML response = new VoiceResponse.Builder().say(say).record(recording).pause(pause).build();

                String Url = "http://twimlets.com/message";
                Url = Url + "?Message%5B0%5D=" + messageB.toString();

                Call call = Call.creator(
                        new PhoneNumber("+" + input.split(" ")[1]),
                        new PhoneNumber("+xxxxxxxxxxx"),
                        URI.create(Url))
                        .create();
                System.out.println("Call ID: " + call.getSid());

                System.out.println(Url);

A: Twilio developer evangelist here.
You can't use a VoiceResponse at the time you are making an API call to Twilio to start a call.
Instead, you need to set up a web application that can respond to incoming HTTP (webhook) requests from Twilio. When the call connects, Twilio will make a request to the URL you send as part of the request and you can use the VoiceResponse at that point to build and return the response you want.
You might find it useful to follow one of our tutorials to better understand this. Here's one on building a click to call system with Java.
Let me know if this helps at all.


text:
Q: Checking statistical significance of regression coefficients in DLM package (R) My time series is modeled as a random walk plus regression terms:
#DLM package
model <- function(u) {
  local <- dlmModPoly(order = 1, dV = c(1e-06), dW = exp(u[1]))
  reg <- dlmModReg(x1, dV = exp(u[2]), addInt = FALSE)
  reg2 <- dlmModReg(x2, dV = exp(u[3]), addInt = FALSE)

  return(local + reg + reg2)
}

init <- c(rep(0, 3))
outMLE2 <- dlmMLE(data, init, model)
dlmModel <- model(outMLE2$par)

Is there a way to get t-statistics and p-values for the estimated regression coefficients?


text:
Q: FUNCIONES LLAMADAS DESDE OTRAS CLASES -> lNK2019 UNRESOLVED EXTERNAL SYMBOL llevo horas comiéndome la cabeza con el error LNK2019 y no entiendo que me falla. Soy nuevo en C++.
Si alguien me puede echar una mano, se agradece.
Esto es lo que me salta la consola:

1>Escribir.obj : error LNK2019: unresolved external symbol "public:
  int __thiscall Leer::introducirSegundos(void)"
  (?introducirSegundos@Leer@@QAEHXZ) referenced in function "bool
  __cdecl escritor(enum estado,int)" (?escritor@@YA_NW4estado@@H@Z)
1>Escribir.obj : error LNK2019: unresolved external symbol "public:
  int __thiscall Leer::introducirMinutos(void)"
  (?introducirMinutos@Leer@@QAEHXZ) referenced in function "bool __cdecl
  escritor(enum estado,int)" (?escritor@@YA_NW4estado@@H@Z)
1>Escribir.obj : error LNK2019: unresolved external symbol "public:
  int __thiscall Leer::introducirHoras(void)"
  (?introducirHoras@Leer@@QAEHXZ) referenced in function "bool __cdecl
  escritor(enum estado,int)" (?escritor@@YA_NW4estado@@H@Z)
1>Escribir.obj : error LNK2019: unresolved external symbol "public:
  class std::basic_string,class
  std::allocator > __thiscall Leer::introducirNombre(void)"
  (?introducirNombre@Leer@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ)
  referenced in function "bool __cdecl escritor(enum estado,int)"
  (?escritor@@YA_NW4estado@@H@Z)
1>Escribir.obj : error LNK2019: unresolved external symbol "public:
  int __thiscall Leer::introducirTracks(void)"
  (?introducirTracks@Leer@@QAEHXZ) referenced in function "bool __cdecl
  escritor(enum estado,int)" (?escritor@@YA_NW4estado@@H@Z)
1>Leer.obj : error LNK2019: unresolved external symbol "public: int
  __thiscall Escribir::devolverListaS(int)" (?devolverListaS@Escribir@@QAEHH@Z) referenced in function "int
  __cdecl lector(enum estado)" (?lector@@YAHW4estado@@@Z)
1>Leer.obj : error LNK2019: unresolved external symbol "public: int
  __thiscall Escribir::devolverListaM(int)" (?devolverListaM@Escribir@@QAEHH@Z) referenced in function "int
  __cdecl lector(enum estado)" (?lector@@YAHW4estado@@@Z)
1>Leer.obj : error LNK2019: unresolved external symbol "public: int
  __thiscall Escribir::devolverListaH(int)" (?devolverListaH@Escribir@@QAEHH@Z) referenced in function "int
  __cdecl lector(enum estado)" (?lector@@YAHW4estado@@@Z)
1>Leer.obj : error LNK2019: unresolved external symbol "public: int
  __thiscall Escribir::devolverListaId(int)" (?devolverListaId@Escribir@@QAEHH@Z) referenced in function "int
  __cdecl lector(enum estado)" (?lector@@YAHW4estado@@@Z)
1>Leer.obj : error LNK2019: unresolved external symbol "public: class
  std::basic_string,class
  std::allocator > __thiscall Escribir::devolverListaNomb(int)"
  (?devolverListaNomb@Escribir@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z)
  referenced in function "int __cdecl lector(enum estado)"
  (?lector@@YAHW4estado@@@Z)
1>Main.obj : error LNK2019: unresolved external symbol "public: void
  __thiscall Escribir::escritor(enum estado,int)" (?escritor@Escribir@@QAEXW4estado@@H@Z) referenced in function _main
1>Main.obj : error LNK2019: unresolved external symbol "public: enum
  estado __thiscall Gestionar::gestor(enum estado,int)"
  (?gestor@Gestionar@@QAE?AW4estado@@W42@H@Z) referenced in function
  _main
1>Main.obj : error LNK2019: unresolved external symbol "public: int
  __thiscall Leer::lector(enum estado)" (?lector@Leer@@QAEHW4estado@@@Z) referenced in function _main
1>C:\Users\morti\documents\visual studio 2010\Projects\2.0
  LectorCDs\Debug\2.0 LectorCDs.exe : fatal error LNK1120: 13 unresolved
  externals
1>
1>Build FAILED.

Leyendo diversas reseñas, mi problema creo que no es la declaración de las funciones en el encabezado:
Leer.h
#pragma once

#include <iostream>

class Leer
{
    public:

        int lector(enum estado estadoActual);

        std::string introducirNombre();
        int introducirTracks();
        int introducirSegundos();
        int introducirMinutos();
        int introducirHoras();
};

Escribir.h
#pragma once

#include <iostream>

class Escribir
{
    private:
        std::string toString (int n);
        void sumadorDeTiempo(int hora, int minuto, int segundo);
        void restadorDeTiempo(int hora, int minuto, int segundo);

    public:

        void escritor(enum estado estadoActual, int lector);
        std::string devolverListaNomb(int i);
        int devolverListaId(int i);
        int devolverListaH(int i);
        int devolverListaM(int i);
        int devolverListaS(int i);
};

ClsTracks.h
#include <string>

class ClsTracks
{
private:
    int id;
    std::string nombre;
    int minutos;
    int segundos;
    int horas;
    bool CD;
public:

    ClsTracks();

    ClsTracks(int id, std::string nombre, int segundos, int minutos, int horas, bool CD);

    void SetSegundos(int segundos);
    int GetSegundos();

    void SetMinutos(int minutos);
    int GetMinutos();

    void SetHoras(int horas);
    int GetHoras();

    void SetNombre(std::string nombre);
    std::string GetNombre();

    void SetId(int id);
    int GetId();

    void SetCD(bool cd);
    bool GetCD();

};
MUCHAS GRACIAS DE ANTEMANO


text:
Q: How do you boot from USB using CentOS Minimal? I followed these instructions to create a bootable USB using my Mac. This is so I can install CentOS from a USB.
They worked great for the Centos Netinstall and the Centos LiveCD. Both these booted from the USBs on my server.
However, when I did it for the Centos Minimal iso it won't boot. Is this an issue with the Minimal ISO??
I really want to install Centos Minimal, but can only install the full Centos from the LiveCD. I dont want the GUI or any GUI apps.
Thanks a lot

A: I guess that Minimal ISO is not a hybrid iso which means it is not dd able(Gentoo minimal is also not dd able. While Arch minimal is dd able).
You can still make it dd able, but it is a bit complex.
I propose you use UltraISO, it can make a bootable liveUSB easily.

A: try this command.
dd if=/path/to/iso/file of=/dev/usbdevice
For example:
dd if=~/images/xxx-boot.iso of=/dev/sdb


text:
Q: Elasticsearch nested aggregations returns duplicate results With this mapping:
PUT pizzas
{
  "mappings": {
    "pizza": {
      "properties": {
        "name": {
          "type": "keyword"
        },
        "types": {
          "type": "nested",
          "properties": {
            "topping": {
              "type": "keyword"
            },
            "base": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

And this data:
PUT pizzas/pizza/1
{
  "name": "meat",
  "types": [
    {
      "topping": "bacon",
      "base": "normal"
    },
    {
      "topping": "pepperoni",
      "base": "normal"
    }
  ]
}

PUT pizzas/pizza/2
{
  "name": "veg",
  "types": [
    {
      "topping": "broccoli",
      "base": "normal"
    }
  ]
}

If I run this nested aggregation query:
GET pizzas/_search
{
  "size": 0,
  "aggs": {
    "types_agg": {
      "nested": {
        "path": "types"
      },
      "aggs": {
        "base_agg": {
          "terms": {
            "field": "types.base"
          }
        }
      }
    }
  }
}

I get this result:
{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "types_agg": {
      "doc_count": 3,
      "base_agg": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "normal",
            "doc_count": 3
          }
        ]
      }
    }
  }
}

I expected my aggregation to return a doc_count of 2 because there are only two documents which match my query. However it is clear that because it's an inverted index, it is finding 3 results and therefore 3 documents.
Is there anyway to get it to return unique document counts?
(tested in Elasticsearch 5.4.3)

A: Just discovered the answer shortly after asking the question.
Changing the aggregation query to be:
GET pizzas/_search
{
  "size": 0,
  "aggs": {
    "types_agg": {
      "nested": {
        "path": "types"
      },
      "aggs": {
        "base_agg": {
          "terms": {
            "field": "types.base"
          },
          "aggs": {
            "top_reverse_nested": {
              "reverse_nested": {}
            }
          }
        }
      }
    }
  }
}

Yields the result:
{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "types_agg": {
      "doc_count": 3,
      "base_agg": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "normal",
            "doc_count": 3,
            "top_reverse_nested": {
              "doc_count": 2
            }
          }
        ]
      }
    }
  }
}

The important part which was added to the query was:
"aggs": {
    "top_reverse_nested": {
        "reverse_nested": {}
    }
}

Reverse nested join back to  the root of the document so it only gets unique aggregations.
You can read about reverse_nested here.


text:
Q: Newlines in legend labels plotly Creating a graph using plotly  . I have more than 10 traces in my graph and I want to set them horizontally. But I can hardly see 4-5 at a time others are not visible. Is there any way to break the line and display all legends horizontally?
I don't want to use legend group as it will toggle(hide/show) legends in a group. Below are my sample code:

var chartId = 'plotly';
var $chart = $('#' + chartId);
if ($chart.width() < 450) $chart.css('width', 450);

var data = [{
    "x": [1, 2, 3, 4],
    "y": [63.69, 62.55, 61.64, 61.39],

    // XXX: Comment out the line below to restore legend wrapping
    "legendgroup": 1
  },
  {
    "x": [1, 2, 3, 4],
    "y": [58.24, 54.93, 42.11, 50.75],
  }, {
    "x": [1, 2, 3, 4],
    "y": [51.49, 49.59, 37.12, 31.45],
  }, {
    "x": [1, 2, 3, 4],
    "y": [49.09, 58.54, 53.91, 43.12],
  }, {
    "x": [1, 2, 3, 4],
    "y": [70.53, 72.51, 72.28, 78.65],
  }, {
    "x": [1, 2, 3, 4],
    "y": [62.69, 59.09, 63.82, 62],
  }, {
    "x": [1, 2, 3, 4],
    "y": [76.27, 71.43, 59.83, 64.34],
  }, {
    "x": [1, 2, 3, 4],
    "y": [71.15, 81.82, 88.46, 74.29],
  }, {
    "x": [1, 2, 3, 4],
    "y": [57.89, 57.38, 52.08, 63.83],
  }, {
    "x": [1, 2, 3, 4],
    "y": [65.4, 63.27, 65.78, 64.03],
  }];

var layout = {
  "legend": {
    "orientation": "h"
  }
};

var p = Plotly.plot(chartId, data, layout);


text:
Q: Manipulating an array in Access I have a set of numeric values as an array, like so
100,120,0,100,90 etc

I also have an integer variable n
I have to count the zero's in the array, and replace the lowest non-zero (first occurence) with a zero, until the count of zero's = n
So given the data above, and an n = 3
 I would end up with
 0,120,0,100,0 etc

I need to then sum the values.
I'm not familiar with Access vba arrays, and it appears that there are not many in built array manipulation functions at all. Is anyone able to help?

A: Sort your array
Then loop through your array starting at N to get a running total.
The thing is, you don't have to convert the lowest values to zero. All you have to do is exclude it from the summation, hence you start your running total at N (assuming 0 based array).
Reading the comments, I amended my answer to deal with empty arrays & array sizes less than N.
Function ArrayTotal(MyArray() As Long, N As Long)
    Dim Idx As Long
    Dim Total As Long

    On Error Resume Next
    Idx = UBound(MyArray)
    If Err.Number <> 9 Then
        QuickSort1 MyArray
        If N < UBound(MyArray) Then
            For Idx = N To UBound(MyArray)
                Total = Total + MyArray(Idx)
            Next Idx
        End If
    End If
    ArrayTotal = Total
End Function

' Omit plngLeft & plngRight; they are used internally during recursion
Public Sub QuickSort1(ByRef pvarArray As Variant, Optional ByVal plngLeft As Long, Optional ByVal plngRight As Long)
    Dim lngFirst As Long
    Dim lngLast As Long
    Dim varMid As Variant
    Dim varSwap As Variant

    If plngRight = 0 Then
        plngLeft = LBound(pvarArray)
        plngRight = UBound(pvarArray)
    End If
    lngFirst = plngLeft
    lngLast = plngRight
    varMid = pvarArray((plngLeft + plngRight) \ 2)
    Do
        Do While pvarArray(lngFirst) < varMid And lngFirst < plngRight
            lngFirst = lngFirst + 1
        Loop
        Do While varMid < pvarArray(lngLast) And lngLast > plngLeft
            lngLast = lngLast - 1
        Loop
        If lngFirst <= lngLast Then
            varSwap = pvarArray(lngFirst)
            pvarArray(lngFirst) = pvarArray(lngLast)
            pvarArray(lngLast) = varSwap
            lngFirst = lngFirst + 1
            lngLast = lngLast - 1
        End If
    Loop Until lngFirst > lngLast
    If plngLeft < lngLast Then QuickSort1 pvarArray, plngLeft, lngLast
    If lngFirst < plngRight Then QuickSort1 pvarArray, lngFirst, plngRight
End Sub


text:
Q: session based shopping cart Originally I got it to work fine, in passing the product id over, through the array_push() function, going from  addtocart.php to  Shoppingcart.php displaying the items. But when I add more variables/into the array_push() function, other that the single  product id $_GET['id'], ... on the next page that receives this array, it gives me an error.
The problem is:
In the original  $sql query it was getting the id it needs to display the products info from the array_push() and display it on to  Shoppingcart.php, but when I add more variables/info into the push_array() I get an error. Because its confuses the $sql query, because of the WHERE id IN clause … the ID is still in there, now along with the other info($_GET['size'] & $_GET['qty']), I just don't know how to access it...
How can I add more info into the push array, but some how define it so I can grab the id for my $sql query, to get the product info, but also have access to the size & Qty for my while() loop.
addtocart.php
array_push($_SESSION['cart'], $_GET['id']); //working MAIN
header('Location:shoppingCart.php');

How 2: array_push($_SESSION['cart'], $_GET['id'], $_GET['size'],  $_GET['qty']);
//Not Working

shoppingcart.php
    <?php
    $whereIn = implode(',', $_SESSION['cart']); //working MAIN
    $sql = " SELECT * FROM inventory WHERE id IN ($whereIn) "; ?>

 <?php while($row = mysql_fetch_array($result)) { ?>

SIZE: ""XL?? (Extra Large??)

<img src="<?php echo $row['imgThumb'];?>" />

        <p class=
STYLE#<?php echo $row['styleNUM']; ?>

<?php } ?>

A: I think making your $_SESSION['cart'] a little more complex may do the trick. Try to separate out your id and such into their own array(s). Maybe something like.
addtocart.php
if(isset($_SESSION['cart'])) {
        // Store just ids
        // Use array_unique to filter this array
        $_SESSION['cart']['id'] = array_unique($_SESSION['cart']['id']);
        // Save new cart array with that items basics
        $_SESSION['cart'][$_GET['id']]['size'][] = $_GET['size'];
        $_SESSION['cart'][$_GET['id']]['qty'][]  = $_GET['qty'];
        header('Location:shoppingCart.php');
        exit;
    }

shoppingcart.php
// Implode just the id array, no other array in the cart session
// (make sure your addtocart checks for is_numeric so you don't get someone
// injecting sql junk into your db
$whereIn    =    implode(',', $_SESSION['cart']['id']);
$sql        =    "SELECT * FROM inventory WHERE id IN ($whereIn)";

EDIT: Here is a way to do it so that you break out your items into sizes (incase you are adding multiple items with the same id but at different sizes and quantities:
    function AddToCart()
        {
            // Confirm that an id is being added
            // I am assuming there is an "add" trigger
            if(isset($_GET['add']) && is_numeric($_GET['id'])) {
                    // Create the item in the cart
                    // Record size
                    if(isset($_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']))
                        // Notice here that if there is already this item in the cart
                        // with the exact same size, it will sum
                        $_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']    +=  $_GET['qty'];
                    else
                        // If not in cart at this size, it will add qty
                        $_SESSION['cart'][$_GET['id']]['size'][$_GET['size']]['qty']    =   $_GET['qty'];
                }
        }

    // Fetch ids for your query
    function FetchItems()
        {
            if(isset($_SESSION['cart'])) {
                    foreach($_SESSION['cart'] as $itemcode => $array) {
                            $items[]    =   $itemcode;
                        }

                    return (isset($items))? $items:false;
                }
        }

    // Start the session
    session_start();

    // Add to cart
    AddToCart();
    // This will fetch your ids for your query
    $mysqlIds   =   implode(",",FetchItems());

    echo '
';
    print_r($mysqlIds);
    echo '
'; ?>

    <a href="?add=true&id=1&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 1
    <a href="?add=true&id=2&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 2
    <a href="?add=true&id=3&size=<?php echo rand(1,12); ?>&qty=<?php echo rand(0,5); ?>">ID 3

WILL GIVE YOU:
// Session array after adding items to it.
Array
(
    [cart] => Array
        (
            [2] => Array
                (
                    [size] => Array
                        (
                            [21] => Array
                                (
                                    [qty] => 1
                                )

                            [9] => Array
                                (
                                    [qty] => 2
                                )

                            [8] => Array
                                (
                                    [qty] => 0
                                )

                            [7] => Array
                                (
                                    [qty] => 20
                                )

                            [2] => Array
                                (
                                    [qty] => 5
                                )

                        )

                )

            [3] => Array
                (
                    [size] => Array
                        (
                            [9] => Array
                                (
                                    [qty] => 3
                                )

                            [1] => Array
                                (
                                    [qty] => 0
                                )

                            [7] => Array
                                (
                                    [qty] => 4
                                )

                            [10] => Array
                                (
                                    [qty] => 6
                                )

                            [3] => Array
                                (
                                    [qty] => 20
                                )

                            [2] => Array
                                (
                                    [qty] => 10
                                )

                            [12] => Array
                                (
                                    [qty] => 2
                                )

                            [6] => Array
                                (
                                    [qty] => 10
                                )

                        )

                )

            [1] => Array
                (
                    [size] => Array
                        (
                            [11] => Array
                                (
                                    [qty] => 1
                                )

                            [3] => Array
                                (
                                    [qty] => 3
                                )

                            [2] => Array
                                (
                                    [qty] => 2
                                )

                        )

                )

        )

)

// This is for the ids for your mysql query
2,3,1


text:
Q: Can't send a message when the first word of a sentence is specified I am trying to make a discord bot. I have a done a ping function when the bot answers pong. This a properly working. But now i am trying to make a music bot so the command is ~play url
I'm taking the first word of the command to be sure it's ~play. But my way to analyze the sentence is not correct apparently.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
  if (message.content === '~ping') {
    message.reply('pong');
  }
  var msg = message.content;
  var play = msg.split(" ", 1);
  if (play === '~play') {
    console.log('jioejfaoi');
  }
});

client.login('mytoken');

A: The split function returns an array, even if it has only one value.
var play = msg.split(" ", 1)[0]


text:
Q: Start Mysql when Mysql cluster is installed I have a problem with starting mysql when i have installd mysql cluster on a singel server.
I have read somewhere that if you install Mysql cluster you do not have to download the MySQL server or client (apt-get install mysql-server / client)
becuse these will end up in conflict. Mysql packets should be in the mysql-cluster-gpl-7.4.7-linux-glibc2.5-x86_64 file that I downloaded from here.
But how can I start mysql without install mysql-server or client?
If I write mysql in promp, I get this error message:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

And if i search "mysql-cluster-gpl-7.4.7-linux-glibc2.5-x86_64" then i cant find any matching files to mysqld.sock
I have also tried to start mysqld but i got alot off errors.
2015-08-19 14:52:00 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2015-08-19 14:52:00 4208 [ERROR] Can't find messagefile '/usr/local/mysql-cluster-gpl-7.4.7-linux-glibc2.5-x86_64/share/mysql/errmsg.sys'
2015-08-19 14:52:00 4208 [Warning] Can't create test file /usr/local/mysql/data/Idrottskoll.lower-test
2015-08-19 14:52:00 4208 [Warning] Can't create test file /usr/local/mysql/data/Idrottskoll.lower-test
2015-08-19 14:52:00 4208 [Warning] Buffered warning: Changed limits: max_open_files: 1024 (requested 5000)

2015-08-19 14:52:00 4208 [Warning] Buffered warning: Changed limits: table_cache: 431 (requested 2000)

2015-08-19 14:52:00 4208 [Note] Plugin 'FEDERATED' is disabled.
mysqld: Unknown error 1017
2015-08-19 14:52:00 4208 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2015-08-19 14:52:00 4208 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-08-19 14:52:00 4208 [Note] InnoDB: The InnoDB memory heap is disabled
2015-08-19 14:52:00 4208 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2015-08-19 14:52:00 4208 [Note] InnoDB: Compressed tables use zlib 1.2.8
2015-08-19 14:52:00 4208 [Note] InnoDB: Using Linux native AIO
2015-08-19 14:52:00 4208 [Note] InnoDB: Using CPU crc32 instructions
2015-08-19 14:52:00 4208 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-08-19 14:52:00 4208 [Note] InnoDB: Completed initialization of buffer pool
2015-08-19 14:52:00 4208 [ERROR] InnoDB: ./ibdata1 can't be opened in read-write mode
2015-08-19 14:52:00 4208 [ERROR] InnoDB: The system tablespace must be writable!
2015-08-19 14:52:00 4208 [ERROR] Plugin 'InnoDB' init function returned error.
2015-08-19 14:52:00 4208 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2015-08-19 14:52:00 4208 [ERROR] mysqld: unknown option '--ndbcluster'
2015-08-19 14:52:00 4208 [ERROR] Aborting

2015-08-19 14:52:00 4208 [Note] Binlog end
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'partition'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_METRICS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMPMEM'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_CMP'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_LOCKS'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'INNODB_TRX'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'ARCHIVE'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'BLACKHOLE'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'CSV'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'MRG_MYISAM'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'MEMORY'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'MyISAM'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'sha256_password'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'mysql_old_password'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'mysql_native_password'
2015-08-19 14:52:00 4208 [Note] Shutting down plugin 'binlog'
2015-08-19 14:52:00 4208 [Note]

I'm obviously new to programming, and could really use your help to explain how mysql works with mysql cluster.
I have followed the following link to install mysql cluster:
Mysql Cluster seems to work:
[ndbd(NDB)] 1 node(s)
id=2    @46.21.99.140  (mysql-5.6.25 ndb-7.4.7, Nodegroup: 0, *)

[ndb_mgmd(MGM)] 1 node(s)
id=1    @46.21.99.140  (mysql-5.6.25 ndb-7.4.7)

[mysqld(API)]   1 node(s)
id=3    @46.21.99.140  (mysql-5.6.25 ndb-7.4.7)

If I type: ps aux | grep mysql
root      3800  0.0  0.0   4440   752 ?        S    14:24   0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/usr/local/mysql/data --pid-file=/usr/local/mysql/data/myname.pid

mysql     3951  0.4  5.7 1514076 465052 ?      Sl   14:24   0:05 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/usr/local/mysql/data/myname.err --pid-file=/usr/local/mysql/data/myname.pid --socket=/tmp/mysql.sock

my.cnf

[mysqld]
# Options for mysqld process:
ndbcluster                      # run NDB storage engine

basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
#socket= /tmp/mysql.sock

[mysql_cluster]
# Options for MySQL Cluster processes:
ndb-connectstring=xx.xx.xx.xxx  # location of management server

A: Now it works! I replaced #socket= /tmp/mysql.sock with socket=/var/run/mysqld/mysqld.sock and removed the commented. Created a folder called mysqld and a new file in that folder called mysqld.sock.
After reboot mysql started!
Thanks Marc B for your help!


text:
Q: Is this an efficient way of doing a linq query with dynamic order by fields? I have the following method to apply a sort to a list of objects (simplified it for the example):
private IEnumerable<Something> SetupOrderSort(IEnumerable<Something> input,
    SORT_TYPE sort)
{
    IOrderedEnumerable<Something> output = input.OrderBy(s => s.FieldA).
        ThenBy(s => s.FieldB);
    switch (sort)
    {
        case SORT_TYPE.FIELD1:
            output = output.ThenBy(s => s.Field1);
            break;
        case SORT_TYPE.FIELD2:
            output = output.ThenBy(s => s.Field2);
            break;
        case SORT_TYPE.UNDEFINED:
            break;
    }
    return output.ThenBy(s => s.FieldC).ThenBy(s => s.FieldD).
        AsEnumerable();
}

What I needs is to be able to insert a specific field in the midst of the orby clause.  By default the ordering is: FIELDA, FIELDB, FIELDC, FIELDD.
When a sort field is specified though I need to insert the specified field between FIELDB and FIELDC in the sort order.
Currently there is only 2 possible fields to sort by but could be up to 8.  Performance wise is this a good approach?  Is there a more efficient way of doing this?
EDIT: I saw the following thread as well: Dynamic LINQ OrderBy on IEnumerable<T> but I thought it was overkill for what I needed.  This is a snippet of code that executes a lot so I just want to make sure I am not doing something that could be easily done better that I am just missing.

A: Don't try and "optimize" stuff you haven't proved slow with a profiler.
It's highly unlikely that this will be slow enough to notice. I strongly suspect the overhead of actually sorting the list is higher than switching on one string.
The important question is: Is this code maintainable? Will you forget to add another case the next time you add a property to Something? If that will be a problem, consider using the MS Dynamic Query sample, from the VS 2008 C# samples page.
Otherwise, you're fine.

A: There's nothing inefficient about your method, but there is something unintuitive about it, which is that you can't sort by multiple columns - something that end users are almost sure to want to do.
I might hand-wave this concern away on the chance that both columns are unique, but the fact that you subsequently hard-code in another sort at the end leads me to believe that Field1 and Field2 are neither related nor unique, in which case you really should consider the possibility of having an arbitrary number of levels of sorting, perhaps by accepting an IEnumerable<SORT_TYPE> or params SORT_TYPE[] argument instead of a single SORT_TYPE.
Anyway, as far as performance goes, the OrderBy and ThenBy extensions have deferred execution, so each successive ThenBy in your code is probably no more than a few CPU instructions, it's just wrapping one function in another.  It will be fine; the actual sorting will be far more expensive.


text:
Q: Block Bad Bots in Nginx for Multiple Sites I need to block a bunch of robots from crawling a few hundred sites hosted on a Nginx web server running on a Ubuntu 16.04 machine.
I've found a fairly simple example here
(important part of the code is below) but it seems that this functionality is available only inside of a server block (because of the IF statement) and I think this is a horrible idea, especially with a large number of sites on the machine.
  if ($http_user_agent ~* (ahrefs|wget|crawler|majestic) ) {
    return 403;
  }

So, the question is can something similar be achieved from the main nginx.conf file and work for all the domains currently defined in the sites-enabled folder and the ones added in the future?
I've also read about the map approach and found a whole project on GitHub that uses it - https://github.com/mariusv/nginx-badbot-blocker but it still requires editing of all the files in the sites-enabled folder and this will take too much time for a few hundred already up and running sites.


text:
Q: headers for more than one line How can I read header from mail? Is there regex to do it? I have especially problem with headers like these:
From: John Doe <example@example.com>
MIME-Version: 1.0
Content-Type: multipart/mixed;
        boundary="XXXXboundary text"

What is the space before boundary? Is it tab or what?

A: What language?
I recommend perl for this task.  Visit cpan.org and get MIME::Tools if your perl installation doesn't come with those modules.


text:
Q: Cannot merge node using null property even if there'are not null values I want to create my first project in Neo4j and I was trying to import data from a csv file.
The data looks like this:
category, film, name, winner(y/n), year
My table doesn't have null values or empty rows. When I tried this statement, it gave me the following error:

Cannot merge node using null property value for value

However, I don't have null in the year column.
LOAD CSV FROM "file:///golden_globe.csv" AS row WITH { category: row[0], film: row[1], nomination_name: row[2],
   winner: row[3], year: row[4]} AS data

SKIP 1
MERGE (y:Year {value:data.year})
MERGE (c:Category {name: data.category})
MERGE (n:Nomination {name: data.nomination_name})
MERGE (m:Movie {title: data.film})
CREATE (a:Golden_Globe) SET a = data
CREATE (c)<-[:IN_CATEGORY]-(a)-[:IN_YEAR]->(y)
CREATE (a)-[:NOMINATED]->(n), (a)-[:FOR_MOVIE]->(m)
MERGE (n)-[:ACTED_IN]->(m)
WITH * WHERE data.winner = "yes" SET a:Winners;

What is causing the error?


text:
Q: Getskel.com - Firefox mobile not recognize template as mobile I'm using Getskel.com as responsive framework. It perfect works on every device and every browser, except Firefox mobile on android. Debugging it using ADP.exe I found that the template is recognized as desktop instead of mobile. This is my skel.init:
    skel.init({
    reset: 'full',
    breakpoints: {
        'global': { range: '*', href: '/templates/responsivegs/css/style.css' },
        'desktop': { range: '737-', href: '/templates/responsivegs/css/style-desktop.css', containers: 1200, grid: { gutters: 25 } },
        '1000px': { range: '737-1200', href: '/templates/responsivegs/css/style-1000px.css', containers: 1000, grid: { gutters: 20 }, viewport: { width: 1080 } },
        'mobile': { range: '-736', href: '/templates/responsivegs/css/style-mobile.css', containers: '100%!', grid: { collapse: true, gutters: 20 }, viewport: { scalable: false } }
    },

Do anybody have had the same problem?

A: Yes I have the same problem and I noticed that in newer version of skel.js media recognition is chaged to
        // Global.
            global: {
                href: 'css/style.css',
                containers: 1400,
                grid: {
                    gutters: ['2em', 0]
                }
            },

        // XLarge.
            xlarge: {
                media: '(max-width: 1680px)',
                href: 'css/style-xlarge.css',
                containers: 1200
            },

        // Large.
            large: {
                media: '(max-width: 1280px)',
                href: 'css/style-large.css',
                containers: 960,
                grid: {
                    gutters: ['1.5em', 0]
                },
                viewport: {
                    scalable: false
                }
            },

        // Medium.
            medium: {
                media: '(max-width: 980px)',
                href: 'css/style-medium.css',
                containers: '90%',
                grid: {
                    zoom: 2
                }
            },

        // Small.
            small: {
                media: '(max-width: 736px)',
                href: 'css/style-small.css',
                containers: '90%',
                grid: {
                    zoom: 3,
                    gutters: ['1.25em', 0]
                }
            },

        // XSmall.
            xsmall: {
                media: '(max-width: 480px)',
                href: 'css/style-xsmall.css',
                grid: {
                    zoom: 4
                }
            }

A: I found a workaround! Ii think is a bug of the old version of skel.js
Try to change:
'1000px': { range: '737-1200', href: '/templates/responsivegs/css/style-1000px.css', containers: 1000, grid: { gutters: 20 }, viewport: { width: 1080 } },

in:
'1000px':   { range: '(min-width: 737px) and (max-width: 1200px)', href: '/templates/responsivegs/css/style-1000px.css', containers: 1000, grid: { gutters: 20 }, viewport: { width: 1080 } },


text:
Q: Java Google App Engine won't send email via Mailgun SMTP I have followed through the tutorials and set up the GCP firewalls for both ingress and outgress on the port 2525. Running the code locally on my machine successfully sends the email however, deploying the project to App Engine Standard (Java runtime) does not throw an error but also does not send the email.
I also have a GCP VM instance that is also able to send the email. Does anyone know what could be causing this?
Dependencies :
Dependencies
    String email = "target@email.com";
    String API_KEY = "KEY";

    HttpResponse<JsonNode> req = Unirest.post("https://api.mailgun.net/v3/" + "my.custom.domain" + "/messages")
            .basicAuth("api", API_KEY)
            .field("from","Admin <admin@my.custom.domain>")
            .field("to", email)
            .field("subject","Welcome!")
            .field("text", "testing")
            .asJson();
    req.getBody();

throws :
        Exception in thread "main" java.lang.ExceptionInInitializerError
         at tech.incineratez.email.Main.main(Main.java:14)
    Caused by: kong.unirest.UnirestException: It looks like you are using an
    older version of Apache Http Client.
    For security and performance reasons Unirest requires the most recent
    version. Please upgrade.
    at kong.unirest.Config.setDefaults(Config.java:109)
    at kong.unirest.Config.<init>(Config.java:85)
    at kong.unirest.Unirest.<clinit>(Unirest.java:30)
    ... 1 more
    Caused by: java.lang.BootstrapMethodError: java.lang.IllegalAccessError:
    no such constructor: kong.unirest.apache.ApacheAsyncClient.<init>
    (Config)void/newInvokeSpecial
    at kong.unirest.Config.setDefaults(Config.java:106)
    ... 3 more
    Caused by: java.lang.IllegalAccessError: no such constructor:
    kong.unirest.apache.ApacheAsyncClient.<init>(Config)void/newInvokeSpecial
    at
java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:483)
    ... 4 more
    Caused by: java.lang.NoClassDefFoundError:
    org/apache/http/nio/reactor/ConnectingIOReactor
    at java.lang.invoke.MethodHandleNatives.resolve(Native Method)
    at java.lang.invoke.MemberName$Factory.resolve(MemberName.java:975)
    at java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1000)
    at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1394)
    at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(MethodHandles.java:1750)
    at
java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(MethodHandleNatives.java:477)
    ... 4 more
    Caused by: java.lang.ClassNotFoundException: org.apache.http.nio.reactor.ConnectingIOReactor
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 10 more
Working code if ran seperately on my computer and not on the Google Cloud Platform :
                Properties props = System.getProperties();
                props.put("mail.smtps.host", "smtp.mailgun.org");
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.port", "2525");

                Session session = Session.getInstance(props, null);
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("admin@my.custom.domain"));

                InternetAddress[] addrs = InternetAddress.parse(email, false);
                msg.setRecipients(Message.RecipientType.TO, addrs);

                msg.setSubject("Welcome!");
                msg.setText("Test");
                msg.setSentDate(new Date());

                SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
                t.connect("smtp.mailgun.org", "postmaster@my.custom.domain", "KEY");
                t.sendMessage(msg, msg.getAllRecipients());

                System.out.println("Email sent" + t.getLastServerResponse());

                t.close();

Dependencies : Dependencies2
The code above when ran on the Google Cloud Platform does nothing at all.

A: I'm guessing you are talking about this tutorial to configure the sending of mails through Compute Engine (which explains why it works well on your VM instance).
That tutorial is for Compute Engine, in the case of App Engine Standard applications, you have the option of using Mail API, however, since Google is no longer accepting quota increases for that API, is advised to use a third-party service such as MailGun or SendGrid.
To connect your App Engine standard application (with Java runtime) with those third-party services you will need to specify the "dependicies" on your "pom.xml" file and modify your "app.yaml" with the API Key:
env_variables:
     EMAIL_API_KEY: key-from-third-party

The Email API Key will be provided by the third-party service, for example, in the case of MailGun, their documentation specifies the following:

When you sign up for an account, you are given an API key. You
  authenticate to the Mailgun API by providing your API key in the
  request. You can manage your API key in the "Security" tab under the
  Account section of the Control Panel.

For the step by step instructions on how to configure your App Engine Standard App to connect with these third-party services, please refer to this documentation.
EDIT:
It looks like in your case, you could be using another dependencies (hence, the dependency error). When you created the code did you refereed to the App Engine Java 8 documentation samples or to the Mailgun samples? because I noticed they use different dependencies, and also the App Engine sample uses env variables (which according to the snippet code you shared, you are not using).
My advice is to follow the sample given for Google App Engine Standard Java 8.
These are the steps I took to get the sample successfully up and running on App Engine:
1. Downloaded the sample code.
2. Created an account on Mailgun (simple account, not credit data attached). You will need to verify your account through the specified email.
3. Once your are logged inside MailGun, you will see a menu on the left, navigate to Sending > Overview page.
4. At the right you will see an "Authorized Recipients" box, add the email or the person that will receive the email, they will need to confirm also on their side, so try adding an email on which you have access for the sake of the test. Note: you need to do this if you haven't verified your domain.
5. Copy the value of the domain you have for default (or the one you have verified).
6. On the same box there's a menu with the link to "Api Keys", click on it and copy the key under "HTTP webhook signing key" (this is also your private key, so be careful where you put it).
7. Head to the GCP sample that was downloaded, and edit the file "/mailgun/src/main/webapp/WEB-INF/appengine-web.xml" with those values (domain and key).
8. If you are using Maven run the commands:
mvn appengine:run  (if you want to test locally)

or
mvn appengine:deploy (if you want to deploy to App Engine)

note: some of these steps might have look rather obvious for you but I have explained it this way so other people can follow it as well.


text:
Q: Iframe not launching URL just by changing subdmain (not a X-Frame-Options issue) I set up a wildcard SSL certificate on *.clipr.co, from Amazon AWS.
But I have a subdomain (adyoulike) that could not be launched in a iframe.
Iframe provides no error in console, and this is NOT a X-Frame-Options issue.
Ex with two subdomains mysecurite & adyoulike. There is not a single line of code or server configuration that is mentioning one of these two, so the exact same code is running.
It looks like iframe does not even try to launch adyoulike.clipr.co.

We are on AWS, using Route 53 for routing and Beanstalk to run our code. But I doubt this is a AWS issue. SSL certificate has been generated with AWS too.
Does anyone encoutered the same issue ?
EDIT : Miss the codepen link to show the evidence :
https://codepen.io/anon/pen/bJomay

A: The content of the second iframe (which has "adyoulike", which starts with "ad", in the hostname) loads … but only after I disable my advert-blocking privacy filters.

A: This might be caused by the browsers "Same origin Policy" which only allows content from one domain to be loaded.
If you need cross origin content you need to set the Access-Control-Allow-Origin header to the required domains


text:
Q: Plot cumulative distribution with networkx and numpy I want to implement the cumulative distribution for a graph. Here is my code:
g = nx.read_edgelist('graph', create_using= nx.Graph(), nodetype=int)
degree_sequence = sorted([d for n, d in g.degree()], reverse=True)  # degree sequence
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
cs = np.cumsum(deg)
plt.loglog(deg, cs, 'bo')
plt.title("Cumulative Distribution plot")
plt.ylabel("Sample with value > Degree")
plt.xlabel("Degree")
plt.show()

To plot cumulative I know that I must have at the x-axis the degree and in the y-axis the samples with value > Degree. The result using my code is the following:

But the expected result must be something like this:

I am not sure if I am getting the expected plot using my code. Can anyone help me and explain me if is something wrong?

A: I believe it should be:
cs = np.cumsum(cnt)

Full code:
g = nx.read_edgelist('graph', create_using= nx.Graph(), nodetype=int)
degree_sequence = sorted([d for n, d in g.degree()], reverse=True)  # degree sequence
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
cs = np.cumsum(cnt)
plt.loglog(deg, cs, 'bo')
plt.title("Cumulative Distribution plot")
plt.ylabel("Sample with value > Degree")
plt.xlabel("Degree")
plt.show()

Usually when implementing cumulative degree distributions you want the total number of counts until a given degree, P(K<k).


text:
Q: Can a child post an app to the app store? I am 11 years old, and I have made an app I want to post to the App Store. Is there any way to do that, or do I have to use my mom's account? (I have an Apple id because of Family Sharing)

A: The Apple discussions thread can i be an apple developer under 18? is exactly what your are looking for :

No. An adult would have to do that for you. To have a developer
  account you must be 18 or older.

…

You can always start a corporation and the individual age restriction
  is not relevant anymore.

A: Yes and no.
Strictly speaking you need to register as a developer and to do that as an individual you need to meet minimum age requirements. Typically this is 18, although it could be different in various countries.
Also, depending on your jurisdiction, there may be other requirements you must meet before being able to register as a developer.
In your case, you could have a parent register and then use their developer account. When uploading an app you need to complete a number of metadata fields, one of which is who the app is copyrighted to. So you could still put your name in that field.
Another option is to set up a company (or something similar) in which case there wouldn't be the age restriction. However, depending on your jurisdiction there could be an age requirement for registration of a company.
A good place to start (if you haven't already) is to explore https://developer.apple.com for answers to your questions.


text:
Q: Operating on the lists in a list, storing the result in the global environment I am using mice library(mice) to impute a large amount of databases.
I have written a code which makes imputations for all dataframes in my global environment.
The result of this exercise is a large list of lists called dfmice.
For each list within the list, I would like to use the complete operation of mice
Manually I could do this by doing the following:
list1 <- list(a = 2, b = 3)
list2 <- list(c = "a", d = "b")
dfmice <- list(list1, list2)

library(mice)
listitem1 <- dfmice[[1]]
listitem1 <- mice::complete(listitem1)
listitem2 <- dfmice[[2]]
listitem2 <- mice::complete(listitem2)
etc.

I however need to do this for about 450 dataframes.
How do I write the loop that does this automatically for each item in the list? I was thinking of something like (thanks @A. Suliman !):
try (for (i in 1:length(dfmice))  {
  tryCatch({
    listitem[i]=mice::complete(dfmice[[i]])
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
})

This works, but somehow gives a list where, what should be a dataframe, turns out to be just 1 column. Apparently I am feeding the code a column instead of a dataframe somewhere.
I saw this link: R operating on lists within lists
and tried the following without succes:
dfmiceimp <- rapply(dfmice, mice::complete, how = "list" )

Error in (function (data, action = 1L, include = FALSE, mild = FALSE,  :
  'data' not of class 'mids'

I would be very happy when someone could show me how to write the syntax for this.


text:
Q: Regex for multiple spaces between words I need a regex that detects words inside a string. My regex works fine when the class consists of a single word, but not for multiple words.
function repl(string){
  return string.replace(// , (n)=>{
  return <Symbol/>
}
}

Works:
repl('') /==> <Symbol/>

Does not work:
repl('')

A: You can simplify your expression to: //i
Make sure your HTML element attributes are double-quoted.
Note: Please be aware that the closing  tag is mandatory and should never be ommited.

const repl = (str) =>
  str.replace(//i, () => '<Symbol />');

console.log(repl(''));
console.log(repl(""));
console.log(repl(''));


text:
Q: Show method name in "Find all references" - C# Visual Studio When i rightclick something in visual studio and press Find all references i get a list of all locations where this object occur.
Is there any way to also show the scope of this location (Namespace.Class.Method) instead of just a line-number. Now i have to doubleclick all of the results to see where it actually is.

A: One more vote for ReSharper.  Check here for some screenshots as to the type of results.  You can change how the results are presented (My favourite is Project+Namespace+Member, so I can see which methods the references are coming from.)
You also have a few options to refine your searches.  For example:

*

*Search project / file or even include referenced libraries

*Search for Read or Write usages

*Search for "text" matches

They have a free trial available... try it out.

A: Sorry, for this you'll need a productivity tool, like Reshaper. (Other productivity tools, such as DevExpress, do exist, however I don't know if they also provide such a feature.)

A: Using the default feature in Visual Studio, you can't achieve that. The Find All References seems to use the same search engine as the Find In File.
As M.Chohan said, a plugin like Reshaper or DevExpress CodeRush might have the feature you are seeking.


text:
Q: Unique key, INSERT IGNORE and table partitioning So I have a table:
CREATE TABLE `slots` (
 `customerid` int(11) NOT NULL,
 `orderid` int(11) NOT NULL,
 `queueid` int(11) NOT NULL AUTO_INCREMENT,
 `item_id` int(3) NOT NULL,
 `variable1` int(3) NOT NULL,
 `variable2` int(3) NOT NULL,
 `variable3` int(3) NOT NULL,
 `variable4` int(3) NOT NULL,
 `variable5` int(3) NOT NULL,
 `variable6` int(3) NOT NULL,
 `variable7` tinyint(1) NOT NULL,
 `variable8` tinyint(1) NOT NULL,
 `variable9` tinyint(1) NOT NULL,
 PRIMARY `queueid` (`queueid`),
 UNIQUE KEY (`customerid`,`orderid`),
 KEY `orderid` (`orderid`)
) ENGINE=InnoDB AUTO_INCREMENT=25883472 DEFAULT CHARSET=latin1

That I want to partition horizontally by customerid. The problem is that customerid and orderid must form a unique combination -> I've created an unique key for that and use INSERT IGNORE to ignore inserts that would result in a duplicate row.
Would that still work with partitioned table? Or it wouldn't help with my insert speed (I am partitioning the table to achieve higher INSERT speed  but I still need to watch out to not insert one row multiple times ).

A: In this case if you want to partition based on customerId & also want to keep UNIQUE KEY on customerId & orderId
Add customerId to your PK
MySQL doc says
every unique key on the table must use every column in the table's partitioning expression. (This also includes the table's primary key, since it is by definition a unique key.

So customerId should be part of both UNIQUE KEY as well PRIMARY KEY.

A: The partitioning docs have this to say;

All columns used in the partitioning expression for a partitioned table must be part of every unique key that the table may have.

In other words, it will work as long as you're partitioning on customerid, orderid or both, otherwise your unique key is invalid.


text:
Q: htaccess redirect a specific page with cookie value if exists otherwise redirect another page I'm using the below redirection code in php but this should be done in htaccess. Please help me.
//when user open this link
$canonical="/category/story/horror/?search=ghost&page=2";
if(empty($_COOKIE['lang']))
{
  //asking user to select the language. then store it in cookie.
} else
{
  //redirect him to language page
  $canonical="/category/story/horror/en/?search=ghost&page=2";
}

These are dynamic pages. So I can't add language to the menu directly. The user will click on the type or category on the homepage. On the type or category page ("/category/story/love") it will open in the default language (I get it via the location API) but a pop-up will open immediately to confirm the user's language. If a user clicks on a language there, it will be redirected to another page for that language.("/category/story/love/en/" or "/category/story/love/fr/"). This link will be available for all searches and filters from now on. But the only thing is, the first link does not have any language name, because it can be opened from the main menu or social media.
RewriteRule ^category/([A-Z0-9_-]+)/([A-Z0-9_-]+)/?$ message/?type=$1&category=$2 [NC,QSA,L]
RewriteRule ^message/([A-Z]{2})/?$ message/?lang=$1 [NC,QSA,L]
RewriteRule ^type/([A-Z0-9_-]+)/?$ message/?type=$1 [NC,QSA,L]
RewriteRule ^category/([A-Z0-9_-]+)/([A-Z0-9_-]+)/?$ message/?type=$1&category=$2 [NC,QSA,L] [NC,QSA,L]

These are previous redirections. See the last two. Now I need to find out if there is a cookie labeled "lang" and use this cookie name in the last two URLs above. Something like below:
RewriteCond %{HTTP_COOKIE} !lang=$name [NC]
RewriteRule ^type/([A-Z0-9_-]+)/{$name}/?$ message/?type=$1 [NC,QSA,L]
RewriteRule ^category/([A-Z0-9_-]+)/([A-Z0-9_-]+)/{$name}/?$ message/?type=$1&category=$2 [NC,QSA,L]

Please guide me with right syntax.


text:
Q: how to obtain value from scanner without printing on screen So I'm creating a sorting machine using a USB scanner and raspberry pi. The bar code value scanned must be checked in the database. If its marked as pass then machine continues to move, else if its marked as fail in database then the machine stops. Now I dont want the scanner input to be printed on the screen, how can I use the bar code value in the program without printing on screen. Im using python to program.
    from Tkinter import *
    import Tkinter as tk
    import MySQLdb

   #creating window and entry box
   root=Tk()
   root.title("PCBA Registration")

    entry=Entry(root,fg="black",bg="white",width=15)
    entry.grid(row=0,column=4,sticky=W)
    entry_value=entry.get()
   #label
    label1=Label(root,bg="black",fg="white",text="SCAN   HERE").grid(row=0,column=2,stick=W)

    def check():
          db=MySQLdb.connect (host='localhost', user = "root", passwd = "passwd", db = "server")

   #creation of cursor to access database
      cur=db.cursor()
      do1="SELECT Workorder_No FROM pcba_registration where PCB_Sno='%s'" %(entry.get())
      cur.execute(do1)
workorder=cur.fetchall()
      for row1 in workorder:
            print row1[0]
            workorder_value=row1[0]
      do2=("SELECT approval_Status FROM workorder_release where  workOrder_No='%s'" %(workorder_value))
      cur.execute(do2)
      status=cur.fetchall()
      print status
      for row2 in status:
          print row2[0]

  check=Button(root,text="CHECK",width=5,command=check).grid(row=2,column=4,stick=W)

     #to run main loop
    if __name__ == '__main__':
          root.mainloop()

For now I have created an interface using Tkinter to to print out the scanned bar code. But I dont want that. Im an absolute beginner and new to stack overlflow too. Please help me! Thanks!


text:
Q: MVC linq query and dropdown lists I am trying to get details from the database to be edited. It actually works fine, my problem is that I am also trying to populate data from the db to two dropdown lists (these dropdown lists work fine with the "create" ActionResult
Could you guys kindly provide some examples on how to include the dropdown lists in the controller to be passed to the view?
Please see below: the area within comments (//) is what I want to do, but it only brings the fields empty in the view. The area outside the comments works fine (brings the details from the database, without the dropdown lists, though).
 // GET: /PropertiesHut/EditRent/3
    public ActionResult EditRent(int id)
    {
        //AdDetail ad = db.AdDetails.Single(a => a.AdType == id);

        //var vm = new InsertAd()
        //     {
        //         AdDetail = ad,
        //         PropertyType = new SelectList(db.PropertyTypes.OrderBy(o =>
        //           o.PropertyName).ToList(), "PropertyId", "PropertyName"),

        //         State = new SelectList(db.States.OrderBy(o =>
        //           o.StateShortName).ToList(), "StateId", "StateShortName")
        //     };
        //return View(vm);

// THIS IS WHAT WORKS
        var viewModel = from a in db.AdDetails
                        where a.AdType == id
                        select a;

        return View(viewModel.FirstOrDefault());
    }

A: Controller:
ViewBag.RgnId = new SelectList(
     _db.Regions
     .OrderBy(r => r.name)
     .Select(x => new { x.id, x.name }), "id", "name", model.RgnId);

HTML:
@Html.DropDownListFor(model => model.RgnId, (SelectList)ViewBag.RgnId, "Any Region")


text:
Q: "The earliest being" or "the earliest of which is"? I have just received the following correction:

These date back to trigonometric and logarithmic tables, the earliest of which being [is]  a base-10 logarithm table from Briggs (1617).

with the suggestion:

either use "the earliest being ..." or "the earliest of which is ...".

Please could someone expand on which is better for what context, or are they interchangeable? Only British English please.


text:
Q: VS Code File Explorer filter not including all matches When I click into the VS Code v1.71.2 file explorer, press ctrl+F to open the file explorer search option, and type the name of the file I want to search for, VSCODE only pulls up some of the matches, but not nearly all of them. In fact, it only seems to randomly reveal file matches that I've recently opened or opened the parent folder of. What's with this random behavior? I tried closing and re-opening vscode to no avail. I still only get a couple matches out of 50 files with that name:

A: Command palette (Ctrl + P) does fuzzy search on the entire solution when used without any modifiers.
Note that opening the command palette with Ctrl + Shift + P would append the ">" modifier and set the palette into command mode.


text: Q: MySQL in directory of java project I am creating a Java Swing application in netbeans. I am using MySQL for database and I don't want to host my database online. So is there a way that I can move my MySQL database files in the project folder so that when I make the .exe file the database can be used in all devices.


text:
Q: How to initialize an array of arrays with non-constant length? I am trying to make an array which contains 1D arrays of varying length. Due to the variation in length, I cannot use a 2D array. My code is as follows:
int ROW = 6;
int COL = 4;
int faceverts[6][4] = {{3,2,1,0}, {4,5,1,0}, {2,6,5,1}, {2,3,5,6}, {7,3,0,4}, {1,6,7,4}};
int (*q)[4] = faceverts;

int main(){
    for (int i = 0; i < ROW; i++){
        for (int k = 0; k < COL; k++)
            printf("%d ", *(*(q+i)+k));
        printf("\n");
    }
}

My goal is to be able to get rid of those ROW and COL variables, as well as not have a fixed 2D array, but rather an array of 1D arrays of varying length. I have been told that using pointers is key to doing this task, but I do not know how to do this myself.

A: One approach is to create an array of structures.  Each structure element contains a pointer and count to  an array.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
  int *a;
  size_t n;
} TwoD;

#define AN(a) (sizeof (a)/sizeof (a)[0])

int smallest[1] = { 1 };
int smaller[2] = { 2, 3 };
int small[3] = { 4, 5, 6 };
int big[4] = { 7, 8, 9, 10 };
int bigger[5] = { 11, 12, 13, 14, 15 };
int biggest[6] = { 16, 17, 18, 19, 20, 21 };

TwoD faceverts[6] = {
    { smallest, AN(smallest) }, { smaller, AN(smaller) }, { small, AN(small) },
    { big, AN(big) }, { bigger, AN(bigger) }, { biggest, AN(biggest) } };

int main(void) {
  // Let us change things a bit at run time
  int change[] = { 22,23,24,25,26,27,28 };
  faceverts[0] = (TwoD) {change, AN(change)};  // compound literal
  for (size_t row = 0; row < AN(faceverts); row++) {
    for (size_t col = 0; col < faceverts[row].n; col++) {
      printf(" %d", faceverts[row].a[col]);
    }
    printf("\n");
  }
  return 0;
}

Output
 22 23 24 25 26 27 28
 2 3
 4 5 6
 7 8 9 10
 11 12 13 14 15
 16 17 18 19 20 21

A: There is only 1D array in memory. (2D array is actually a long 1D array)
Allocate a 2D array (rows, cols)
int *arr;
int size;
size = width * height;
arr = (int *) malloc(sizeof(int) * size);

Access element (x, y) in the array
int e;
int offset;
offset = x * cols + y;
e = *(arr + offset);

Free the array
free(arr);

Allocate a irregular 2D array (col_0, col_2, ...., col_n-1);
int arr;
int size = 0;
// size = col_0 + ... + col_n-1;
arr = (int *) malloc(sizeof(int) * size);

Access element (x_row, y_col) in the array
int e;
int offset;
// offset = col_1 + ... + col_x-1 + y_col;
e = *(arr + offset);


text:
Q: How to get the bounded rectangle of a particular word in a TextView/EditText in android I have a multi-line TextView and I want to get the bounded rectangle of a particular word in that TextView. I have ClickableSpan Text in TextView, so when user clicks on a word, I want to show him/her a small window above that word. But to achieve this I must know the location of that word in that TextView or in that Windows.
Till now I can detect the exact word user has clicked. Any help would be appreciated. :)
P.S: Of course I can get the bounding rectangle of TextView as a whole but I want it at character/word level or AT LEAST LINE LEVEL.


text:
Q: Как задать столбцу GridView отдельную вьюху? В столбце очень много всего и одной лямбдой не обойтись. Мне надо вынести столбец в отдельный файл. Не нашел нигде как такое сделать стандартными средствами. Т.е. мне надо что-то вроде свойства itemView в ListView.

A: Пока что решил так:
$getRenderer = function($view) {
    return function($model) use($view) {
        return $this->render($view, ['model' => $model]);
    };
};

// и в столбце

'value' => $getRenderer('my_view'),

Но очень надеюсь что все-же предусмотрено какое-то стандартное решение типа того же itemView у ListView.


text:
Q: send SCSI commands using C# I'm controlling my self-designed USB device using SCSI interface with C by opening a file handle, ioctl and using sg_io_hdr_t structure. I have to design a GUI, and i should do that with C#. I am not too familiar with C#. Could u suggest a way to do that with C#

A: You have a few options
1- Use p/invoke (platform invoke) interoperability. Using this you can do one of two things. Either use p/invoke to call the Win32 api from .NET, alternatively you can write a C dll that exports a simplified interface to control the device and then interop to this dll.
2- You could use managed C++, and create a library that you can call from C#.
3- You could wrap your C code as a COM object and use COM interop from C#.
Since you presumably have some working C code, I think the easiest would be to create a DLL that exports a easy to invoke interface and then use P/Invoke to call that from C#


text:
Q: How can I pass data from collectionView and tableView to detailViewController? I can get the segue to work, however none of the data from either the collection/table viewController's will pass to the detail (I get just the white screen.)
This is the collectionViewController (named MemeCollectionViewController)
import UIKit
import Foundation

class SentMemesCollectionViewController: UICollectionViewController {

    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!

    var _collectionView = SentMemesCollectionViewController!.self

    //calling memes from array in Delegate
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var memes: [Meme] {
        return appDelegate.memes
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        collectionView?.reloadData()

        flowLayoutSettings()

    }
    func flowLayoutSettings() {

        let space: CGFloat = 3.0
        let dimension = (self.view.frame.size.width - (2 * space)) / 3

        flowLayout.minimumInteritemSpacing = space
        flowLayout.minimumLineSpacing = space
        flowLayout.itemSize = CGSize(width: dimension, height: dimension)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                return memes.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MemeCollectionViewCell", for: indexPath) as! MemeCollectionViewCell

        let meme = self.memes[indexPath.item]
        cell.getCellMeme(meme.memedImage)

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MemeDetailViewController" ,
        let nextScene = segue.destination as? MemeDetailViewController ,
            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: "MemeCollectionViewCell", for: IndexPath) {
            let selectedMeme = memes[IndexPath]

        }
    }

}
The tableViewController which is named MemeTableViewController
    import UIKit

class SentMemesTableViewController: UITableViewController {

    var _tableView: UITableView!
    var memeData: [Meme] = []

    //calling memes from array in Delegate
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var memes: [Meme] {
        return appDelegate.memes

    }

    override func viewWillAppear(_ animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.isScrollEnabled = true

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "MemeDetailViewController" ,
        let _ = segue.destination as? MemeDetailViewController,
            let indexPath = tableView.indexPathForSelectedRow {
            let selectedMeme = memeData[indexPath.row]
            _ = SentMemeImage(memedImage: selectedMeme.memedImage)
        }
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            //navigationController!.pushViewController(MemeDetailViewController, animated: true)

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return memes.count
    }

    // Here it is! -----

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let tableViewCell = tableView.dequeueReusableCell(withIdentifier: "sentMemesTableView") as! MemeTableViewCell
        let meme = memes[indexPath.row]

        tableViewCell.tableViewImage.image = meme.memedImage
        tableViewCell.tableViewLabel.text = "\(meme.topText)...\(meme.bottomText)"

        return tableViewCell
    }

    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return false

    }

    func deleteMemesInTableViewCell(_ index: Int) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.memes.remove(at: index)
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.delete) {
            tableView.beginUpdates()
            deleteMemesInTableViewCell(indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
            tableView.endUpdates()
        }

    }
}

Heres is the detailController, named MemeDetailViewController
    import UIKit

class MemeDetailViewController: UIViewController {

    var meme: SentMemeImage?

    @IBOutlet weak var sentMemesBtn: UIBarButtonItem!
    @IBOutlet weak var editBtn: UIBarButtonItem!
    @IBOutlet weak var sentMemeView: UIImageView!

    override func viewWillAppear(_ animated: Bool) {
        displayMeme()
    }

    func displayMeme() {
        self.sentMemeView.image = self.meme?.memedImage

    }

    @IBAction func launchMemeEditorViewController(_ sender: Any) {
        _ = navigationController?.popViewController(animated: true)

    }

    //unwinding to the view before (the collectionView, or the tableView)

    @IBAction func unwindVC(for unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
        self.dismiss(animated: true, completion: nil)
    }
}

A: You gonna have to create an instance of the DetailView Controller and then assign its properties the data you want pass to it.
Like:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

if (segue.identifier == "yourSegueIdentifer") {
    // initialize new view controller and cast it as your view controller
    var viewController = segue.destinationViewController as AnotherViewController
    // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
}
}

A: You need to update destination View Controller (MemeDetailViewController) with data you want to pass like in the first example:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MemeDetailViewController" ,
    let nextScene = segue.destination as? MemeDetailViewController ,
        let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: "MemeCollectionViewCell", for: IndexPath) {
        let selectedMeme = memes[IndexPath]
        nextScene.meme = selectedMeme

    }
}


text:
Q: How to make aggregations work for text fields I am trying to write a elasticsearch query to get unique locality towns. my locality_town_keyword is of keyword type. when I try to search into locality_town_keyword, I get search hits but nothing in "aggregations":"Buckets".
Following is how my schema looks like...
                "locality_town": {
                    "type": "text"
                },
                "locality_town_keyword": {
                    "type": "keyword"
                },

My Search query looks like following
{
    "query":
    {
        "prefix" : { "locality_town" : "m" }
    },
    "size": "1",
    "_source": {
        "includes": [
            "locality_town*"
        ]
    },
    "aggs": {
        "loc": {
            "terms": {
                "field": "locality_town_keyoword",
                "size": 5,
                "order": {
                    "_count": "desc"
                }
            }
        }
    }
}

Here is the output it gives
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 799,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "tenderindex_2",
        "_type": "tender_2",
        "_id": "290077",
        "_score": 1.0,
        "_source": {
          "locality_town": "Manchester",
          "locality_town_keyword": "Manchester"
        }
      }
    ]
  },
  "aggregations": {
    "loc": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": []
    }
  }
}

This is how one document looks like
{
    "_index": "tenderindex_2",
    "_type": "tender_2",
    "_id": "290077",
    "_version": 1,
    "_seq_no": 39,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "Legal Services",
        "buyers": "CENTRAL MANCHESTER UNIVERSITY HOSPITALS NHS FOUNDATION TRUST",
        "postal_code": "M13 0JR",
        "publish_date": "2015-03-03T15:48:45Z",
        "status": "cancelled",
        "start_date": "2017-03-03T00:00:00Z",
        "endt_date": "2020-03-03T00:00:00Z",
        "url": "https://www.temp.com",
        "country": "England",
        "description": "desc......",
        "language": "en-GB",
        "service": "OPEN_CONTRACTING",
        "value": "0",
        "value_currency": "GBP",
        "winner": "",
        "create_time": "2019-05-11T21:39:42Z",
        "deadline_date": "1970-01-01T00:00:00Z",
        "address": "Central Manchester University Hospitals NHS Foundation Trust Wilmslow Park",
        "locality_town": "Manchester",
        "locality_town_keyword": "Manchester",
        "region": "North West",
        "tender_type": "planning",
        "cpv": "Health services ",
        "strpublish_date": "2015-03-03T15:48:45Z",
        "strstart_date": "2017-03-03T00:00:00Z",
        "strend_date": "2020-03-03T00:00:00Z",
        "strdeadline_date": "",
        "winner_email": "",
        "winner_address": "",
        "winner_town": "",
        "winner_postalcode": "",
        "winner_phone": "",
        "cpvs": "[\"Health services (85100000-0)\"]"
    }
}

A: Looks like you have a typo in your aggregation query:
"aggs": {
    "loc": {
        "terms": {
            "field": "locality_town_keyoword", <== here
            "size": 5,

Try with locality_town_keyword instead!
Hope this helps!


text:
Q: Map matrix element to string I would like to map numeric output from a matrix to a string.
Given
compute=[ 7, 4, 3; 3, 4, 7]

how can one obtain a string mapping as
Out=[Run, Walk, Jog; Jog, Walk, Run]

The actual output might be a cell array of strings.

A: >> map={'a','b','Jog','Walk','e','f','Run'}

map =

    'a'    'b'    'Jog'    'Walk'    'e'    'f'    'Run'

>> map(compute)

ans =

    'Run'    'Walk'    'Jog'
    'Jog'    'Walk'    'Run'

A: I assume you have the map in a form of a cell array
>> map{3} = 'Jog';
>> map{4} = 'Walk';
>> map{7} = 'Run';

Now use the map
map( compute )

will give you a cell array of strings

A: MATLAB has a Map container type that makes this very straighftorward:
keySet = [7, 4, 3];
valSet = {'Run', 'Walk', 'Jog'};
map = containers.Map(keySet,valSet);

Get the requested values:
>> vals = values(map,num2cell(compute))
vals =
    'Run'    'Walk'    'Jog'
    'Jog'    'Walk'    'Run'

This is a class after all, so you can also use a more familiar OOP syntax for calling the values method:
>> vals = map.values(num2cell(compute))
vals =
    'Run'    'Walk'    'Jog'
    'Jog'    'Walk'    'Run'

A: You can use cell array
strs = {'one','two','Jog','Walk','five','six','Run'};
compute=[ 7, 4, 3; 3, 4, 7];
out = strs(compute);
out =
'Run'    'Walk'    'Jog'
'Jog'    'Walk'    'Run'


text:
Q: Google Maps - iOS: maintain map position after rotate device I have 2 layouts (landscape and portrait) and each one with a UIWebView for show a map (Google Maps). Now I found the new SDK for iOS and want migrate, but I have yet a problem in both solutions:
the map open in the actual position (pos1) and I can move or make zoom (pos2). If I rotate the  device, with the new layout take again the pos1 and don't maintain the pos2.
How can I do for the map maintain the same position in both layouts?

A: the easiest way is to use Autolayout to avoid having 2 different views.
otherwise you can use the delegate method mapView:(GMSMapView *)mapView
    didChangeCameraPosition:(GMSCameraPosition *)position and save the position in a variable in your viewController


text:
Q: If there is an invariant measure, is it necessarily unique (up to a constant multi- plication)? When I was doing an exercise " When $(X_n)$ is irreducible Markov chain, If there is a reversible measure, is it necessarily unique (up to a constant multiplication)?" The answer is yes, and the proof is simple as $\mu(x)p^{(n)}(x,y)= \mu(y)p^{(n)}(y,x) \, \forall n$.
But I cannot prove or disprove the similar question for invariant measure " When $(X_n)$ is irreducible Markov chain, If there is in invariant measure, is it necessarily unique (up to a constant multiplication)?".
There is a theorem stating that when $(X_n)$ is recurrent the answer is yes, but what about general conditions? Can someone provide an example or a proof? Thanks in advance!
Update: Here the invariant measure should not be zero measure, and the measure should be nonnegative but can have infinite mass over the whole contable state space $S$.


text:
Q: Difference between Bias and Error? In statistics, what is the difference between Bias and Error?
You can say, Bias is a type of error? or Bias is an error with some tendency?

A: We can talk about the error of a single measurement, but bias is the average of errors of many repeated measurements. Bias is a statistical property of the error of a measuring technique. Sometimes the term "bias error" is used as opposed to "root-mean-square error".

A: The term error appears in several related (but not identical) contexts throughout science in general and statistical science in particular.
Error still carries the flavour of mistake (something erroneous), at least in the context of measurement error and particularly when scientists are thinking about their data. But its primary meaning in statistical science has long since been simply that of more or less uncontrolled variation (something erratic or errant). Sampling error, for example, refers to sampling variation, the uncontrolled and uncontrollable fact that different samples, responsibly taken, will include different data; hence in general any statistics (such as means, correlations, fraction blue) based on those samples will differ from sample to sample.
In simple regression-type models, error refers to individual disturbances in specifications such as
response variable $=$ function of predictors $+$ stochastic error
and error can refer more generally to the conditional distribution of the response variables given the predictors.
Bias refers to the difference between the true or correct value of some quantity and a measurement or estimate of that quantity. In principle it cannot be calculated therefore unless that true  or correct value is known, although this problem bites to varying degrees.

*

*In the simplest kind of problem, the true value is known (as when the centre of a target is visible and the distance of a shot from the centre can be measured; this is a common analogy) and bias is then usually calculated as the difference between the true value and the mean (or occasionally some other summary) of measurements or estimates.

*In other problems, some careful method is regarded as the state of the art and so yielding the best possible measurements, and so other methods are regarded as more or less biased according to their degree of systematic departure from the best method (in some fields termed a gold standard).

*In yet other problems, we have one or more methods all deficient to some degree and assessment of bias is then difficult or impossible. It is then tempting, or possibly even natural, to change the question and judge truth according to consistency between methods.
The two terminologies can be made consistent with the idea that systematic measurement errors have non-zero means (hence their summary quantifies bias) and random errors have zero mean. (Equivalently, that is how we label error as systematic or random.)
In mathematical statistics, standard analyses analyse whether particular estimators are biased in small samples, asymptotically, etc,, either in general or under particular circumstances.
This sketch at times implies that error is defined additively, so that
measured value $=$ true value $+$ error
but that is just the simplest situation. Nothing here rules out the idea that error may be multiplicative rather than additive, or defined on more complicated scales (e.g. in measuring proportions or percents, error may be better considered on something like a logit scale).
Comments on erroneous and erratic here were inspired by discussions in Jeffreys, Harold. 1939/1948/1961. Theory of probability. London: Oxford University Press.

A: The difference between the two is not only semantic, one can also express the difference in a formula: the bias-variance-tradeoff.
The following is the bias-variance decomposition as in Elements of Statistical Learning or the wikipedia page on bias-variance tradeoff:
$$ \text{MSE}(\hat{\theta}) = \text{Var}(\hat{\theta}) + \text{Bias}^2(\hat{\theta},\theta).$$
Where $\hat{\theta}$ is the estimator for $\theta$, $\text{MSE}(\hat{\theta}) = \mathbb{E}(\hat{\theta}-\theta)^2$ is the mean square error, $\text{Var}(\hat{\theta})=\mathbb{E}(\hat{\theta}-\mathbb{E}\hat{\theta})^2$ is the variance of $\hat{\theta}$ and $\text{Bias}^2(\hat{\theta},\theta)= (\mathbb{E}\hat{\theta} - \theta)^2$ is the bias (systematic deviation) of the estimator.
Form this identity we can see that in the context of estimators,

*

*bias is an error because it is a component of the mean square error.

*not every error is a bias (unfortunately)

*(this is not related to the question) there might be biased estimators that can have a lower MSE than unbiased estimators although it is a nice property for an estimator to be unbiased.

What I present here is about the terms error and bias for estimators but I think the principles hold true for the words as they are used in statistics in general:
One can decompose error into a systematic and an unsystematic component. Bias is a name for the systematic error.

A: To put it succinctly, bias is the difference of the expected value of your estimate (denote as $\hat{\theta}$) with the true value of what you are estimating (denote as $\theta$).
$$E[\hat{\theta}] - \theta$$
Error is the difference of your estimate with the true value of what you are estimating.
$$\hat{\theta} - \theta$$
You can have a fantastic estimator which is unbiased, but still have error because your observed value of the estimator didn't get it exactly right.

A: Error means wrong, e.g. type 1 & 2 errors. Bias means shifted or straying from a true value, e.g. underreporting of alcohol consumption.
Sometimes error is used to refer to fundamental or unmeasured randomness, such as the error term in a regression model, or measurement error. In some cases, but not always, such error causes bias, but they are not exchangeable terms. Error will increase variance, however.
As an example, suppose families above median household income are 60% likely to vote Republican, and families below are 30% likely to vote Republican. The odds ratio is 0.6/0.5 / (0.3/0.5) or 2. However, suppose respondents on the survey misreport their income, so that 10% misclassify from low to high, and 10% misclassify from high to low - a typical problem when non-working household members respond to these surveys. The odds ratio becomes (0.60.9 + 0.30.1)/0.5 / ((0.30.9 + 0.60.1)/0.5) or 1.7