text:
Q: The Stack Overflow logo seems a bit too low in the blog I get the impression when looking at the logos in The Overflow blog's top right corner that the Stack Exchange logo stands out for being aligned slightly too low.

(The strange thing is that every logo seems to have a different alignment anyway, but somehow the SO logo does stand out among the group. I suppose that kind of subtle and inconspicuous prominence can actually be considered good design.)

A: Yes it is slightly too low. Opening developer tools gives us this:

As you can see, the image second from the right has a little bit too much space too! Nearly all images aren't centered properly (if the lines are correctly placed that is), including the SO icon. In terms of height centering, the SO icon should be booted up a few pixels up.
The "find something tool" seems to be poking out a little on the left side of it:

Unless of course, it didn't line up properly somehow when I opened it and simply shifting it leftwards a few pixels would center all the images.


text:
Q: Why is try-catch-finally not re-prompting the user? I am relatively new to Java and all programming in general. I'm writing a simple GuessNumber program for school. The user enters a number 1-10 and it is compared to a random number 1-10. The req spec states that all invalid input should be checked and the user should be re-prompted if invalid input is found. I am using try-catch-finally for this. My catch block finds the exception for int guess if it is indeed not an integer, but it does not re-prompt the user, and instead keeps the initial value of 0. I only initialized guess before user input because the terminal repeatedly yelled at me about it until I did. I am also not sure why the variable must be initialized before the try block.
I looked all over but every solution I've found has code nearly identical to mine in structure. I'm guessing this must be something that I simply am not familiar with/others neglect to mention because it is so elementary. This is my first time using try-catch-finally by the way.
int guess = 0;
int number = (int)((Math.random()*10) + 1);
System.out.print("Please guess a number between 1 and 10, inclusive: ");

//open try
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

  guess = Integer.parseInt(br.readLine());

  //monitor input
  while(guess < 1 || guess > 10) {//open while

    System.out.print("You seem to have entered something wrong. Please only");
    System.out.println(" enter ");
    System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
    guess = Integer.parseInt(br.readLine());

  }//close while

  //close try
} catch(NumberFormatException e) {//open catch

  System.out.print("You seem to have entered something wrong.  Please only");
  System.out.println(" enter ");
  System.out.print("an integer number between 1 and 10, 1 and 10 included: ");

  //close catch
} finally {//open finally

  //user feedback
  if(number == guess){

    System.out.println("You got it! You guessed the number correctly. It is "
    + number + ".");

  } else {

    System.out.println("I'm sorry! That is not the number I was thinking of.");
    System.out.println("You guessed " + guess + ", but the number is "
    + number + ".");

  }
}//close finally

If the user enters an exclamation point ! for example, the program does out put the catch block code. However, it then moves on with 0 as the guess and runs the rest of the program, and ends. The program works correctly if an integer is entered, however. Any input is greatly appreciated!
EDIT: I deleted the finally block, and threw the try-catch blocks inside a while loop with a boolean variable boolean done = false; with the condition while(!done) if the try is successful, it sets done = true; and the program ends. That wasn't good enough and I had infinite looping from exceptions, so I threw some continue; statements at the end of the catch blocks and that worked. Can anyone explain why the continue statements were necessary/how they affect the flow of the program?
    //init vars needed
    int guess;
    int number = (int)((Math.random()*10) + 1);
    boolean done = false;
    System.out.print("Please guess a number between 1 and 10, inclusive: ");

    while(!done) {//open while
      try {//open try
        guess = Integer.parseInt(br.readLine());

        while(guess < 1 || guess > 10) {
          System.out.print("You seem to have entered something wrong. Please only");
          System.out.println(" enter ");
          System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
          guess = Integer.parseInt(br.readLine());
        }

        if(number == guess) {
          System.out.println("You got it! You guessed the number correctly. It is "
          + number + ".");
        } else if(number != guess) {
          System.out.println("I'm sorry! That is not the number I was thinking of.");
          System.out.println("You guessed " + guess + ", but the number is "
          + number + ".");
        }

        done = true;
      } //close try

      catch(NumberFormatException e) {//open catch
        System.out.print("You seem to have entered something wrong. Please only");
        System.out.println(" enter ");
        System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
        continue;
      }//close catch

      catch(IOException e) {//open catch
        System.out.print("You seem to have entered something wrong. Please only");
        System.out.println(" enter ");
        System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
        continue;
      }//close catch

    }//close while

A: An exception thrown from parseInt causes your loop to break. You probably want your loop to contain a try-catch-finally clause, and not vice-versa.

A: You should organize your code, first as other coments said you should execute your code in try and handle the exceptions on the catch, finally is redundant if you are going to execute in the try block. Use this as an example, you also have another question where they can explain better than me. Hope it helped.
[link] Does a finally block always get executed in Java?
    try {
        System.out.println("Im the try block");
    }
    finally {
        System.out.println("Im the finally block");
    }

Output:

Im the finally block
Im the try block

Also NumberformatException is going to work when you put a number but you missed the IOException I think.

A: Finally section will happen anyway, regardless of exception or not.
you should put the code from the finally section in the try section.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WinForms: Добавление значений в DataGridView c подключенной Sql таблицей На форме есть элемент DataGridView, в которой есть подключенная SQL таблица. Также на форме имеется несколько элементов для ввода данных и кнопка, при нажатии на которую должен выполняться непосредственно процесс добавления данных. У меня ошибок нет, но при этом данные не вводятся. Заранее спасибо. Вот код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace Курсовая.Приложение
{
    public partial class ProfileForm : Form
    {
        public ProfileForm()
        {
            InitializeComponent();
        }
        private void ProfileForm_Load(object sender, EventArgs e)
        {
            TouristGridView.DataSource = GetTouristList();
        }
        private DataTable dtTourist = new DataTable();
        private DataTable GetTouristList()
        {
            string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(connString))
            {
                using (MySqlCommand cmd = new MySqlCommand("SELECT FIO AS 'ПІП', dob AS 'Дата народження', phone AS 'Номер телефону' FROM tourist", con))
                {
                    con.Open();
                    MySqlDataReader reader = cmd.ExecuteReader();
                    dtTourist.Load(reader);
                }
            }
            return dtTourist;
        }
        private void btnSearch(object sender, EventArgs e)
        {
            MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([ФИО], [Дата рождения], [Номер телефона]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')");
        }
    }
}

A: Как я понимаю, добавление данных должно происходить в процедуре btnSearch()?
Тогда - все довольно понятно.
попробую объяснить, пользуясь только Вашим собственным кодом:
смотрим на ту часть, колторая работает:
там есть такая штука, которая создаёт коннекшн к базе данных
    using (MySqlConnection con = new MySqlConnection(connString))

и есть такое место, где этот коннекш открывается
    con.Open();

А в том месте, где у Вас должно происходить добавление данных - васего этого нет, есть только создание команды, которая должна добавить новые данные.
Следовательно, попробуем поменять код так:
    private void btnSearch(object sender, EventArgs e)
    {
        string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(connString))
        {
            con.Open();
            MySqlCommand Command = new MySqlCommand("INSERT INTO [tourist] ([ФИО], [Дата рождения], [Номер телефона]) VALUES ('" + NametextBox.Text + "','" + dobDate.Value + "','" + PhonetextBox.Text + "')");
            Command.ExecuteNonQuery();
        }
    }

Это - уже имеет все шансы на то, чтобы работать. По крайней мере, данные будут добавляться.
Но у этого кода я вижу еще 3 недостатка:

*

*при добавлении данных Вы этого не увидите на экране. Потому что данные добавлятся в базу данных, но информация, отображенная на экране, при этом не обновится. Хорошо бы заново вызвать метод  ProfileForm_Load(), или каким то другим совособом "дернуть" процедуру, которая заново нарисует на экране данные, только что полученные из базы

*строка коннекта к базе в коде дублируется. Она, конечно, берется из ConfigurationManager - но всё равно, можно вынести её куда то в "глобальные переменные".

*Не очень хорошая практика - "клеить" запрос, используя при этом строковые значения полей. Это нехорошо по нескольким причинам: по первых, sql injection. Это само по себе интересно, почитайте. Во вторых, там могут быть пустые строки на месте незаполненных полей, что может приводить к ошибкам. И, наконец, типы данных: например, дата - это штука, которая зависит от location, и еще и от того, как именно напишет её пользователь.
Поэтому в тех случаях, когда надо в команду "зафигачить" параметры - используют конструкцию такого типа:
    cmd.Parameters.AddWithValue("@id", r_id);

Дополнение.
Очень опытный участник форума aepot обратил внимание на то, что в смысле использования .AddWithValue() - я даю плохой совет.
Это утверждение встречалось мне настолько часто, что я провел небольшие изыскания, и нашел исходную короткую статью, которая, вроде  бы, раскрывает смысл утверждения "AddWithValue - зло".
я перевел это в силу своего понимания, получилось вот что:
-начало перевода-
Оригинал:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Можно уже прекратить пользоваться AddWithValue?
Это нужно прекратить.
Есть проблема с функцией AddWithValue: она должна по переданному значению определить соответсвующий SQL Type в базе данных. Но вот в чем дело:  иногда она ошибается...
Это особенно часто происходит при работе с Object arrays или аналогичными, где часть важной информации, которую ADO.Net использует для определения типа, отсутствует. Однако, это может случаться даже тогда, когда .Net type известен. Простейший пример: какой тип должен получиться на стороне базы данных из параметра, тип которого - string: VarChar, NVarChar или Char? Date или DateTime - другой пример.
Хорошая новость заключается в том, что в большинстве случаев эти несоответствия типов не имеют значения. Но иногда они действительно имеют значение, и даже большое значение.
Например, предположим, что у вас есть столбец базы данных varchar, но вы отправляете строковый параметр с помощью функции AddWithValue(). ADO.Net отправит это в базу данных как значение nvarchar. Базе данных не разрешено неявно преобразовывать ваш параметр nvarchar в значение varchar, чтобы оно соответствовало типу столбца для запроса. Понятно, почему: это будет сужающее преобразование, которое может привести к потере информации из исходного значения (поскольку в параметре могут быть нелатинские символы), и если это произойдет - база данных может выдать неправильные результаты запроса. Вместо этого базе данных, вероятно, потребуется преобразовать столбец varchar в nvarchar для этого запроса (что представляет собой расширяющее преобразование, которое гарантированно не потеряет информацию). Проблема в том, что это преобразование нужно будет сделать для каждой строки вашей таблицы.
Такое преобразование может произойти и с другими комбинациями типов. Например, колонка базы, содержащая тип Date может быть "расширена" до C#-типа DateTime. И даже страшно представить, что произойдет при несоответствии типа Data или числового типа на стороне базы данных, и типа string со стороны C#. Даже с nvarchar или nchar Вы можете обнаружить, что длины не совпадают, и, таким образом, для каждого значение в базе нужно модифицировать длинну строки.
Если такие операции кажутся вам дорогостоящими (потенциальные преобразования во время выполнения для данных в таблице, возможно, содержащей миллионы строк), вы правы. Да. Но это только начало. Эти недавно преобразованные значения теперь технически не совпадают со значениями, хранящимися в любых индексах, которые могут использовать этот столбец, что делает эти индексы бесполезными для выполнения вашего запроса. Теперь мы действительно бьем ниже пояса. Использование индексов существенно снижает производительность базы данных. Неспособность попасть в индекс может быть разницей между запросом, занимающим часы или секунды, между запросом, занимающим минуты, или мгновенным возвратом. А все началось с AddWithValue...
Но что вы должны сделать вместо этого? Решение состоит в том, чтобы знать базовый тип базы данных, который вам нужен, а затем создать параметр запроса, который использует именно этот тип.
Вот пример использования базы данных типа DateTime:
    cmd.Parameters.Add("@Parameter", SqlDbType.DateTime).Value = MyDateTimeVariable;

Вот другой пример, использования decimal(11,4):
    cmd.Parameters.Add("@Parameter", SqlDbType.Decimal, 11, 4).Value = MyDecimalVariable;

Обратите внимание, что хотя это немного длиннее, это все еще одна строка кода. Вот и все. Это простое изменение в том, как вы определяете параметры, потенциально может сэкономить значительные потери производительности.
-конец перевода-
Мой краткий вывод:
вообще говоря, совет, данный в конце статьи "используйте максимально близкие типы в коде C# и в базе данных" - довольно очевиден. Со своей стороны, я бы сказал немного иначе: "если вы хорошо понимаете, что делаете, то использование .AddWithValue() ничем не отличается от использования Add() с явно указанным типом. Но если есть шанс перепутать, или этот код попадёт в руки другому человеку, который не будет фанатично следить за соответсвием типов - лучше не использовать .AddWithValue()".
По крайней мере, теперь мы лучше знаем, в чем  именно состоит зло .AddWithValue().


text:
Q: Why am I having trouble on the Ruby on Rails tutorial by Mike Hartl at section Listing 5.1? When I load up the Rails server, my home page comes up fine. However, after I input the code from section 5.1 to update "app/views/layouts/application.html.erb" with the following code:
<!DOCTYPE html>

    <title><%= full_title(yield(:title)) %></title>
    <%= stylesheet_link_tag    "application", media: "all" %>
    <%= javascript_include_tag "application" %>
    <%= csrf_meta_tags %>

          <%= link_to "sample app", '#', id: "logo" %>

<%= link_to "Home",    '#' %>

<%= link_to "Help",    '#' %>

<%= link_to "Sign in", '#' %>

      <%= yield %>

I get the error:
NoMethodError in Static_pages#home
undefined method `full_title' for #<#<Class:0x38ac7e0>:0x472fce0>

This is the extracted source (around line #4):
1: <!DOCTYPE html>
2:
3:
4:     <title><%= full_title(yield(:title)) %></title>
5:     <%= stylesheet_link_tag    "application", media: "all" %>
6:     <%= javascript_include_tag "application" %>
7:     <%= csrf_meta_tags %>

Can anyone explain why it's not working?

A: Did you add this to your app/helpers/application_helper.rb?
module ApplicationHelper
  # Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end
end


text:
Q: Fold/unfold only the div I select instead of all? Greetings,
I am a newbie who just started with jQuery. I am building a basic PHP app for our team that displays a list of open helpdesk tickets.
To avoid cluttering the screen, I only want to display the title of the ticket and if clicked, its description.
Here's my code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>Animate my Div</title>

        <?php
        $con = mysql_connect("korg", "joe", "bob");
        if (!$con) {                die('Could not connect: ' . mysql_error());   }
        mysql_select_db("wfr11", $con);
        $result = mysql_query(" select title, description from webcases");
        while ($row = mysql_fetch_array($result)) {
        ?>

<?php echo $row['title']; ?>

<?php echo $row['description']; ?>

        <?php
        }            mysql_close($con);            ?>

Right now, my code works but unfolds all the divs for all open tickets, regardless of what ticket name I clicked.
Ideally, I'd like to show the description of for the ticket name I clicked. Not all of them. Is it possible?
Thanks for your help.

A: Entirely possible, yes.
First issue you have is that you are repeating an ID in the loop, HTML IDs must be unique.  I would suggest using a class there.  Wrap the two components together in a DIV to make them in to a combined item that can be dealt with individually as well
<?php
while ($row = mysql_fetch_array($result)) {
?>

<?php echo $row['title']; ?>

<?php echo $row['description']; ?>

<?php
}
?>

Then, you need to make your jQuery select just the adjacent description DIV.
$(document).ready(function(){
  $(".entry a").click(function() {
    $(this).parents('.entry').find('.description').slideToggle(1000);
  });
});

Remember to use htmlentities() on your echo's from the database if they are not already in proper HTML form.

A: Yep, you're after a toggle. Maybe use an id to select the divs you want rather than just the plain div.
$(".link_class").click(function(){   $("#my_div").slideToggle(1000);                });

Target particular divs by assigning a class to the link.


text:
Q: Gaussian Elimination in OpenMP - Performance Problems I'm new to openMP, and I was trying to parallelize a Gaussian Elimination, and I'm having troubles with performance. I'm compiling the code below using:
gcc -o gaussian_elimination gaussian_elimination.c -lm -lgsl -lgslcblas -fopenmp -Wall
And setting the number of threads on the terminal with export OMP_NUM_THREADS
And my problem is that the parallel version of this code is running way slower than the serial version of the same. I believe that this is because I declared #pragma parallel for inside the external loop, and this would force openMP to create and destroy thread at each iteration, which would be incredibly costly, but I haven't seen any other clear way to do the same kind of operation, and I don't think I can exchange the external loop with the internal parallel ones.
I'm probably missing something, but I have not found any other forum threads here commenting on this particular problem. As far as execution correctness goes, my code seems to be functioning alright, the problem is just performance-wise.
Thanks in Advance
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <omp.h>
#include <stdbool.h>
#include <time.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>

#define DEBUG_MODE false

int random_matrix(double *A, int N,long long int seed);

int print_matrix(double *A, int N);

int print_vector(float *b,int N);

int main(int argc, char **argv){
  int N=1000;
  int i,j,k,l,i_p,s,err,D=N+1;
  long long int seed=9089123498274; // just a fixed seed only not to bother
  double *A,pivot,sw,tmp,begin,end,time_spent;
  double *Aref,*bref;
  gsl_matrix_view gsl_m;
  gsl_vector_view gsl_b;
  gsl_vector *gsl_x;
  gsl_permutation *gsl_p;

  /* Input */

  //scanf("%d",&N);

  A = (double*)malloc(N*(N+1)*sizeof(double));
  if(A==NULL){
    printf("Matrix A not allocated\n");
    return 1;
  }

  Aref = (double*)malloc(N*N*sizeof(double));
  if(Aref==NULL){
    printf("Matrix A not allocated\n");
    return 1;
  }
  bref = (double*)malloc(N*sizeof(double));
  if(bref==NULL){
    printf("Vector B not allocated\n");
    return 2;
  }

  /*
  for(i=0;i<N;i+=1)
    for(j=0;j<N;j+=1)
      scanf("%f",&(A[i*N+j]));

  for(i=0;i<N;i+=1)
    scanf("%f",&(b[i]));
  */

  /*
  for(i=0;i<N*N;i++)
    A[i]=(float) a_data[i];
  for(i=0;i<N;i+=1)
    b[i]=(float) b_data[i]; */

  err= random_matrix(A,N,seed);
  if(err!=0)
    return err;

  for(i=0;i<N;i++)
    for(j=0;j<N;j+=1)
      Aref[i*N+j]= A[i*D+j];
  for(i=0;i<N;i+=1)
    bref[i]= A[i*D+N];//b[i];

  printf("GSL reference:\n");

  gsl_m = gsl_matrix_view_array (Aref, N, N);
  gsl_b = gsl_vector_view_array (bref, N);
  gsl_x = gsl_vector_alloc (N);
  gsl_p = gsl_permutation_alloc(N);

  begin = clock();

  gsl_linalg_LU_decomp(&gsl_m.matrix, gsl_p, &s);
  gsl_linalg_LU_solve(&gsl_m.matrix, gsl_p, &gsl_b.vector, gsl_x);

  end = clock();
  time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
  printf("gsl matrix solver: %lf s\n",time_spent);

  if(DEBUG_MODE==true)
   gsl_vector_fprintf(stdout,gsl_x,"%f");

  gsl_permutation_free(gsl_p);
  gsl_vector_free(gsl_x);

  begin = omp_get_wtime();

  for(i=0;i<N;i+=1){

    i_p = i;
    pivot = fabs(A[i*D+i]);
    for(j=i;j<N;j+=1)
      if(pivot<fabs(A[j*D+i])){
        pivot = fabs(A[j*D+i]);
        i_p = j;
      }

    #pragma omp parallel for shared(i,N,A,i_p) private(j,sw)
    for(j=i;j<D;j+=1){
      sw = A[i*D+j];
      A[i*D+j] = A[i_p*D+j];
      A[i_p*D+j] = sw;
    }

    pivot=A[i*D+i];
    #pragma omp parallel for shared(i,D,pivot,A) private(j)
    for(j=0;j<D;j++)
      A[i*D+j]=A[i*D+j]/pivot;

    #pragma omp parallel for shared(i,A,N,D) private(tmp,j,k,l)
    for(j=i+1;j<N+i;j++){
      k=j%N;
      tmp=A[k*D+i];
      for(l=0;l<D;l+=1)
        A[k*D+l]=A[k*D+l]-tmp*A[i*D+l];
    }
  }

  end = omp_get_wtime();
  time_spent = (end - begin);
  printf("omp matrix solver: %lf s\n",time_spent);

  /* Output */

  if(DEBUG_MODE==true){
    printf("\nCalculated: \n");
    for(i=0;i<N;i+=1)
      printf("%.6f \n",A[i*(N+1)+N]);
    printf("\n");
  }

  free(A);

  return 0;
}

int random_matrix(double *A, int N,long long int seed){
  int i,j;
  const gsl_rng_type * T;
  gsl_rng *r;
  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc (T);

  for(i=0;i<N;i++)
    for(j=0;j<=N;j++)
      A[i*(N+1)+j]= gsl_rng_uniform (r);

  gsl_rng_free (r);

  return 0;
}

int print_matrix(double *A, int N){
  int i,j;
  for(i=0;i<N;i++)
    for(j=0;j<=N+1;j++){
      if(j==0 || j==N || j==N+1)
        printf(" | ");

      printf("%.2f ",A[i*(N+1)+j]);

      if(j==N+1)
        printf("\n");
    }

  return 0;
}

int print_vector(float *b,int N){
  int i;

  for(i=0;i<N;i+=1)
    printf("%f\n", b[i]);

  return 0;
}

I updated the code above with the omp_get_wtime(), and now it reads as the wtime diminishing as I include more and more threads, so, it does behave as it should, although not as clean as I would like.
For 1000 x 1000 matrices I get 0.25 s for the GSL lib, 4.4 s for the serial omp run and 1.5 s for the 4-thread run.
For 3000 x 3000 matrices, I get ~ 9s for the GSL lib, ~ 117 s for the serial omp run and ~ 44 s for the 4 thread-run, thus at least adding more threads indeed speeds up the program!
Thanks a lot everyone


text:
Q: Spin correlation function in a Heisenberg model and its relationship to Green function in Hubbard model Consider the Hubbard model on a lattice:
$$\hat{H} = -t\sum_{\langle i,j \rangle, \sigma}\hat{c}^\dagger_{i\sigma}\hat{c}_{j\sigma}+U\sum_i \hat{n}_{i\uparrow}\hat{n}_{i\downarrow}.$$
Downfolding technique shows that, in the limit $U/t$ large, the effective hamiltonian for the half-filled system, acting only on the subspace of states for which each site is exactly single-occupied, is:
$$\hat{H}=J\sum_{\langle i,j \rangle}\hat{\vec{S}}_i \cdot \hat{\vec{S}}_j,$$
where the spin operators are $\hat{\vec{S}}_i = \sum_{\sigma, \sigma^\prime} \vec{P}_{\sigma \sigma^\prime}\hat{c}^\dagger_{i\sigma}\hat{c}_{i\sigma^\prime}$ (the $\vec{P}_{\sigma \sigma^\prime}$ is the vector of $(\sigma,\sigma^\prime)$ components of the $s=\dfrac{1}{2}$ Pauli matrices) and $J=2U/t^2.$ In this Heisenberg model, I want to find an spectral quantity in terms solely of spin operators which is equivalent to the causal Green function $G_{i,j}(t) = \langle T[\hat{c}^\dagger_{i\sigma}(t)\hat{c}_{j\sigma}] \rangle  $ (expected value over ground state of the Hubbard hamiltonian). The downfolding suggests that the "equivalent" of the creation/anihilation operators are the spin ladder operators $\hat{S}_i^+,\hat{S}_i^-,$ so my first thought was that the relevant spectral function in the Heisenberg model is
$$\tilde{G}_{i,j}(t) = \langle T[\hat{S}^+_{i}(t)\hat{S}^-_{j}] \rangle $$ (expected value over ground state of the spin Heisenberg hamiltonian).
Numerical experiments for small clusters (2,3,4 sites) show that this is indeed the case (up to a unimportant multiplicative constant) for $U/t$ large (around 8 is actually enough). However, I cannot prove this in general. Is there a general argument showing this equivalence? The idea of course is to use block matrix inversion, and I used that to go from the Hubbard hamiltonian to the Heisenberg one, but when computing expected values of the time-ordered product of operators I cannot identify the spin operators.


text:
Q: catch nested_attributes on create to stop duplicates Using Rails, I have the following form...
Events#New - Form Partial
<%= simple_form_for @event, multipart: true do |f| %>

  ...

  <% unless signed_in? %>
    <%= f.simple_fields_for :user do |u| %>
      <%= u.input :name %>
      <%= u.input :email %>
    <% end %>
  <% end %>

  ...

  <%= f.submit %>

<% end %>

Once that form is submitted it will create the form and the nested_attribute. Which an Event belongs to one user.
Event Model
class Event < ActiveRecord::Base
  belongs_to :user

  accepts_nested_attributes_for :user
end

However my issue is, these fields are required and you don't need to be logged in to submit this form.
What I want is when you fill out the form and the user email exists it should just add the event to that user, otherwise it should create a new User record. Right now all it does is add additional user records.
I managed to get something working in the way of not using nested_attributes and just accepting the params[:name] and params[:email] then did a check, if it exists added it as a User.find_by(email: params[:email]).builds.events(event_params) but I wanted to directly modify the way the model handles the data as I feel the controller isn't the right place for this logic.
Any help on this would be appreciated!
Thanks :)

A: Don't use nested attributes, go for a form class approach, see section "3. Extract Form Objects" on http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ for one way how to do it,
nested attributes have a way of biting you over and over again and you just found one of them


text:
Q: How can I merge two JSON objects with Rust? I have two JSON files:
JSON 1
{
  "title": "This is a title",
  "person" : {
    "firstName" : "John",
    "lastName" : "Doe"
  },
  "cities":[ "london", "paris" ]
}

JSON 2
{
  "title": "This is another title",
  "person" : {
    "firstName" : "Jane"
  },
  "cities":[ "colombo" ]
}

I want to merge #2 into #1 where #2 overrides #1, producing following output:
{
  "title": "This is another title",
  "person" : {
    "firstName" : "Jane",
    "lastName" : "Doe"
  },
  "cities":[ "colombo" ]
}

I checked out the crate json-patch which does this but it does not compile against stable Rust. Is it possible to do something similar with something like serde_json and stable Rust?

A: Since you wanted to use json-patch, I assume you were looking specifically for a JSON Merge Patch (RFC 7396) implementation since that is what that crate implements. In that case, merging an object should unset those keys whose corresponding value in the patch is null, which the code samples in the other answers do not implement.
The code that accounts for that is below. I modified the patch to delete the person.lastName key by setting it to null as a demonstration. It also does not need to unwrap() the Option returned by as_object_mut(), unlike one of the other answers.
use serde_json::{json, Value};

fn merge(a: &mut Value, b: Value) {
    if let Value::Object(a) = a {
        if let Value::Object(b) = b {
            for (k, v) in b {
                if v.is_null() {
                    a.remove(&k);
                }
                else {
                    merge(a.entry(k).or_insert(Value::Null), v);
                }
            }

            return;
        }
    }

    *a = b;
}

fn main() {
    let mut a = json!({
        "title": "This is a title",
        "person" : {
            "firstName" : "John",
            "lastName" : "Doe"
        },
        "cities":[ "london", "paris" ]
    });

    let b = json!({
        "title": "This is another title",
        "person" : {
            "firstName" : "Jane",
            "lastName": null
        },
        "cities":[ "colombo" ]
    });

    merge(&mut a, b);
    println!("{:#}", a);
}

The expected output is
{
  "cities": [
    "colombo"
  ],
  "person": {
    "firstName": "Jane"
  },
  "title": "This is another title"
}

Notice person.lastName has been unset.

A: Placing the answer suggested by Shepmaster below
#[macro_use]
extern crate serde_json;

use serde_json::Value;

fn merge(a: &mut Value, b: Value) {
    match (a, b) {
        (a @ &mut Value::Object(_), Value::Object(b)) => {
            let a = a.as_object_mut().unwrap();
            for (k, v) in b {
                merge(a.entry(k).or_insert(Value::Null), v);
            }
        }
        (a, b) => *a = b,
    }
}

fn main() {
    let mut a = json!({
        "title": "This is a title",
        "person" : {
            "firstName" : "John",
            "lastName" : "Doe"
        },
        "cities":[ "london", "paris" ]
    });

    let b = json!({
        "title": "This is another title",
        "person" : {
            "firstName" : "Jane"
        },
        "cities":[ "colombo" ]
    });

    merge(&mut a, b);
    println!("{:#}", a);
}

A: This worked for me
#[macro_use]
extern crate serde_json;

use serde_json::Value;

fn merge(a: &mut Value, b: &Value) {
    match (a, b) {
        (&mut Value::Object(ref mut a), &Value::Object(ref b)) => {
            for (k, v) in b {
                merge(a.entry(k.clone()).or_insert(Value::Null), v);
            }
        }
        (a, b) => {
            *a = b.clone();
        }
    }
}

fn main() {
    let mut a = json!({
        "title": "This is a title",
        "person" : {
            "firstName" : "John",
            "lastName" : "Doe"
        },
        "cities":[ "london", "paris" ]
    });

    let b = json!({
        "title": "This is another title",
        "person" : {
            "firstName" : "Jane"
        },
        "cities":[ "colombo" ]
    });

    merge(&mut a, &b);
    println!("{:#}", a);
}


text:
Q: Why does the letter 'o' appear in the word 'people'? My two daughters demanded to know this. I speculated that it was artificially inserted, perhaps in the 17th-18th century, perhaps to make the word look more like populus, somewhat similar to the way the spurious 's' was added to 'island'.  I later learned that the Middle English spelling was peeple or peple, which I think tends to support this hypothesis, but I don't know. The picture is further confused by the existence of the Old French form people. Perhaps the 'o' was dropped, and then the older form was revived?
I consulted several dictionaries before posting this, including the Online Etymology Dictionary, and did not find any with a definitive answer.
Is anything specific known about the introduction of the 'o'?

A:
People:
  late 13c., "humans, persons in general," from Anglo-French people, Old French peupel "people, population, crowd; mankind, humanity," from Latin populus "a people, nation; body of citizens; a multitude, crowd, throng," of unknown origin, possibly from Etruscan. The Latin word also is the source of Spanish pueblo, Italian popolo. In English, it displaced native folk.

Source: etymonline
Looks like the Latin influence is responsible for the "o"

A: I consulted Jesse Sheidlower, an editor-at-large for the Oxford English Dictionary. He said that my characterization of the Middle English form as having been peple or peeple was incorrect, and that "Middle English had a tremendous number of spellings", the 'eo' form among them.  So my idea that the 'o' was dropped and later revived is certainly wrong.  Rather, the many other forms died out, leaving only the 'eo' form that we still have.  Mr. Sheidlower says "it's not clear why the 'eo' form became the standard one". It seems likely that there is no definitive answer to the question of why 'people' now has an 'o'.

A: Latin populus meaning folk. populus Romanus - the Roman folk or all the Romans or all Roman people.The Latin o changed in French to a vowel between o and e (le peuple)  and in English the o became /i:/. Instead of writing ee one chose to write eo to show the connection with Latin populus.In German there is still the word der Pöbel, meaning people of the lowest social level.

A: I do not know specifically of the word people, but I do know that there was a period from the 16th to 17th century when we tried to formalize spelling by adding silent letters to words to make them more closely resemble their believed (and occasionally incorrect) Latin or Greek roots.
http://en.wikipedia.org/wiki/English-language_spelling_reform#16th_and_17th_centuries

A: It should not come as a surprise that modern English spelling may have little to do with the way a word is pronounced, though sometimes it is transparent to its history. People entered Middle English through the  Anglo-Norman poeple, people, peple and restricted the native Germanic word folk to narrower usage. The Anglo-French word had a vowel probably similar to the Modern French peuple [ö], a rounded vowel foreign to English phonology. Whether spelled oe or eo, the two letters were a digraph for this single vowel sound.
One of the earliest witnesses in Middle English already suggests something closer to the modern English pronunciation:

Þre kinges and dukes fiue His cheualrie adoun ginneþ driue, And meche oþer peple ischent. — Romance of Bevis of Hampton, ca. 1300–1330.

John Gower retains one of the Anglo-Norman spellings:

Til so befell, as seith the bok,
  That god a poeple for himselve
  Hath chose of the lignages tuelve…     — John Gower, Confessio amantis 5.1598-5.1600. 1390.

By the Tudor era, the spelling had more or less regularized to people. A similar change in pronunciation — though not spelling — occurred with Anglo-Norman boef to English beef.

A: People, noun [French, peuple; Latin, populus; ME. peple.] Its obvious that through word blending the present usage was derived. We owe much to French & Latin in the orthography of English words. Source: Webster's Dictionary of the English Language, 1828 & 1981 editions.


text:
Q: Objective-C wait for asynchronous operation and enqueue completion handlers I have to calculate a costly value. After this value is computed, I'd like to run a completion handler block:
-(void) performCostlyCalculationWithCompletionHandler:(void (^)(void)complete
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        id result = [self costlyCalculation];
        dispatch_async(dispatch_get_main_queue(), ^{
            complete(result);
        });
    });
}

Pretty standard.
Now, I'd like to be able to call this function repeatedly, without re-enqueueing costlyCalculation. If costlyCalculation is already running I'd like to just save the completion blocks and call them all with the same result once costlyCalculation finishes.
Is there a simple way to do this with GCD or an NSOperationQueue? Or should I just store the completion blocks in an NSArray and call them myself? If I do this, what sort of synchronization do I need to put around this array?
UPDATE
I'm able to get close with dispatch_group_notify. Basically, I can enqueue the work blocks and enqueue all completion handlers to run after the group:
dispatch_group_t group = dispatch_group_create();

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue, ^(){
    // Do something that takes a while
    id result = [self costlyCalculation];
    dispatch_group_async(group, dispatch_get_main_queue(), ^(){
        self.result = result;
    });
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^(){
    complete(result);
});

This would work, but how can I tell if costlyCalcuation is already running and not enqueue the work if I don't need to?

A: I think you've mostly solved the problem already. I just came up with an alternative using NSOperationQueue and dependency between NSOperations. Here's a pseudo code I think.
// somewhere, create operation queue
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];

-(void)tryCalculation:(CompletionBlockType)completionBlock
{
    if(opQueue.operationCount > 0)
    {
        NSOperation *op = [[NSOperation alloc] init];
        op.completionBlock = completionBlock;
        // you can control how to synchronize completion blocks by changing dependency object. In this example, all operation will be triggered at once when costly calculation finishes
        [op addDependency:[opQueue.operations firstObject]];
        [opQueue addOperation:op];
    }
    else
    {
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(costlyCalculation) object:nil];
        op.completionBlock = completionBlock;
        [opQueue addOperation:op];
    }
}

Still, there can be subtle timing issue. Maybe we could use additional flag in costlyCalculation function.


text:
Q: Rebuild only if the source was modified by a previous command I have a python script which extracts information from a C++ source file and writes it to a header file. Whenever this generated header changes (which happens rarely), I want to re-compile it (via the GCC precompiled header feature).
Obviously, the command invoking the script depends on the source file, and the recompiling command depends on the header file generated by the script.
add_custom_command(OUTPUT "file.pch.h" COMMAND <script> DEPENDS "file.cpp")
add_custom_command(OUTPUT "file.pch.h.gch" COMMAND <compile> DEPENDS "file.pch.h")

But now file.pch.h.gch depends on file.cpp and is recompiled whenever it changes. How can I avoid this?

A: Have your script write the header to a temporary file, and only copy it over the existing file.pch.h if it's changed. Then the (fast) script runs every time file.cpp changes, but the precompiled header only gets reprecompiled if it's changed.
If you don't want to modify the script, you can use a separate move-if-change script, running a command along these lines:
myscript < file.cpp > file.pch.h.tmp && move-if-change file.pch.h.tmp file.pch.h

There might be a nicer way to do this with Cmake, but this is the old-fashioned way to solve this problem with Make.

Here's a working example with CMake.
The main program, foo.c:
#include "foo.pch.h"

#ifndef FOO_PCH
#include <stdio.h>
#endif

int main() {
    printf("Hello, world\n");
    return 0;
}

The program to generate the precompiled header, make-pch:
#!/bin/bash

(echo '#define FOO_PCH 1'
 awk '/^#endif/ { p = 0 }
      p { print $0 }
      /^#ifndef FOO_PCH/ { p = 1 }') < foo.c > foo.pch.h.tmp

if ! cmp -s foo.pch.h{.tmp,}; then
    echo 'Header changed, updating'
    mv foo.pch.h{.tmp,}
else
    echo 'Header not changed'
    rm -f foo.pch.h.tmp
fi

And CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
add_executable(foo foo.c foo.pch.h.gch)
add_custom_command(OUTPUT "foo.pch.h" COMMAND ./make-pch DEPENDS "foo.c")
add_custom_command(OUTPUT "foo.pch.h.gch"
                   COMMAND echo calling gcc
                   COMMAND gcc foo.pch.h
                   DEPENDS "foo.pch.h")

Let's build it:
$ cmake .
-- The C compiler identification is GNU 4.2.1
-- The CXX compiler identification is Clang 4.1.0
-- Checking whether C compiler has -isysroot
-- Checking whether C compiler has -isysroot - yes
-- Checking whether C compiler supports OSX deployment target flag
-- Checking whether C compiler supports OSX deployment target flag - yes
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/andrew/sx/14662471
$ make
[ 33%] Generating foo.pch.h
Header changed, updating
[ 66%] Generating foo.pch.h.gch
calling gcc
Scanning dependencies of target foo
[100%] Building C object CMakeFiles/foo.dir/foo.c.o
Linking C executable foo
[100%] Built target foo
$ ./foo
Hello, world
$ # it's up-to-date, so calling make again does nothing
$ make
[100%] Built target foo
$ Let's change the C file
$ sed -i -e 's/Hello, world/Hello there, world/' foo.c
$ make
[ 33%] Generating foo.pch.h
Header not changed
Scanning dependencies of target foo
[ 33%] Generating foo.pch.h
Header not changed
[ 66%] Building C object CMakeFiles/foo.dir/foo.c.o
Linking C executable foo
[100%] Built target foo
$ # note that the precompiled header was *not* recompiled
$ ./foo
Hello there, world
$ # now let's add a header file
$ sed -i -e $'s/stdio.h>/stdio.h>\\\n#include <stdlib.h>/' foo.c
$ make
[ 33%] Generating foo.pch.h
Header changed, updating
[ 66%] Generating foo.pch.h.gch
calling gcc
Scanning dependencies of target foo
[100%] Building C object CMakeFiles/foo.dir/foo.c.o
Linking C executable foo
[100%] Built target foo
$ # the precompiled header file *was* recompiled


text:
Q: sharepoint 2007 - how to change the css formting of webpart titles? how can i control the CSS of the tiles of web parts in sharepoint 2007?

A: Heather solomon provides great sharepoint branding articles. This describes your questions http://www.heathersolomon.com/blog/articles/207.aspx


text:
Q: can we show some part of image in jquery? I try to make one image slider  in which user slide it images .I am able to make slider but there is issue in that .it show one image at one time . In other words it show one image in ul.
but I want

*

*when app run it show first image along the it show some part of image two .see below image

*

*when user click on next .it show second image along that it also show some part of third and first image .as example

can we make this type of slider in jquery .
I tried like this
https://jsfiddle.net/uvsb6asa/10/
$(function(){
    $('#next').click(function(){
        addToMarginLeft($('.outer ul'), -210);
    });
    $('#pre').click(function(){
        addToMarginLeft($('.outer ul'), 210);
    });

  function addToMarginLeft(elem, pixels) {
    var ml = parseFloat(elem.css('margin-left'));
    elem.animate({
    'margin-left': (ml + pixels) + 'px'
    },1000)

  }
});

A: Change in CSS the width in .outer and margin-left in .outer ul
.outer {
width:400px;
overflow:hidden
}
.outer ul {
    width: 610px;
    margin:0;
    padding:0px
    margin-left:100px;
}

$(function(){
 $('#next').click(function(){
  addToMarginLeft($('.outer ul'), -210);
 });
 $('#pre').click(function(){
  addToMarginLeft($('.outer ul'), 210);
 });

  function addToMarginLeft(elem, pixels) {
   var ml = parseFloat(elem.css('margin-left'));
    elem.animate({
    'margin-left': (ml + pixels) + 'px'
    },1000)

  }
});
.outer {
width:300px;
overflow:hidden
}
.outer ul {
    width: 610px;
    margin:0;
    padding:0px
    margin-left:100px;

}

.outer li {
    display: inline-block;

}
.outer li img {
   width:200px;
   height:200px;
}

     <button id='pre'>
    previous
    </button>
    <button id='next'>
    next
    </button>


text:
Q: Question Regarding solution of this Problem $ \lim\limits_{x \rightarrow \infty }f(x) + f'(x) =L $ I Know how to solve this Problem. The difficulty which I face is about the way in Which my Friend solved this Question
If  $\lim\limits_{x\rightarrow\infty} f(x)+f'(x) = L$ Then prove that $\lim\limits_{x\rightarrow\infty} f(x)= L$
He done it by taking  $g(x)=e^{x} f(x).$
then  $Dg(x)=e^{x}f(x)+e^{x}Df(x)=e^{x} \left( f(x)+Df(x) \right).$
Then by $\lim_{x \to +\infty} f(x) = \lim_{x \to +\infty} \frac{g(x)}{e^x} = \lim_{x \to +\infty} \frac{Dg(x)}{e^x} = \lim_{x \to +\infty} Df(x)+f(x)$
My Question is, Is there any analysis problem there, when we apply  l'Hospital's theorem.
Why they kept $e^x$ and then differentiated . I think we can make some wired things if it is allowed there  ...

A: You just need to check that you are allowed to use L'Hopital's rule: you need to verify that indeed $\lim_{x\to+\infty}g(x) = +\infty$.
As to why they used $e^x$, I think the answer lies in the differentiation of $g$ itself: you can see for yourself that it's indeed a fairly nice trick.
Hint to another way to solve this: what would happen if $\lim_{x\to+\infty}f(x)$ (provided it exists) were a number $R \not= L$ (or $\pm\infty$)? What could you say about the derivative?


text:
Q: Why can't NSSpeechsynthesier's class method availableVoices be bridged to a Swift array of strings? In Apple's Working with Cocoa Frameworks it reads as if the Foundation and Swift Foundation frameworks work together through bridging.  However, I noticed that while attempting to use NSSpeechSynthesizer's class method availableVoices() it allows me to received an returned array of NSStrings but not Strings.
This compiles and runs just fine:
let voices = NSSpeechSynthesizer.availableVoices as [NSString]
        print(voices)

However this won't compile:
let voicesTwo = NSSpeechSynthesizer.availableVoices as [String]

Why wouldn't this work if the voiceName documentation shows that VoiceName is a string property?
I see the term 'rawValue' in the VoiceName documentation so is the reasoning having anything to do with this being some sort of an enum?

A: It looks like NSSpeechSynthesizer.VoiceName is an Enum with a rawValue of String. That is not the same thing as being a string.
Try using
NSSpeechSynthesizer.availableVoices.map { $0.rawValue }


text:
Q: Run action after Gtk window is shown I have a multi-window Gtk application, which is an installer.
During the installation process, which takes some time, I want to show a Window with a label to notify the user that the installation is in progress.
So I tried to bind the respective method to the show event.
However, that causes the appearance of the window to be delayed until the the method finishes, after which the next window is immediately shown.
The result is, that the previous window shows, then the screen goes blank for the duration of the actual installation and then the final window is shown.
I boiled the issue down to the fact, that the show event is obviously triggered, before the window is actually shown.
Here's a minimal snipped to clarify my issue.
The window shows after the call to sleep(), not before.
#! /usr/bin/env python3

from time import sleep

from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI(Gtk.ApplicationWindow):

    def __init__(self):
        """Initializes the GUI."""
        super().__init__(title='Gtk Window')
        self.set_position(Gtk.WindowPosition.CENTER)
        self.grid = Gtk.Grid()
        self.add(self.grid)
        self.label = Gtk.Label()
        self.label.set_text('Doing stuff')
        self.grid.attach(self.label, 0, 0, 1, 1)
        self.connect('show', self.on_show)

    def on_show(self, *args):
        print('Doing stuff.')
        sleep(3)
        print('Done stuff.')

def main() -> None:
    """Starts the GUI."""

    win = GUI()
    win.connect('destroy', Gtk.main_quit)
    win.show_all()
    Gtk.main()

if __name__ == '__main__':
    main()

How can I achieve, that the window shows before the method on_show() is called?
The desired program flow is

*

*Show window

*run installation

*hide window (and show next one)

without any user interaction.

A: I fixed it by using multiprocessing :
from ast import Gt
from time import sleep
from multiprocessing import Process

from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI(Gtk.ApplicationWindow):

    def __init__(self):
        """Initializes the GUI."""
        super().__init__(title='Gtk Window')
        self.set_position(Gtk.WindowPosition.CENTER)
        self.grid = Gtk.Grid()
        self.add(self.grid)
        self.label = Gtk.Label()
        self.label.set_text('Doing stuff')
        self.grid.attach(self.label, 0, 0, 1, 1)

def on_show():
    print('Doing stuff.')
    sleep(3)
    print('Done stuff.')

def main() -> None:
    """Starts the GUI."""

    win = GUI()
    win.connect('destroy', Gtk.main_quit)
    win.show_all()
    p1 = Process(target = on_show)
    p1.start()
    Gtk.main()

if __name__ == '__main__':
    main()

Basically, what was happening is that Gtk.main() renders your app while show_all() just packs the widgets, so putting a sleep func before it delays the render.

A: another method is to use threading (which also provides you an easy way to implemant a progress bar) :
from ast import Gt
from time import sleep

import threading

from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI(Gtk.ApplicationWindow):

    def __init__(self):
        """Initializes the GUI."""
        super().__init__(title='Gtk Window')
        self.set_position(Gtk.WindowPosition.CENTER)
        self.grid = Gtk.Grid()
        self.add(self.grid)
        self.label = Gtk.Label()
        self.label.set_text('Doing stuff')
        self.grid.attach(self.label, 0, 0, 1, 1)
        thread = threading.Thread(target=self.on_show)
        thread.daemon = True
        thread.start()

    def on_show(self, *args):
        print('Doing stuff.')
        sleep(3)
        print('Done stuff.')

def main() -> None:
    """Starts the GUI."""

    win = GUI()
    win.connect('destroy', Gtk.main_quit)
    win.show_all()
    Gtk.main()

if __name__ == '__main__':
    main()

Further informations on threads


text:
Q: If I times a float by it's multiple (1.3 * 10) to put it into an integer, is it more accurate than staying with the float in computation? OK OK.  I know there's libraries out there.  I know there's quite a few posts on this subject of float accuracy but the ones I've run into haven't really answered the question for me.  Being the inquisitive individual that I am, I want a thorough answer.
TLDR;
Is "converting" a float to an integer by it's multiple more accurate as a way of computing very large floats in JavaScript rather than by just the floats?  Meaning: in an equation 1.3e-12 * 1.4, if I (1.3e-12 * 10000000000000) * (1.4 * 10000000000000) / 10000000000000, is it more accurate?
LONGER
I want to know if I take a number say: 1.3e-11 and ~~(1.3 * Math.pow(11, 10)), is the not operator ~~, or any bitwise operator that will truncate 64bit floats, even needed to ensure that a float goes to an integer?  If the numbers are stored in javascript as floats anyway, it doesn't appear to me that it's really needed.  Also is "converting" floats to integers in JavaScript safe and supremely accurate?  If I work with large decimals in this way, it DOES appear to heighten output accuracy.
For instance:
144 * 0.3048 / 0.0254
the conversion from 144 sqft to inches yields 1728.000000000002.  However:
var a, b, c, p = 4;
a = 144 * Math.pow(10, p);
b = 0.3048 * Math.pow(10, p);
c = 0.0254 * Math.pow(10, p);
console.log((a * b / c) / Math.pow(10, p));

Yields exactly 1728.
Another question I have is: Does stored very long computed floats that have not been converted to larger ints less accurate in a series of computations?


text:
Q: powrshell command does not run when I run the entire script I wrote a ps1 script to automate some package installation but the strange part is when I run the command snippet for executing the .exe file for SEP (Symantec Endpoint Protection) , it is executing fine , but when I execute the entire script , it does run the command snippet.
Iam only running a simple .exe file , and even if I run it manually , it does not show any installer , rather it installs silently in the background.
So in the script, Iam only running the .exe file, thats it .
Should I be giving any wait time or any other inputs ?
Start-Process -Wait -FilePath "C:\Temp\Symantec-Windows\SEP 14.3.3384.1000 x64.exe" -passthru
$SymVersion = Get-WmiObject -Class Win32_Product -ComputerName $hostname | Where-Object -FilterScript {$_.Name -eq "symantec endpoint protection"} | Format-List -Property version, InstallState, name
echo $SymVersion
if($SymVersion)
{
echo 'Symantec is successfully installed' -ForegroundColor Green
}
else
{
echo 'Symantec is not successfully installed' -ForegroundColor Red
}

A: The symantec antivirus exe files are made for silent installations. If you want to proceed with GUI mode, better unzip the file and use MSI file with arguments. With your current script,Its better to check the process is exited with code 0. The following code is not tested.
$process = Start-Process -FilePath "C:\Temp\Symantec-Windows\SEP 14.3.3384.1000 x64.exe" -passthru -Wait
if($process.ExitCode -ne 0)
{
    throw "Installation process returned error code: $($process.ExitCode)"
} else { Write-Host "Installation Successful"}


text:
Q: Confusion about Angular Router logic for multiple empty paths While learning how the Angular router works, I have come across some puzzling behavior that I don't quite understand.  It seems that if you have a routes config setup like so (with the lazy loaded modules each having their own route config that just contains an empty path and a component:
export const appRoutes: Routes = [
   { path: "", component: DefaultComponent },
   { path: "", loadChildren: "./module-one/module-one.module#ModuleOne" },
   { path: "two", loadChildren: "./module-two/module-two.module#ModuleTwo" },
   { path: "three", loadChildren: "./module-three/module-three.module#ModuleThree" },
   { path: "one", loadChildren: "./module-one/module-one.module#ModuleOne" },
]

and you navigate to /two, then ModuleOne will be be created, then ModuleTwo will be created and finally the SecondComponent that ModuleTwo creates will be created.  However, the component that ModuleOne was supposed to create was not created.

*

*1) why was ModuleOne created at all and why first?

*2) Why didn't ModuleOne create its component?

*2) Why did the Router choose to go with the second empty path and not the first?
I think I understand why ModuleOne was created (and why first).  The docs say that an empty path doesn't consume any url segments, so I guess when the Router finds an empty path, it performs whatever the empty path is supposed to do and then starts re-parsing the url tree from where it found the empty path?  (not 100% about that behavior).  That doesn't explain why it ignored the empty path that loads the DefaultComponent though.
Another strange thing is, when the second route with an empty path is commented out:
//{ path: "", loadChildren: "./module-one/module-one.module#ModuleOne" },

and we are left with only one empty path that goes to the DefaultComponent, that path never gets triggered when navigating to /two, even though the other empty path did.  Is there something obvious in the docs I'm not picking up on?
Here is a StackBlitz to see what I'm talking about https://stackblitz.com/edit/angular-gitter-o5tttb
I enabled tracing in the Router, which is how I know what modules/components are created.

A: When you navigate to two, the router starts to process routes one by one. So it starts with the first one:
{ path: "", component: DefaultComponent },

it matches as empty string always matches. Then the remaining segments is two and the router tries to find if the currently processing route has a child route with the path two. This route doesn't have any children so the router discards it.
It then transitions to the second route:
{ path: "", loadChildren: "./module-one/module-one.module#ModuleOne" },

again, it's an empty string route so it matches. Now, for the router to check if there are any child routes that will match the remaining segment two it needs to fetch that route. Once the module is fetched it should be compiled and instantiated as it defines the new routes using RouterModule.forChild(moduleOneRoutes). Once the module is created the router fetches the routes and finds out that there's only one route with an empty path and it doesn't match the remaining segment two. The route is rejected.
It then proceeds to the third route:
{ path: "two", loadChildren: "./module-two/module-two.module#ModuleTwo" }

which matches the segment completely so it fetches the module and instantiates the component it brings.


text:
Q: How to re-ID multidimensional arrays in PHP? I have a multidimensional array in php. I have also a DB, which has the same data, but different ID for them. I have to match the two ...
$ad_types = array(
    array('Személyi kölcsön', 0, array(
        'Adósságrendező hitel',
        'Hitel autóvásárlásra',
        'Szabad felhasználású hitel',
        'Hitelkiváltás',
        'Hitel fix részletre',
        'Online hitel',
        'Akciós hitel',
        'Gyorskölcsön',
        'Hitel alacsony kamatra',
        'Kis összegű hitel',
    )),
    array('Jelzáloghitel', 0, array(
        'Jelzáloghitel használt lakásra',
        'CSOK',
        'Akciós jelzáloghitelek',
        'Adósságrendező hitel',
        'Szabad felhasználású hitel',
        'Jelzáloghitel építésre/bővítésre',
        'Jelzáloghitel korszerűsítésre',
        'Jelzáloghitel fix részletre',
        'Jelzáloghitel alacsony kamatra'
    )),
    array('Hitelkártya', 5, array(
        'Pontgyűjtő',
        'Akciós',
        'Aranykártya',
        'Kedvező tankolás'
    )),
);

I have to re-ID them, so their ID would look like:
+----+-----------------------------------------+
| id | name                                    |
+----+-----------------------------------------+
|  0 | Személyi kölcsön                        |
|  1 | Adósságrendező hitel                    |
|  2 | Hitel autóvásárlásra                    |
|  3 | Szabad felhasználású hitel              |
|  4 | Hitelkiváltás                           |
|  5 | Hitel fix részletre                     |
|  6 | Online hitel                            |
|  7 | Akciós hitel                            |
|  8 | Gyorskölcsön                            |
|  9 | Hitel alacsony kamatra                  |
| 10 | Kis összegű hitel                       |
| 11 | Jelzáloghitel                           |
| 12 | Jelzáloghitel használt lakásra          |
| 13 | CSOK                                    |
| 14 | Akciós jelzáloghitelek                  |
| 15 | Adósságrendező hitel                    |
| 16 | Szabad felhasználású hitel              |
| 17 | Jelzáloghitel építésre/bővítésre        |
| 18 | Jelzáloghitel korszerűsítésre           |
| 19 | Jelzáloghitel fix részletre             |
| 20 | Jelzáloghitel alacsony kamatra          |
| 21 | Hitelkártya                             |
| 22 | Pontgyűjtő                              |
| 23 | Akciós                                  |
| 24 | Aranykártya                             |
| 25 | Kedvező tankolás                        |
+----+-----------------------------------------+

how can i do that, do their ID will match with the one in my DB?

A: function reIdArray($array)
{
    $reIdArray = array();
    foreach ($array as $subArray) {
        $reIdArray = array_merge($reIdArray, array($subArray[0]), $subArray[2]);
    }
    return $reIdArray;
}

// print_r(reIdArray($ad_types));


text:
Q: Ubuntu 15.10 upgrade hangs on "Calculating the changes" I'm trying to upgrade my linode server from Ubuntu 15.04 to Ubuntu 15.10.
I run do-release-upgrade, and the script hangs here:
Checking package manager
Reading package lists... Done
Building dependency tree
Reading state information... Done
Building data structures... Done

Calculating the changes

Calculating the changes

I've waited over 24 hours and it's still at the same place, and not using much CPU. Has anyone run into this problem, or does anyone know how to resolve it?


text:
Q: Border-top shadow and triangle down in css I'd like to achieve something like this in CSS. Is it possible? How?
I can create a border top with shadow as well as a triangle down, but the issue if I do this is that there's a border on 3 sides of the triangle so the rendering is not the same.
Many thanks,

A: you can try this:
Speech bubble with a border

css:
body { padding: 100px 10px;text-align: center;}
.bubble {
    background-color: #eee;border: 2px solid #333;box-shadow: 5px 1px 5px #888888;border-radius: 5px;color: #333;display: inline-block;font:16px/24px sans-serif;padding: 12px 24px;position: relative;}
.bubble:after,
.bubble:before {
    border-left: 20px solid transparent;border-right: 20px solid transparent;border-top: 20px solid #eee;bottom: -20px;content: '';left: 50%;margin-left: -20px;position: absolute;}
.bubble:before {
    border-left: 23px solid transparent;border-right: 23px solid transparent;border-top: 23px solid;border-top-color: inherit;bottom: -23px;margin-left: -23px;}


text:
Q: Determine distance between two lines in an image I have the following image:

In this image there are 5 more or less vertical peaks in total. Let the x-axis be the horizontal axis and y-axis be the vertical axis. I would like to determine the distance between the center of the most intense peak (peak in the middle of the image) and the centers of the 4 symmetrically surrounding peaks for every given y-value. So that I know the distance of these peak-centers as a function of y.
For reasons of testing the code, I have selected a smaller area in the original image file:

Within my code this image is called: testlong.jpg
My code so far:
img2 = Import["filepath\\testlong.jpg"];
data2 = ImageData[img2];
Dimensions[data2]

For[column = 1, column < 83, column++, pc[column] =
Position[data2[[All,  column]], Max[data2[[All, column]]]];
pb[column] = Position[data2[[1 ;; 60, column]], Max[data2[[1 ;; 60,
column]]]];
pt[column] = 239 + Position[data2[[240 ;; 282, column]], Max[data2[[240
;; 280, column]]]];];

For[lauf = 1, lauf < 83, lauf++, pcflat[lauf] = Flatten[pc[lauf]]];
For[lauf = 1, lauf < 83, lauf++, pbflat[lauf] = Flatten[pb[lauf]]];
For[lauf = 1, lauf < 83, lauf++, ptflat[lauf] = Flatten[pt[lauf]]];

Now what's to do is to plot pcflat, ptflat, pbflat, fit each one with a line of best fit and determine the distance between these lines. But I don't seem to be able to plot pcflat, ptflat, pbflat. If I use:
ListPlot[Table[pcflat[i],{i,1,82}],PlotRange->All]

Mathematica plots 3 points within the interval [1,2]
The problem is, that pcflat, pbflat, etc are nested lists with unequal length, because some x-values correspond with more than one y-value where there is a maximum (peaks are not delta peaks but have a width). How do I plot that?

A: Since you are looking for vertical lines, the problem is 1D. Start by summing the pixels for each column of the image:
img2 = Import["http://s4.postimg.org/dearql4iz/XZ_85.png"];
data2 = ImageData[img2];
sums = Map[Tr, Transpose@data2];
ListPlot[sums]

It seems the 5 five lines you are mentionning are not so clear. But we can see clearly three of them.
Using FindPeaks to find the positions of the lines, sorting them with respect to the second component and selecting the five first ones:
peaks = FindPeaks[sums];
selectedPeaks = Sort[peaks, #1[[2]] > #2[[2]] &][[1 ;; 5]]
Show[ListPlot[sums, PlotRange -> Full],
      ListPlot[selectedPeaks, PlotStyle -> Red]]

Show[img2, Graphics[{Red, Dashed, Map[Line[{{#, 0}, {#, h}}] &, selectedPeaks[[All, 1]] ]}]]

A: There are some problems with the way you generate your data. The biggest one is that Position returns multiple locations because maximum pixel value happens more than once for one y-value. For example, from your code, if you look at pb[2], you'll get {{29}, {33}, {34}, {35}}. This means that the maximum value occurs four times in that column. The easiest way to fix this is to take the average of all the locations. Here's a working solution.
img2 = Import["C:\\Users\\labuser\\Downloads\\testlong.jpg"];
data2 = ImageData[img2];
Dimensions[data2];

For[column = 1, column < 83, column++,
  pc[column] =
   Mean[Flatten[
     Position[data2[[All, column]], Max[data2[[All, column]]]]]];
  pb[column] =
   Mean[Flatten[
     Position[data2[[1 ;; 60, column]],
      Max[data2[[1 ;; 60, column]]]]]];
  pt[column] =
   Mean[Flatten[
     239 + Position[data2[[240 ;; 282, column]],
       Max[data2[[240 ;; 280, column]]]]]]];
pbflat = Table[pb[i], {i, 1, 82}];
ptflat = Table[pt[i], {i, 1, 82}];
pcflat = Table[pc[i], {i, 1, 82}];
ListPlot[{pbflat, ptflat, pcflat}]

After that, it's just a matter of fitting a line to each of the data set.
I haven't changed much of your code. There are things you could do that could make it much more efficient. For example, your code could be a lot faster by using Map/Scan/Apply instead of procedural programming, i.e. for loop. See this 10 tips for writing fast Mathematica code, item#9 for a comparison. Unfortunately, I can't post the link to this article because my reputation is not enough. (Tragedy). But a quick google of the article's name will turn it up.


text:
Q: Creating list of ip's in ansible using given range within jinja template i want to generate a list of ip addresses (using range of last 8bits so 120-190 translates to x.x.x.120 - x.x.x.190) in defaults/main.yml in my role, and later use it to create new network interfaces and generate a new config file. I tried this approach:
defaults/main.yml:
ip_list: "{%for address_end in range(50,99)%} 192.168.0.{{address_end}}{%endfor%}"
conf_list: "{%for ip in ip_list%}server {{ip}}:6666 {%endfor%}"
and then to use it in template
template.conf.j2:
{% for conf_line in conf_list %}
{{conf_line}}
{% endfor %}

and all i got in generated config file was:
            s
            e
            r
            v
            e
            r

            :
            6
            6
            6
            6

            s
            e
            r
            v
            e
            r

            1
            :
            6

so my guess is that i'm not generating a list but just a long string and when I use for loop in template.conf.j2 I iterate over single chars. I tried using answer to this problem but all i got was syntax error. Any ideas for what might help me ?

A: You should format your vars as JSON lists if you want them to be lists.
1.1.1.1 2.2.2.2 3.3.3.3 is a string.
['1.1.1.1', '2.2.2.2', '3.3.3.3'] will be converted to list.
But there is alternative approach for you:
ip_list: "{{ lookup('sequence', 'start=50 count=12 format=192.168.0.%d', wantlist=True) }}"
conf_list: "{{ ip_list | map('regex_replace','(.*)','server \\1:6666') | list }}"

A: Kostantin answer was of much help, but i found just realized that generating config entries in my case could be solved in an less complex way. Instead of trying to iterate over list or a string variable variable in jinja template file template.conf.j2 like did with :
{% for conf_line in conf_list %}
{{conf_line}}
{% endfor %}

you could just enter insert new line signs while generating string in defaults/main.yml:
conf_list: "{%for ip in ip_list%}server {{ip}}:6666\n{%endfor%}"

and then just insert that whole string into a template.conf.j2 like this:
{{conf_line}}

nevertheless i have no other idea how to generate list of ip addresses other than the one Konstantin proposed.


text:
Q: Android RecyclerView inside RecyclerView? I am using RecyclerView that displays different categories list. Each row item also contains RecyclerView to show category items' list. Parent RecyclerView is populated with vertial LinearLayoutManager and child RecyclerViews are populated with GridLayoutManager (2 columns). Child RecyclerViews are not showing all category items except first 2 even it has many category items. All remaining category items are hiding for specific category. In other words, you can say child RecyclerView is not expanding as much as items it contains.
I found different solution here but no one worked. That's why posting again.

A: You can easily achieve it with only one RecyclerView using this library. See the image below:

First create a Section class:
class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new MyHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }
}

Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data for each year
MySection section1 = new MySection("Categories 1", categories1DataList);
MySection section2 = new MySection("Categories 2", categories2DataList);

// Add your Sections to the adapter
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);


text:
Q: Array values reutilization in another array definition I am trying to perform an array definition in bash using values of another array as the name of the new array and assign the values inside the array from another array which is dynamically populated.
Here is an example of the code so far:
adduser() {
  declare -i segment=$1
  segment_length=${#segment[@]}
  for (( a = 0; a < "${segment_length}"; a++ )); do
    data=($(cat $filename | grep -w ${segment[a]} | awk -F ";" '{print $1}' | tr '\n' ' ' | sed 's/^/ /g'))
    ${segment[a]}=($(echo "${data[*]}"))
  done
}

cat $filename | tail -n+2 | awk -F ";" '{print $2}' | awk '{ for (i=1; i<=NF; i++) print $i }' | sed 's/\r//g' | sort -u > segments.txt
IFS=$'\r\n' GLOBIGNORE='*' command eval  'segments=($(cat segments.txt))'
for (( i = 0; i < ${#segments[@]}; i++ )); do
adduser ${segments[i]}
done

The objective is to dynamically populate arrays (data in one column of csv) with values from another column and then massively work on them.
The csv has the following format:
Header1;Header2
Value1;1 2 3
Value2;2 4 5

Take for example the value 2 from column Header2.
The objective is to dynamically create the array 2 with values Value1 and Value2:
2=( Value1 Value2 )

Testing the two answers provided:
I will continue here as comments are too short: Here is the result from the answer with a random file (same format as the example):
ivo@spain-nuc-03:~/Downloads/TestStackoverflow$ awk -F'[; ]' '/;[0-9] / { for (i=2; i<=NF; i++) printf "%s ", $1 > $i".txt" }' real.csv
ivo@spain-nuc-03:~/Downloads/TestStackoverflow$ ll
total 68
drwxr-xr-x  2 ivo ivo  4096 Nov 27 17:16 ./
drwxr-xr-x 28 ivo ivo 32768 Nov 27 17:15 ../
-rw-rw-r--  1 ivo ivo    99 Nov 27 17:16 155.txt
-rw-rw-r--  1 ivo ivo   132 Nov 27 17:16 155?.txt
-rw-rw-r--  1 ivo ivo    99 Nov 27 17:16 2.txt
-rw-rw-r--  1 ivo ivo    66 Nov 27 17:16 2?.txt
-rw-rw-r--  1 ivo ivo   198 Nov 27 17:16 3.txt
-rw-rw-r--  1 ivo ivo    33 Nov 27 17:16 3?.txt
-rw-r--r--  1 ivo ivo  1369 Nov 27 17:14 real.csv

While with the answer above you get the following:
ivo@spain-nuc-03:~/Downloads/TestStackoverflow$ ./processing.sh real.csv

ivo@spain-nuc-03:~/Downloads/TestStackoverflow$ ll
total 112
drwxr-xr-x  2 ivo ivo  4096 Nov 27 17:25 ./
drwxr-xr-x 28 ivo ivo 32768 Nov 27 17:15 ../
-rw-rw-r--  1 ivo ivo   100 Nov 27 17:25 102.txt
-rw-rw-r--  1 ivo ivo   100 Nov 27 17:25 105.txt
-rw-rw-r--  1 ivo ivo    67 Nov 27 17:25 106.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 112.txt
-rw-rw-r--  1 ivo ivo   991 Nov 27 17:25 155.txt
-rw-rw-r--  1 ivo ivo   694 Nov 27 17:25 2.txt
-rw-rw-r--  1 ivo ivo   859 Nov 27 17:25 3.txt
-rw-rw-r--  1 ivo ivo    67 Nov 27 17:25 51.txt
-rw-rw-r--  1 ivo ivo    67 Nov 27 17:25 58.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 59.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 65.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 67.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 72.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 78.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 81.txt
-rw-rw-r--  1 ivo ivo    34 Nov 27 17:25 82.txt
-rwxrwxr-x  1 ivo ivo  1180 Nov 27 17:25 processing.sh*
-rw-r--r--  1 ivo ivo  1369 Nov 27 17:14 real.csv
ivo@spain-nuc-03:~/Downloads/TestStackoverflow$

Thanks to everyone for their participation!

A: Finally I went for a simpler method according to the comments I got to simplify:
cat $1 | tail -n+2 | awk -F ";" '{print $2}' | awk '{ for (i=1; i<=NF; i++) print $i }' | sed 's/\r//g' | sort -u > segments.txt
IFS=$'\r\n' GLOBIGNORE='*' command eval  'segments=($(cat segments.txt))'
for (( i = 0; i < ${#segments[@]}; i++ )); do
cat $1 | grep -w ${segments[i]} | awk -F ";" '{print $1}' | tr '\n' ' ' | sed 's/^/ /g' > ${segments[i]}.txt
done
rm segments.txt

And then just process the remaining txt files in the folder.
I would really like to see this done in the way I was going initially though as it is more suitable for more data...

A: If I'm reading it right, and assuming you are ok with having no proper newline on the files since you were explicitly squashing them out, this should do all the above in one awk call.
awk -F'[; ]' '/;[0-9] / { for (i=2; i<=NF; i++) printf "%s ", $1 > $i".txt" }' yourInputFile

A: All-bash using array -
declare -a set=()                          # set is an array
while IFS=';' read -r key lst              # read each line into these 2 splitting on semicolons
do [[ $key =~ Header* ]] && continue       # ignore the header
   read -a val <<< "$lst"                  # split the list of values to the right of the semicolon into an array
   for e in "${val[@]}"                    # for each of those
   do  case "${set[e]:-}" in
       *$key*) : already here, no-op   ;;  # ignore if already present
           '') set[e]="$key"           ;;  # set initial if empty
            *) set[e]="${set[e]} $key" ;;  # add delimited if new
       esac
   done
done < csv                                 # reads directly from the CSV file

At this point the sets should be loaded as space-delimited strings into each element of set[], indexed by the values on the line in the second column of the csv. To print them out for verification -
for n in "${!set[@]}"
do echo "$n: ${set[n]}"
done

Executed on the test csv content provided:
1: Value1
2: Value1 Value2
3: Value1
4: Value2
5: Value2

so set[4] is Value2, and set[2] is Value1 Value2. You can pull them from there to do whatever is needed.
No need for cat/tail/awk/grep/tr/sed/sort chains.
Does it need something more?


text:
Q: Uploading an image to a server: stuck at FileInputStream Im trying to upload image to server, but somehow the code stopped at FileInputStream line. not sure why and i don't know how to debug or check it. here my source code:
 public class CreateSetcardStep1Activity extends AppCompatActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        String filename = appHelper.dateToString(new Date(), "yyyyMMdd-hhmmss");
        destination = new File(Environment.getExternalStorageDirectory(), filename + ".jpg");

        buttonTakePhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
                startActivityForResult(intent, REQUEST_IMAGE);
            }
        });

        buttonSubmitPhoto.setVisibility(View.GONE);
        buttonSubmitPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog = ProgressDialog.show(CreateSetcardStep1Activity.this, "", "Uploading file...", true);

                new Thread(new Runnable() {
                    public void run() {
                        uploadFile(imagePath);
                    }
                }).start();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            try {
                buttonSubmitPhoto.setVisibility(View.VISIBLE);
                Log.e(LOG, "breakpoint 1");
                setcardPic.setVisibility(View.VISIBLE); Log.e(LOG, "breakpoint 2 destination: "+destination);
                FileInputStream in = new FileInputStream(destination); Log.e(LOG, "breakpoint 3");
                BitmapFactory.Options options = new BitmapFactory.Options(); Log.e(LOG, "breakpoint 4");
                options.inSampleSize = 10; Log.e(LOG, "breakpoint 5");
                imagePath = destination.getAbsolutePath(); Log.e(LOG, "breakpoint 6 imagePath: "+imagePath);
                Log.e(LOG, "PATH === " + imagePath);
                //tvPath.setText(imagePath);
                Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
                setcardPic.setImageBitmap(bmp);
                showUploadButton = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } else {
            showUploadButton = false;
            Toast.makeText(getApplicationContext(),
                    R.string.request_cancelled,
                    Toast.LENGTH_LONG).show();
        }
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;
        showUploadButton = false; //revert upload button to hidden
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {
            dialog.dismiss();
            Log.e(LOG, "Source File not exist :" +imagePath);
            return 0;
        }
        else
        {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("Filedata", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename="+ fileName + "" + lineEnd);
                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i(LOG, "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

                if(serverResponseCode == 200){

                    runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(CreateSetcardStep1Activity.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(CreateSetcardStep1Activity.this, "MalformedURLException",
                                Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e(LOG, "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(CreateSetcardStep1Activity.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e(LOG, "Exception : "
                        + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;

        }
    }
}

Is there any way to check where the issue is? the logcat stopped at breakpoint 2: breakpoint 2 destination: /storage/emulated/0/20171215-051851.jpg
so the file is there if i check the explorer

A: This happens because you haven't requested EXTERNAL_STORAGE permission.
Starting from android API level 23 (marshmallow), android permission framework (I don't know whether that's the right term for it or not), have changed.
Before marshmallow you just had to declare permissions in the manifest file. But on and above marshmallow, android permissions have been categorized into Normal permissions and Dangerous permissions. If you are using a normal permission, things are the same on all android versions. But if you are using a dangerous permission, you have to request the user to grant that permission at runtime.
In your case, you are uploading an image, which require READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions. Those are categorized as dangerous permissions. So you have to request those permissions before you do any actions that require those permissions.
But you don't have to request both the permissions separately, since those permissions fall under one permission group.
From official docs,

If an app requests a dangerous permission listed in its manifest, and the app already has another dangerous permission in the same permission group, the system immediately grants the permission without any interaction with the user..

ie, if you have declared a couple of permissions that are on a single permission group, you have to request for only one of those permissions. If the user grants permission for that permission group, all those permissions you declared, which are in the same permission group will be granted by the system.
Here is the code to request storage permission
private static final int STORAGE_REQ_ID=3465;

if (ContextCompat.checkSelfPermission(CreateSetcardStep1Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            {

                if (ActivityCompat.shouldShowRequestPermissionRationale(CreateSetcardStep1Activity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {

                    //THIS CONDITION WORKS WHEN WE ARE REQUSETING PERMISSION AGAIN SINCE USER DENIED PERMISSION ON PREVIOUS REQUEST(S)

                    ActivityCompat.requestPermissions(CreateSetcardStep1Activity.this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                STORAGE_REQ_ID);

                } else {

                    //REQUESTING PERMISSION FOR FIRST TIME, EXPLAIN WHY THE APPLICATION NEED PERMISSION

                    AlertDialog.Builder builder = new AlertDialog.Builder(CreateSetcardStep1Activity.this);
                    builder.setTitle("Permission Request");
                    builder.setMessage("To upload image, Application need External storage permission");
                    builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            ActivityCompat.requestPermissions(CreateSetcardStep1Activity.this,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                    STORAGE_REQ_ID);
                        }
                    });
                    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    ActivityCompat.requestPermissions(CreateSetcardStep1Activity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           STORAGE_REQ_ID);
                }
            }
            else startImageCapture();
        }

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

//HERE YOU HANDLE PERMISSION REQUEST RESULTS
    switch (requestCode) {
        case STORAGE_REQ_ID: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                //PERMISSION GRANTED!!
                startImageCapture();

            } else {

                //USER DENIED PERMISSION, NOTIFY THE USER THAT PERMISSION IS DENIED, MAY BE A TOAST?

            }
            return;
        }

    }
}

private void startImageCapture(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
    startActivityForResult(intent, REQUEST_IMAGE);
}

Everything else is pretty much the same. (And sorry for my poor English)
More on permission request here

A: Hi please check first Permission like(Read External,Write External and Camera if used) into Manifest file after that put Runtime  permission code for Greater then Marshmallow devices.And Use File Provider to get Image Uri from SD Card.
And put below code into onActivityResult().
                 if (mPhotouri != null) {
                    try {
                        mBitmap = MediaStore.Images.Media.getBitmap(
                                getContentResolver(), mPhotouri);
                        Uri tempUri = getImageUri(this, mBitmap);
                        finalFile = new File(getRealPathFromURI(tempUri, this));
                        mSelectedImagePath = finalFile.getAbsolutePath();

                        if (mSelectedImagePath != null)
                            mFileSelectedImage = new File(mSelectedImagePath);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

public static Uri getImageUri(Activity inContext, Bitmap inImage) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

public static String getRealPathFromURI(Uri uri, Activity signupActivity) {
    Cursor cursor = signupActivity.getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

hope it helps.

A: add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

and for api 23+ , read this tutorial:
Runtime Permissions


text:
Q: How Get Value for General Properties Html.DisplayFor how implement This Code in mvc core
when Generate Model In Mvc Core
@foreach (var itemRow in Model)
                {

                        @foreach (var itemValue in itemRow.GetType().GetProperties())
                        {

                                @Html.DisplayFor(modelItem => itemValue)

              //@itemRow.GetType().GetProperty(itemValue.Name).GetValue(itemRow, null)

                        }

                }

A: You can try below:
@foreach (var item in Model) {

                        @Html.DisplayFor(modelItem => item.Name)

        }


text:
Q: Why worldsheet current associated to spacetime supersymmetry is the integral of the vertex opertor? Sorry, I just haven't enough reputations for adding a comment in that post.
@MISC {389179,
    TITLE = {Polchinski equation 11.2.7},
    AUTHOR = {Nogueira (https://physics.stackexchange.com/users/35399/nogueira)},
    HOWPUBLISHED = {Physics Stack Exchange},
    NOTE = {URL:https://physics.stackexchange.com/q/389179 (version: 2018-04-19)},
    EPRINT = {https://physics.stackexchange.com/q/389179},
    URL = {https://physics.stackexchange.com/q/389179}
}
So my question is, why this formula,
$Q_{s}=\oint_C\frac{dz}{2\pi i}\mathcal{V}_s$
is right? Seems most papers just cite it. I don't see any physical reason behind it. Q is the supercharge while V is the vertex operator corresponding to an R or NS sector vacuum. For more detail, one can read Polchinski Vol.2 P50


text:
Q: how to change values between tags in a string If I have the following string:
str="hello %%one_boy%%'s something %%four_girl%%'s something more"

how would I edit it to get the following output from printing str:
"hello ONE_BOY's something FOUR_GIRL's something more"

I have been trying to use 'gsub' and 'upcase' methods but am struggling with the regex to get each word between my '%%' symbols.

A: s.gsub(/%%([^%]+)%%/) { $1.upcase }

A: ruby-1.9.2-p136 :066 > str.gsub(/%%([^%]+)%%/) {|m| $1.upcase}
 => "hello ONE_BOY's something FOUR_GIRL's something more"

The [^%]+ says it will match 1 or more characters except %, and the $1is a global variable that stores the back reference to what was matched.

A: Here's a quick and dirty way:
"hello %%one_boy%%'s something %%four_girl%%'s something more".gsub(/(%%.*?%%)/) do |x|
    x[2 .. (x.length-3)].upcase
end

The x[2 .. (x.length-3)] bit slices out the middle of the match (i.e. strips off the leading and trailing two characters).

A: If you're able to choose the delimiters, you might be able to use String.interpolate from the Facets gem:
one_boy = "hello".upcase
str = "\#{one_boy}!!!"
String.interpolate{ str }    #=> "HELLO!!!"

But I'd first check that Facets doesn't cause any conflicts with Rails.

A: str.gsub(/%%([^%]+)%%/) { |match| $1.upcase }