text:
Q: Merge Syntax is not correct I have the following script that, I'm using to update a column in a table but, I'm missing something. Can someone help. Basically, the script joins two tables by matching substrings of the name, address to find a match but the syntax for the actual MERGE is what does not work. I can run the script outside the MERGE code with no issues and it shows me the matches. The problem is when I use the MEGRE code for the update.
Merge Solicitor_Prospects AS T
USING
(
/* ------------------------------------------------ */
select *
  from  (SELECT
          S.[id_Number],
          S.[mrn],
          S.CnBio_First_Name,
          S.CnBio_Last_Name ,
          S.CnAdrAll_1_01_Addrline1,
          S.CnAdrAll_1_01_ZIP,
          S.CnBio_Name,
          S.CnBio_ID,
          S.CnBio_Last_Name+LEFT(S.CnBio_First_Name,3)+MED.DBO.RemoveSpecialChars(LEFT(MED.DBO.Format_address(S.CnAdrAll_1_01_Addrline1,1),5))+left(S.CnAdrAll_1_01_ZIP,5) as DUP_KEY,

          'Address 1 Line 1' As Dup_Source
FROM Solicitor_Prospects AS S
WHERE S.CnAdrAll_1_01_Addrline1 IS NOT NULL) AS p
   join (select s.* from med..LMC_ENTITY s
        ) AS awa on p.CnBio_First_Name = awa.First_Name and p.CnBio_Last_Name = awa.Last_Name and
                 left(p.CnAdrAll_1_01_ZIP,5) = left(awa.Pref_Zip,5) and
                 left(med.[dbo].[fn_remove_char](med.[dbo].[Format_address](p.CnAdrAll_1_01_Addrline1,1)),5) = left(med.[dbo].[fn_remove_char](med.[dbo].[Format_address](awa.Pref_Line1,1)),5)
                 where LEN(p.Dup_Source) > 1
/* ------------------------------------------------ */
)
WHEN MATCHED
       THEN UPDATE SET T.ID_NUMBER = S.IN_NUMBER
GO

A: Try this:
Merge Solicitor_Prospects AS T
USING
(
/* ------------------------------------------------ */
select *
  from  (SELECT
          S.[id_Number],
          S.[mrn],
          S.CnBio_First_Name,
          S.CnBio_Last_Name ,
          S.CnAdrAll_1_01_Addrline1,
          S.CnAdrAll_1_01_ZIP,
          S.CnBio_Name,
          S.CnBio_ID,
          S.CnBio_Last_Name+LEFT(S.CnBio_First_Name,3)+MED.DBO.RemoveSpecialChars(LEFT(MED.DBO.Format_address(S.CnAdrAll_1_01_Addrline1,1),5))+left(S.CnAdrAll_1_01_ZIP,5) as DUP_KEY,

          'Address 1 Line 1' As Dup_Source
FROM Solicitor_Prospects AS S
WHERE S.CnAdrAll_1_01_Addrline1 IS NOT NULL) AS p
   join (select s.* from med..LMC_ENTITY s
        ) AS awa on p.CnBio_First_Name = awa.First_Name and p.CnBio_Last_Name = awa.Last_Name and
                 left(p.CnAdrAll_1_01_ZIP,5) = left(awa.Pref_Zip,5) and
                 left(med.[dbo].[fn_remove_char](med.[dbo].[Format_address](p.CnAdrAll_1_01_Addrline1,1)),5) = left(med.[dbo].[fn_remove_char](med.[dbo].[Format_address](awa.Pref_Line1,1)),5)
                 where LEN(p.Dup_Source) > 1
/* ------------------------------------------------ */
) S on S.ID_NUMBER = T.ID_NUMBER -- !!! You forgot alias and condition. I took ID_NUMBER, but I think you should write here other columns (which should be used for to link target and source sets) !!!
WHEN MATCHED
       THEN UPDATE SET T.ID_NUMBER = S.IN_NUMBER
GO


text:
Q: Why try/catch behavior is different in a coroutine scope and in a simple suspending function (Kotlin)? As I tried to managed the rethrow in a coroutine context, I finally understood that in suspending function we can use try/catch as usual (thanks @Tenfour04).
fun main(): Unit = runBlocking {
    launch {
        doAction()
    }

    launch {
        delay(2000)
        println("Printed2")
    }
}

suspend fun doAction() {
     try {
        delay(1000)
        throw Error("Some error")
    } catch (e: Throwable) { // nope, does not help here
        println("Printed1")
    }
}
// Printed1
// Printed2

But what was confusing me (and make me use badly the CoroutineExceptionHandler) is in the following code the try/catch is not working as usual, as the exception kills the coroutine :
fun main(): Unit = runBlocking {
    // Don't wrap in a try-catch here. It will be ignored.
    try {
        launch {
            delay(1000)
            throw Error("Some error")
        }
    } catch (e: Throwable) { // nope, does not help here
        println("Will not be printed")
    }

    launch {
        delay(2000)
        println("Will not be printed")
    }
}
// Exception in thread "main" java.lang.Error: Some error...

In both case, we are in a coroutine context. The difference is :

*

*the first one has not a coroutine scope as this

*the second one as coroutine scope as this

I'm not very clear of why the try/catch behavior is different in the both cases

A: Ok I understood. This is because the try/catch is outside of coroutine. If I change the try/catch and the launch, the exception not kill the coroutine.
import kotlinx.coroutines.*
import kotlinx.coroutines.runBlocking

fun main(): Unit = runBlocking {
    // Don't wrap in a try-catch here. It will be ignored.
    launch {
        try {
            delay(1000)
            throw Error("Some error")
        } catch (e: Throwable) { // nope, does not help here
            println("Will not be printed")
        }
    }

    launch {
        delay(2000)
        println("Will not be printed")
    }
}

Sorry, it was so evident.
Tenfour04 told me in the previous question, but I did't get that.
Stackoverflow is a good therapy :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: H3 is aligning right of center, need a fresh set of eyes I have a potentially stupid question here.
I've got a fiddle with a block of welcome text coming up off-center. I'm usually excellent at trouble-shooting my own CSS but this is making me absolutely batty. I've stripped all of the extra margin autos and text-align centers away to make this clearer. You can actually delete the entire JS segment and set the #welcome DIV opacity back to 1 for further clarity.
http://jsfiddle.net/Imperative/29Aat/88/
Here's the relevant CSS:
html, body {
    height: 100%;
    margin: 0 auto;
}
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
#wrap {
    zoom: 1;
    position: relative;
    min-height: 100%;
    overflow: hidden;
}
#welcome {
    position: relative;
    opacity: 0;
    top: 0px;
}
#welcome h3 {
    font-family:'Alegreya SC', serif;
    font-size: 42px;
    color: rgb(230, 230, 230);
}

I'm clearly missing something really novice and really obvious but I'm too close to this thing 88 iterations in and I'm completely missing the boat.
What is cascading downwards from html, body, wrap and causing the whole #welcome block to shift right? I would have expected a lot of positions without any efforts at centering anything but a 50% shift to the right? What the frack?

A: Your <nav> element can't contain <li> elements. You have to put them into a <ul>:
nav
  ul
    li
    li

As for your actual problem: your header is collapsing because it contains floating elements. Give it overflow: auto and it will resize to fit them:
header.topbar {
    overflow: auto;
    /* Get rid of this: height: 80px; */
}

Finally, center the text:
#welcome {
    text-align: center;
}

And it works: http://jsfiddle.net/29Aat/103/

A: If I understood you correctly you want the header completely in the center. But you didn't define nav width.
Here's the updated fiddle:JSFiddle
Here's what I added:
nav {
    width: 100%;
}

#welcome h3 {
    text-align: center
}

A: Ended up being a simple solution:
#welcome {
    position: relative;
    opacity: 0;
    top: 0px;
    clear: both;
}
#welcome h3 {
    font-family:'Alegreya SC', serif;
    font-size: 42px;
    color: rgb(230, 230, 230);
    text-align: center;
}

I had to clear the float on the Welcome, at which point positioning went back to normal. At that point, adding the center back to the H3 worked as expected.
Fixed Fiddle: http://jsfiddle.net/Imperative/29Aat/102/

A: Without seeing the HTML, I would first wonder if the #wrap is sitting beside the #welcome, causing it to move off center?
Okay, I'm still learning  this stackoverflow thing, so cut me a bit of slack on operations here please. That being said, I see now what this jsfiddle thing can do.
Looking at the html code, you never closed the wrap-div before opening the welcome-div.
That the problem you looking at? I tried closing the div tag and adding a text-align:center to the css, but now the welcome banner has disappeared.

Okay, a bit of code tinkering lead to this:
1) Close the Wrap-div tag (I'm pretty certain that I managed to put it in the right place)
2) Modify the CSS bank:
position: absolute;
opacity: 0;
top: 25%;
width:100%;
text-align:center;


text:
Q: Small oscillations of a dynamical system near stable equilibrium points I'm having problems solving this lagrangian dynamical system:
Let $P$ and $Q$ be two points in $\mathbb R^2$ s.t. $P\in\Gamma_1\equiv y=x^2$ and $Q\in\Gamma_2\equiv y=-x^2$.
The two points are connected by a spring of constant $k>0$, with rest lenght zero. I have to find the frequency of small oscillations in a neighbourhood of the stable equilibrium points, but I don't manage to deduce their staility. This is what I've done:
$$P=(u,u^2)\text{ and }Q=(v,-v^2)\\V(u,v)=mgu^2-mgv^2+\dfrac k2(d(P,Q))^2=mg(u^2-v^2)+\dfrac k2[(u-v)^2+(u^2-v^2)^2]\\ T(\dot u,\dot v)=\dfrac{m}{2}(\dot u^2+\dot v^2+4(u^2\dot u^2+v^2\dot v^2).$$
In order to find the points of equilibrium I imposed $\nabla V(u,v)=(0,0)$, which (I think) generates the solutions
$E=\{(u,v)\in\mathbb R^2:u=v\}$. The Hessian of the potential is given by
$$D^2V=\begin{pmatrix}k[(2u^2+2uv+1)+(4u+2v)(u-v)]+2mg &&-k(2u^2+2uv+1)\\-k[(2u^2+2uv+1)+2u(u-v)]&&-k[-(2v^2+2uv-1)+(u-v)(4v+2u)]-2mg\end{pmatrix}$$
and now I should evaluate this matrix in $(u,v)\in E$, but it seems to be really tedious.
I always found stable equilibrium points of the form $(x_0,y_0)\in\mathbb R^2$ so I don't know how to find small oscillations via linearized Lagrange equation $D^2T\cdot\ddot q +D^2V\cdot q=0$ .

A: Indeed, setting $\ddot u=\ddot v= \dot u=\dot v=0$ for a stationary solution, one finds that the ODE reduces to $∇V(u,v)=(0,0)$. In detail these equations read
\begin{align}
0&=2mgu+k(u-v)+2ku(u^2-v^2)\\
0&=-2mgv+k(v-u)+2kv(v^2-u^2)
\end{align}
Combining the equations to eliminate the third-degree terms gives
$$
0=2mg(u^2-v^2)+k(u-v)^2
$$
so that either $u=v$ leading to $u=v=0$, or
$$
0=2mg(u+v)+k(u-v)\implies v=-\frac{2mg+k}{2mg-k}u=-au
$$
Inserting into the first equation then gives
$$
0=2mgau+2ku^3(1-a^2)\\
u^2=\frac{mga}{k(a^2-1)}=\frac{4m^2g^2-k^2}{8k^2}
$$
So as conjectured in the comments, if $k$ is small enough, one gets additional non-zero stationary positions, at $k=2mg$ there is a fork bifurcation.


text:
Q: capturing input from JTextInput when user doesn't press Enter In my Swing app, I have a screen that has a bunch of JTextFields.  Each JTextField uses an ActionListener's actionPerformed method to copy the user-entered text to my data model object.
This method seems to only be called if the user presses Enter.  How can I copy the user-entered text to my data model object if the user doesn't press Enter but instead 1) tabs between fields or 2) uses the mouse to click from one field to the next?

A: muJTextField.addFocusListener(/* focus listener here */); for focus changes
myJTextField.getDocument().addDocumentListener(/* document listener here */); for document changes
For document changes use changeUpdate()

A: If you only want to perform an action when the user moves away from the field (not on every character changing in the field) then listen to the focus events:
JTextField textField = ...
textField.addFocusListener(new FocusAdapter(){ void focusLost(FocusEvent e)
  { doSomething(); } );

You might want to take a look at JFormattedTextField which handles this kind of thing for you.

A: the problem with mouseclick, is that the component you click on must grab focus, else focus lost will not be called...
i had the same problem, so i used a timer to commit my code, every x milliseconds...if you sure that focus lost will be called when you click on some other component, a simple focus listener will do the trick...


text:
Q: Header redirect works at random times - alternative? Login code and if successful, a header redirect is implemented. It works at random times, I don't know what I'm doing to get it working and then for it to fail.
 <?php
ob_start();
require ("include/PassHash.php");

if(isset($_POST['login'])){

    // Returns more than 0 rows (Email found)
    if($total>0 && PassHash::check_password($row['password'], $_POST['password'])){
        // Correct credentials.
        $_SESSION['user_id'] = $row['id'];
        $_SESSION['user_email'] = $email;
        session_set_cookie_params(24*60*60);
        header("Location: /index.php?p=user_account");
        exit();
        ob_end_flush();
    } else {
        // Incorrect password / email.

    }
}
?>

A: In php, if you are writing any code that involves sessions or headers, you need to be careful about preventing any output before the code is called. Once output is sent, the response headers also get sent and you wont be able to change them.
Output can be anything from echo/print statements, but more commonly, its leading spaces or linebreaks before your PHP code. You need to have the <?php open tag to start on the first line and first character of the file.


text:
Q: Ionic-Angular problem with ngx-translate/http-loader I am using ngx-translate and ngx-translate/http-loader for translating my ionic/angular project. I have this code inside app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    HttpClientModule,
    AppRoutingModule,
    ReactiveFormsModule,
    FormsModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: createTranslateLoader,
        deps: [HttpClient],
      },
    }),
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}

In
export function createTranslateLoader(http: HttpClient) {
      return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
    }

I have this error:
Use const or class constructors instead of named functionseslint(prefer-arrow/prefer-arrow-functions)
I searched online but I not find a solution, what is the problem?
My configuration is:
"dependencies": {
    "@angular/common": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "@ionic/angular": "^6.0.0",
    "@ngx-translate/core": "^14.0.0",
    "@ngx-translate/http-loader": "^7.0.0",
    "cordova-android": "10.1.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4"
  }


text:
Q: Como destacar determinado elemento de uma table a partir do JS Estou fazendo um bingo simples utilizando html, css, ajax e JS.
Os elementos da tabela, são trazidos a partir de uma requisição, dentro de um array e posicionados na table(...).
Utilizando a função onclick, pego um número aleatório por outra requisição, a meta é, quando o número sorteado for igual a um dos números presentes na tabela, a posição do número receba um 'X', ou qualquer outra coisa que o marque.
HTML

<button type="button" id="preencher" onclick="preencherATabela()">Preencher Tabela</button>

        Cartela

<button type="button" id="jogar" onclick="sortearNumero()">Sortear Nº</button>

            Números Sorteados

<link rel="stylesheet" href="style.css">

JS
let buttonPreencherTabela = document.getElementById("preencher")
let buttonSortearNumero = document.getElementById("jogar")
let tabela = document.getElementById("table1")
let tbody1 = tabela.getElementsByTagName("tbody")[0]
let tabelaNumerosSorteados = document.getElementById("table2")
let tbody2 = tabelaNumerosSorteados.getElementsByTagName("tbody")[0]

tbody1.innerHTML = `

`

function preencherATabela(){
buttonSortearNumero.style.visibility = "visible"
buttonPreencherTabela.style.visibility = "hidden"
let Numeros = new Array;

var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

                Numeros = JSON.parse(this.responseText);
                console.log(Numeros);
                tbody1.innerHTML = ' '

                for(let i = 0; i < 20; i++){

                   tbody1.innerHTML += `<tr> <td> ${Numeros[i]} </td> <td> ${Numeros[i+1]} </td> <td> ${Numeros[i+2]} </td> <td> ${Numeros[i+3]} </td> <td> ${Numeros[i+4]} </td>  </tr>`;
                    i+=3
                }

            }
        };
        xhttp.open("GET", "dados.php", true);
         xhttp.send();

      }

      function sortearNumero(){

      let Numerosorteado;

      var xhttp = new XMLHttpRequest();
       xhttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200) {

       Numerosorteado = this.responseText;
       console.log(Numerosorteado);

       tbody2.innerHTML += `<tr><td>${Numerosorteado}</td></tr>`;

            }
             }
         xhttp.open("GET", "dados2.php", true);
         xhttp.send();

          }

https://i.stack.imgur.com/UuXFe.png

A: Você pode varrer as células da tabela procurando o texto que combina com o número sorteado.
Crie uma classe no CSS que altera a cor de fundo da célula para vermelho, por exemplo:
.marcado{
   background-color: red;
}

No JavaScript você adiciona a classe .marcado na célula que combina:
const celulas = tabela.querySelectorAll("tbody td");
for(let c of celulas){
   if(c.textContent.trim() == Numerosorteado){
      c.classList.add("marcado");
   }
}

Coloque o código acima após a linha Numerosorteado = this.responseText;.
Para saber quando todas as células foram marcadas, basta você contar quantas delas possui a classe .marcado:
const marcados = tabela.querySelectorAll("tbody td.marcado").length;
if(marcados == 25){
   alert("acabou");
}

O código acima você coloca após a linha tbody2.innerHTML += ...;
Veja que você irá comparar a variável marcados ao número de células, que são 25 no total. Se esse número 25 for variar, aí é preciso contar o número de células na tabela:
const total_celulas = tabela.querySelectorAll("tbody td").length;
const marcados = tabela.querySelectorAll("tbody td.marcado").length;
if(marcados == total_celulas){
   alert("acabou");
}


text:
Q: Parse SDK - similarTo type of query I have an app in iOS and android and I'm getting the user's location in both of them! With CoreLocation for iOS and Google Maps in android... After the location retrieval, we apply reverse geocoding, to get the locality out of them... Once we do, we perform equalTo queries to find photos of a specific location...
The thing is, there are occasions where the locality of iOS, is slightly different to android's! For example, "Palaiochori" in iOS and "Paleochori" in android! Observe that two letters are different!
So, whereas the location is the same in both devices, the equalTo query will obviously fail!
What I want to know, is if there is any way to create a type of query, where we don't check for equality. Instead, we check for similarity!
Notice, that we do use cloud code, so any server-side solution is acceptable and preferred!!

A: Clearly the location name can not guarantee uniqueness. Two possible solutions:

*

*Ensure consistency of your database

Store a GeoPoint for these locations. When you already have Palaiochori in your database and a user finds himself in Paleochori, before saving a new object, run a whereNear() query to see if you have near places for that location.
If you have results within a reasonable radius, ask the user: Do you mean <list of near places>? The user will likely recognize the place with a similar name, and tap on it. This way you avoid duplication.

*Use a consistent location database

As soon as you have lat/lng, you could use Google Places API to ask for places near that location. Google will return a Place object with a unique placeId that you can store in your database. The id is guaranteed to remain the same and can be used for your queries reliably.


text:
Q: Why the git command failing I have a git repository on a linux server and same repository folder is synced to my Mac using Unison. When I run following command on Linux, I see the changed files.
git -c core.quotepath=false -c log.showSignature=false status --porcelain -z --untracked-files=no -- .

When I run the same command on my Mac inside the repository, I get following error.
fatal: not a git repository (or any of the parent directories): .git

I have checked the repository and it has the .git folder, so I'm clueless what the problem here. I have tried installing git from multiple sources but same problem. Looks like there is some problem within my git repo but how can I debug this?
I have other git repository which I sync using Unison and I don't see this issue. This issue only happens for only one repo.

A: Generally that means that you no .git folder in that directory you're in. When you "sync" your folder it's possible that files starting with a dot aren't replicated because they are hidden. So you should "clone" the repo on your mac. Then it should work.

A: You say the .git dir is present, so it's most likely been damaged in some way by the Unison copy. Try checking permissions or comparing the .git directory contents.
However, in all honesty using Unison on a .git dir probably is going to keep breaking. Unison will effectively merge the .git dirs most likely producing something that is invalid.
I would embrace git's decentralised nature and make a new clone on OS X. You can even clone directly from the Linux checkout (as opposed to cloning from the origin of the Linux checkout) if that makes things easier.
This may lead to a lot of temporary commits, that only exist for the purpose of syncing code between your machines. Don't worry about this, you can always squash the commits later to tidy things up before you push your tidied commits to the upstream origin.


text:
Q: Rendering two LineSeries without being scaled I have 2 line series-es, one which follow the other in its data, they both represent month days, for example:
1st Series:
1 2 3 4 5 6 7
2nd Series:
1 2 3 4 5 6 7 8 ... 29 30 31
The first series is always contained in (or equals to) the second one.
I want to represent these two series-es on a Line Chart, in a way that the first series is not scaled up on the full chart width (7 / 31 ~= 0.25, so it must occupy the first horizontal quarter of the X axis).
So, I think I need some kind of a Chart Axis which will render the 31 days and then the 2 series-es will follow that axis and be rendered according to it. (without scaling the 1st series to fill all the horizontal space of the X axis).

A: It seems to be quite simple.
Here is the screenshot, 7 blue points represent the 1st series, 31 red points - the 2nd series. Check if it is that what you need

If the chart is displayed right, here is its source code:
XAML
    <chart:Chart>
        <chart:LineSeries ItemsSource="{Binding FirstWeekItems}"
                          IndependentValueBinding="{Binding Day}"
                          DependentValueBinding="{Binding Value}" />
        <chart:LineSeries ItemsSource="{Binding MonthItems}"
                          IndependentValueBinding="{Binding Day}"
                          DependentValueBinding="{Binding Value}" />
    </chart:Chart>

Code-behind
public partial class MainPage : UserControl
{
    public MainPage()
    {
        this.InitializeComponent();

        Random rd = new Random();
        var vm = new ChartModel
        {
            FirstWeekItems = Enumerable.Range(1,7).Select(i => new ItemViewModel{Day = i, Value = rd.Next(23,25)}).ToList(),
            MonthItems = Enumerable.Range(1, 31).Select(i => new ItemViewModel { Day = i, Value = 20+i }).ToList()
        };
        this.DataContext = vm;
    }
}

public class ChartModel
{
    public List<ItemViewModel> FirstWeekItems { get; set; }

    public List<ItemViewModel> MonthItems { get; set; }
}

public class ItemViewModel
{
    public int Day { get; set; }
    public double Value { get; set; }
}


text:
Q: Big CSV parsing I'm having quite a hard time to figure out a robust and light algorithm for post-processing some big CSV files. Here's a minimal example of how they look like:

Time    a     b     c
0      2.9   1.6   4.1
0      3.6   1.1   0.5
0      3.4   0.2   1.7
1.2    0.1   4.2   1.9
1.201  2.3   3.1   4.8
9.99   0.2   0.8   1.2
10     3.1   3.3   2.3
10     3.6   3.5   3.0
10.01  1.1   4.5   3.9
10.01  2.2   3.0   2.3
17     4.3   2.3   3.8
20     1.0   3.2   3.0
30     4.1   3.0   4.9
40     3.8   3.3   1.6

I need to postprocess my CSV based on those rules:

*

*only lines whose time is a multiple of 10 need to be considered

*if multiple line have the same time tamp, take the average value of each column across the different rows

Here's the output I'd like to get:

Time    a     b     c
0      3.3   0.97  2.1
10     2.04  3.02  2.54
20     1.0   3.2   3.0
30     4.1   3.0   4.9
40     3.8   3.3   1.6

Now the constraint: my script needs to handle pretty big CSV (up to few hundreds MB) on a Windows machine without much memory available for this. Because of that, I'm not keen on storing all the CSV in a big array of dictionary, but I'd prefer to do this row by row.
Here's my first naive attempt. It's very poor and not properly working. (Small margin note: the average is not a true average but a kind of weird "running average". Bear with me here, I was trying to assess the workflow and don't really care for the numbers at this stage.)
filename = "test"
sampling_time = 10.0
tolerance = 1e-1

Dim FSO, input, output
Const ForReading = 1
Const ForWriting = 2

'Create the objects
Set FSO = CreateObject("Scripting.FileSystemObject")
Set input = FSO.OpenTextFile(filename & ".csv", ForReading, False)
Set output = FSO.OpenTextFile(filename & "_output.csv", ForWriting, True)

'First line: write headers
s = input.ReadLine()
output.WriteLine s

'Second line: initialize sSplit_old
s = input.ReadLine()
sSplit = Split(s, ",")
sSplit_old = sSplit

'Keep reading...
Do Until input.AtEndOfStream
    'read new line and split it into its components
    'this is needed to read the first element of the line, i.e. the time
    s = input.ReadLine()
    sSplit = Split(s, ",")

    'If the remainder of time/sampling_time is below the tolerance then the
    'line has to be processed.
    'Here the "\" operator (i.e. the integer division: 5\2=2, while 5/2=2.5)
    'is used as the "Mod" operator return integer remainders.
    If CDbl(sSplit(0))-sampling_time*(CDbl(sSplit(0))\sampling_time) < tolerance Then
        'If the current time is close to the previous one (within a tolerance)...
        If Abs(CDbl(sSplit(0))-CDbl(sSplit_old(0))) < tolerance Then
            '... cycle through the arrays and store the average
            For i = 0 To UBound(sSplit)
                sSplit_old(i) = (CDbl(sSplit(i)) + CDbl(sSplit_old(i))) / 2.0
            Next
        Else
            '... otherwise just write the previous time and save the current
            'one to compare it to the next one
            s = Join(sSplit_old, ",")
            output.WriteLine s
            sSplit_old = sSplit
        End If
    End If
Loop

output.WriteLine s
input.Close
output.Close

A: When you paid (too much) for your Windows OS, you also paid for a SQL engine. So use it:
Option Explicit

Dim db : Set db = CreateObject("ADODB.Connection")
Dim dd : dd = "E:\work\proj\soa\47155733\data"
Dim cs
If "AMD64" = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%PROCESSOR_ARCHITECTURE%") Then
   cs = "Driver=Microsoft Access Text Driver (*.txt, *.csv);Dbq=" & dd & ";Extensions=asc,csv,tab,txt;"
   WScript.Echo "64 Bit:", cs
Else
   cs = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" & dd & ";Extensions=asc,csv,tab,txt;"
   WScript.Echo "32 Bit:", cs
End If
db.Open cs

Dim ss : ss = "SELECT * FROM [47155733.txt]"
WScript.Echo ss
WScript.Echo db.Execute(ss).GetString(2,,vbTab,vbCrlf,"*")

ss =   "SELECT t, avg(a), avg(b), avg(c) FROM [47155733.txt]" _
     & " WHERE t = Int(t) And 0.0 = t Mod 10 GROUP BY t"
WScript.Echo ss
WScript.Echo db.Execute(ss).GetString(2,,vbTab,vbCrlf,"*")

ss = "SELECT Round(1/3, 3)"
WScript.Echo ss
WScript.Echo db.Execute(ss).GetString(2,,vbTab,vbCrlf,"*")

output:
cscript 47155733.vbs
SELECT * FROM [47155733.txt]
0       2,9     1,6     4,1
0       3,6     1,1     0,5
0       3,4     0,2     1,7
1,2     0,1     4,2     1,9
1,201   2,3     3,1     4,8
9,99    0,2     0,8     1,2
10      3,1     3,3     2,3
10      3,6     3,5     3
10,01   1,1     4,5     3,9
10,01   2,2     3       2,3
17      4,3     2,3     3,8
20      1       3,2     3
30      4,1     3       4,9
40      3,8     3,3     1,6

SELECT t, avg(a), avg(b), avg(c) FROM [47155733.txt] WHERE t = Int(t) And 0.0 = t Mod 10 GROUP BY t
0       3,3     0,966666666666667       2,1
10      3,35    3,4     2,65
20      1       3,2     3
30      4,1     3       4,9
40      3,8     3,3     1,6

SELECT Round(1/3, 3)
0,333

Tested for 32 and 64 bit on Windows 10; German locale. I prefer to specify the file format in a schema.ini file:
[47155733.txt]
Format=Delimited(,)
ColNameHeader=True
DecimalSymbol=.
Col1=t Double
Col2=a Double
Col3=b Double
Col4=c Double

Background:
Connectionstrings, odbc Connectionstrings, Driver download.


text:
Q: Why do light rays intersect (or appear to intersect) at a specific point on reflection from spherical mirror? Consider a spherical (say concave) mirror. Let an object be placed beyond its focus so that a real image is formed on reflection. The location of the image is found by considering a point on the object as a point source, drawing a couple of light rays from it, and finding their point of intersection on reflection.
My question is how do we know that all the other infinite light rays that can be drawn from the point source will also intersect at that same point on reflection?

A: The answer is that you are dealing with approximations which are reasonable in some circumstances but not in others.
If you look at a derivation of the mirror formula $\frac 1 u + \frac 1 v = \frac 1 f = \frac 2 R$ you will always find an approximation made as shown in the diagram below.

However there is another flaw in the diagram in that the assumption which has been made is that all the rays parallel to the principal axis meet at the focal point $F$ where the focal length is half the radius of curvature of the mirror.
If you have ever looked at tea, coffee or water in a mug you will know that this meeting at a point for all parallel rays does not happen.
A caustic curve is formed.

This type of defect of a spherical mirror produced when the rays are not mear to the principal axis is called spherical aberration.
Correction is possible but not for all rays.
The most common type of correction is for use in reflecting telescopes where either a parabolic reflector is used or a aspherical reflector is used with a Schmidt corrector plate in front of it.
Even that does not completely eliminate spherical aberration as is shown below with parallel rays not parallel to the principal axis.

So the title to your question "Why do light rays intersect (or appear to intersect) at a specific point on reflection from spherical mirror?" is a good one in that it has in it the word "appear" which you can interpret as being related to the degree of accuracy of reproduction of the object as an image.
Have you ever looked at yourself in a magnifying shaving/make-up mirror and notices the distortion?

A: You don't know that, and it isn't really important to build an image.
To build an image what you need is each point on the image to look like (to be illuminated by) a corresponding point on the object.
to say another way:
It's not that you need all the light from one point on the object to reach the image...
What you need is some light from each point on the object to be directed to a corresponding point on the image.

A: With a bit of geometry, you can show that if the concave mirror has a spherical profile, all of the light rays emanating from your source will converge at a single point - as long as the point of reflection is near the center of the mirror.  (This is a bit like the small angle approximation you use when you're talking about a pendulum.)
However, rays which reflect from points near the edges of the mirror will indeed fail to intersect at a single consistent location, causing the image to become distorted.  This effect is called spherical aberration.
Interestingly, for rays which are nearly parallel (such as those coming from a faraway star or galaxy), the image can be improved by using a parabolic mirror rather than a spherical mirror, which is why such mirrors are commonly used in telescopes.
Lenses have the same problem, but it's made worse by the fact that the index of refraction of a transparent material depends slightly on the wavelength of the light.  This means that, even with zero geometrical aberration, every color of light will focus through a lens at a slightly different location, causing distortion of the image.  This is called chromatic aberration.


text:
Q: Is it possible to add additional control to browser "open file" dialog? I want to customize "open file" dialog that pops up when I am trying to upload a file. For example, I want to add a button on it which does something when clicked( e.g. pops up another dialog or changes the directory).

A: In theory you could do this when the dialog is opened in your own application.
As you mention javascript and "upload" I assume your frontend is running in a browser. In that case, no, you cannot. That dialog is opened by the browser and you cannot influence it from the client/javascript side.


text:
Q: SED - Insert file at top of another I have been trying to insert a file as the first line of another with following SED command, without much success. Each time the file is inserted after line 1. Is there a switch that will inserted before line 1?
sed -i '1r file1.txt' file2.txt

Thanks in advance.

A: With the N command
Provided that file2.txt has more than one line (else see the other section):
sed -i -e '1 { r file1.txt' -e 'N; }' file2.txt

The trick is to defer the printing of the first line with the N command.
From the manual:

N
Append the next line of input into the pattern space.

With the e command
Provided that file2.txt is not empty (else just do a copy):
sed -i -e '1 e cat file1.txt' file2.txt

GNU sed provides a e command that executes the command in parameter. The result is output is immediately.
From the manual:

e [COMMAND]
This command allows one to pipe input from a shell command into
  pattern space.  Without parameters, the `e' command executes the
  command that is found in pattern space and replaces the pattern
  space with the output; a trailing newline is suppressed.
If a parameter is specified, instead, the `e' command interprets
  it as a command and sends its output to the output stream.
Note that, unlike the 'r' command, the output of the command will
  be printed immediately; the 'r' command instead delays the output
  to the end of the current cycle.

A: The sed command r will place the contents of the specified file in the output before reading the next line of input. Unfortunately you can't specify 0 as the address for this command, so there's no way to insert the contents of a file before the first line of input (without poking around with the hold space).
You could, however, just use plain old cat. It is, after all, the command for concatenating files:
$ cat file1.txt file2.txt >out && mv out file2.txt

To be sure you're writing to a temporary file that does not already exist, one may use the mktemp utility:
$ tmp="$(mktemp)" && cat file1.txt file2.txt >"$tmp" && mv "$tmp" file2.txt

This is slightly awkward on the command line, but a good precaution in any script that needs to write to a temporary file.

A: If you're determined to avoid cating to an explicit temporary file (or via a buffer such as sponge), then it looks like ed at least will accept a 0-address for its r command:
ed -s file2.txt << EOF
0r file1.txt
wq
EOF

or equivalently
printf '0r file1.txt\nwq\n' | ed -s file2.txt

A: If you want to insert the same file on top of multiple files within the same directory, the following based on Kusalananda's answer might be used:
for i in file*; do tmp="$(mktemp)" && cat file1 $i >"$tmp" && mv "$tmp" $i; done


text:
Q: unable to get data though model function code igniter I have created one new function in a existing controller, in which I am accessing a model's function which has a query to get the list.
I have loaded the model in controller. This model function works with other function but not working for new created function.
class Cart extends CI_Controller
{
    function Cart()
    {
        parent::__construct();
        $this->mdl_common->checkUserSession();
        $this->load->model('mdl_friend_web');
        $this->load->model('api/mdl_friend','mdl_friend_api');
        $this->load->model('mdl_cart_web');
        $this->load->library('pagination');
    }

//works for this function
    function ajax_get_cart_list($offset = 0)
    {
        is_ajax();
        $this->load->model('mdl_cart_web');

        $limit = PER_PAGE;

        $s_data = $_POST;

        $carts = $this->mdl_cart_web->get_cart_list($limit,$offset,$s_data)->result_array();
        $totalRows = $this->mdl_cart_web->get_total_cart_product($s_data)->num_rows();

        $data = $this->mdl_common->pagination_data('cart/get_cart_list/',$totalRows,$limit,'show_data');
        $data['carts'] = $carts;
        $data['total_cart'] = $totalRows;

        $html = $this->load->view('cart/ajax_cart_list',$data,true);
        echo $html;
    }

//not working for this
    function calculate_distance()
    {

        $limit = '';

        $delivery = 0;

        $previousName = '';
        $count = 0;
        $oneShop = '0';
        is_ajax();
       // $this->load->model('mdl_cart_web');
        $lat1 = $_POST['lat1'];
        $long1 = $_POST['long1'];
      //  $user_id = $_POST['user_id'];

        $user_id = $this->session->userdata('user_id');

        $carts = $this->mdl_cart_web->get_cart_list($limit,0,'')->result_array();

        $response = array();
        $data['carts'] = $carts;
        foreach($data['carts'] as $row) {

            echo $row['store_latitude'];

        }

    }

model
<?php
class Mdl_cart_web extends CI_Model
{
/*=================================================================================
                                Get cart list
==================================================================================*/

    function get_cart_list($limit,$offset,$data)
    {
        $this->db->select('c.*,p.*,s.name as store_name,s.latitude as store_latitude,s.longitude as store_longitude,count(r.product_id) as review , IFNULL(AVG(r.star),0) as avg_star,i.*',false);
        $this->db->join('p_product as p','c.product_id = p.product_id','left');
        $this->db->join('p_product_image as i','c.product_id = i.product_id','left');
        $this->db->join('p_product_review as r','c.product_id = r.product_id','left');
        $this->db->join('p_store as s','s.store_id = p.store_id','left');
        $this->db->limit($limit,$offset);
        $this->db->where('c.user_id',$this->session->userdata('user_id'));
        $this->db->group_by('c.cart_id');
        $this->db->from('p_cart as c');

        return $this->db->get();
    }

?>

I am not able to get the array data.I can see blank alert.
What is going wrong here? Please help.Thank you.

A: I think you are writing your query not properly try this:
$this->db->select('c.*,p.*,s.name as store_name,s.latitude as store_latitude,s.longitude as store_longitude,count(r.product_id) as review , IFNULL(AVG(r.star),0) as avg_star,i.*',false);
$this->db->from('p_cart as c');
$this->db->join('p_product as p','c.product_id = p.product_id','left');
$this->db->join('p_product_image as i','c.product_id = i.product_id','left');
$this->db->join('p_product_review as r','c.product_id = r.product_id','left');
$this->db->join('p_store as s','s.store_id = p.store_id','left');
$this->db->limit($limit, $offset);
$this->db->where('c.user_id', $this->session->userdata('user_id'));
$this->db->group_by('c.cart_id');
return $this->db->get();

A: As Above comment and after seeing your question that the model works fine for the one function and not for the other so I think that loading a model is what you have to look properly.
I see that in your not working function you have noticed some basic problems.

*

*You have commented the model loading code after is_ajax(). // $this->load->model('mdl_cart_web'); so first remove that comment and try again.

*Send Correct and proper data to the model. Please Check this below line of code that is executing properly or not.
In Your Not working model.
$carts = $this->mdl_cart_web->get_cart_list($limit,0,'')->result_array();

In Your Working Model:
$carts = $this->mdl_cart_web->get_cart_list($limit,$offset,$s_data)->result_array();

And One thing I want if you are using the same model in more functions in the same controller then you should use __construct()
public function __construct() {
    parent::__construct ();
    $this->load->model('mdl_cart_web');
}

By adding a model into the __construct() you can use it in the entire controller and all of the functions.


text:
Q: Convert Maven Desktop App to Dynamic App in Eclipse I have a Maven based desktop App and I have to convert it to a dynamic web app in eclipse or any other IDE ( I am using Eclipse Neon-Java EE).
I have tried with Project Facets (Right click on project name --> Properties --> Project Facets --> dynamic web app) It generates some files but it doesn't seem to be converted to web as in the project folder still appears the letter "M" and not the golobe icon. When I try to run it in Tomcat it doesn't work.
Project Folder
Any suggestion?
Thank you

A: Look into the project if you have the Maven convert option...
If not, you should check the property of the project, and change them manually, starting from the Deployment Assembly, the target runtime, check all the facets..
Then take a look into the folder of the project, into .classpath and .project and see if they have been refreshed by Eclipse, the pom should package as a war and so on...
The problem here is that you are fighting with Maven and Eclipse togheter, so my main suggestion to do this in lees time, is to create a new Dynamic project and then to copy and paste all the previous Desktop project.. you can do this in a lot of ways...
Or directly from the IDE, or simply by hand than importing again the project...
Let me know if you try one of the above suggestions :)
Moreover obviously after all of this it won't start in tomcat, you have before to configure your web.xml and so on... but at least your structure will follow the Dynamic Web Project structure standards..


text:
Q: Why isn't winsock delivering WSAESHUTDOWN here? Minimal, reproducable example:
#include <cassert>
#include <thread>
#include <WinSock2.h>
#pragma comment(lib, "Ws2_32.lib")

constexpr int BUF_SZ = 512;
void RecvThread(SOCKET sock)
{
    int iResult = 0;
    char buf[BUF_SZ] = {};

    iResult = recv(sock, buf, BUF_SZ, 0);

    assert(iResult == SOCKET_ERROR);
    assert(WSAGetLastError() == WSAESHUTDOWN);
}

int main()
{
    int iResult;

    WSADATA wsaData;
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    assert(iResult == 0);

    SOCKET sock_1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    assert(sock_1 != INVALID_SOCKET);

    SOCKET sock_2 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    assert(sock_2 != INVALID_SOCKET);

    in_addr loopback = {};
    loopback.S_un.S_un_b.s_b1 = 127;
    loopback.S_un.S_un_b.s_b2 = 0;
    loopback.S_un.S_un_b.s_b3 = 0;
    loopback.S_un.S_un_b.s_b4 = 1;

    sockaddr_in addr_1 = {};
    addr_1.sin_family = AF_INET;
    addr_1.sin_port = 51234;
    addr_1.sin_addr = loopback;

    iResult = bind(sock_1, (sockaddr const*)&addr_1, sizeof addr_1);
    assert(iResult != SOCKET_ERROR);

    sockaddr_in addr_2 = {};
    addr_2.sin_family = AF_INET;
    addr_2.sin_port = 51235;
    addr_2.sin_addr = loopback;

    iResult = bind(sock_2, (sockaddr const*)&addr_2, sizeof addr_2);
    assert(iResult != SOCKET_ERROR);

    std::thread t1(RecvThread, sock_1);
    std::thread t2(RecvThread, sock_2);

    iResult = shutdown(sock_1, SD_BOTH);
    assert(iResult != SOCKET_ERROR);
    t1.join(); // after shutdown, join the recv thread

    iResult = shutdown(sock_2, SD_BOTH);
    assert(iResult != SOCKET_ERROR);
    t2.join(); // after shutdown, join the recv thread

    // note: everything works if we delay t1.join() until after shutdown(sock_2)

    iResult = closesocket(sock_1);
    assert(iResult != SOCKET_ERROR);

    iResult = closesocket(sock_2);
    assert(iResult != SOCKET_ERROR);

    iResult = WSACleanup();
    assert(iResult != SOCKET_ERROR);

    return 0;
}

This hangs when attempting to join the recv thread, which is blocked on recv. If all created sockets have been shutdown, WSAESHUTDOWN is delivered and the program exits cleanly.
Am I doing something wrong, misunderstand how shutdown is supposed to work, or is this a Windows bug?
Since this may be a Windows bug, I'm on Microsoft Windows Version 21H1 (OS Build 19043.1165).
I expect to receive WSAESHUTDOWN when I shutdown the socket, and that occurs when I shutdown both sockets, but if I shutdown one socket and then block on the thread join, the program hangs. It's this hang that I'm attempting to diagnose.
UPDATE: the original question used recv, but apparently this is problematic with UDP sockets, and the lack of shutdown error occurs with either recv or recvfrom.

A: You can't use recv() on a UDP socket unless you first call connect() to statically associate a remote peer with the socket.  Otherwise, recv() can't return any datagrams, since it won't know which ones are from the desired peer, so it will discard everything.
Since you are not calling connect(), you should be getting a WSAENOTCONN error in both threads.
If you are not going to connect() the sockets, you need to use recvfrom() instead.


text:
Q: jQuery Pass Multiple Checkbox Value to PHP using Ajax I have jQuery to get multiple checkbox value.
You can refer for the demo here
The function for that jQuery is OK, when We tick the checkbox then We can see what We choose based on data-id after btnUpdate click.
But now I want to pass and store it to database using PHP by Ajax.
So Example output,
1 -> read
1 -> update
2 -> update

Then save it to database on table:
ID | chkStatus
1  | read
1  | update
2  | update

Here is the HTML

  Nama
  Create
  Read
  Update
  Delete

  coba
  <input type="checkbox" data-id="1" data-tipe="create">
  <input type="checkbox" data-id="1" data-tipe="read">
  <input type="checkbox" data-id="1" data-tipe="update">
  <input type="checkbox" data-id="1" data-tipe="delete">

  coba 2
  <input type="checkbox" data-id="2" data-tipe="create">
  <input type="checkbox" data-id="2" data-tipe="read">
  <input type="checkbox" data-id="2" data-tipe="update">
  <input type="checkbox" data-id="2" data-tipe="delete">

  <input type="button" id="btnUpdate" value="Update"/>

jQuery
$(function(){
  $('#btnUpdate').click(function(){
    var cb = [];
    $.each($('input[type=checkbox]:checked'), function(){
      cb.push($(this).data('id') + ' -> ' +$(this).data('tipe'));
    });
    $('#status').val(cb.join("\n"));
  })
});

A: You can send arrays server side via both get or post, in your case here I'd recommend modifying how you're building the array mind:
$(function(){
    $('#btnUpdate').click(function(){
        var cb = [],
            post_cb = []

        $.each($('input[type=checkbox]:checked'), function(){
            var id = $(this).data('id'),
                tipe = $(this).data('tipe')

            cb.push(id + ' -> ' + tipe);
            post_cb.push({
                'id': id,
                'tipe': tipe
            });
        });
        $('#status').val(cb.join("\n"));

        $.ajax({
            'type': 'post',
            'url': '/path/to/script.php',
            'data': {
                'cb': post_cb
            },
            'success': function(response) {
                // Do something
            },
            'error': function(response) {
                // Do something
            }
        });
    })
});

And then in your PHP file:
<?php

print_r($_POST['cb']);
/*

Array
(
    [0] => Array
        (
            [id] => 1
            [tipe] => read
        )

    [1] => Array
        (
            [id] => 1
            [tipe] => update
        )

    [2] => Array
        (
            [id] => 2
            [tipe] => update
        )

)

*/

?>


text:
Q: unique key/attribute/property in zodb Very simple senario:
class User(Persistent):
  def __init__(self, username, email):
    self.username = username
    self.email = email

I want to store the User instances in zodb by its username while keeping email unique.
u1 = User(username="u1",email="u1@example.com")
zodb_container[u1.username] = u1

I use the username as key to store this object, so it will be unique. My question is how to keep the email attribute unique? Is there any elegant way to do this in an object database?

A: No.
ZODB is somewhat misnamed.  It's not a "database" like Postgres or MySQL is a database that has constraints and a query language and all that stuff that people presume a database has.  It's, instead, a persistent object store.  There's nothing that ZODB does for you that Python's pickle module doesn't do for you except manage working sets that are larger than available memory, handle transactions, and allow you to share object representations between processes.  It's in effect "superpickle".
So your answer wouldn't be any different than if you had asked the same question about pickle, really.


text:
Q: how to interpret this derivation of beta function as a ratio of gamma functions? The derivation is here (screenshot included in case the link changes in the future). The parts that confuse me are

*

*Why is it important that we state the determinant of the Jacobian of the transformation?

*why are the limits of integration for $v$ listed as $[0, 1]$


text:
Q: What kind of join to I need here in R? Please help me first to make a clearer subject for that question.
To point is I don't know the correct R-terminology for what I need here. Is "join" a correct word?
set.seed(0)
df <- data.frame(a = sample(c(T,F), 10, replace=TRUE),
                 b = sample(c(T,F), 10, replace=TRUE),
                 c = sample(c(T,F), 10, replace=TRUE),
                 d = sample(c(T,F), 10, replace=TRUE))

a <- addmargins(table(df$a))
b <- addmargins(table(df$b))
c <- addmargins(table(df$c))
d <- addmargins(table(df$d))

This is the data
FALSE  TRUE   Sum
    7     3    10

FALSE  TRUE   Sum
    4     6    10

FALSE  TRUE   Sum
    4     6    10

FALSE  TRUE   Sum
    5     5    10

And what I want is to make the data look like this
   FALSE  TRUE   Sum
a      7     3    10
b      4     6    10
c      4     6    10
d      5     5    10

Sounds simple, dosn't it? I was using ddply in the past. But I don't get here how to use ddply or anything else.

A: Here is a simple one-liner to perform the table command and then to add the margins:
addmargins(t(sapply(df, table)))

#or this for just the row sums:
addmargins(t(sapply(df, table)), 2)

sapply to apply the table function to each column.
t to transpose the results
addmargins for the row/column sums

A: This is just stacking rows, you want rbind (for "binding" rows together. cbind is the equivalent for columns).
rbind(a, b, c, d)
#   FALSE TRUE Sum
# a     7    3  10
# b     4    6  10
# c     4    6  10
# d     5    5  10

A join is typically done when you have some shared columns but some different columns, and you want to combine the data such that the shared columns line up, and the different corresponding different columns are kept. For example, if you had one data frame of people and addresses, and another data frame of people and orders, you would join them together to see which address goes with which order. In base R, joins are done with the merge command.


text:
Q: Не сохраняется указатель в динамически выделенной структуре Когда не пытался работать с динамической памятью и объявлял через добавление в стек - всё было гладко, но вот я стал использовать new, и в структурах стало невозможным чтение yказателей, ни через st->mem, ни через *st->mem.
Через дебаггер я проверил, visual studio пишет что память повреждена - в то время как cheat engine определяет что память в структуре доступна, но при этом на протяжении работы цикла-переборщика модyлей, меняют содержимое хотя бы один раз - разные поля, кроме modBaseAddr.
Хотя, иногда и modBasеAddr полyчало какое-то значение, но оно никогда не являлось базовым адресом модyля. Это были обычно цифры 7, 77 или 2. Возможно, мyсор.
И это мне не понятно.
В поисках ценных ремарок в описании фyнкции на сайте микромягких, я нашёл информацию о том что;

The modBaseAddr and hModule members are valid only in the context of the process specified by th32ProcessID.

И он валидный. Я написал свою фyнкцию для полyчения пида по имени, и она работает безотказно - и пид совпадает с тем что она выводит, и тем что я нашёл в структуре через чит энжин, что оправдывает её работy.
Стало быть,  проблема в выделении, или что?
void SM::sn_GetModuleBase(char* name, byte nLnght, char* Pname, byte PnLnght, byte* moduleBase)
{
    printf("func %s is incomplete \n", nov(sn_GetModuleBase()));
    allo(HANDLE, hndl);
    allo(DWORD, pid);
    SM::sn_GetProcessId(Pname, PnLnght, pid);
    allo(MODULEENTRY32, mntry);
    mntry->dwSize = sizeof(MODULEENTRY32);
    *hndl = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, *pid);
    if (*hndl == NULL)
    {
        printf("%s: snapshot failed", nov(SM::sn_GetModuleBase()));
        rtrn;
    }
    void* strptr = calloc(wmax, 1);
    if (!Module32FirstW(*hndl, mntry))
    {
        allo(DWORD, rr);
        *rr = GetLastError();
        CloseHandle(*hndl);
        printf("%s fuck'd up in %s \nError code: %X\n", nov(Module32FirstW()), nov(sn_GetModuleBase()),*rr);
        dlt rr;
        free(strptr);
        rtrn;
    }
    else
        while(Module32NextW(*hndl,mntry))
        {
            if (!CharToOemW(mntry->szModule, (char*)strptr))
                printf("%s: cant compare \"%s\" and \"%s.\"\n", nov(sn_GetModuleBase()),(char*)strptr,name);
            if (!strcmp((char*)strptr, name))
            {
                printf("%s\n%s\n", (char*)strptr, name);
                goto suсс;
            }
        }
//fail:
    allo(DWORD, rr);
    *rr = 0;
    *rr = GetLastError();
    printf("module \"%s\" not found\nLast error:%X", name,*rr);
    dlt rr;
    CloseHandle(*hndl);
    dlt mntry;
    free(strptr);
    rtrn;

suсс:
    moduleBase = 0;
    printf("\n%X\n", mntry);
    printf("Bad:%d.\n", GetLastError());
    CloseHandle(*hndl);
//  dlt mntry;
    free(strptr);
    rtrn;
}

Сама суть вопроса была таковой: почемy из динамически выделенной структуры невозможно прочесть yказатель с разыменованием? (*modBasеAddr = *st->modBasеAddr;)
Без него - можно, но эти данные ничего не значат. Это какой-то адрес в памяти, по которомy ничего не хранится. (она там не выделена)
Прошy помощи, т.к. гyгл мне не помог - те, кто тоже задавали вопрос по access violation в чтении этого поля, не выделяли память динамически.


text:
Q: Problem with new rake task, why is rspec getting triggered? I've written a rake task in lib/tasks in my rails 3 project and it seems to run fine, only I get the following error after it runs:
$ rake dictionary:import_italian

(See full trace by running task with --trace)
/usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load': no such file to load -- /home/fletch/Dropbox/bin/kp/dictionary:import_italian (LoadError)
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load_spec_files'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `map'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load_spec_files'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:18:in `run'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:55:in `run_in_process'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:46:in `run'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:10:in `autorun'
from /usr/bin/rake:19

Can anybody tell me what is causing this?
Update:  After having another look I found out that it happens with the other built in rake tasks, though rake spec seems to work fine.
$ rake db:migrate
(in /home/fletch/Dropbox/bin/kp)
==  AddIndexesToWords: migrating ==============================================
-- add_index(:words, :title)
   -> 0.1121s
-- add_index(:words, :language_id)
   -> 0.0869s
==  AddIndexesToWords: migrated (0.1992s) =====================================

/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:235:in `load': no such file to load -- /home/fletch/Dropbox/bin/kp/db:migrate (LoadError)
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:235:in `load'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:225:in `load_dependency'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:596:in `new_constants_in'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:225:in `load_dependency'
from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.4/lib/active_support/dependencies.rb:235:in `load'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load_spec_files'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `map'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/configuration.rb:386:in `load_spec_files'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/command_line.rb:18:in `run'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:55:in `run_in_process'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:46:in `run'
from /usr/lib/ruby/gems/1.8/gems/rspec-core-2.5.1/lib/rspec/core/runner.rb:10:in `autorun'
from /usr/bin/rake:19

A: Okay, turns out it was in my rake task, I used the word describe instead of desc to give it a description.  Not sure why that effected all of my other rake tasks, though.


text:
Q: How do I connect power to a light bulb? I can't seem to figure out how to connect my light bulb to the generator to make it turn on.  How do I do this?

A: So after blowing through a lot of copper, as far as I can tell anything with out a direct power connection (lights, T.V.'s, ...) can be powered by being in a AOE proximity to either a switch, conduit or a pylon. Also a small generator seems to be able to power several lights (not just three).

A: I'm going to try and answer this as clearly as I can as I have just worked out how to get everything working. This is how you connect power to objects in your settlement:

*

*What you want to do first, as I realise you have already, is get the source of power, i.e. your generator

*Next, couple the generator with one of the 'power pylons' from the 'connectors and switches tab'. Add a cable between the generator and the pylon

*The next step is optional; add a 'switch', again from the 'connectors and switches' tab, and place it on a wall somewhere. Attach a wire between the pylon and the switch
Some lights, like the 'construction' lights, can be wired straight into the switch, and when you come out of workshop mode, you just flick the switch and they will come on

*For other lights, TVs, etc you will need a 'power conduit', again from 'connectors and switches'. There are three types of conduit, there is one for ceiling, wall and floor, and depending on which of these surfaces your desired item is going on, you choose the appropriate conduit. e.g. if you want a wall mounted light, you add a wall mounted conduit

*Wire your conduit to the switch or to your power source that you installed earlier, then, add lights and TVs to your hearts content. You don't need to wire them to anything

You must have copper in your (or your workshop's) inventory to attach a wire, although you can delete a previously-built wire for a refund of copper used.

A:
This picture should tell you how to connect power to a light bulb.

A: You don't add a wire to the ceiling and wall lights.
Add a generator, and once running, put a light in close proximity to it. That's it. If you need it farther away you have to add a power conduit and run a wire from the generator.  Then place the light in proximity to the conduit. Usually within the same room.
Remember, generators are also rated for power. So if you've used 4 of 5 of the power units and add something that requires 2 units. It won't turn on until there is adequate power.

A: You need to connect the generator via anything in the Connectors & Switches section under Power in the Workshop build menu. Once you've got a switch or pylon in place, when you hover over it you have the option to Attach Wire:

Select this option and connect a wire to the generator and the light (or other object) and then flip the switch if required.

Additionally, some items appear to power just by being in the vicinity of power infrastructure (pylons, conduits, etc):

A: Use power conduits on the roof near a light bulb and power the conduit

A: You could try connecting the generator to a pylon with a switch and then running the power with conduits? All light bulbs within that vicinity should work.
Alternatively, you could try placing a coupling capacitor (I think that was the name), near the object you want powered.

A: Step 1: set up generator
Step 2: set up a switch appropriately with environment  (try to get it in between generator and conduit, which is coming up next) wire the switch to the generator.
Step 3: place conduit near desired area of electricity (inside or outside wall is acceptable) wire the conduit back to the generator.
Step 4: place light is desired area (near conduit)
Step 5: If the light(s) DIDNT already come on, try flipping the switch, or pressing A on the item in workshop mode.
I struggled, and this is what worked for me. Still haven't mastered the whole power/defense thing yet


text:
Q: How to use Kinect depth data in watershed image segmentation I have both RGB and depth images from Kinect as png format. I'm trying to use depth data with the watershed segmentation but I don't know how to combine both data and obtain a more accurate result. I checked some papers but I didn't understand the results or couldn't find a solution written specifically for the watershed algorithm. How can I include the depth data as a reference point to the segmentation process?
I'm using MatLab's Image Processing Toolbox.
The images are from Nathan Silberman et. al.'s database on Silberman's website
An example RGB image and its corresponding depth file are shown below (note that the depth image, originally it is a binary image, is converted to uint8):

Update: I tried to create a weighted grayscale image from the RGB source together with the depth data by taking each channel (red, green, blue and depth) and calculating their weights; then including the values multiplied with their weights for every corresponding pixel. But the resulting grayscale image does not improve the result significantly. It's not that better than the solely RGB based segmentation. What else could I do if I follow this approach? Alternatively, how can I see the effects of the depth data?

A: unless you had an error uploading, the depth image is black and doesnt contain any depth data. Keep in mind that (dutch term) your comparing apples and pears here.
Whatershed images are not depth images, they are extractions of contour.
Then there is a next thing where you go wrong, depth images have a lower resulotion then color images. for the kinect v2 its only 512x424, and the kinect one's true depth vision is even lower then its returned bitmap size (it is a low res depth and not every pixel in is a result of a measurement, in contrast to kinect v2). But then the v2 has even better video output.
If you want better watershed of a rgb image, then average out multiple camera frames to get rid of camera noise.
PS i recomend you download the windows kinect sdk and take a look of the samples provided with it.


text:
Q: R - Need help speeding up a for loop I have two dataframes; one is 48 rows long and looks like this:
name = Z31
     Est.Date   Site    Cultivar   Planting
1   24/07/2011  Birchip Axe           1
2   08/08/2011  Birchip Bolac         1
3   24/07/2011  Birchip Derrimut      1
4   12/08/2011  Birchip Eaglehawk     1
5   29/07/2011  Birchip Gregory       1
6   29/07/2011  Birchip Lincoln       1
7   23/07/2011  Birchip Mace          1
8   29/07/2011  Birchip Scout         1
9   17/09/2011  Birchip Axe           2
10  19/09/2011  Birchip Bolac         2

The other is > 23000 rows and contains output from a simulator. It looks like this:
name = pred
    Date        maxt    mint    Cultivar    Site    Planting    tt  cum_tt
1   5/05/2011   18       6.5    Axe        Birchip  1        12.25  0
2   6/05/2011   17.5     2.5    Axe        Birchip  1        10     0
3   7/05/2011   18       2.5    Axe        Birchip  1        10.25  0
4   8/05/2011   19.5       2    Axe        Birchip  1        10.75  0
5   9/05/2011   17       4.5    Axe        Birchip  1        10.75  0
6   10/05/2011  15.5    -0.5    Axe        Birchip  1        7.5    0
7   11/05/2011  14       5.5    Axe        Birchip  1        9.75   0
8   12/05/2011  19         8    Axe        Birchip  1        13.5   0
9   13/05/2011  18.5     7.5    Axe        Birchip  1        13     0
10  14/05/2011  16       3.5    Axe        Birchip  1        9.75   0

What I want to do is have the cum_tt column start to add the tt column of the current row to the cum_tt of the previous row (cumulative addition) ONLY if the date in the pred DF is equal to or greater than the Z31 est.Date. I have written the following for loop:
for (i in 1:nrow(Z31)){
  for (j in 1:nrow(pred)){
    if (Z31[i,]$Site == pred[j,]$Site & Z31[i,]$Cultivar == pred[j,]$Cultivar & Z31[i,]$Planting == pred[j,]$Planting &
        pred[j,]$Date >= Z31[i,]$Est.Date)
    {
      pred[j,]$cum_tt <- pred[j,]$tt + pred[j-1,]$cum_tt
    }
  }
}

This works but it is so slow it will take about an hour to run the entire set. I know loops are not R's strong point so can anyone assist me with vectorising this operation?
Thanks in advance.
UPDATE
Here's the output from dput(Z31):
structure(list(Est.Date = structure(c(15179, 15194, 15179, 15198,
15184, 15184, 15178, 15184, 15234, 15236, 15230, 15238, 15229,
15236, 15229, 15231, 15155, 15170, 15160, 15168, 15165, 15159,
15170, 15170, 15191, 15205, 15198, 15203, 15202, 15195, 15203,
15206, 15193, 15193, 15195, 15200, 15193, 15205, 15200, 15205,
15226, 15245, 15231, 15259, 15241, 15241, 15241, 15241), class = "Date"),
    Site = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Birchip", "Gatton",
    "Tarlee"), class = "factor"), Cultivar = structure(c(1L,
    2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
    1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L,
    8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L,
    7L, 8L), .Label = c("Axe", "Bolac", "Derrimut", "Eaglehawk",
    "Gregory", "Lincoln", "Mace", "Scout"), class = "factor"),
    Planting = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L)), .Names = c("Est.Date", "Site",
"Cultivar", "Planting"), row.names = c(NA, -48L), class = "data.frame")
Here's pred. Note there are some extra colums here. I've just included the relevant ones above for ease of reading.
structure(list(Date = structure(c(15099, 15100, 15101, 15102,
15103, 15104, 15105, 15106, 15107, 15108, 15109, 15110, 15111,
15112, 15113, 15114, 15115, 15116, 15117, 15118), class = "Date"),
    flowering_das = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Zadok = c(9, 9,
    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11.032, 11.085,
    11.157), stagename = structure(c(8L, 8L, 8L, 8L, 8L, 8L,
    8L, 8L, 9L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 1L, 3L, 3L, 3L), .Label = c("emergence",
    "end_grain_fill", "end_of_juvenil", "floral_initiat", "flowering",
    "germination", "maturity", "out", "sowing", "start_grain_fi"
    ), class = "factor"), node_no = c(0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 2, 2.032, 2.085, 2.157), maxt = c(18,
    17.5, 18, 19.5, 17, 15.5, 14, 19, 18.5, 16, 16, 15, 16.5,
    16.5, 20.5, 23, 25.5, 16.5, 16.5, 15), mint = c(6.5, 2.5,
    2.5, 2, 4.5, -0.5, 5.5, 8, 7.5, 3.5, 6, 1, 5.5, 2, 7, 7,
    9, 13.5, 11.5, 8.5), Cultivar = c("Axe", "Axe", "Axe", "Axe",
    "Axe", "Axe", "Axe", "Axe", "Axe", "Axe", "Axe", "Axe", "Axe",
    "Axe", "Axe", "Axe", "Axe", "Axe", "Axe", "Axe"), Site = c("Birchip",
    "Birchip", "Birchip", "Birchip", "Birchip", "Birchip", "Birchip",
    "Birchip", "Birchip", "Birchip", "Birchip", "Birchip", "Birchip",
    "Birchip", "Birchip", "Birchip", "Birchip", "Birchip", "Birchip",
    "Birchip"), Planting = c("1", "1", "1", "1", "1", "1", "1",
    "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
    "1"), `NA` = c("Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out",
    "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out", "Birchip TOS1 Axe.out"
    ), tt = c(12.25, 10, 10.25, 10.75, 10.75, 7.5, 9.75, 13.5,
    13, 9.75, 11, 8, 11, 9.25, 13.75, 15, 17.25, 15, 14, 11.75
    ), cum_tt = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0)), .Names = c("Date", "flowering_das", "Zadok",
"stagename", "node_no", "maxt", "mint", "Cultivar", "Site", "Planting",
NA, "tt", "cum_tt"), row.names = c(NA, 20L), class = "data.frame")

UPDATE
Thanks everyone for your help. I'm still new to the vector way of doing things and I wasn't able to implement some of the more complex solutions in time. I've got some timing below for the way Subs suggested. It's fast enough now to do what I need. These number are in seconds for one iteration of Z over P.
my way: 59.77
Subs: 14.62
Subs using numeric date: 11.12

A: Sure that we can do this in a few seconds... my first answer on here so go gentle!
## first make sure we have dates in a suitable format for comparison
## by using strptime, creating the columns estdate_tidy and date_tidy
## in Z31 and pred respectively

Z31$estdate_tidy = strptime(as.character(Z31$Est.Date), "%d/%m/%Y")
pred$date_tidy = strptime(as.character(pred$Date), "%d/%m/%Y")

## now map the estdate_tidy column over to pred using the match command -
## Z31_m and pred_m are dummy variables that hopefully make this clear

Z31_m = paste(Z31$Site, Z31$Cultivar, Z31$Planting)
pred_m = paste(pred$Site, pred$Cultivar, pred$Planting)
pred$estdate_tidy = Z31$estdate_tidy[match(pred_m, Z31_m)]

## then define a ttfilter column that copies tt, except for being 0 when
## estdate_tidy is after date_tidy (think this is what you described)

pred$ttfilter = ifelse(pred$date_tidy >= pred$estdate_tidy, pred$tt, 0)

## finally use cumsum function to sum this new column up (looks like you
## wanted the answer in cum_tt so I've put it there)

pred$cum_tt = cumsum(pred$ttfilter)

Hope this helps :)
UPDATE (7 June):
The vectorised code to tackle the new specification - i.e. that the cumsum should be done separately for each set of conditions (Site/Cultivar/Planting) - is shown below:
Z31$Lookup=with(Z31,paste(Site,Cultivar,Planting,sep="~"))
Z31$LookupNum=match(Z31$Lookup,unique(Z31$Lookup))
pred$Lookup=with(pred,paste(Site,Cultivar,Planting,sep="~"))
pred$LookupNum=match(pred$Lookup,unique(pred$Lookup))

pred$Est.Date = Z31$Est.Date[match(pred$Lookup,Z31$Lookup)]
pred$ttValid = (pred$Date>=pred$Est.Date)
pred$ttFiltered = ifelse(pred$ttValid, pred$tt, 0)

### now fill in cumsum of ttFiltered separately for each LookupNum
pred$cum_tt_Z31 = as.vector(unlist(tapply(pred$ttFiltered,
                                          pred$LookupNum,cumsum)))

Runtime is 0.16 seconds on my machine, and the final pred$cum_tt_Z31 column matches exactly with the answer from the non-vectorised code :)
For completeness, it's worth noting that the final complicated tapply line above can be replaced by the following simpler approach with a short loop over the 48 possible cases:
pred$cum_tt_Z31 = rep(NA, nrow(pred))
for (lookup in unique(pred$Lookup)) {
    subs = which(pred$Lookup==lookup)
    pred$cum_tt_Z31[subs] = cumsum(pred$ttFiltered[subs])
}

The runtime only increases slightly to 0.25 seconds or so, because the loop here is very small and the work done inside the loop is vectorised.
Think we've cracked it! :)
Some quick observations on vectorisation (8 June):
The process of vectorising the steps of the process brought runtime down from close to an hour to 0.16 seconds in total. Even allowing for different machine speeds, this is a speedup by at least a factor of 10,000, which dwarfs the factors of 2-5 one might get from making minor tweaks but still retaining a loop structure.
The first key observation to make: in the solution, every line creates - without looping - an entire new vector with the same length as the columns in Z31 or pred. For neatness, I often find it useful to create these new vectors as new data frame columns, but obviously this is not strictly necessary.
Second observation: the required Est.Date column gets transferred correctly from Z31 to pred using a "paste'n'match" strategy. There are alternative approaches to this sort of task (e.g. using merge), but I take this route as it is completely failsafe and guarantees to preserve the order in pred (which is crucial). Essentially the paste operation just lets you match up several fields at once, because if the pasted strings match then all their constituent parts match. I use ~ as a separator (provided I know that symbol won't appear in any of the fields) to avoid the paste operation causing any ambiguity. If you use a space separator, then pasting together something like ("A B", "C", "D") would give the same result as pasting ("A", "B C", "D") - and we want to avoid any headaches!
Third observation: it's easy to vectorise logical operations such as seeing if one vector exceeds another (see pred$ttValid), or choosing one value or another based on the value of a vector (see pred$ttFiltered). In the current situation, these could be combined into one line, but I broke things down a little more as a demonstration.
Fourth observation: the final line that creates pred$cum_tt_Z31 essentially just does a cumsum operation across the rows corresponding to each separate value of pred$LookupNum, using tapply, which allows you to apply the same function over different groups of rows (here, we're grouping by pred$LookupNum). The definition of pred$LookupNum helps enormously here - it's a numeric index with a block of 1s, followed by a block of 2s, and so on. This means the final list of cumsum vectors that comes out of the tapply can simply be unlisted and put into a vector and is automatically in the right order. If you do a tapply and split by groups that aren't ordered like this, you normally need a couple of additional lines of code to match things back up again correctly (though it isn't tricky).
Final observation: if the final tapply is too scary, it's worth highlighting that a quick loop over a small number of cases (48 say) isn't always disastrous if the work within the loop is nicely vectorised. The "alternative method" at the end of the UPDATE section shows that the cumsum-on-groups step can also be achieved by pre-preparing an answer column (initially all NAs) and then going through the 48 subsets one by one and filling in the each block with the appropriate cumsum. As noted in the text, though, this single step is roughly half the speed as the clever tapply approach, and if more subsets were needed this would be considerably slower.
If anyone has any follow up questions on this kind of task, please don't hesitate to give me a shout.

A: a quick solution is to define a vector  outside the loop as:
 temp_cumtt=c(rep(0,nrow(pred)))

and then  use this:
if (Z31[i,2] == pred[j,5] & Z31[i,3] == pred[j,4] & Z31[i,4] == pred[j,6] & pred[j,1] >= Z31[i,1]){
   temp_cumtt[j]=pred[j,7] + pred[j-1,8]
}

instead of updating the data.frame column directly.
After you come out of the loop, you can update the column:
 pred$cum_tt = temp_cumtt

The other thing is you have to be careful when using j-1 with index of j starting at 1. In your example it doesn't lead to that conditional-problem.
EDIT:
Now looking at your data-format, I have these suggestions.
1) Don't convert into Date class, instead keep it as a vector of values.
2) Sort the Z31 data_frame according to Date-vector: Z31=Z31[with(Z31, order(-Date)), ] (Note in descending order since you want to compare pred[,Date index]>=Z31[,Date index]
3) Use the 1st loop as pred. First take the Date of pred -> pred[i,1] and try to binary sort and find which index in Z31 it satisfies and from that index onwards go down the list. If Date condition satisfies then check for the rest of the conditions and fill the temp_cumtt[i] as before.
This should be blazing fast (since binary sort only on 48 rows of Z31 and you can compare the run time .with the other solution.

A: Let's make use of data.table, which should speed things up a whole lot.
Z31 <- data.table(Z31,key="Site,Cultivar,Planting")
pred <- data.table(pred)

## First, let's create an extra column in `pred` to see the corresponding date from `Z31`
## Note 1: The JT is necessary since both sets have the same column names
## Note 2: I needed to use as.integer on Planting to make it work

pred[,Z31Est.Date:={JT=J(Site,Cultivar,as.integer(Planting)); Z31[JT,Est.Date][[4]]}]

## Now we can see for each row whether the date in `pred` is higher than or equal to that from `Z31`.

pred[,DateTrue:=Date>=Z31Est.Date]

## Finally, we only have to add up `pred[i,tt]` and `pred[i-1,cum_tt]` for each row where `DateTrue` equals `TRUE`.

for (i in 1:nrow(pred)) set(pred,i,13L,if(pred[i,DateTrue]) pred[i-1,cum_tt]+pred[i,tt] else(0))


text:
Q: Bootstrap 4 row not center aligned I have a bootstrap row, with 4 columns in it. Originally I had 3 columns with icons, and they all aligned perfectly. I added a fourth in, and now the new one I added is slightly further down the page than the rest. It just doesn't sit in line

Also take a look at my Github, Free Code Camp, Team Treehouse and LinkedIn profiles!

GitHub

Free Code Camp

Team Treehouse

LinkedIn

It's the third column (team treehouse) that doesn't sit in line with the rest.
Also, they are all within a row div, it's just not shown.
EDIT:
It seems the problem is 3 of the icons are from Font Awesome, and the Treehouse icon is from Foundation Icons. Now I know the problem, but im not sure how to fix it. They are all styled to the same size

A: If you believe it is the icon, test your theory by adding a border to the icons class. This way you will be able to tell if the third icon is positioned oddly, or has padding built into the image itself. If that is the case copy the image and edit it to suit.
Or you can hack the offending icon with some CSS like so:
.fi-social-treehouse {
  margin-top: -20px;
  }

A: Well, I checked inside the CSS sheet for Foundation Icons and compared it to the CSS sheet of Font Awesome, and couldn't find a difference. So I ended up hard coding a negative margin to the column that the treehouse icon is within. If anyone has a better solution, I would be happy to hear it!


text:
Q: vagrant up fails when destroying and associated drives When I run vagrant up command it give me error while it destroying VM and associated drives.
amit@Amit:/var/www/myhomestead/homestead$ vagrant up

Bringing machine 'default' up with 'virtualbox' provider...

==> default: Box 'hashicorp/precise32' could not be found. Attempting to find and install...

    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Loading metadata for box 'hashicorp/precise32'

    default: URL: https://vagrantcloud.com/hashicorp/precise32

==> default: Adding box 'hashicorp/precise32' (v1.0.0) for provider: virtualbox

    default: Downloading: https://vagrantcloud.com/hashicorp/boxes/precise32/versions/1.0.0/providers/virtualbox.box
==> default: Successfully added box 'hashicorp/precise32' (v1.0.0) for 'virtualbox'!

==> default: Importing base box 'hashicorp/precise32'...

==> default: Matching MAC address for NAT networking...

==> default: Checking if box 'hashicorp/precise32' is up to date...

==> default: Setting the name of the VM: homestead_default_1417506056689_3037

==> default: Destroying VM and associated drives...

/opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:450:in `initialize': Permission denied - /home/amit/.vagrant.d/data/lock.fpcollision.lock (Errno::EACCES)

from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:450:in `open'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:450:in `block in lock'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:474:in `lock'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:449:in `lock'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/handle_forwarded_port_collisions.rb:41:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/prepare_forwarded_port_collision_params.rb:30:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/env_set.rb:19:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/provision.rb:80:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/clear_forwarded_ports.rb:15:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/set_name.rb:50:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/clean_machine_folder.rb:17:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/check_accessible.rb:18:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/call.rb:53:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/call.rb:53:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/call.rb:53:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/box_check_outdated.rb:68:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/config_validate.rb:25:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/match_mac_address.rb:16:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/import.rb:32:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/customize.rb:40:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/check_accessible.rb:18:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/call.rb:53:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/config_validate.rb:25:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'enter code here
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/handle_box.rb:56:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:95:in `block in finalize_action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builtin/call.rb:53:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/plugins/providers/virtualbox/action/check_virtualbox.rb:17:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/warden.rb:34:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/builder.rb:116:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `block in run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/util/busy.rb:19:in `busy'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/action/runner.rb:66:in `run'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/machine.rb:196:in `action_raw'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/machine.rb:173:in `block in action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/environment.rb:474:in `lock'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/machine.rb:161:in `call'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/machine.rb:161:in `action'
from /opt/vagrant/embedded/gems/gems/vagrant-1.6.5/lib/vagrant/batch_action.rb:82:in `block (2 levels) in run'

A: My permission are messed up because of i ran as sudo vagrant up. after that my .vagrant directory owner has changed that's why my vagrant up fails.
thanks Carpetsmoker and halfer for helping me to understand.


text:
Q: Bellman Criteria (Graphtheory) Lemma (Bellman Criteria)  [Brandes 2001]
Let $G$ be a graph and $s, t, v \in V(G)$.
A  vertex $v \in V(G)$ lies on a shortest path between vertices $s, t \in  V$, if and only if dist(s,t) = dist(s,u)+dist(u,t).
Can i show by the definition that dist(s,v)+dist(v,t) is the shortest path from $s$ to $t$ via $v$ and then show by contradiction that ">" "<" is valid and thus equality must apply? Or is it possible to show that only by equivalence direction?

A: The distance between two vertices is by definition the length of a shortest path between them. So if $d(s,v)+d(v,t)=d(s,t)$ there is an $st$-path containing $v$, which is a shortest path from $s$ to $t$.
Conversely assume that $d(s,v)+d(v,t)\neq d(s,t)$ and note that by definition of the latter distance we indeed have $d(s,v)+d(v,t)>d(s,t)$. Moreover any $st$-path $P$ containing $v$ satisfies $\operatorname{len} P \geq d(s,v) + d(v,t)$, since it decomposes into an $sv$-path $P_s$ and $vt$-path $P_t$, which by definition satisfy $\operatorname{len} P_s \geq d(s,v)$ and $\operatorname{len} P_t \geq d(v,t)$. But this way $v$ cannot possibly lie on a shortest $st$-path.


text:
Q: How to send an Email in a separate thread? I was sending emails from my website fine, but Email part was slow,
so I have decided to try and put this in a new thread,
And came up with this
    public bool sendmail()
    {
        Thread T1 = new Thread(delegate()
        {
            MailMessage eMail = new MailMessage();
            SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"]);
            string EmailFromGCBS = (ConfigurationManager.AppSettings["EmailFROM"]);

            eMail.From = new MailAddress(EmailFromGCBS);
            eMail.To.Add(new MailAddress(emailTo));
            eMail.Subject = emailSubject;
            eMail.IsBodyHtml = isHtml;
            eMail.Body = emailBody;
            smtpClient.Send(eMail);

        });
        T1.Start();

        return true;
    }

the thread runs, but there is no emails sent any idea why this is?


text:
Q: UIAccessibility in gridView - doesn't see new cells In my project I have tableView, as a row there is a custom UITableViewCell, that has one of it property - GMGridView (its similar to a UICollectionView), it has its delegate methods:
- (GMGridViewCell *)GMGridView:(GMGridView *)gridView cellForItemAtIndex:(NSInteger)index {
GMGridViewCell *cell = [gridView dequeueReusableCell];

    if (!cell)
    {
        cell = [[GMGridViewCell alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
        cell.contentView = [[GridViewContentView alloc] initWithFrame:cell.frame style:GridViewStyleNews];
     }
    Item *feed = _contentArray[index];
       GridViewContentView *contentView = (GridViewContentView *)cell.contentView;
           contentView.textLabel.text = feed.textLabel;
    [contentView.imageView setURL:[NSURL URLWithString:feed.imageLink] withPreset:self.preset];
    cell.contentView = contentView;
    NSLog(@"Address index %d - %p:", index, cell);
        return cell;
}

At this stage - created custom contentView  -GridViewContentView and is identities as cells contentView.
This custom content view is defined as Accessible inside of it there are next methods:
 - (BOOL)isAccessibilityElement {
    return YES;
}

- (NSString *)accessibilityLabel {
    return [NSString stringWithFormat:@"%p, %@", self.superview, self.textLabel.text];
}

In my case I have 19 items in GridView.
So when the tableView is loaded on iPad(in landscape) created 6 items they are inserted into NSArray inside of GridView:
2016-08-07 17:04:39.626 DummyAccessibility[2785:230602] Address index 0 - 0x7a0162e0:
2016-08-07 17:04:39.632 DummyAccessibility[2785:230602] Address index 1 - 0x797390e0:
2016-08-07 17:04:39.633 DummyAccessibility[2785:230602] Address index 2 - 0x79643db0:
2016-08-07 17:04:39.639 DummyAccessibility[2785:230602] Address index 3 - 0x7a013290:
2016-08-07 17:04:39.640 DummyAccessibility[2785:230602] Address index 4 - 0x7a0114f0:
2016-08-07 17:04:39.641 DummyAccessibility[2785:230602] Address index 5 - 0x7965ef30:

and Voice over tells correct text - that belongs to taped item.
But When I scroll - additionally created next 2 items (6 and 7) , and the first 2 - is reused for items (8 and 9).
new items:
2016-08-07 17:04:59.961 DummyAccessibility[2785:230602] Address index 6 - 0x79674ac0:
2016-08-07 17:05:00.366 DummyAccessibility[2785:230602] Address index 7 - 0x7a074f20:

reused items:
2016-08-07 17:05:00.982 DummyAccessibility[2785:230602] Address index 8 - 0x7a0162e0:
2016-08-07 17:05:05.704 DummyAccessibility[2785:230602] Address index 9 - 0x797390e0:

After debugging I identified that these newly items are never accepted by UIAccessibility. When I try to tap on it - VoiceOver tells - is redirected inside of the cell (number 5) and takes the textValue from it.
So when I tries to tap on the reused items - it tells correct (reused textInfo). Such a situation (with these new items keeps the even when they are also reused). I can't understand why it is like that.

I spend a lot of time with it, but can't understand why it works like that. I would really appreciate any idea.
Thanks a lot in advance.

A: I found the solution on the base of Sean Howell answer here
iOS Accessibility for CollectionView in a TableViewCell
So I added additional property - UIView in my custom tableViewCell,
and then added into it -in my case - GMGridView.
    self.trickView = [[UIView alloc]initWithFrame:self.bounds];
    self.trickView.backgroundColor = [UIColor clearColor];
    self.trickView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    _trickView.accessibilityElements = @[gmGridView];
    [self.contentView addSubview:_trickView];
    [self.gridView removeFromSuperview];
    self.gridView = nil;
    self.gridView = gmGridView;
    [self.trickView addSubview:gmGridView];