text:
Q: Should we required to check iPhone is jailbraked Some of our application is already in AppStore...
But suddenly one thing comes into my mind, that I want to clear before submitting my next application.
The thing is : As a programmer's point of view, should we require to handle if iPhone Device is jailbreaked ? If yes, then how we can tackle with this ?
Thanks in advance....

A: On a general note, jail-breaking the device is an issue between the user, Apple and potentially the carrier. You are not a side in this relationship, and the user has no contractual obligations to you with regards to their device.
You could choose to attempt detecting jail-broken devices in an attempt to prevent piracy of your app. However:

*

*If the device is jail-broken, there's nothing you can do to reliably verify it's not jail-broken, since none of the OS APIs (including networking) is guaranteed to function as you expect. Your code could be running in a non-jail-broken simulation on top of jail-broken device.

*Of course, you could check by attempting to do one of the things you currently know Apple actively prevents apps from doing. However, there's no guarantee that Apple is not going to allow that particular action in future. And, there's the chance that your app might get rejected because you are attempting to do something prohibited by Apple.

*There is no official criteria from Apple on what constitutes a jail-broken device and what does not. And even if there was, you are not guaranteed to be notified in a timely manner (or at all) by Apple if they decide to change any such criteria. But even assuming you do get notified somehow, you can't update your app quick enough to avoid falsely detected jail-broken devices, thus potentially denying access to your app to legitimate users.

A: If you would like to cut off a large group of users, then sure, go ahead and require it.
Unless your application specifically requires it, there should be no reason to force users to have a jailbroken iPhone or a non-jailbroken iPhone.

A: If you program is legitimate (no private API calls etc), then you should not concern yourself with JB. You don't need to handle anything differently if the users phone has been JB'd. If it has, and your software doesn't run (say memory issues because they are using backgrounder to run 2 other things) then that's their problem not yours. Make your code well behaved, not leak memory, dump cache's etc with memory warnings, and you should be fine.

A: As you asked for the "programmer's point of view", I'd say: make sure your app runs on as many devices as possible.
Meaning: as long as you app is safe to run on an iPhone whether it's JB or not, I wouldn't care.

A: One thing I have found, at least early on (not seen it for a while) is that most reports I got of strange behaviour with my app (vConqr) turned out to be from people with jailbroken phones.
That's not to say I think that's good reason to block them. But if you do any sort of custom crash reporting, or other diagnostics it could be useful to log the fact to save time on troubleshooting.

A: Do a search on the Internet. You'll find several articles that shows some ways you can detect a pirated app. I make no claim on their effectiveness, but I do use some of these in my own apps. These techniques do not try to detect if a phone is jailbroken; they focus on detecting if your app has been tampered with.


text:
Q: Vue 3 Modal Comes Back With Old Data When Reopen I'm using Vue 3 and Vuex 4. When I open the modal, the main object (car) becomes equal to the default object, and those default values fill the modal's form. The codes down below are the simplified version.
Vuex module:
state: {
    car: {}
    defaults: {
        brand: "",
        color: "",
        value: ""
        ...
    }
},
actions: {
    fillTheCar(state, commit) {
        commit("SET_CAR", state.defaults)
    },
},
mutations: {
    SET_CAR(state, payload) {
        state.car = payload
    }
}
getters: {
    data(state) {
        return state.car
    }
}

When I fill out any input fields, the "car" object is updated as it's supposed to be. When I closed the modal:
methods: {
    closeModal() {
        this.$store.commit("Cars/SET_CAR", {})
        // I have a different Vuex module to control all toggled items
        // such as sidebar, modals, header, etc.
        // I change modal visibility on there.
        this.$store.commit("Toggles/SET_VISIBILITY", {modal: false}
    }
}

My file structure is like so:
App.vue
/ Components
  / Modal.vue
  / Input.vue
  / ...
/ Pages
  / Cars
    / Show.vue
    / Edit.vue
    / Create.vue
    / Delete.vue
    / CarModal.vue

When I go to "/cars" route, Show.vue is displayed in App.vue.
When I click "Create" button, Create.vue, which includes CarModal.vue and all functions related to creating a car, becomes visible.
CarModal.vue has all necessary form items for CRUD action and injects itself into /components/Modal.vue
//components/Modal.vue
<template>
    <teleport to="body">
        <slot name="header"></slot>
        <slot name="content"></slot>
        <slot name="actions"></slot>
    </teleport>
</template>

I hope those details will be enough to get help. Here is my problem:
If I fill out some inputs and close the modal, then reopen it, it comes back with data in the previously filled inputs, even though I make empty the car object when I close the modal. I tried the destroy Modal, CarModal, and Create files by using v-if. It didn't make any changes. I tried to set :key="Math.floor(Math.random() * 1000000)" to containers on the same files and change the key randomly at the modal close. It didn't work too. I don't know any other option to reset the form. I hope someone can point out what I'm missing here. BTW, I'm sure the car object becomes empty when I close the modal.

A: I believe problem lies in your store
actions: {
    fillTheCar(state, commit) {
        commit("SET_CAR", state.defaults)
    },
},
mutations: {
    SET_CAR(state, payload) {
        state.car = payload
    }
}

When I open the modal, the main object (car) becomes equal to the default object, and those default values fill the modal's form
So when you opening the modal, you are calling fillTheCar action which will in turn call mutation - result is, state.car points to the same object as state.defaults. So when you change something in the modal, you are actually changing properties of state.defaults too (should be easy check in Vue Dev Tools)
When closing modal, this.$store.commit("Cars/SET_CAR", {}) will just set state.car to a new object but when you open it again, it will be again set to state.defaults (already modified from before)
TLDR
This is not Vue/Vuex issue but JavaScript usage one...
To set state.car to some defaults, instead of commit("SET_CAR", state.defaults) do commit("SET_CAR", { ...state.defaults }) ...this will create new object with property values copied from state.defaults (assuming all properties are value types as strings, numbers etc. ie. not passed by reference)

redpajama_set_name: RedPajamaStackExchange


text:
Q: GNOME session not starting after filesystem corruption I'm running Ubuntu 9.10 desktop edition. Suddenly today /home became corrupted and I was prompted to run fsck manually. I ran fsck -y /home and rebooted the system. The system booted but I got no GUI interface (GNOME session) but a black screen with a user prompt instead. Any tricks here to start my system normally? Any help is greatly appreciated.
EDIT:1
The error were similar to the the following(may be with some mistakes as I had to type it manually):
machine1 login: root
password:
at login Sun Jan 16 15:30:46 IST 2011 on tty1
EXT3-fs error (devie sda1): ext3_lookup :deleted inode referenced
aborting journal on device sda1
Remounting filesystem read-only
root@machine1:~# startx
ktemp: failed to create file via template `/tmp/serverauth.xxxxxxxxxxx: Read-only file
/usr/bin/startx: line 157: cannot create temp file for here-document: Read-only file
xauth: error in locking authority file /root/.Xauthority
/usr/bin/startx: line 173: cannnot create temp file for here-document: Read-only file
xauth: error in locking authority file /root/.Xauthority
/usr/bin/startx: line 173: cannnot create temp file for here-document: Read-only file
X: cannot stat /tmp/.x11-unix (No such file or directory), aborting giving up.
xinit: No such file or directory (errno 2): unable to connect to xserver
xinit: No such process (errno 3): Server error
xauth: error in locking authority file /root/.Xauthority

A: Log in and try startx
Is your /home on a separate partition?

A: Just running fsck -y /, or fsck -y /dev/sda1 fixed the issue and system started gnome as usual. The best way of running fsck would be booting the system from live cd or usb stick. But before running fsck, backing up necessary data is also to be considered mandatory.


text:
Q: Getting test-only to work outside SBT console I'm using Specs2 for tests, with latest Play, Scala and SBT.
In sbt console, this works great, running only tests in UserServiceSpec:
[my-project] $ test-only services.UserServiceSpec

Outside sbt console, in project root directory, this does not work:
$ sbt test-only services.UserServiceSpec

This runs all the tests. (Same happens with testOnly.)
How is test-only supposed to work outside sbt console?
Follow-up question: using Specs2 tags, how to execute only tagged tests on the command line, outside sbt console?
$ sbt test-only -- include unit

The above, again, tries to to execute all tests (while test-only -- include unit in sbt console works fine).
Basically, I'd like to run all unit tests on a CI server, and Specs2 tags seem like a good tool for separating different kinds of tests. In this scenario I couldn't use the sbt console, right?

A: Sbt consider two parameters as two separate commands. You should mark it as one.
Try: sbt "testOnly services.UserServiceSpec"


text:
Q: coin change algo using recursion Give a set of coins and target . Need to print all the solutions possible in a list using recursion.
The solution i have come up with print all the solutions in single list . How do i make it a list of lists ? Please advise.
def coin_change(A, target):
    if target in A:
        return [target]
    ll = []
    for i in A:
        if i < target:
            ll = ll + [i] + coin_change(A, target - i)
        else:
            ll = ll +  [-1]
    return ll

coins = [3,10,7]
target = 5

A: There are likely different ways to do this, here's one that returns all potential results, even duplicates, in a hopefully understandable list structure of alternate solutions:
def coin_change(coins, target):
    ''' returns a list of lists of alternate solutions '''

    if target in coins:
        return [[target]]  # only one possibility, base case

    possibilities = []

    for coin in coins:
        if coin < target:
            possibilities += [[coin, *possibility] for possibility in coin_change(coins, target - coin)]

    return possibilities

print(coin_change([5, 10, 25], 30))

OUTPUT
[[5, 25], [10, 5, 5, 10], [10, 5, 10, 5], [10, 10, 10], [25, 5]]

In the case of no solution, it should return the empty list.


text:
Q: How do I prevent JQuery's val() from dropping everything after a whitespace? I'm writing something that fetches states and cities dynamically, based on select values. If, for example,a user chooses "United States" as a country, the page sends a query via AJAX to the server and populates States with "Ohio", "Alabama", "Florida" and so on. When the user chooses "Florida" it will populate the Cities dropdown with "Orlando", "Miami" and so on.
I listen for changes using $().change. When a change is detected, I get the value from the select field with $().val().
     País: <select name="country" id="newCompCountry"></select>
 - Estado: <select name="state" id="newCompState"></select>
 - Ciudad: <select name="city" id="newCompCity"></select><br />

The option tags are populated like so:
$.get("../process/getCountries.php",  function(data){
        var countries = $("#newCompCountry");
        countries.empty();
        for(var i = 0; i < data.length; i++)
        {
            countries.append("<option value=" + data[i] +">"+ data[i] +"</option>");
        }
    }, "json");

    $.get("../process/getStates.php", {country_name : $("#newCompCountry").val()}, function(data){
        var states = $("#newCompState");
        states.empty();
        for(var i = 0; i < data.length; i++)
        {
            states.append("<option value=" + data[i] +">"+ data[i] +"</option>");
        }
        console.log("ESTADO: " + $("#newCompState").val());
    }, "json");

    $.get("../process/getCities.php", {country_name : $("#newCompCountry").val(), state_name : $("#newCompState").val()}, function(data){
        var cities = $("#newCompCity");
        cities.empty();
        for(var i = 0; i < data.length; i++)
        {
            cities.append("<option value=" + data[i] +">"+ data[i] +"</option>");
        }
    }, "json");

The thing is, when I grab the .val() from any field, and that .val() happens to have spaces, everything is dropped when the space is detected.
Take for example my country. I live in "Bolivia", in the department of "La Paz", in the city of "La Paz". When I grab the value of "La Paz", it just comes out as "La".
This is a problem, because the database holds city names with spaces and a few other special characters you may find in other peculiar cities. Is there a way to force jquery to not drop anything after a whitespace is detected?
Here's a screenshot to show you what I mean (this is the log you can find in the code above):

Any help you can give me will be really appreciated.

A: Look at the rendered HTML:
<option value=La Paz>La Paz</option>

Now do you see the problem?
Try adding quotes. Alternatively, use vanilla JS:
var states = document.getElementById("newCompState");
states.options.length = 0;
for(var i = 0; i < data.length; i++) {
    states.appendChild(new Option(data[i]));
}


text:
Q: Hierarichal Grid with Angular JS 2 I am trying to implement  Hierarchical Grid in my Angular 2 application similar to this one http://demos.telerik.com/kendo-ui/grid/hierarchy
So I started out by creating two components. The Parent Component is for parent table and Child Component is for child table. So when click on row from parent table, the child table will load right below it (like above example).
This is how my html looks like

{{pageTitle}}

                    User Name
                    Email
                    Billing Method

                    <button (click)="getDetail(invoice)"></button>
                    {{invoice.username}}
                    {{invoice.email}}
                    {{invoice.billingMethod}}

But I am having two issues:
1) How to load child table on a correct location in DOM? The problem is when my parent table render, all of it's rows gets created using ngFor directive. Now when click on a row, how to load it's child table right below it? How to identify the location?
2) In order to load child table, I was thinking to use DynamicComponentLoader Class, but looks like the communication between Components won't be possible when using DCL.
Please suggest

A: I was able to fulfill your requirements using the template syntax of ngFor
pre 2.0.0-beta.17 syntax:
<template ngFor #item [ngForOf]="items" #i="index">

...

</template>

2.0.0-beta.17 syntax:
<template ngFor let-invoice [ngForOf]="invoices" let-i="index">

...

</template>

Check out this plunker
In your situation it will be:
<template ngFor let-invoice [ngForOf]="invoices" let-i="index">

        <button (click)="getDetail(invoice)"></button>
        {{invoice.username}}
        {{invoice.email}}
        {{invoice.billingMethod}}

            <child-table [details]="details"></child-table>

</template>

The isInvoiceOpened() function will return true if that particular row is opened. Which means you should have an array to hold opened rows indexes, i.e.
_openedDetails = [];

isInvoiceOpened(i){
  return this._openedDetails.indexOf(i)>-1;
}

getDetail(i){
  let index = this._openedDetails.indexOf(i);
  if(index > -1)
    this._openedDetails.splice(index,1);
  else
    this._openedDetails.push(i);
}


text:
Q: Некорректная отправка файла через socket Пытаюсь отправлять любой файл по TCP с моего клиента (на мобильном устройстве) на консольный сервер (на компьютере).
Подключение, отправка, получение, по-моему, происходят нормально, однако есть проблема с записью данных в файл.
Например, музыка в него записывается несколько раз, а у картинки записывается только одна "линия".
Я подозреваю, что проблема где-то в цикле, но не могу понять точно.
Код сервера, в котором происходит получение байтов из сокета и запись в файл:
String fileName;
int size;
try {
    size = sInput.readInt();
    fileName = sInput.readUTF();
    try {
        FileOutputStream fos = new FileOutputStream("C:\\Users\\admin\\Downloads\\FileSenderDownload\\" + fileName);
        byte[] buffer = new byte[size];
        int receivedBytes = 0;
        while (true) {
            if (receivedBytes == -1)
                break;
            receivedBytes = input.read(buffer);
            System.out.println(receivedBytes);
            fos.write(buffer, 0, buffer.length);
        }
        System.out.println("Запись");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
} catch (Exception e) {
    e.printStackTrace();
}

Код клиента для отправки файла:
try {
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    ObjectOutputStream output= new ObjectOutputStream(socket.getOutputStream());
    output.writeInt((int)sendingFile.length());
    output.flush();
    System.out.println("File size" + sendingFile.length());
    output.writeUTF(sendingFile.getName());
    output.flush();
    System.out.println("File name" + sendingFile.getName());
    FileInputStream input = new FileInputStream(sendingFile);
    int size = (int)sendingFile.length();
    byte[] buffer = new byte[size];
    int receivedBytes;
    while(true) {
        receivedBytes = input.read(buffer);
        if (receivedBytes == -1) {
            break;
        }
        if (receivedBytes > 0) {
            out.write(buffer, 0, receivedBytes);
            out.flush();
        }
    }
    input.close();
    out.close();
    socket.close();
} catch (IOException e) {
    e.printStackTrace();
}

Как исправить этот код?

A: Проблемы в цикле while (true) на сервере:

*

*receivedBytes = input.read(buffer); должно быть до проверки if (receivedBytes == -1).

*Нужно в fos.write указывать количество считанных байтов, а не длину буфера: fos.write(buffer, 0, receivedBytes);
В итоге цикл выглядит так:
while (true)
{
    receivedBytes = input.read(buffer);
    if (receivedBytes == -1)
        break;
    totalCount += receivedBytes;
    fos.write(buffer, 0, receivedBytes);
}

И по поводу кода в целом: использование try-with-resources и констант помогает улучшить код:
Клиент:
public void send(File sendingFile)
{
    try (Socket socket = new Socket(SERVER_ADDRESS, PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
            FileInputStream input = new FileInputStream(sendingFile))
    {
        output.writeInt((int)sendingFile.length());
        output.writeUTF(sendingFile.getName());
        byte[] buffer = new byte[BUFFER_SIZE];
        int readCount;
        while ((readCount = input.read(buffer)) != -1)
        {
            output.write(buffer, 0, readCount);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

Сервер:
private void get(Socket socket)
{
    try (ObjectInputStream sInput = new ObjectInputStream(socket.getInputStream()))
    {
        int size = sInput.readInt();
        String fileName = sInput.readUTF();
        try (FileOutputStream fos = new FileOutputStream(FILES_DIRECTORY + fileName))
        {
            byte[] buffer = new byte[BUFFER_SIZE];
            int receivedBytes = 0;
            while (receivedBytes < size)
            {
                int readCount = sInput.read(buffer);
                if (readCount == -1)
                {
                    break;
                }
                receivedBytes += readCount;
                fos.write(buffer, 0, readCount);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

Если через одно socket-соединение всегда будет передаваться только один файл, то на сервере можно не заморачиваться с подсчетом количества полученных байтов и сделать по аналогии с клиентом:
try (FileOutputStream fos = new FileOutputStream(FILES_DIRECTORY + fileName))
{
    byte[] buffer = new byte[BUFFER_SIZE];
    int readCount;
    while ((readCount = sInput.read(buffer)) != -1)
    {
        fos.write(buffer, 0, readCount);
    }
}

При таком допущении код можно упростить ещё больше с использованием Files.copy:
Клиент:
public void send(File sendingFile)
{
    try (Socket socket = new Socket(SERVER_ADDRESS, PORT);
            ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream()))
    {
        output.writeUTF(sendingFile.getName());
        Path path = sendingFile.toPath();
        Files.copy(path, output);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

Сервер:
private void get(Socket socket)
{
    try (ObjectInputStream sInput = new ObjectInputStream(socket.getInputStream()))
    {
        String fileName = sInput.readUTF();
        Path path = Paths.get(FILES_DIRECTORY + fileName);
        Files.copy(sInput, path, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}


text:
Q: Python to C# Zlib decompression conversion It tooks me hours trying to figure out how to mimic the exact decompression in this project: https://github.com/crimsoncantab/aok-hotkeys/blob/master/modules/hkizip.py but to no avail.
If you go to this website: http://aokhotkeys.appspot.com/ you can click any preset and download it to see for yourself.
The decompression is supposed to output a .hki file to text file
This is my attempt, which may not be as accurate as in the python project linked above:
private string ZlibCodecDecompress(byte[] compressed)
{
    int outputSize = 2048;
    byte[] output = new Byte[outputSize];

    // If you have a ZLIB stream, set this to true.  If you have
    // a bare DEFLATE stream, set this to false.
    bool expectRfc1950Header = false;

    using (MemoryStream ms = new MemoryStream())
    {
        ZlibCodec compressor = new ZlibCodec();
        compressor.InitializeInflate(expectRfc1950Header);

        compressor.InputBuffer = compressed;
        compressor.AvailableBytesIn = compressed.Length;
        compressor.NextIn = 0;
        compressor.CompressLevel = Ionic.Zlib.CompressionLevel.Level8;

        compressor.OutputBuffer = output;

        foreach (var f in new FlushType[] { FlushType.None, FlushType.Finish })
        {
            int bytesToWrite = 0;
            do
            {
                compressor.AvailableBytesOut = outputSize;
                compressor.NextOut = 0;
                compressor.Inflate(f);

                bytesToWrite = outputSize - compressor.AvailableBytesOut;
                if (bytesToWrite > 0)
                    ms.Write(output, 0, bytesToWrite);
            }
            while ((f == FlushType.None && (compressor.AvailableBytesIn != 0 || compressor.AvailableBytesOut == 0)) ||
                   (f == FlushType.Finish && bytesToWrite != 0));
        }

        compressor.EndInflate();

        return UTF8Encoding.UTF8.GetString(ms.ToArray());
    }
}

This method returns: "Ionic.Zlib.ZlibException: Bad state"
I'd appreciate any help.


text:
Q: trying to understand some codes which is related to variable declaration in js <script type="text/javascript">
function sayAlice() {
  var sayAlert = function() { console.log(alice); }
  var alice = 'Hello Alice';
  return sayAlert;
}
sayAlice()();
</script>

In console, it shows Hello Alice
Question:
var alice(variable declaration) is after  var sayAlert, why it still shows the right result, not something like 'undefined'?

A: Because at the time that sayAlert is actually executed (in the sayAlice()() call), Hello Alice has been assigned to alice.  Because of closures in JavaScript, alice is available to sayAlert at execution time.

A: It's the JavaScript Scoping and Hoisting mechanism.
Look at this. Due to hoisting, javascript interprets your script like this:
<script type="text/javascript">
   function sayAlice() {
      var alice;
      var sayAlert = function() { console.log(alice); }
      alice = 'Hello Alice';
      return sayAlert;
    }
    sayAlice()();
</script>

The var alice; is hoisted to before the declaration of var sayAlert = function() { console.log(alice); }.

A: Because saysAlert is a function and
it is only implemented when you return saysAlert which house the function and after the fact that you declared alice.
This one will give you an undefined variable:
<script type="text/javascript">
function sayAlice() {
var sayAlert='';
console.log(alice); // alice is undefine up to this line
var alice = 'Hello Alice';
return sayAlert;
}
sayAlice()();
</script>

Your original code:
<script type="text/javascript">
function sayAlice() {
  var sayAlert = function() { console.log(alice); } // function sayAlert is not yet implemented
  var alice = 'Hello Alice';
  return sayAlert; // function alert is implemented after the alice variable is define
 }
 sayAlice()();
 </script>

A: <script type="text/javascript">
1:    function sayAlice() {
2:       var sayAlert = function() { console.log(alice); }
3:       var alice = 'Hello Alice';
4:       return sayAlert;
5:    }
6:    sayAlice()();
</script>

*

*Line 2 is defining a function sayAlert, but not calling/executing it.  If you put () after the closing brace (}), then the log would print undefined because, as you mentioned, alice isn't defined until after.

*Line 4 just returns the sayAlert function, but again does not yet call it (notice it still doesn't have the ())

*Line 6 receives the function previously returned from the sayAlice() call and adds () to call the returned function (sayAlert).  So after Line 6 runs sayAlice, it effectively looks like sayAlert(), when it does that is when console.log(...) is called.  alice is still exposed and in scope as it has not yet been destroyed by the garbage collector (similarly how closures) work.


text:
Q: Using oldstyle figures of palatino (mathpazo) in math mode I am using \usepackage[osf]{mathpazo} for oldstyle figures and the dcolumn package to align the contents of tables at their decimal point. The problem is that dcolumn automatically sets the aligned content in math mode which sometimes results in a strange mixture of oldstyle numbers and lining numbers.
Is there an option to set digits in math mode to oldstyle by default?

Edit: (I hope editing the post is the right way in the local Netiquette to enhance my question).
@Mico I think the siunitx package is the way to go since it allows escaping math mode in tables completely and allows using a different math font in the document. But trying to use siunitx with my tables results in the phenomenon that there is white space for digits in parentheses, when the entry has fewer digits than previous entries (most of my tables are created by the esttab plugin for Stata, by the way). The following MWE illustrates the problem:
\documentclass{scrartcl}

\usepackage{booktabs}
\usepackage{siunitx}
\usepackage[osf]{mathpazo}

%SFor Tables created by estout
    \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} %for symbols in Table

\begin{document}

\begin{tabular*}
{\textwidth}{@{\hskip\tabcolsep\extracolsep\fill}l*{2}{S
    [mode=text,
    table-auto-round,
%   table-format=4.3,   % how is this supposed to work when we have entry with a different amount of digits?
    table-align-text-post=false,
    input-open-uncertainty=,
    input-close-uncertainty=]
    }   }
\toprule
\emph{Age}          &                     &                     \\
\hspace{0.1cm} 18-24&   [-1360.228]\sym{*}  &   -1371.941\sym{*}  \\
                    &   (6.915)         &   (-7.953)         \\
\hspace{0.1cm} 25-34&    -219.216         &    -240.271         \\
                    &   (514.894)         &   (515.348)         \\
\hspace{0.1cm} 35-44&    -310.715         &    -311.438         \\
                    &   (485.780)         &   (486.013)         \\
\hspace{0.1cm} 55+  &      -5.135         &      [2.656]         \\
                    &   (53.267)         &   (533.875)         \\
\bottomrule
\end{tabular*}

\end{document}

A: I don't know how you might achieve your objective using the functionality of the dcolumn package. Fortunately, it's fairly straightforward to do if you're willing to use the siunitx package and its S column type.
In the example below, I've taken your code and made a few changes that instruct siunitx how to deal with symbols such as parentheses and brackets. Basically, the code tells siunitx not to do anything "special" with these symbols. Note that I've moved most instructions related to the appearance of material in S columns to the preamble. The only instruction provided as an option to the two S columns is table-format=4.4, as this is likely something that will change from table to table. Doing this is, of course, mainly a stylistic or taste issue.
\documentclass{scrartcl}
\usepackage{booktabs}
\usepackage[osf]{mathpazo}
% For Tables created by estout
\newcommand{\sym}[1]{\ensuremath{^{#1}}} % for symbols in Table
\usepackage{siunitx}
\sisetup{ detect-mode,
          group-digits            = false ,
          input-signs             = ,
          input-symbols           = ()[]-+ ,
          input-open-uncertainty  = ,
          input-close-uncertainty = ,
          table-align-text-post   = false
        }
\begin{document}
\begin{tabular*}{\textwidth}{
    l @{\extracolsep\fill} *{2}{S[table-format=4.4]} @{}}
\toprule
\multicolumn{1}{@{}l}{\emph{Age}}  \\[0.5ex]
18--24 &   [-1360.228]\sym{*}  &  -1371.941\sym{*}  \\
       &       (6.915)         &    (-7.953)        \\
25--34 &     -219.216          &   -240.271         \\
       &     (514.894)         &   (515.348)        \\
35--44 &     -310.715          &   -311.438         \\
       &     (485.780)         &   (486.013)        \\
55$+$  &       -5.135          &     [2.656]        \\
       &      (53.267)         &   (533.875)        \\
\bottomrule
\end{tabular*}
\end{document}

A: You may consider to switch to another mathversion:
\documentclass[11pt,a4paper]{article}
\usepackage[osf]{mathpazo}
\usepackage{dcolumn}
\DeclareMathVersion{oldstyle}%
\SetSymbolFont{operators}{oldstyle}{OML}{zplmj}{m}{it}
\newenvironment{oldstyletabs}{\mathversion{oldstyle}}{}

\begin{document}

\begin{tabular}{*{3}{D{.}{.}{2}}}
\multicolumn{3}{c}{normal tabular}\\
  1.23 & 2.66  & 0.21 \\
123.45 & 567.8 & 987.32
\end{tabular}\bigskip

\begin{oldstyletabs}
\begin{tabular}{*{3}{D{.}{\textrm{.}}{2}}}
\multicolumn{3}{c}{oldstyle tabular}\\
  1.23 & 2.66  & 0.21 \\
123.45 & 567.8 & 987.32
\end{tabular}
\end{oldstyletabs}

Non-numbers may be displayed wrong. That's why I had to use \textrm{.}
Another possibility is to use the package rccol, which is very similiar to dcolumn.  This package prints in the aktive font. So you get oldstyle-figures numbers when setting your tabular in text-mode and lining figures in math-mode. No switching to another mathversion is needed.

A: As mentioned in my earlier comment, you can use the mathastext package. It will allow you to typeset basic math with the same font and options as text; however, it will affect all math throughout your document (so I would only recommend it for a mainly non-technical paper that contains some occasional, short math expressions).
Have a look at the documentation file to find the options that are right for you, and play around with it a bit.


text:
Q: Pass select value to controller without refreshing the page (AJAX, RAILS, JS) I'm a newbie using AJAX and now I'm trying to work on a group of select boxes so that when the user selects a value from the first, the second updates its values. I'm trying to use AJAX, JQuery and ROR, but so far, I can't fetch the value from the first box and pass it to the controller in order to filter the results of the second.
This is my code for index.html.erb
<%= form_tag(posts_path, remote: true, :method => 'get', class: "forma") do %>

   <%= select_tag("box", options_from_collection_for_select(@posts, :content,     :content), :prompt => "Select") %>

   <%= select_tag("nbox", options_from_collection_for_select(@listposts, :content,         :id), :prompt => "Select") %>

   <%= submit_tag "Show", class: "btn btn-info" %>

    <% end %>

This is my index.js.erb
$(document).ready(function() {

   $(".btn").on("click", function() {
           $('.table').fadeToggle();
   })

   $('#box').change(function(){
          $.ajax({
             type: 'POST',
             url: '/jess/rails/dummy/app/controllers/posts_controller',
             data: {'filter' : $(this).val() },
             success: function(data){
             }
          })
          $('#nbox').fadeIn();
      $('.btn').fadeIn();
   })
})

This is my controller
class PostsController < ApplicationController

  respond_to :html, :js

  def new
    @post = Post.new
  end

  def create
    @posts = Post.all
    @post = Post.new(post_params)
    if @post.save
      flash.now[:notice] = "YEAH"
      respond_to do |format|
        format.html {redirect_to @post.content}
        format.js
      end
    else
      render "/"
    end
  end

  def show
    @post = Post.find(params[:id])
  end

  def index
    @posts = Post.all
    @listposts = Post.where('content LIKE ?', params[:box])
  end

  def next
     @listposts = Post.where('content LIKE ?', params[:box])
   end

  private

    def post_params
        params.fetch(:post, {}).permit(:content)
    end

end

I think I'm doing it wrong with the AJAX part in the js.erb but I've changed it so many times I don't know anymore. Your help would be so very much appreciated!!

A: It looks like there are a couple of small problems.
First, it looks like the URL you are using may be wrong. The URL for the AJAX request would be the same format as the URL if you were to view that page in your browser.
With what you provided I can't tell exactly what it should be, but I can give you an example. Assuming you access your index page by just "http://example.com/index" (or something similar),  you would also call the function you want as something based on it's route. If the route was "update", then it would be something like "http://example.com/update".
Basically, don't use the folder path but use the web path instead.
Second, you don't do anything your success callback in your AJAX request. With AJAX, you send and receive info from the server, then you have to use JavaScript to update whatever you need updated manually. So, you'll need to have your update action return some information which you can then use to change the state of your second set of boxes.


text:
Q: Cannot Find Private URL For Opening Files App From Within Another App On iOS I need to open up the Files app from within my app. This is an internal application not going on the app store so I'm not worried about trying to use private URLs.
I've tried
"App-Prefs:root=files"
"App-Prefs:root=FILES"
"App-Prefs:root=Files"

in
let url = URL.init(string: "App-Prefs:root=Files")!
UIApplication.shared.open(url, options: [:]) { (Bool) in
    print("opened")
}

Depending on the string it will either not open anything or open the settings application.

A: According to this thread, you can use shareddocuments:// as the URLScheme to open the Files app. You can read more about how to use URLSchemes in this document in the section called Using URL Schemes to Communicate with Apps.

A: For anyone looking for the code:
    // give your initial URL as fileUrl
let sharedPath = fileUrl.absoluteString.replacingOccurrences(of: "file://", with: "shareddocuments://")
                                guard let sharedUrl = URL(string: sharedPath) else {
                                    return
                                }
     UIApplication.shared.open(sharedUrl)


text:
Q: Why does Eclipse mark pseudo-errors in my source? I have locally forked (via hg clone) a C/C++ (Eclipse CDT) project and imported it into my Eclipse workspace. My editor window for the forked project now looks like this:

Clearly, these are not real errors, since the code builds correctly. Also, these errors are not marked in the original project from which this one was forked.
Why does Eclipse think there are errors in this source?
EDIT:  Eclipse error messages when hovering over the "bugs" are, e.g., Type int64_t could not be resolved and symbol 'cout' could not be resolved.
EDIT: I've noticed that Eclipse usually shows a "folder" named includes in the project. It is missing for this project. How can I get it back?

A: Eclipse has to know the paths where to find the include files. This may be set using general eclipse settings or project by project.
For some reason it seems like the default paths are not set for your current project.
What you can do:
Open the project settings and go to C/C++ General -> Paths and Symbols (at least that is how it is called in my eclipse version) and fix the include directories.
Maybe it is enough to load the default configuration for that specific project. Maybe you have to set up your include pathes by yourself. On Unix / OS X this should usually be usr/include. On Windows I have no idea, but that should be easy to find out.
Afterwards it may be necessary that your rebuild your eclipse index (right click on your project, then index -> rebuild).
If that does not help please share a screenshot of the Paths and Symbols dialog of your project.
Also see the eclipse documentation on this topic.

A: I had to include

*

*CDT Cross GCC Built-in Compiler Settings

*CDT GCC Built in Compiler Settings [ Shared ]
in Properties for the project -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> Providers

A: add this define in Eclipse to Project Properties->C/C++ General->Paths and Symbols
__STDC_FORMAT_MACROS

Rebuild your eclipse index. It will work.

A: This worked on Mac OS X Yosemite 10.10.5, Eclipse version Mars.1 Release (4.5.1):
Since the includes are usually discovered by Eclipse through the toolchain, check that you have an actual toolchain set (when I ran into this problem after importing a project, the toolchain was set to "No toolchain."):
Project -> Properties -> C/C++ Build -> Tool Chain Editor -> Current toolchain
If no toolchains appear in the dropdown, try unchecking "Display compatible toolchains only" and choosing a toolchain (I chose Cross GCC). When I saved the changes and re-opened the project properties to look at this field again, "Display compatible toolchains only" was automatically re-checked.
Then re-index the project:
Project -> C/C++ Index -> Rebuild
This solved the problem for me (the "pseudo-errors" disappeared, and the includes "folder" appeared under my project in the file system view).

A: Have you #included the correct files in your code? For std::cout it would be:
#include <iostream>

and for int64_t:
#include stdint.h


text:
Q: Java: Most Efficient Way to Get Input Integer Array I'm working on a problem that requires me to store a very large amount of integers into an integer array. The input is formatted so that one line displays the amount of integers and the next displays all of the values meant to be stored. Ex:
3
12 45 67

In the problem there is closer to 100,000 integers to be stored. Currently I am using this method of storing the integers:
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();

int[] iVau = new int[n];

String[] temp = scanner.nextLine().split(" ");

for(int i = 0; i < n; i++) {
    iVau[i] = Integer.parseInt(temp[i]);
}

This works fine, however the problem I am solving has a strict time limit and my current solution is exceeding it. I know that there is a more efficient way to store this input using buffered readers and input streams, but I don't know how to do it, can someone please show me.

A: The way you are using Scanner makes your program save a String containing the whole numbers at once, in memory. With 100000 numbers in the 2nd line of your input, it is not so efficient, you could read numbers one after the other without keeping the previous one in memory. So, this way, avoiding using Scanner.readLine() should make your program run faster. You will not have to read the whole line one time, and read a 2nd time this String to parse the integers from it: you will do both of these operations only once.
Here is an example. The method testing() does not use any Scanner. The method testing2() is the one you provided. The file tst.txt contains 100000 numbers. The output from this program, on my Mac Mini (Intel Core i5@2.6GHz) is:
duration without reading one line at a time, without using a Scanner instance: 140 ms
duration when reading one line at a time with a Scanner instance: 198 ms

As you can see, not using Scanner makes your program 41% faster (integer part of (198-140)/140*100 equals 41).
package test1;
import java.io.*;
import java.util.*;

public class Test {
    // Read and parse an Int from the stream: 2 operations at once
    private static int readInt(InputStreamReader ir) throws IOException {
        StringBuffer str = new StringBuffer();
        int c;
        do { c = ir.read(); } while (c < '0' || c > '9');
        do {
            str.append(Character.toString((char) c));
            c = ir.read();
        } while (!(c < '0' || c > '9'));
        return Integer.parseInt(str.toString());
    }

    // Parsing the input step by step
    private static void testing(File f) throws IOException {
        InputStreamReader ir = new InputStreamReader(new BufferedInputStream(new FileInputStream(f)));
        int n = readInt(ir);
        int [] iVau = new int[n];
        for (int i = 0; i < n; i++) iVau[i] = readInt(ir);
        ir.close();
    }

    // Your code
    private static void testing2(File f) throws IOException {
        Scanner scanner = new Scanner(f);
        int n = scanner.nextInt();
        int[] iVau = new int[n];
        scanner.nextLine();
        String[] temp = scanner.nextLine().split(" ");
        for(int i = 0; i < n; i++)
            iVau[i] = Integer.parseInt(temp[i]);
        scanner.close();
    }

    // Compare durations
    public static void main(String[] args) throws IOException {
        File f = new File("/tmp/tst.txt");

        // My proposal
        long t = System.currentTimeMillis();
        testing(f);
        System.out.println("duration without reading one line at a time, without using a Scanner instance: " + (System.currentTimeMillis() - t) + " ms");

        // Your code
        t = System.currentTimeMillis();
        testing2(f);
        System.out.println("duration when reading one line at a time with a Scanner instance: " + (System.currentTimeMillis() - t) + " ms");
    }
}

NOTE: creating the input file is done this way, with bash or zsh:
echo 100000 > /tmp/tst.txt
for i in {1..100000}
do
  echo -n $i" " >> /tmp/tst.txt
done

A: I believe this is what you're looking for. A BufferedReader can only read a line at a time, so it is necessary to split the line and cast Strings to ints.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try {
    int n = Integer.parseInt(br.readLine());
    int[] arr = new int[n];

    String[] line = br.readLine().split(" ");
    for (int i = 0; i < n; i++) {
        arr[i] = Integer.parseInt(line[i]);
    }
} catch (IOException e) {
    e.getStackTrace();
}

A: Just a thought, String.split returns an array of Strings. You say the input can be around 100,000 values. So in order to split the array in this way, String.split must be iterating through each element. Now in parsing the new array of strings to Integers you have iterated through the collection twice. You could do this in one iteration with a few small tweaks.
Scanner scanner = new Scanner(System.in);
String tmp = scanner.nextLine();
scanner = new Scanner(tmp);

for(int i = 0; scanner.hasNextInt(); i++) {
  arr[i] = scanner.nextInt();
}

The reason for linking the scanner to a String instead of leaving it on System.in is so that it ends properly. It doesn't open System.in for user input on the last token. I believe in big O notation this is the difference between O(n) and O(2n) where the original snippet is O(2n)

A: I am not quite sure why OP has to use Integer.parseInt(s) here since Scanner can  just do the parsing directly by new Scanner(File source).
Here is a demo/test for this idea:
public class NextInt {
    public static void main(String... args) {
        prepareInputFile(1000, 500); // create 1_000 arrays which each contains 500 numbers;
        Timer.timer(() -> readFromFile(), 20, "NextInt"); // read from the file 20 times using Scanner.nextInt();
        Timer.timer(() -> readTest(), 20, "Split"); // read from the file 20 times using split() and Integer.parseInt();
    }

    private static void readTest() {
        Path inputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
        try (Scanner scanner = new Scanner(new File(inputPath.toString()))) {
            int n = Integer.valueOf(scanner.nextLine());
            int[] iVau = new int[n];
            String[] temp = scanner.nextLine().split(" ");
            for (int i = 0; i < n; i++) {
                iVau[i] = Integer.parseInt(temp[i]);
            }
        } catch (IOException ignored) {
            ignored.printStackTrace();
        }
    }

    private static void readFromFile() {
        Path inputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
        try (Scanner scanner = new Scanner(new File(inputPath.toString()))) {
            while (scanner.hasNextInt()) {
                int arrSize = scanner.nextInt();
                int[] arr = new int[arrSize];
                for (int i = 0; i < arrSize; ++i) {
                    arr[i] = scanner.nextInt();
                }
//                System.out.println(Arrays.toString(arr));
            }
        } catch (IOException ignored) {
            ignored.printStackTrace();
        }
    }

    private static void prepareInputFile(int arrCount, int arrSize) {
        Path outputPath = Paths.get(Paths.get("").toAbsolutePath().toString().concat("/src/main/java/io/input.txt"));
        List<String> lines = new ArrayList<>();
        for (int i = 0; i < arrCount; ++i) {
            int[] arr = new int[arrSize];
            for (int j = 0; j < arrSize; ++j) {
                arr[j] = new Random().nextInt();
            }
            lines.add(String.valueOf(arrSize));
            lines.add(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
        }
        try {
            Files.write(outputPath, lines);
        } catch (IOException ignored) {
            ignored.printStackTrace();
        }
    }
}

Locally tested it with 1_000 arrays while each array has 500 numbers, reading all the elements cost about: 340ms using Scanner.nextInt() while OP's method about 1.5ms.
NextInt: LongSummaryStatistics{count=20, sum=6793762162, min=315793916, average=339688108.100000, max=618922475}
Split: LongSummaryStatistics{count=20, sum=26073528, min=740860, average=1303676.400000, max=5724370}

So I really have doubt the issue lies in the input reading.

A: Since in your case you are aware of the total count of elements all that you have to do is to read X integers from the second line. Here is an example:
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int count = in.nextInt();
        int array[] = new int[count];

        for (int i = 0; i < count; i++) {
            array[i] = in.nextInt();
        }
}

If this is not fast enough, which I doubt, then you could switch to the use of a BufferedReader as follows:
public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        int count = Integer.parseInt(in.readLine());
        int array[] = new int[count];

        for (int i = 0; i < count; i++) {
            int nextInteger = 0;
            int nextChar = in.read();
            do {
                nextInteger = nextInteger * 10 + (nextChar - '0');
                nextChar = in.read();
            } while (nextChar != -1 && nextChar != (int)' ');
            array[i] = nextInteger;
        }
}

In your case the input will be aways valid so this means that each of the integers will be separated by a single whitespace and the input will end up with EoF character.
If both are still slow enough for you then you could keep looking for more articles about Reading Integers in Java, Competative programming like this one: https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
Still my favorite language when it comes to competitions will always be C :) Good luck and enjoy!


text:
Q: React form pass headers to api I want to post a JSON to a external api from a react form. the api needs headers (username:password) to access it. I wanted to see how I would set up a form to take the inputs of a user and pass it as headers to the api then post some json. I am able to do this with cURL but Im relatively new to react and this has been causing me some problems.

A: If you are using fetch to make API call you can do something like :
function signIn(username, password, body) {
    const options = {
        method: method,
        headers: new Headers({username, password}),
        mode: 'no-cors'
    };

    options.body = JSON.stringify(body);

    fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data));
}

You might wanna read more about the same here

A: 0
fetch(your_url,a_json_object) Here,json_object has one element called headers,just use your custom header in it. But most noobies forget to add the header in backend.I am showing a correct example:
front end:
fetch('fdf.api/getid',{
method:'post',
headers:{"a_custom_header":"custom_value"}
})

backend:
const express = require('express')
const app = express()

app.use(function(req,res,next){
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS,
       PUT,PATCH, DELETE');

  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,a_custom_header'); //notice here carefully

  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
 })


text:
Q: Why this SSL connection ends abruptly I am trying to make an HTTPS POST request. The connection ends abruptly at the very beginning. I took the following capture with Wireshark. 192.168.0.33 is my client attempting to connect to the server. 192.185.47.210 is the server.
No.     Time           Source                Destination           Protocol Length Info
     51 2.476681000    192.168.0.33          192.185.47.210        TCP      62     1143→443 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 SACK_PERM=1
     52 2.534541000    192.185.47.210        192.168.0.33          TCP      62     443→1143 [SYN, ACK] Seq=0 Ack=1 Win=29200 Len=0 MSS=1460 SACK_PERM=1
     53 2.534559000    192.168.0.33          192.185.47.210        TCP      54     1143→443 [ACK] Seq=1 Ack=1 Win=65535 Len=0
     54 2.534720000    192.168.0.33          192.185.47.210        TLSv1    163    Client Hello
     56 2.592332000    192.185.47.210        192.168.0.33          TCP      60     443→1143 [ACK] Seq=1 Ack=110 Win=29200 Len=0
     57 2.594550000    192.185.47.210        192.168.0.33          TLSv1    191    Server Hello, Change Cipher Spec, Encrypted Handshake Message
     58 2.596455000    192.168.0.33          192.185.47.210        TCP      54     1143→443 [FIN, ACK] Seq=110 Ack=138 Win=65398 Len=0
     60 2.654542000    192.185.47.210        192.168.0.33          TCP      60     443→1143 [FIN, ACK] Seq=138 Ack=111 Win=29200 Len=0
     61 2.654558000    192.168.0.33          192.185.47.210        TCP      54     1143→443 [ACK] Seq=111 Ack=139 Win=65398 Len=0

I suspect the problem is with packet 57, because upon receiving this packet, client initiates a disconnect of the TCP connection. Packet 57 looks like
Frame 57: 191 bytes on wire (1528 bits), 191 bytes captured (1528 bits) on interface 0
Ethernet II, Src: Actionte_39:b9:de (18:1b:eb:39:b9:de), Dst: CadmusCo_f6:2b:9b (08:00:27:f6:2b:9b)
Internet Protocol Version 4, Src: 192.185.47.210 (192.185.47.210), Dst: 192.168.0.33 (192.168.0.33)
Transmission Control Protocol, Src Port: 443 (443), Dst Port: 1143 (1143), Seq: 1, Ack: 110, Len: 137
Secure Sockets Layer
    TLSv1 Record Layer: Handshake Protocol: Server Hello
        Content Type: Handshake (22)
        Version: TLS 1.0 (0x0301)
        Length: 81
        Handshake Protocol: Server Hello
    TLSv1 Record Layer: Change Cipher Spec Protocol: Change Cipher Spec
        Content Type: Change Cipher Spec (20)
        Version: TLS 1.0 (0x0301)
        Length: 1
        Change Cipher Spec Message
    TLSv1 Record Layer: Handshake Protocol: Encrypted Handshake Message
        Content Type: Handshake (22)
        Version: TLS 1.0 (0x0301)
        Length: 40
        Handshake Protocol: Encrypted Handshake Message

Other info:
The client is a C# program running on Windows XP. The call is made by the WebRequest (https://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx) class. The server is on shared hosting (Hostgator) with dedicated IP and an SSL certificate from COMODO.
Question
Can anyone help me understand why receiving packet 57 is causing the client to disconnect?

A: Based on this Q&A I linked to in comments, and the additional edited-in fact, that connection attempt is made by C# in Windows XP, the most likely reason is that verification against Trusted Roots might fail.
The problem you're seeing might not appear in browsers; this could be surprising. It's so because web browsers typically provide their own set of trust data, in addition to what's in the system - and probably more up-to-date, whereas Windows has to rely on updates/service packs, which don't appear anymore (and even if, OS policy about these things might be a bit stricter than the browsers').
The solution will be adding root to ones trusted by the system, or loading it programmatically in your application.

A: Probably the server requires the client to send a client certificate, and you didn't. Closing the connection is the server's only defence.


text:
Q: are empty parameters in a long url string acceptable practice This post indicates that an empty parameter in a URL string isn't such a bad thing. But it only asks about one parameter. It may seem a silly extension of the question, but if I have a long list of parameters, is it still considered acceptable practice?
www.web.com?id=123&last_purchase_id=&last_purchase_date=&is_buyer=false

A:
Are empty parameters in a long url string acceptable practice?

Yes and No.
Yes in the fact that even an empty value represents a value. That is the absence of a value. Use cases would be reset, default, or opt-out a parameter.
No in the fact that if empty parameters are required for your code to properly execute. Instead you should default those values in code.

A: There is a difference to the server between empty parameters and the non-existence of parameters.
isset($_GET['last_purchase_id'])

would be true even for an empty last_purchase_id. Therefore, whether you send the server empty parameters is up to your server's current implementation.


text:
Q: A part of a website in an iframe, how to open it's links in the parent's window? I have the following code to insert a part of a website via an iframe on my webpage:
<iframe  scrolling="no" frameBorder="0"
  src="http://www.dn.se/"
  style="width:100%; height:150px; border:none;">
</iframe>

I would like to open all links on the "iframed" website in my webpage's window (and not in the iframe). I have read on SO questions like this one, that I should use:
<base target="_parent" />

But I don't seem to get it right.
How can I open all links in a iframe window in it's parent's window, if it's a website I'm iframing?
(If possible I don't want to use a javascript library like jQuery.)

A: If your website and the iFrame are not on the same domain name, the browser will not allow this.
It's called Cross-Site Scripting (XSS)


text:
Q: R knitr save_kable plain html output I'm trying to export a set of data frames to HTML files. I tried the following configuration:
library(knitr)
library(kableExtra)

writeDFtoHTML<-function(df,path){
    df%>%
        kable(escape = F) %>%
        kable_styling(bootstrap_options = c("condensed","basic"),font_size = 9,full_width = F, position = "left")%>%
        save_kable(file = path, self_contained = F,bs_theme = "simplex", extra_dependencies = NULL)

}

I call the writeDFtoHTML function from within a for loop and I write the df data frames in different folders for specification.
The problem is that in each path folder save_kable creates a lib dir containing JavaScript libraries:
lib/bootstrap-3.3.5
lib/jquery-1.11.3
lib/kePrint-0.0.1
Those libraries weigh a lot: about 4MB for each df folder. I have 50 df to save, one for folder, and this makes over 200MB output. Impossible since I need a simple, plain, static HTML.
Another issue is that save_kable creates those lib dirs again and again each time I export my data frames, regardless if the lib folders already exist.
Is there a method I can use to force save_kable to create a plain html file?
Thank you.

A: Use self_contained=TRUE as an argument.


text:
Q: Let subproject use external library in iOS I've a problem managing subprojects in iOS. Here are my projects:
PROJECT A, main project
    - imports B
    - imports C
    - uses D

PROJECT B, personal subproject
    - contains D

PROJECT C, external lib
    - contains D

LIBRARY D

I need to let project A import subproject B and subproject C, but there is a problem: A, B and C use the same library D (as described).
The solution I've tried was to leave the library D in project C, with this solution A works, B doesn't (it can't read library from C).
Is there a solution (like to let project A to import B except for the library D)?
Thanks!

A: One way to do this would be to use Git submodules. That way you have the benefits of only needing to make changes in one place, yet still be able to use the code in different places.


text:
Q: Seeking clarification on page request life-cycle I'm just trying to get my head around the "life-cycle" of a typical page request in WordPress. The Action Reference page lists 38 actions that occur during a typical page load, but two things aren't clear to me:

*

*does functions.php get invoked before any of the hooks are executed?

*does the framework call your "page.php", etc., somewhere within the sequence of hooks, or after all hooks have been executed?

Thanks.
(apologies if my terminology is a little off, but I believe I understand the idea behind hooks being made available by the framework, and actions being associated with these hooks by the theme author)

A: To see both when an action is fired and when a file is included, take a look here:
http://wp-roadmap.com/demo/
Note that it only covers things inside WP Core, along with the default theme.

A:
does functions.php get invoked before any of the hooks are executed?

It is processed during theme(s) load, right before after_setup_theme hook.

does the framework call your "page.php", etc., somewhere within the sequence of hooks, or after all hooks have been executed?

If I am not mistaken specific template is determined and processed in template_redirect hook.


text:
Q: java code throws error after uploading on Amazon AWS cloud services  Instances train1 = new Instances(new BufferedReader(new FileReader("d:\\jacx.arff")));
    int lastIndex = train1.numAttributes() - 1;
    train1.setClassIndex(lastIndex);

This code runs properly on localhost but after uploading Amazon AWS it gives error.

"jacx.arff" file is not uploaded to aws.

how to upload it???
and tell me how to read uploaded file.


text:
Q: No puedo cargar scripts de Jquery en Wordpress Tengo el siguiente sitio, el cual está hecho en Wordpress:
http://www.endeavor.cl/
Quiero agregar una ventan de popup, por lo cual elegí usar jquery-ui. Sigo las indicaciones tal como salen aquí y no pasa nada:
https://jqueryui.com/dialog/
Fuí al archivo header.php de mi template y ahí agregué esto:

Y en el mismo header.php también agregué esto:

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

Aquí está mi header.php completo, no sé qué puedo estar haciendo mal. No es sólo esto, también he probado con modales de Bootstrap y nada. Lo único que me funciona es el alert() de Javascript.

<!DOCTYPE html>

<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<?php if (have_posts()):while(have_posts()):the_post(); endwhile; endif;?>

<meta property="fb:app_id" content="570150036476648" />

<?php
if (in_category('categoria-videos')) { ?>
    <meta property="og:url" content="<?php the_permalink() ?>"/>
    <meta property="og:title" content="<?php single_post_title(''); ?> | <?php bloginfo('name'); ?>" />
    <meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" />
    <meta property="og:type" content="article" />
    <meta property="og:image" content="http://i.ytimg.com/vi/<?php the_field('video-youtube-id'); ?>/hqdefault.jpg" />
    <meta property="og:image:width" content="300"/>
    <meta property="og:image:height" content="300"/>
<?php } elseif (is_single()) { ?>
    <meta property="og:url" content="<?php the_permalink() ?>"/>
    <meta property="og:title" content="<?php single_post_title(''); ?> | <?php bloginfo('name'); ?>" />
    <meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" />
    <meta property="og:type" content="article" />
    <?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'medium' ); ?>
    <meta property="og:image" content="<?php echo $feat_image;?>" />
    <meta property="og:image:width" content="300"/>
    <meta property="og:image:height" content="300"/>
<?php } elseif (is_page()) { ?>
    <meta property="og:url" content="<?php the_permalink() ?>"/>
    <meta property="og:title" content="<?php single_post_title(''); ?> | <?php bloginfo('name'); ?>" />
    <meta property="og:description" content="Endeavor lidera el movimiento global que busca impulsar el crecimiento económico sostenible, a través de la selección de Emprendedores de Alto Impacto" />
    <meta property="og:type" content="article" />
    <?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    <meta property="og:image" content="<?php bloginfo('template_directory'); ?>/template/FotoShare.jpg" />
    <meta property="og:image:width" content="450"/>
    <meta property="og:image:height" content="298"/>
<?php } elseif(is_home()) { ?>
    <meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
    <meta property="og:title" content="Endeavor Chile | www.endeavor.cl" />
    <meta property="og:description" content="Endeavor lidera el movimiento global que busca impulsar el crecimiento económico sostenible, a través de la selección de Emprendedores de Alto Impacto" />
    <meta property="og:type" content="website" />
    <meta property="og:image" content="<?php bloginfo('template_directory'); ?>/template/FotoShare.jpg" />
    <meta property="og:image:width" content="450"/>
    <meta property="og:image:height" content="298"/>
<?php } else { ?>
    <meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
    <meta property="og:description" content="Endeavor lidera el movimiento global que busca impulsar el crecimiento económico sostenible, a través de la selección de Emprendedores de Alto Impacto" />
    <meta property="og:type" content="website" />
    <meta property="og:image" content="<?php bloginfo('template_directory'); ?>/template/FotoShare.jpg" />
    <meta property="og:image:width" content="450"/>
    <meta property="og:image:height" content="298"/>
<?php } ?>

<title>
 <?php
 // Print the <title> tag based on what is being viewed.
 global $page, $paged;

 wp_title( '|', true, 'right' );

 // Add the blog name.
 bloginfo( 'name' );

 // Add the blog description for the home/front page.
 $site_description = get_bloginfo( 'description', 'display' );
 if ( $site_description && ( is_home() || is_front_page() ) )
  echo " | $site_description";

 // Add a page number if necessary:
 if ( $paged >= 2 || $page >= 2 )
  echo ' | ' . sprintf( __( 'Page %s', 'twentyeleven' ), max( $paged, $page ) );

 ?>
</title>

<link rel="shortcut icon" href="<?php bloginfo('template_directory'); ?>/template/favicon.ico" type="image/x-icon" />

<?php include(TEMPLATEPATH . '/fancybox/lib/fancyincludes.php'); ?>

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" />

<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/popup/jquery.modal.min.css" type="text/css" />

<?php include('includes/preload.php'); ?>

     <?php wp_nav_menu( array( 'theme_location' => 'menu_sup', 'menu_class' => 'primary', 'fallback_cb' => '') ); ?>

menu

        <a href="<?php echo get_settings('home'); ?>"><img id="logo-top" src="<?php bloginfo('template_directory'); ?>/template/logo-top.svg">

             <form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
                 <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Buscar…', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
                    <button type="submit" role="button" class="btn btn-default right"/>></button>
               </form>

            <img id="facebook-top" class="boton" src="<?php bloginfo('template_directory'); ?>/template/iconos/facebook-blanco.svg">

            <img id="twitter-top" class="boton" src="<?php bloginfo('template_directory'); ?>/template/iconos/twitter-blanco.svg">

            <img id="youtube-top" class="boton" src="<?php bloginfo('template_directory'); ?>/template/iconos/youtube-blanco.svg">
            <img id="linkedin-top" class="boton" src="<?php bloginfo('template_directory'); ?>/template/iconos/linkedin-blanco.svg">

    <?php include('includes/prox-evento.php'); ?>

This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

A: Revisa la consola de JavaScript de tu navegador. Con seguridad verás el error que está ocurriendo.
Es probable que estés cargando dos versiones de jQuery y por eso no funcione, o bien el archivo jQuery esté en el lugar equivocado.

$(function() {
  $( "#dialog" ).dialog();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

    Estás cargando mal los archivos de jQuery.

En general y a menos que hayas hecho el tema a mano, editar los archivos de un tema se considera una mala práctica. Es mejor editar los cambios en el archivo functions.php y aún mejor crear un plugin donde puedas aplicar los cambios que creas necesarios a cualquier tema.
El método adecuado para usar una versión de jQuery distinta a la que usa WordPress (y en general para cualquier script y/o hoja de estilo) es primero registrarlo y después encolarlo.
Por ejemplo, para registrar y encolar jquery-ui a tu tema, tendrías que hacer algo como esto:
function my_theme_scripts() {
    wp_enqueue_script( 'jquery-ui', 'https://code.jquery.com/ui/1.12.1/jquery-ui.js', array( 'jquery' ), '1.12.1', true );
}
add_action( 'wp_enqueue_scripts', 'jquery-ui' );

Con esto, registras el script jquery, específicas dónde se obtiene y las dependencias (en este caso jquery).

Nota
En realidad, WordPress ya incluye jquery-ui-dialog en su instalación. Revisa la lista en este enlace: https://developer.wordpress.org/reference/functions/wp_enqueue_script/#defaults.

Nota 2 - La función wp_head()
La función wp_head() es un "gancho" que nos ayuda a colgar de manera controlada y ordenada scripts y hojas de estilo en un tema. Se coloca antes de  para que WordPress y los plugins que lo necesiten inserten sus dependencias. En mi opinión, el uso de wp_head() es obligatorio.  Deberías considerar la posibilidad de añadir esta función a tu tema.

Alternativa
Si por alguna razón decides no usar la función wp_head(), intenta colocando jquery al inicio del header... digamos después de la etiqueta </title>.


text:
Q: What are the rules for resolving symbols as macros vs. function parameters? I was surprised to find that alpha-conversion is not safe in Clojure:
Clojure> ((fn [o] (o 3 2)) +)
5

Clojure> ((fn [or] (or 3 2)) +)
3

Clojure> ((fn [def] (def 3 2)) +)
java.lang.RuntimeException: First argument to def must be a Symbol

(I expected all three snippets to evaluate to 5).
What's the rule(s) for symbol resolution when shadowing and macros, and special forms are involved?
I'm using the version on Try Clojure.

A: You cannot shadow special forms, according to the documentation:

A Symbol is resolved:

*

*If it is namespace-qualified, the value is the value of the binding of the global var named by the symbol. It is an error if there
  is no global var named by the symbol, or if the reference is to a
  non-public var in a different namespace.

*If it is package-qualified, the value is the Java class named by the symbol. It is an error if there is no Class named by the symbol.

***Else, it is not qualified and the first of the following applies:

*

*If it names a special form it is considered a special form, and must be utilized accordingly.**

*A lookup is done in the current namespace to see if there is a mapping from the symbol to a class. If so, the symbol is considered to
  name a Java class object. Note that class names normally denote class
  objects, but are treated specially in certain special forms, e.g. '.'
  and new.

*If in a local scope (i.e. in a function definition), a lookup is done to see if it names a local binding (e.g. a function argument
  or let-bound name). If so, the value is the value of the local
  binding.

*A lookup is done in the current namespace to see if there is a mapping from the symbol to a var. If so, the value is the value of the
  binding of the var referred-to by the symbol.

*It is an error.

And I'm not sure, but I interpret this passage (from the same page) to mean that you cannot shadow macros, either:

Macros are functions that manipulate forms, allowing for syntactic
  abstraction. If the operator of a call is a symbol that names a global
  var that is a macro function, that macro function is called and is
  passed the unevaluated operand forms. The return value of the macro is
  then evaluated in its place.
If the operator is not a special form or macro, the call is considered
  a function call.

A: The first two both evaluate to 5 for me (Clojure 1.4 in Eclipse / Counterclockwise REPL). I suspect there is a bug in Try Clojure if you are getting 3.
You should be able to locally shadow over both function and macro names (though it often isn't a good idea since it can result in some subtle and confusing bugs!).
The third won't work because def is a special form. Special forms get special treatment from the Clojure reader and/or compiler, so you can't shadow them.


text:
Q: Understanding runtime of this python function def loopy_loop(n):
  for i in range(n):
    for j in range(i):
      if j*j > i:
        break

Where n is a positive integer.
Let's say I take n=10
The outer loop will run n times for sure (n=10 times)
The inner loop will run based on the values.

*

*n = 0, the inner loop runs 0 times

*n=1, the inner loop runs once

*n=2, the inner loop runs 3 times

*n=3, the inner loop runs 4 times(until j=3, and 9>3)

*n=4, the inner loop runs 4 times as well

*and so on until n=9, where it will run 5 times
I'm having difficulties putting everything together to express the runtime using big O notation. Is there a set algorithm that could help me for this specific snippet of code an others?

A: The outer loop runs n times.
The inner loop runs sqrt(i) times (because when i is given it stops when j**2 reaches i) but i grows (roughly) like n (n//2 average)
The complexity is O(n**1.5)  (n times square root of n)
More accurate estimate:
def loopy_loop(n):
    counter=0
    for i in range(n):
        for j in range(i):
            counter+=1
            if j*j > i:
                break
    return counter,int((n)*(n//2)**0.5)

print(loopy_loop(5))
print(loopy_loop(10))
print(loopy_loop(100))
print(loopy_loop(1000))
print(loopy_loop(15000))

result (count vs estimate):
(10, 7)
(31, 22)
(810, 707)
(22579, 22360)
(1247250, 1299038)


text:
Q: createBrowserRouter How to nest child routes inside another route that itself is a nested child route? I am new to react router I followed the tutorial for the latest version 6.4.3 and am using the createBrowserRouter.
For my App component below I attempted to add a children object to the index path but when I do this the app doesn't render all of a sudden.  I have tried this on the other paths having the same results. Not exactly sure what to do please help!
App.js Code below:
import logo from './logo.svg';
import './App.css';
import './index.css';

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Root from './routes/Root';
import Home from './routes/Home';
import Projects from './routes/Projects';
import ErrorPage from './error/ErrorPage';
import Contact from './routes/Contact';
import Certificates from './routes/Certificates';
import Skills from './routes/Skills';
import Cycling from './routes/HobbyRoutes/Cycling';
import Minis from './routes/HobbyRoutes/Minis';
import Chivalry from './routes/HobbyRoutes/Chivalry';
//import NavBar from '../src/NavBar/NavBar';

const router = createBrowserRouter([
    {
        path: '/',
        element: <Root />,
        errorElement: <ErrorPage />,
        children: [
            {
                index: true,
                element: <Home />,
                children: [
                    {
                        path: '/home/minis',
                        element: <Minis/>
                    }
                ]
            },
            {
                path: '/projects',
                element: <Projects />,
                errorElement: <ErrorPage />,
            },
            {
                path: '/certificates',
                element: <Certificates />,
            },
            {
                path: '/skills',
                element: <Skills />,
            },
            {
                path: '/contact',
                element: <Contact />,
            },
        ],
    },
]);

function App() {
  return <RouterProvider router={router} />;
}

export default App;

For my App component below I attempted to add a children object to the index path but when I do this the page doesn't render all of a sudden.
Expectations is that the page renders.

A: Add < Outlet /> to your parent route's render method.

An < Outlet > should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

Read more: https://reactrouter.com/en/main/components/outlet


text:
Q: Find the limit distribution of $Y_n =\frac{\sum_{i=1}^{n}X_i}{\sqrt{\sum_{i=1}^{n}|X_i|^2} }$ Let $X_1,X_2,X_3,\ldots$ be i.i.d. with uniform distribution on $[-1,1]$. Find the limit distribution of $$Y_n =\frac{\sum_{i=1}^{n}X_i}{\sqrt{\sum_{i=1}^{n}|X_i|^2} }$$
I think this is just a direct application of central limit theorem and I need to do some transformation. I got stuck when I had following results:
$$Y_n =\frac{\sum_{i=1}^{n}X_i}{\sqrt{\sum_{i=1}^{n}|X_i|^2} } =\frac{\sum_{i=1}^{n}X_i-n0}{\sqrt{n}\sigma }\times \sigma \times \sqrt{\frac{n}{\sum_{i=1}^{n}|X_i|^2}}$$
I'm not sure how to solve the third term when $n$ goes to infinity.
Thanks guys!I think weak law of large numbers is the one I need.

A: Hint : In probability theory, Slutsky's theorem extends some properties of algebraic operations on convergent sequences of real numbers to sequences of random variables.
The theorem was named after Eugen Slutsky. Slutsky's theorem is also attributed to Harald Cramér.

A: You decomposition is absolutely right. Now you need to figure out to which $\frac{1}{n}\sum_{i = 1}^n X_i^2$ converges, by weak law of large numbers,
$$\frac{1}{n}\sum_{i = 1}^nX_i^2 \to E(X_1^2) = \text{var}(X_1) + (E(X_1))^2 = \frac{1}{12}(1 - (-1))^2 + 0^2 = \frac{1}{3} \text{ in probability}.$$
Based on your decomposition, by Slutsky's theorem and continuous mapping theorem,
$$Y_n \Rightarrow N(0, \sigma^2) \times \sqrt{3} = N(0, 1)$$
as $n \to \infty$ since $\sigma^2 = \text{var}(X_1) = \frac{1}{3}$.


text:
Q: How to post grouped input data within a form in Rails I have a form that contains 4 input fields.
<%= semantic_form_for @some_model, html: {class: "horizontal-form"} do |f| %>
  <%= f.input :person_id %>
  <%= f.input :car_id %>

  <%= f.input :person_id %>
  <%= f.input :car_id %>

  <%= f.actions do %>
    <%= f.action :submit, button_html: {class: "btn btn-primary"} %>
  <% end %>
<% end %>

As you can see the input fields are identical.
I want to group these fields so they can be posted as an array like this:
[ [3838, 9090], [2938, 893] ]

Ang then i can be able to loop this array and fetch the data i need from an external api.
How can i achieve this?

A: version of HTML
    <input type="textbox" name="person_id[]", value="person A">
    <input type="textbox" name="car_id[]", value="car A">
    <input type="textbox" name="person_id[]", value="person B">
    <input type="textbox" name="car_id[]", value="car B">

OR
    = simple_form_for @ some_model do |f|
    = f.input_field :name, multiple: true
    = f.input_field :name, multiple: true
    = f.submit

A: Could you not create another field on your Model to hold the array.
Then create a Private controller method that runs when the form is saved and appends all the values to the array?


text:
Q: @Validate not skipping invalid rows when used with CsvRoutines in UniVocity parser I am using Univocity parser version 2.7.3. I have a CSV file that has 1 Million records and might grow in future. I am reading only a few specific columns from the  file and below are my requirements:

*

*DO NOT store the CSV contents into memory at any point

*Ignore/skip bean creation if either of latitude or longitude columns
in CSV are null/blank
To meet these requirements, I tried implementing CsvRoutines so that the CSV data is not copied over to memory. I am using @Validate annotation on both "Latitude" and "Longitude" fields and have used error handler to not throw back any exception so that the record will be skipped on validation failure.
Sample CSV:
#version:1.0
#timestamp:2017-05-29T23:22:22.320Z
#brand:test report
    network_name,location_name,location_category,location_address,location_zipcode,location_phone_number,location_latitude,location_longitude,location_city,location_state_name,location_state_abbreviation,location_country,location_country_code,pricing_type,wep_key
    "1 Free WiFi","Test Restaurant","Cafe / Restaurant","Marktplatz 18","1233","+41 263 34 05","1212.15","7.51","Basel","test","BE","India","DE","premium",""
    "2 Free WiFi","Test Restaurant","Cafe / Restaurant","Zufikerstrasse 1","1111","+41 631 60 00","11.354","8.12","Bremgarten","test","AG","China","CH","premium",""
    "3 Free WiFi","Test Restaurant","Cafe / Restaurant","Chemin de la Fontaine 10","1260","+41 22 361 69","12.34","11.23","Nyon","Vaud","VD","Switzerland","CH","premium",""
    "!.oist*~","HoistGroup Office","Office","Chemin de I Etang","CH-1211","","","","test","test","GE","Switzerland","CH","premium",""
    "test","tess's Takashiro","Cafe / Restaurant","Test 1-10","870-01","097-55-1808","","","Oita","Oita","OITA","Japan","JP","premium","1234B"

TestDTO.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TestDTO implements Serializable {

    @Parsed(field = "location_name")
    private String name;
    @Parsed(field = "location_address")
    private String addressLine1;
    @Parsed(field = "location_city")
    private String city;
    @Parsed(field = "location_state_abbreviation")
    private String state;
    @Parsed(field = "location_country_code")
    private String country;
    @Parsed(field = "location_zipcode")
    private String postalCode;

    @Parsed(field = "location_latitude")
    @Validate
    private Double latitude;

    @Parsed(field = "location_longitude")
    @Validate
    private Double longitude;

    @Parsed(field = "network_name")
    private String ssid;
}

Main.java
 CsvParserSettings parserSettings = new CsvParserSettings();
        parserSettings.detectFormatAutomatically();
        parserSettings.setLineSeparatorDetectionEnabled(true);
        parserSettings.setHeaderExtractionEnabled(true);
        parserSettings.setSkipEmptyLines(true);
        parserSettings.selectFields("network_name", "location_name","location_address", "location_zipcode",
                "location_latitude", "location_longitude", "location_city","location_state_abbreviation", "location_country_code");

        parserSettings.setProcessorErrorHandler(new RowProcessorErrorHandler() {
            @Override
            public void handleError(DataProcessingException error, Object[] inputRow, ParsingContext context) {
                //do nothing
            }
        });

        CsvRoutines parser = new CsvRoutines(parserSettings);
        ResultIterator<TestDTO, ParsingContext> iterator = parser.iterate(TestDTO.class, new FileReader("c:\\users\\...\\test.csv")).iterator();

        int i=0;
        while(iterator.hasNext()) {
            TestDTO dto = iterator.next();
            if(dto.getLongitude() == null || dto.getLatitude() == null)
                i++;
        }

        System.out.println("count=="+i);

Problem:
I actually expected the count to be zero since I have added error handler and haven't thrown back the data validation exception but seems thats not the case. I thought @Validate will throw back an exception when it encounters a record with either Latitude or Longitude as null (both the columns may be null in same record as well) which is handled and ignored/skipped at error handler.
Basically I do not want UniVocity to create and map unnecessary DTO objects in heap (and lead to out of memory) since there are chances that the incoming CSV file might have more than 200 or 300k records with either Latitude/Longitude as null.
I even tried adding custom validator in @Validate as well but in vain.
Could someone please let me know what am I missing here?

A: Author of the library here. You are doing everything right. This is a bug and I just opened this issue here to be resolved today.
The bug appears when you select fields: the reordering of values makes the validation run against something else (in my test, it validated the city instead of latitude).
In your case, just add the following line of code and it will work fine:
parserSettings.setColumnReorderingEnabled(false);

This will make the rows be generated with nulls where fields were not selected, instead of removing the nulls and reordering the values in the parsed row. It will avoid the bug and also make your program run slightly faster.
You will also need to test for null in the iteration bit:
TestDTO dto = iterator.next();
if(dto != null) { // dto may come null here due to validation
    if (dto.longitude == null || dto.latitude == null)
        i++;
    }
}

Hope this helps and thank you for using our parsers!


text:
Q: Function to zip a CSV file in python I am trying to make a function which uses as arguments the source path, source file, target path, target file and that way convert an CSV file into zip. I am new to both python and this site so if you can please help me.

A: import os
from zipfile import ZipFile

def create_zip(source_path, source_file, target_path, target_file):
    # get full path of source and target
    source_filepath = os.path.join(source_path, source_file)
    target_filepath = os.path.join(target_path, target_file)
    # make a new empty zip file at target
    with ZipFile(target_filepath, 'w') as new_zipfile:
        # write source into it
        new_zipfile.write(source_filepath)


text:
Q: How to set cron job but only using ftp details i dont have cpanel I am developing application in codeigniter ,i want to run my controller method every mid night where i am updating status of some table field according to date wise.
I know it can be done using cron job with cPanel ,but client does not have cpanel ,he has only ftp details,so any one has idea how i can set cron job using ftp ? any script which run automatically?
Thank you.

A: Normally CLI from Codeigniter require access to SSH terminal to add a cron job via crontab -e or if you have cpanel via cronjobs panel.
The solution can be if you can call the address via GET so in this case you can add a cron job in another server and call that address with GET.
Add cron via SSH on shell:
Login to SSH shell via Putty on Windows, Terminal on Mac and Terminal on Linux:
Type: crontab -e
(If you don't have an editor pre-selected it will ask you to choice one, i recommend "nano")
Add a new line:
59 23 * * * /path/to/codeigniter/index.php controller Method

and it will call every day at 23:59 the Controller "controller" and Method 'Method"
Cheers

A: You will not be able to set up a cron job on your server using ftp. What you could do is put all the script you want to run in a single page and use a service like www.pingdom.com to visit that page every midnight.
Dan


text:
Q: Does anyone know why this Ajax wont work? I have some code, some to change the class of a div, the rest to load content into the ajax div.
The ajax div however, does not load content. Why might this be?

These divs start the ajax code (or should do at least)

Everyone, everywhere

Favourites Only

Why won't it work :(

A: DEMO
Delete your div onclick event,since already you are manipulating your click event in the script.
Edited div

Everyone, everywhere

Favourites Only

And I don know what argument you are passing in to loadXMLDoc('indexFav'); and  loadXMLDoc('indexEveryone'); apart from that your javascript code is correct.
Hope this helps
Thank you

A: One obvious problem I can see is that you pass a string to loadXMLDoc, then you try to access .data on that string.


text:
Q: What is the easiest way to simulate a database table with an index in a key value store? What is the easiest way to simulate a database table with an index in a key value store? The key value store has NO ranged queries and NO ordered keys.
The things I want to simulate (in order of priority):

*

*Create tables

*Add columns

*Create indexes

*Query based on primary key

*Query based on arbitrary columns

A: If you use Redis (an advanced key-value store that supports strings, lists, sets, etc.) Then this is quite easy. I have already developed a C# redis client that has native support for storing POCO's data models. These exact same POCO's can be used by OrmLite to store it in a RDBMS.
By the way Redis is fast, I have a benchmark that stores and retrieves the entire Northwind Database (3202 records) in under 1.2 seconds (running inside a UnitTest on a 3yo iMac).
I store entities in two ways

*

*Distinct entities, where I combine the Class type name and Primary Key to create a unique key e.g. urn:user:1

*

*I then maintain a separate set of primary keys (in a Redis Set) to keep track of all my entities, using a key like: ids:user

*In a Redis server side list - which acts very much like a table with support for paging, using a key like: lists:user

A: Use a hashtable or dictionary.  If you want unique key values you could use a GUID or hashcode.

A: The key-value store should support ordering the keys and ranged access to the keys.
Then you should create two dictionaries:
id -> payload

and
col1, id -> NULL

, where payload should contain all the data the database table would contain, and the keys of the second dictionary should contain the values of (col1, id) from each entry of the first dictionary.


text:
Q: After upgrade to Sitecore 6.6, thumbnail image size parameters are inappropriately passed We have upgraded from Sitecore 6.5 to 6.6, and after the upgrade we have images throughout the site which are now showing up with ugly black boxes around them.
Changing the Media.DefaultImageBackgroundColor and Media.UseLegacyResizing options does nothing. I mention the former only as an extra hint that caching may be involved somehow. Changing the settings on image fields, restarting the app pool and website, etc. does nothing to solve this problem.
Has anyone found this problem when upgrading to Sitecore 6.6? Any idea as to the cause or fix?

A: Is the box around the entire image, or just top/bottom or left/right? If the latter, then is the height/width dimensions you have provided in the same scale as the original image?
Is not either set AllowStretch to true (pass in as=true) or use MaxHeight/MaxWidth parameters instead (pass in mh=182 and mw=116) which will scale the image appropriately if needed.
This is a bit old, but the parameters should be the same... Sitecore Image Parameters


text:
Q: Save running ECS container as new image and upload to ECR I am launching Apache, MySQL, and memcached docker containers from AWS ECR into an ECS instance. Engineers are able to browse around and make changes as they see fit. These containers expire after a set period of time but they are wanting to save their database changes for use in future containers.
I am looking into seeing if there's a solution I can automate this process to occur before the containers terminate, either with Lambda, aws-cli, or some other utility.
I am looking for a solution that would take the mysql container and create a new image from it. I saw this question and it's mostly what I want:
How to create a new docker image from a running container on Amazon?
But you have to run docker commit from the ECS instance as well as perform the login and push from there. There doesn't appear to be a way to have the committed image pushed to the ECR without having to login with aws ecr get-login --no-include-email and running the output for docker to get the token.
The issue I have with that is if we get to a point where we have multiple ECS instances running it would be difficult to know where the container the engineer is running from, SSHing into that server, and running the docker commit, docker tag, aws ecr login, and docker push commands. To me, that seems kind of hacky and prone to error.
I have the MySQL containers rebuilt and repushed to the ECR every hour so that they have the latest content updates. To launch the containers I am using a combination of ecs-cli and aws-cli to use a docker-compose.yml file to create a task in ECS.
Is there some functionality I can use to commit a running container to ECR with a new name/tag?
The other option I was looking into was starting the MySQL container with persistent storage (EBS/EFS) but am still trying to see if that's doable since I would have to somehow tag the persistent storage so that it will only be used when the engineer launches it that way. Essentially, I would have a unique docker-compose.yml file that is specific to persistent volumes and it would either launch a new container with fresh mysql data or use an existing one if it exists, given a specific name.


text:
Q: E[Z=XY] not matching with Z = Binom(4,p) I tried to multiply two independent binomials, each distributed with $n=2$ and probability p. So using the piecewise function for $P(XY),$ I have $$P(Z=z) = P(XY = xy) = \sum_{xy=z} z \cdot P(X=x, Y=y)$$ leading to $Z \sim \text {Binom}\ (4,p)$. But using the piecewise function to compute $E[XY]$...I got $4p^2.$ But if $Z \sim \text {Binom}\ (4,p),$ the expectation should be $4p.$ Could someone let me know where I went wrong?
Thank you in advance.

A: If $$X \sim \operatorname{Binomial}(2,p), \quad Y \sim \operatorname{Binomial}(2,p), \\ Z = XY, \quad W \sim \operatorname{Binomial}(4,p),$$ and $X$ and $Y$ are independent, then $$\begin{align*}
\Pr[Z = 1] &= \Pr[XY = 1] \\
&= \Pr[(X = 1) \cap (Y = 1)] \\
&= \Pr[X = 1]\Pr[Y = 1] \\
&= \left(\binom{2}{1}p^1 (1-p)^{2-1}\right)^2 \\
&= 4p^2(1-p)^2. \end{align*}$$
However,
$$\Pr[W = 1] = \binom{4}{1} p^1 (1-p)^{4-1} = 4p(1-p)^3 \ne \Pr[Z = 1],$$ demonstrating $W$ and $Z$ are not identically distributed.
In fact, it is the sum of independent and identically distributed binomial random variables that are also binomially distributed, not the product.

A: We have
$$\begin{align*}
\mathsf P(Z=0)
&=\mathsf P(X=0,Y=0)+2\cdot \mathsf P(X=0,Y=1)+2\cdot \mathsf P(X=0,Y=2)\\\\
&=(1-p)^4+4p(1-p)^3+2p^2(1-p)^2
\end{align*}$$
and
$$\begin{align*}
\mathsf P(Z=1)
&=\mathsf P(X=1,Y=1)\\\\
&=\mathsf 4p^2(1-p)^2
\end{align*}$$
and
$$\begin{align*}
\mathsf P(Z=2)
&=2\cdot\left(\mathsf P(X=1,Y=2)\right)\\\\
&=4p^3(1-p)
\end{align*}$$
and
$$\begin{align*}
\mathsf P(Z=4)
&=\mathsf P(X=2,Y=2)\\\\
&=p^4
\end{align*}$$
Hence we get the pmf
$$ p_{Z}(z)=
\begin{cases}
(1-p)^4+4p(1-p)^3+2p^2(1-p)^2 & z=0 \\
4p^2(1-p)^2 & z=1 \\
4p^3(1-p) & z=2 \\
p^4 & z=4 \\
\end{cases} $$
It would behoove you to check that the respective probabilities sum to $1$.


text:
Q: LibAV FFMPEG How to get devices list? I looked up to documantation and found a very convenient AVInputFormat's funciton get_device_list . But the problem is I can't use it.
Here's my short code snippet
#include <QDebug>

extern "C"
{
#include <libavformat/avformat.h>
#include <libavdevice/avdevice.h>
}

int main(int argc, char *argv[])
{
    avdevice_register_all();

    AVFormatContext *formatContext = avformat_alloc_context();

    AVInputFormat *inputFormat = av_find_input_format("dshow");

    AVDeviceInfoList devices;
    inputFormat->get_device_list(formatContext, &devices);

    qDebug() << devices.nb_devices;

    avformat_free_context(formatContext);

    return 0;
}

And that code CRASHES when I'm trying to print devices. How do I use that function properly? The official domentation has no examples using that function.


text:
Q: Show that the sequence can be smaller than any $\varepsilon >0$ How to find an upper-bound for the following sequence to show that it can be smaller than $\forall \varepsilon >0$:
$$a_n=n^{1/n}-1$$
If we do the following operations:
$$a_n = n^{1/n}-1 = e^{\ln n/n}-1>\frac{\ln n}{n}$$
we get unuseful information. I cannot find a workable upper-bound for the situation.
Any help is appreciated.

A: $a_n=e^{\frac 2 n \ln {\sqrt n}} -1<e^{\frac 2 n  ({\sqrt n-1})} -1 <e^{\frac 2 n  ({\sqrt n})} -1$. You can now find an explicit $N$ such that $a_n <\epsilon$ for $n >N$.

A: You don't need a special form for upper bound. Since $e^x-1\sim o(x)$, and $\lim\limits_{n\rightarrow \infty}\frac{\ln n}{n}=0$, the rest will be natural.


text:
Q: Correct way to start a map activity? I want to start as MainActivity a MapActivity and include inside a menu fragment and some more stuff. My dilemma is what would be better, make my MapActivity as main or make another activity with the map and include it inside an empty MainActivity where I will put more stuff later?

A: make your main activity your map activity, MainActivity is really just a name for a class and can be entirely removed or changed, it doesn't have any special meaning, so if the main point of your app is to use maps, make your map activity your main activity.


text:
Q: How can I remove a key binding so that the cua C-x key binding so that I can have the original effects of C-x? While in cua mode, I want C-x to act as if cua mode was not active. I like cua C-c, C-v and C-z. But, I grew accustomed to eMacs use of C-x, and I want C-x to remain exactly as it was, with or without a selection.
(define-key cua--prefix-repeat-keymap (kbd "C-x") nil)

successfully modifies the value to nil, but cua still strangely affects the functioning of C-x, if it does anything at all.
I would like a way to completely remove the keybinding because in this case, setting the value to nil does not cause the binding to be ignored.
For the curious... I prefer delete to cause deleted ranges to enter the yank stack (like the cua C-x would do). I achieved this with the following:
(bind-keys ([delete] . (lambda ()
      "Kill active region to the yank stack.
Otherwise, perform normal delete.
Use backspace for an emacs range delete into register 0."
       (interactive)
       (if (use-region-p)
           (delete-active-region t) ;; yank selection into stack
         (delete-char 1))))) ;; forget singly removed characters

A: Via stack exchange How to implement remove-key to completely undo the effect of define-key, I extracted elisp which successfully removes the key binding.
(defun remove-key (keymap key)
  (define-key keymap key nil)
  (setq key (cl-mapcan (lambda (k)
                         (if (and (integerp k)
                                  (/= (logand k ?\M-\^@) 0))
                             (list ?\e (- k ?\M-\^@))
                           (list k)))
                       key))
  (if (= (length key) 1)
      (delete key keymap)
    (let* ((prefix (vconcat (butlast key)))
           (submap (lookup-key keymap prefix)))
      (delete (last key) submap)
      (when (= (length submap) 1)
        (remove-key keymap prefix)))))

Using remove-key, all cua reaction to C-x is successfully eliminated:
(remove-key cua--prefix-repeat-keymap (kbd "C-x"))

A: Do you care at all about C-c, C-v, and C-z ?
If not, then you just want to use cua-selection-mode instead of cua-mode.


text:
Q: Combining "one" and "they": When one learns, they have to Is it possible to use "one" and "they" in a single sentence like this:

When one learns a language, they have to learn about the culture as
  well.

even though each of this pronoun uses a different grammatical number?

A: Your idiomatic choices are

When you are learning a new language, you...
When one is learning a new language, one ...
When a person is learning a new language, they ...