问:
Dynamic memory allocation for char***
I was trying to dynamically allocate memory for a char***.

```<code>char*** tas;
</code>```

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

```<code>void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
</code>```

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

```<code>tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;
</code>```

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

答:
This is not so hard, you just need to keep your head clear.

First off, keep the general pattern in mind: To allocate an array of n elements of type T, use:

```<code>T * p = malloc(n * sizeof(T));
</code>```

Then initialize the values p[i] for i in the range [0, n), then de-initialize the elements when you're done, if necessary, and then release the array allocation with:

```<code>free(p);
</code>```

Now just do this recursively for your array of arrays of strings, bearing in mind that a string is an array of characters, m rows of n columns of strings:

```<code>// allocate the table (the row pointers)
char *** tas = malloc(m * sizeof(char**));

for (size_t i = 0; i != m; ++i)
{
    // allocate each row (the row cells)
    tas[i] = malloc(n * sizeof(char*));
    for (size_t j = 0; j != n; ++j)
    {
        // initialize the row cell by allocating the string
        tas[i][j] = /* allocate string */
    }
}
</code>```

And on the way back, to free everything:

```<code>for (size_t i = 0; i != m; ++i)
{
    for (size_t j = 0; j != n; ++j)
    {
        free(tas[i][j]);  // free the string
    }

    free(tas[i]);         // free the row
}

free(tas);                // free the table
</code>```

Title: Dynamic memory allocation for char***

Body:
I was trying to dynamically allocate memory for a char***.

char*** tas;

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

Body:
This is not so hard, you just need to keep your head clear.

First off, keep the general pattern in mind: To allocate an array of n elements of type T, use:

T * p = malloc(n * sizeof(T));

Then initialize the values p[i] for i in the range [0, n), then de-initialize the elements when you're done, if necessary, and then release the array allocation with:

free(p);

Now just do this recursively for your array of arrays of strings, bearing in mind that a string is an array of characters, m rows of n columns of strings:

// allocate the table (the row pointers)
char *** tas = malloc(m * sizeof(char**));

for (size_t i = 0; i != m; ++i)
{
    // allocate each row (the row cells)
    tas[i] = malloc(n * sizeof(char*));
    for (size_t j = 0; j != n; ++j)
    {
        // initialize the row cell by allocating the string
        tas[i][j] = /* allocate string */
    }
}

And on the way back, to free everything:

for (size_t i = 0; i != m; ++i)
{
    for (size_t j = 0; j != n; ++j)
    {
        free(tas[i][j]);  // free the string
    }

    free(tas[i]);         // free the row
}

free(tas);                // free the table


来源: stackexchange

问:
gtkmm changing toggle button state without invoking signal
I'm trying to make multiple Gtk::ToggleButton's to act as Gtk::RadioButton's. When one of the buttons is pressed that other switch off.

It would be as simple as creating a switch statement if Gtk::ToggleButton didn't handle switching (pressed or not pressed) on its own.

So, I'm planning to handle it's switching as regular button with calling signal_clicked().connect() which calls for function set_active(true/false) which makes button look pressed or not pressed.

Here is example of what I'm trying to do:

Event calls when button is clicked:

```<code>//enum {infoState, artState, editState, userState, exitState}; is initialised in header

artButt.signal_clicked().connect(sigc::bind<short int>(sigc::mem_fun(*this, &fooclass::toggleButton), artButt));
editButt.signal_clicked().connect(sigc::bind<short int>(sigc::mem_fun(*this, &fooclass::toggleButton), editButt));
</code>```

Toggling button:

```<code>void fooClass::toggleButton()
{
//oldState and enum {infoState, artState, editState, userState, exitState}; are initialised in header
if(oldState != newState)
{
    //disable old togglebutton
    switch (oldState)
        {
            case infoState:
                infoButt.set_active(false);
            break;
            case artState:
                artButt.set_active(false);
            break;
            case editState:
                editButt.set_active(false);
            break;
            case userState:
                userButt.set_active(false);
            break;
        }

        //enable new one
        switch (newState)
        {
            case infoState:
                userButt.set_active(false);
            break;
            case artState:
                artButt.set_active(true);
            break;
            case editState:
                editButt.set_active(true);
            break;
            case userState:
                userButt.set_active(true);
            break;
        }
        oldState = newState;
}
}
</code>```

答: Just useGtk::RadioButton directly. With the draw-indicator property you can make them look like regular toggle buttons.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make multiple Gtk::ToggleButton's to act as Gtk::RadioButton's. When one of the buttons is pressed that other switch off.

It would be as simple as creating a switch statement if Gtk::ToggleButton didn't handle switching (pressed or not pressed) on its own.

So, I'm planning to handle it's switching as regular button with calling signal_clicked().connect() which calls for function set_active(true/false) which makes button look pressed or not pressed.

Here is example of what I'm trying to do:

Event calls when button is clicked:

//enum {infoState, artState, editState, userState, exitState}; is initialised in header

artButt.signal_clicked().connect(sigc::bind<short int>(sigc::mem_fun(*this, &fooclass::toggleButton), artButt));
editButt.signal_clicked().connect(sigc::bind<short int>(sigc::mem_fun(*this, &fooclass::toggleButton), editButt));

Toggling button:

void fooClass::toggleButton()
{
//oldState and enum {infoState, artState, editState, userState, exitState}; are initialised in header
if(oldState != newState)
{
    //disable old togglebutton
    switch (oldState)
        {
            case infoState:
                infoButt.set_active(false);
            break;
            case artState:
                artButt.set_active(false);
            break;
            case editState:
                editButt.set_active(false);
            break;
            case userState:
                userButt.set_active(false);
            break;
        }

        //enable new one
        switch (newState)
        {
            case infoState:
                userButt.set_active(false);
            break;
            case artState:
                artButt.set_active(true);
            break;
            case editState:
                editButt.set_active(true);
            break;
            case userState:
                userButt.set_active(true);
            break;
        }
        oldState = newState;
}
}


问:
Add a unique constraint on multiple columns with FluentNHibernate
I have a class that has a Primary Key as well as 2 foreign keys.  Foreign combinations  must be unique.  I do not see a way to do this (at least since SetAttribute was deprecated).

James touched on this with SetAttribute:
How to create a Multi-Column Index or Unique Constraint with NHibernate

答:
This might be useful to someone else, FNH mapping of unique constraint is accomplished like this:

mapping.References<FirstClass>(x => x.FirstClass).UniqueKey("unique123");
 mapping.References<SecondClass>(x => x.SecondClass).UniqueKey("unique123");

Further, it is explained that this only builds the constraint in the db, but that the developer is responsible to intercept duplicate insert attempts, otherwise an SqlException will be thrown saying an UNIQUE KEY constraint was violated.

from the FNH group

ContentLicense: CC BY-SA 2.5


问:
Regex that matches a number with commas for every three digits
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

```<code>regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches
</code>```

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

```<code>regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]
</code>```

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

答:
You can use whitespace boundary's to match just the properly formatted

thousands place comma numbers.

(?<!\S)\d{1,3}(?:,\d{3})*(?!\S)

Explained

```<code> (?<! \S )            # Whitespace boundary
 \d{1,3}              # Required 1-3 digits
 (?: , \d{3} )*       # Optional comma + 3 digits, 0 to many times
 (?! \S )             # Whitespace boundary
</code>```

Test target 42 1,234 6,368,745 12,34,567 1234

Output

```<code> **  Grp 0 -  ( pos 0 , len 2 )
42

 **  Grp 0 -  ( pos 3 , len 5 )
1,234

 **  Grp 0 -  ( pos 9 , len 9 )
6,368,745
</code>```

Body:
How would you write a regex that matches a number with commas for every three digits? It must match the following: '42', '1,234', and '6,368,745'.

but not the following: '12,34,567' (which has only two digits between the commas), '1234' (which lacks commas).

I know this question has been asked and answered before, but those were only for solutions where the string passed to the regex was one of those numbers. I was wondering what the best way to do it if the regex is passed the whole string '42 1,234 6,368,745 12,34,567 1234'.

I managed to do it by splitting the string first and then looping through it like below:

regexsplit = re.compile(r'^\d{1,3}(,\d{3})*$')
splitstring = string.split()
matches = []

for num in splitstring:
    if regexsplit.search(num) is not None:
        matches.append(regexsplit.search(num).group())

print matches

First, I'm wondering if there is a more efficient way of writing that code. Secondly, I'm wondering if there is a way to do it without splitting the string and using the .findall() method. I know you'd no longer be able to use the ^ and $ to anchor the beginning and end, so I've done:

regexnosplit = re.compile(r'(\d{1,3}(,\d{3})*)')
matches2 = []

for groups in regexnosplit.findall(string):
    print groups[0]

However, I'm obviously still getting '12', '34,567', '123', '4' returned, so I'm guessing I need to pass a more robust regex, but I can't seem to find a solution.

Body:
You can use whitespace boundary's to match just the properly formatted

thousands place comma numbers.

(?<!\S)\d{1,3}(?:,\d{3})*(?!\S)

Explained

 (?<! \S )            # Whitespace boundary
 \d{1,3}              # Required 1-3 digits
 (?: , \d{3} )*       # Optional comma + 3 digits, 0 to many times
 (?! \S )             # Whitespace boundary

Test target 42 1,234 6,368,745 12,34,567 1234

Output

 **  Grp 0 -  ( pos 0 , len 2 )
42

 **  Grp 0 -  ( pos 3 , len 5 )
1,234

 **  Grp 0 -  ( pos 9 , len 9 )
6,368,745


问:
Valet Install On Mac - Cannot Redeclare
I'm installing Valet on my MacBook Pro - El Capitan.

I installed PHP and MySQL with Homebrew as suggested on the Valet documentation page.

However, when I try to install Valet, I get the error:

PHP Fatal error:  Cannot redeclare resolve() (previously declared in /Users/marc/.composer/vendor/hoa/core/Protocol.php:1140) in /Users/marc/.composer/vendor/laravel/valet/cli/includes/helpers.php on line 57

Fatal error: Cannot redeclare resolve() (previously declared in /Users/marc/.composer/vendor/hoa/core/Protocol.php:1140) in /Users/marc/.composer/vendor/laravel/valet/cli/includes/helpers.php on line 57

My composer.json file looks like this:

```<code>{
    "require": {
        "phpunit/phpunit": "~4.2",
        "phpmetrics/phpmetrics": "^1.10",
        "laravel/valet": "^1.1"
    }
}
</code>```

I have tried deleting composer.lock and deleted the vendor directory, then composer install, but nothing changes. Any one have any advice here?

答:
I ran into this recently and I was able to resolve it by uninstalling / reinstalling valet:

composer global remove laravel/valet

then

composer global require laravel/valet

Title: Valet Install On Mac - Cannot Redeclare

Body:
I'm installing Valet on my MacBook Pro - El Capitan.

I installed PHP and MySQL with Homebrew as suggested on the Valet documentation page.

However, when I try to install Valet, I get the error:

PHP Fatal error:  Cannot redeclare resolve() (previously declared in /Users/marc/.composer/vendor/hoa/core/Protocol.php:1140) in /Users/marc/.composer/vendor/laravel/valet/cli/includes/helpers.php on line 57

Fatal error: Cannot redeclare resolve() (previously declared in /Users/marc/.composer/vendor/hoa/core/Protocol.php:1140) in /Users/marc/.composer/vendor/laravel/valet/cli/includes/helpers.php on line 57

My composer.json file looks like this:

{
    "require": {
        "phpunit/phpunit": "~4.2",
        "phpmetrics/phpmetrics": "^1.10",
        "laravel/valet": "^1.1"
    }
}

I have tried deleting composer.lock and deleted the vendor directory, then composer install, but nothing changes. Any one have any advice here?


问:
WPF - Control 2nd window from 1st window
WPF - From Window1 I'm trying to maximize a previously minimized Window2.

This is how I am opening Window2 (I hope to use the same button to maximize it)

```<code> public partial class Window1 : Window
{

    private bool SecondWindowOpen = false;

    public Window1()
    {
        InitializeComponent();
    }

    private void OpenSecondWindow_Click(object sender, RoutedEventArgs e)
    {
        if (SecondWindowOpen == false)
        {
            new Window2().Visibility = Visibility.Visible;
            this.SecondWindowOpen = true;

        }

        else
        {

        }
    }
}
</code>```

Window2 has 2 buttons, one minimizes Window2 while the other closes it.

```<code>public partial class Window2 : Window
{
    public Window2()
    {
        InitializeComponent();
    }

    private void btnMinimize_Click(object sender, RoutedEventArgs e)
    {
        this.WindowState = WindowState.Minimized;
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}
</code>```

So after opening Window2, I click btnMinimize. Now I'm back in Window1 and would like to click OpenSecondWindow and return Window2 to its original position. I would think this is a syntax issue, but I have been unable to find any examples.

Thank You

答:
```<code>public partial class Window1 : Window
{

    private bool SecondWindowOpen = false;
    private Window2 window2;

    public Window1()
    {
        InitializeComponent();
    }

    private void OpenSecondWindow_Click(object sender, RoutedEventArgs e)
    {
        if (SecondWindowOpen == false)
        {
            window2 = new Window2();
            window2.Visibility = Visibility.Visible;
            this.SecondWindowOpen = true;
        }
        else
        {
            //do whatever you want with window2, like window2.Close();
            //or window2.Visibility = Visibility.Hidden;
        }
    }
}
</code>```

Body:
WPF - From Window1 I'm trying to maximize a previously minimized Window2.

This is how I am opening Window2 (I hope to use the same button to maximize it)

 public partial class Window1 : Window
{

    private bool SecondWindowOpen = false;

    public Window1()
    {
        InitializeComponent();
    }

    private void OpenSecondWindow_Click(object sender, RoutedEventArgs e)
    {
        if (SecondWindowOpen == false)
        {
            new Window2().Visibility = Visibility.Visible;
            this.SecondWindowOpen = true;

        }

        else
        {

        }
    }
}

Window2 has 2 buttons, one minimizes Window2 while the other closes it.

public partial class Window2 : Window
{
    public Window2()
    {
        InitializeComponent();
    }

    private void btnMinimize_Click(object sender, RoutedEventArgs e)
    {
        this.WindowState = WindowState.Minimized;
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

So after opening Window2, I click btnMinimize. Now I'm back in Window1 and would like to click OpenSecondWindow and return Window2 to its original position. I would think this is a syntax issue, but I have been unable to find any examples.

Thank You


问:
Ansible not picking up custom module
I'm having issues with Ansible picking up a module that I've added.

The module is called 'passwordstore' https://github.com/morphje/ansible_pass_lookup/.

I'm using Ansible 2.2

In my playbook, I've added a 'library' folder and have added the contents of that GitHub directory to that folder. I've also tried uncommenting library        = /usr/share/ansible/modules and adding the module files there and still doesn't get picked up.

Have also tried setting environment variable to ANSIBLE_LIBRARY=/usr/share/ansible/modules

My Ansible playbook looks like this:

```<code>---

- name: example play
  hosts: all
  gather_facts: false

  tasks:
    - name: set password
      debug: msg="{{ lookup('passwordstore', 'files/test create=true')}}"
</code>```

And when I run this I get this error;

ansible-playbook main.yml

```<code>PLAY [example play] ******************************************************

TASK [set password] ************************************************************
fatal: [backend.example.name]: FAILED! => {"failed": true, "msg": "lookup plugin (passwordstore) not found"}
fatal: [mastery.example.name]: FAILED! => {"failed": true, "msg": "lookup plugin (passwordstore) not found"}
        to retry, use: --limit @/etc/ansible/roles/test-role/main.retry
</code>```

Any guidance on what I'm missing? It may just be the way in which I'm trying to add the custom module, but any guidance would be appreciated.

答:
It's a lookup plugin (not a module), so it should go into a directory named lookup_plugins (not library).

Alternatively, add the path to the cloned repository in ansible.cfg using the lookup-plugins setting.

Title: Ansible not picking up custom module

Body:
I'm having issues with Ansible picking up a module that I've added.

The module is called 'passwordstore' https://github.com/morphje/ansible_pass_lookup/.

I'm using Ansible 2.2

In my playbook, I've added a 'library' folder and have added the contents of that GitHub directory to that folder. I've also tried uncommenting library        = /usr/share/ansible/modules and adding the module files there and still doesn't get picked up.

Have also tried setting environment variable to ANSIBLE_LIBRARY=/usr/share/ansible/modules

My Ansible playbook looks like this:

---

- name: example play
  hosts: all
  gather_facts: false

  tasks:
    - name: set password
      debug: msg="{{ lookup('passwordstore', 'files/test create=true')}}"

And when I run this I get this error;

ansible-playbook main.yml

PLAY [example play] ******************************************************

TASK [set password] ************************************************************
fatal: [backend.example.name]: FAILED! => {"failed": true, "msg": "lookup plugin (passwordstore) not found"}
fatal: [mastery.example.name]: FAILED! => {"failed": true, "msg": "lookup plugin (passwordstore) not found"}
        to retry, use: --limit @/etc/ansible/roles/test-role/main.retry

Any guidance on what I'm missing? It may just be the way in which I'm trying to add the custom module, but any guidance would be appreciated.


问:
Center div with variable width, on top of other content
How do I horizontally center an element of variable width that needs to be on top of the other elements?

The accepted answer here Easy way to center variable width divs in CSS is good for centering variable width, but it pushes everything else down:

Normally I do:

```<code>position:absolute;
width:200px;
left:50%;
margin-left:-100px;
</code>```

But this requires a set width.

(It's for a message box that pops up and needs to be centered on top of the other text.)

答:
I find this solution to be best if you don't want wrapper divs. This positions the left edge of the element to the middle of the parent and then shifts it back by half the width of the element.</p>

```<code>div {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
</code>```

Body:
How do I horizontally center an element of variable width that needs to be on top of the other elements?

The accepted answer here Easy way to center variable width divs in CSS is good for centering variable width, but it pushes everything else down:

Normally I do:

position:absolute;
width:200px;
left:50%;
margin-left:-100px;

But this requires a set width.

(It's for a message box that pops up and needs to be centered on top of the other text.)

Body:
I find this solution to be best if you don't want wrapper divs. This positions the left edge of the element to the middle of the parent and then shifts it back by half the width of the element.

div {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}


问:
What kind of numerical method does 'pdepe' (MATLAB function's) use?
I'm using the MATLAB's function 'pdepe' to solve a problem with some partial differential equations, a parabolic one.

I need to know the kind of numerical method that function uses, 'cause I have to notify this in a report.

The description of the function in MathWorks is "Solve initial-boundary value problems for systems of parabolic and elliptic PDEs in one space variable and time". Is it a finite difference method?

Thanks for helping me.

答: As indicated by Alessandro Trigilio, ode15s is used to advance the solution forward in time.  Exactly what the function is advancing in time is a semi-discrete, second-order Galerkin formulation for non-singular problems or a semi-discrete, second-order Petrov-Galerkin formulation for singular problems (polar or spherical meshes that include the origin).  As such, the spatial discretization is finite element in nature.


问:
MySQL .NET Connector 5.2.3 - Win 2k3 - Random Error - Unable to connect to any hosts - Restart website and it's fixed
I have a strange error on a Win 2k3 box running the MySQL connector 5.2.3. It's happened 3 times in the last 24 hours but only 4 times total in the last 6 months +.

[Exception: Exception of type 'System.Exception' was thrown.] MySql.Data.MySqlClient.NativeDriver.Open() +259

[MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]

If I restart the app pool and website in IIS, the problem is resolved temporarily, but as stated, it's happened 3 times now in the last 24 hours. No server changes during that time either.

Any ideas?

答:
Here's a guess based on limited information.

I don't think you are properly disposing of your database connections.  Make sure you have the connections wrapped in using clauses.  Calling .Close() isn't good enough.  That closes the connection, but it doesn't dispose of it.

Second, the reason why now instead of months ago is probably related to a combination of the amount of traffic you are now seeing versus before and the amount of database connections you are instantiating now versus before.

I just got called to help with an app that exhibited the exact same behavior.  Everything was fine until one day it started crashing.  A lot.  They had the sql command objects wrapped in using clauses, but not the connection.  As traffic increased the connection pool was filling up and bursting.  Once we wrapped the connections in using clauses (forcing a call to dispose()), everything was smooth sailing.

UPDATE

I just wanted to clarify one thing.  SqlConnection is a wrapper to an unmanaged resource; which is why it implements IDisposable.  When your connection object goes out of scope, then it is available to be garbage collected.  From a coding perspective, you really have no idea of when this might happen.  It might be a few seconds, it might be considerably longer.

However the connection pool, which SqlConnection talks to, is a completely separate entity.  It doesn't know the connection is no longer going to be used.  The Dispose() method basically tells the connection pool that this particular piece of code is done with the connection.  Which means that the connection pool can immediately reallocate those resources.  Note that some of the MS documentation states that Close() is equivalent to Dispose() but my testing has shown that this simply isn't true.

If your site creates more connections than it is explicitly disposing of then the connection pool is potentially going to fill up based on when garbage collection takes place.  It really depends on the number of connections created and the amount of traffic received.  Higher traffic = more connections and longer periods of time between GC runs.

Now, a default IIS configuration gives you 100 executing threads per worker process.  And the default configuration of the application pool is 100 connections.  If you are disposing of your connections immediately after using them then you will never exceed the pool size.  Even if you make a lot of db calls, the request thread is doing them one at a time.

However, if you add more worker processes, increase the number of threads per process, or fail to dispose of your connections, then you run into the very real possibility of exceeding the connection pool size.  Note that you can control the pool size in your sql connection string.

Don't worry about performance of calling dispose then reopening the connection several times while processing a single page.  The pool exists to keep connections alive with the server in order to make this a very fast process.


问:
How to deal with different newline conventions with Flex
We're trying to parse the GEDCOM file format. According to its standard, all combinations of CR and LF are valid to denote a newline break.

It's a line based format, so often we want to match the rest of the line when we've already matched the number and the tag. An example of a rule would be

```<code>"NAME ".+               { /* deal with the name */ }
</code>```

The newlines are matched by

```<code>[\r\n]+             {return ENDLINE;}
</code>```

This works fine on Windows, because it converts \r\n to \n behind your back, but it doesn't on Linux. There, \r can be matched by the dot. Because Flex uses the longest matching rule, it will either include the \r in the data, or it will match a known tag to the UNKNOWNTAG rule because this technically correct match will be one byte longer

A solution could be to replace all dots with [^\r\n], but that seem inelegant. Is there a better way?

答:
You can use redefining YY_INPUT to replace \r to \n:

```<code>%{
#define YY_INPUT(buf,result,max_size) {  \
        int c = getc(yyin);              \
        buf[0] = (c == '\r') ? '\n' : c; \
        result = 1;                      \
    }
%}
</code>```

Body:
We're trying to parse the GEDCOM file format. According to its standard, all combinations of CR and LF are valid to denote a newline break.

It's a line based format, so often we want to match the rest of the line when we've already matched the number and the tag. An example of a rule would be

"NAME ".+               { /* deal with the name */ }

The newlines are matched by

[\r\n]+             {return ENDLINE;}

This works fine on Windows, because it converts \r\n to \n behind your back, but it doesn't on Linux. There, \r can be matched by the dot. Because Flex uses the longest matching rule, it will either include the \r in the data, or it will match a known tag to the UNKNOWNTAG rule because this technically correct match will be one byte longer

A solution could be to replace all dots with [^\r\n], but that seem inelegant. Is there a better way?

Body:
You can use redefining YY_INPUT to replace \r to \n:

%{
#define YY_INPUT(buf,result,max_size) {  \
        int c = getc(yyin);              \
        buf[0] = (c == '\r') ? '\n' : c; \
        result = 1;                      \
    }
%}


问:
android studio changing playback speed of audio for API<23
I want to play a soundtrack where I need full control over the playback speed. I have tried several ways to do this in android studio, but I'm facing the following problems:

my API level is 19, so I cannot use MediaPlayer to change the speed

SoundPool is supposed to play short sounds and stops after a few seconds of music

What else could I try?

答:
Something like this:</p>

```<code>public class AudioActivity extends Activity {
AudioTrack audio = new AudioTrack(AudioManager.STREAM_MUSIC,
        44100,
        AudioFormat.CHANNEL_OUT_STEREO,
        AudioFormat.ENCODING_PCM_16BIT,
        intSize, //size of pcm file to read in bytes
        AudioTrack.MODE_STATIC);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //read track from file
        File file = new File(getFilesDir(), fileName);

        int size = (int) file.length();
        byte[] data = new byte[size];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(data, 0, size);
            fileInputStream.close();

            audio.write(data, 0, data.length);
        } catch (IOException e) {}
    }

    //change playback speed by factor
    void changeSpeed(double factor) {
        audio.setPlaybackRate((int) (audio.getPlaybackRate() * factor));
    }
}
</code>```

Body:
Something like this:

public class AudioActivity extends Activity {
AudioTrack audio = new AudioTrack(AudioManager.STREAM_MUSIC,
        44100,
        AudioFormat.CHANNEL_OUT_STEREO,
        AudioFormat.ENCODING_PCM_16BIT,
        intSize, //size of pcm file to read in bytes
        AudioTrack.MODE_STATIC);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //read track from file
        File file = new File(getFilesDir(), fileName);

        int size = (int) file.length();
        byte[] data = new byte[size];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(data, 0, size);
            fileInputStream.close();

            audio.write(data, 0, data.length);
        } catch (IOException e) {}
    }

    //change playback speed by factor
    void changeSpeed(double factor) {
        audio.setPlaybackRate((int) (audio.getPlaybackRate() * factor));
    }
}


问:
C++ - Is it bad practice to have variables that are not class object properties inside a class?
Suppose I have a class Sensor as shown below:

```<code>class Sensor
{
    public:
        Sensor();
        array <float, 3> marker_pos(float, float, float);

    private:
        float range;
        float phi;
        array <float, 3> temp;
        int flag = 0;
};
</code>```

The variables range and phi are properties or variables of the sensor object. But the variables temp and flag are just normal variables that are to be used inside the function marker_pose.

1. Is it bad practice to define/declare temp and flag inside the class ?

2. If I define/declare them inside the function marker_pose, it will be defined every time I call that function. Is that a good idea?

3. What will be the best practice to follow in such situations ?

答: You should always define variables at the minimum possible scope. So if variables are only used inside a function, they should be defined in the function, not in the class.</p>

Body:
Suppose I have a class Sensor as shown below:

class Sensor
{
    public:
        Sensor();
        array <float, 3> marker_pos(float, float, float);

    private:
        float range;
        float phi;
        array <float, 3> temp;
        int flag = 0;
};

The variables range and phi are properties or variables of the sensor object. But the variables temp and flag are just normal variables that are to be used inside the function marker_pose.

1. Is it bad practice to define/declare temp and flag inside the class ?

2. If I define/declare them inside the function marker_pose, it will be defined every time I call that function. Is that a good idea?

3. What will be the best practice to follow in such situations ?


问:
Redirect old articles to new articles .htaccess
This is a pretty specific question, so no answer on Stack or Google could help me.

Recently I've moved my blog from www.example.com to www.example.com/blog.
On www.example.com I have a landing page, so I need it to be working as well.

I would like to redirect all www.example.com/YYYY/MM/DD/article-name to www.example.com/blog/YYYY/MM/DD/article-name, but at the same time to keep www.example.com intact.

Thank you in advance for your help.

答:
Solved with Regular Expression inspired from the above answer from Hello Fishy(Thank you)
RedirectMatch ^/(\d*)/(\d*)/(\d*)/([A-Za-z0-9-]*)/ /blog/$1/$2/$3/$4</p>


问:
PHP: game loop (threads or the sort)
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

```<code><?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>
</code>```

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?

答:
Instead of writing this smelly blocking polling loop, check out some event system based around the reactor pattern like Python Twisted or Ruby EventMachine.

I believe the PHP flavor is call PHP-MIO: http://thethoughtlab.blogspot.com/2007/04/non-blocking-io-with-php-mio.html

Title: PHP: game loop (threads or the sort)

Body:
I am writing PHP code to be a game client. It uses socket; socket_create followed by socket_connect and then socket_read. It works fine, but the issue is that the server can send a packet at any time which means socket_read needs to be happening constantly in a "game loop". So something like this:

<?php
$reply = "";
do {
     $recv = "";
     $recv = socket_read($socket, '1400');
     if($recv != "") {
         $reply .= $recv;
     }
} while($recv != "");

echo($reply);
?>

Doesn't work because it's stuck in the loop (server doesn't terminate connection until game is quit by client) and the PHP code needs to handle the packet stuff as it comes in.

So PHP doesn't really have threading. What's the best way of handling this?


问:
R: sqlAppendTable only works with numbers?
I am unable to get the R language DBI::sqlAppendTable function to work with anything other than numbers. Below is a bit of code illustrating the problem. I suspect the problem is that sqlAppendTable does not quote data. Any fix or workaround would be greatly appreciated.</p>

```<code>num = data.frame(matrix(1:26, ncol=2))
let = data.frame(matrix(letters, ncol=2))

test.sqlAppendTable = function(dfr) {
    #dfr: A data frame.
    conx <- dbConnect(RSQLite::SQLite(), ":memory:")
    on.exit(dbDisconnect(conx))
    dbWriteTable(conx, "temp", dfr[1:5, ])
    temp = dbReadTable(conx, 'temp')
    print(temp)
    sat = sqlAppendTable(conx, 'temp', dfr[6:10, ])
    print(sat)
    rs = dbExecute(conx, sat)
    cat('Result set (rs): ')
    print(rs)
    temp = dbReadTable(conx, 'temp')
    print(temp)
}

test.sqlAppendTable(num) #Runs fine.
test.sqlAppendTable(let) #Generates error:
#Error in rsqlite_send_query(conn@ptr, statement) : no such column: j
</code>```

答:
I have been able to cobble together a workaround:

1) Write the data frame that you want to append as a temporary table (temp) in the SQLite database file.

2) Append it to the target table (target) using the SQLite statement:

```<code>insert into target select * from temp;
</code>```

3) Drop temp.

This runs quite fast, presumably thanks to SQLite being well optimized.

ADDENDUM:

You can indeed append a data frame to a database table using dbWriteTable, with the option append=TRUE. I have tested this against my workaround described above and, surprisingly, the workaround runs almost 40% faster than dbWriteTable.

Body:
I am unable to get the R language DBI::sqlAppendTable function to work with anything other than numbers. Below is a bit of code illustrating the problem. I suspect the problem is that sqlAppendTable does not quote data. Any fix or workaround would be greatly appreciated.

num = data.frame(matrix(1:26, ncol=2))
let = data.frame(matrix(letters, ncol=2))

test.sqlAppendTable = function(dfr) {
    #dfr: A data frame.
    conx <- dbConnect(RSQLite::SQLite(), ":memory:")
    on.exit(dbDisconnect(conx))
    dbWriteTable(conx, "temp", dfr[1:5, ])
    temp = dbReadTable(conx, 'temp')
    print(temp)
    sat = sqlAppendTable(conx, 'temp', dfr[6:10, ])
    print(sat)
    rs = dbExecute(conx, sat)
    cat('Result set (rs): ')
    print(rs)
    temp = dbReadTable(conx, 'temp')
    print(temp)
}

test.sqlAppendTable(num) #Runs fine.
test.sqlAppendTable(let) #Generates error:
#Error in rsqlite_send_query(conn@ptr, statement) : no such column: j

Body:
I have been able to cobble together a workaround:

1) Write the data frame that you want to append as a temporary table (temp) in the SQLite database file.

2) Append it to the target table (target) using the SQLite statement:

insert into target select * from temp;

3) Drop temp.

This runs quite fast, presumably thanks to SQLite being well optimized.

ADDENDUM:

You can indeed append a data frame to a database table using dbWriteTable, with the option append=TRUE. I have tested this against my workaround described above and, surprisingly, the workaround runs almost 40% faster than dbWriteTable.


问:
Meaning of unix v6 assembly code generated by cc compiler?
For example, below is a piece of C code and its assembly code generated by cc compiler.

```<code>// C code (pre K&R C)
foo(a, b) {
    int c, d;
    c = a;
    d = b;
    return c+d;
}
// corresponding assembly code generated by cc
.global _foo
.text
_foo:
~~foo:
~a=4
~b=6
~c=177770
~d=177766
jsr r5, csv
sub $4, sp
mov 4(r5), -10(r5)
mov 6(r5), -12(r5)
mov -10(r5), r0
add -12(r5), r0
jbr L1
L1: jmp cret
</code>```

I can understand most of the code. But I don't know what does ~~foo: do. And where do the magic numbers come from in ~c=177770 and ~d=177766. The hardware is pdp-11/40.

答:
The tildes look like data which determines the stack usage.  You might find it helpful to recall that the pdp-11 used 16-bit integers, and that DEC preferred octal numbers over hexadecimal.

That

```<code>jsr r5, csv
</code>```

is a way of making register 5 (r5) point to some data (perhaps the list of offsets).

The numbers correspond to offsets on the stack in octal.   The caller is assumed to do something like

push a and b onto the stack (positive offsets)

push the return address onto the stack (offset=0)

possibly push other stuff in the csv function

c and d are local variables (negative offsets, hence the "17777x")

That line

```<code>~d=177776
</code>```

looks odd - I'd expect

```<code>~d=177766
</code>```

since it should be below c on the stack.  The -10 and -12 offsets in the register operands look like they're also octal numbers.  You should be able to match up the offsets with the variables, by context.

That's just an educated guess: I adapted the jsr+r5 idiom a while back in a text-editor.

The lines with tildes are symbol definitions.  A clue for that is in the DECUS C Compiler Reference, found at

```<code>ftp://ftp.update.uu.se/pub/pdp11/rsx/lang/decusc/2.19/005003/CC.DOC
</code>```

which says

```<code>  3.3  Global Symbols Containing Radix-50 '$' and '.'
         ______ _______ __________ ________     ___

    With  this  version  of  Decus C, it is possible to generate and
    access global symbols which contain the Radix-50  '.'  and  '$'.
    The  compiler allows identifiers to contain the Ascii '$', which
    becomes a Radix-50 '$' in the object code.  The AS assembly code
    shows  this  character as a tilde (~).  The underscore character
    (_) in a C program  becomes  a  '.'  in  both  the  AS  assembly
    language  and  in  the  object  code.  This allows C programs to
    access all global symbols:

            extern int $dsw;
            .  .  .
            printf("Directive status = %06o\n", $dsw);

    The  above  prints  the current contents of the task's directive
    status word.
</code>```

So you could read

```<code>~a=4
</code>```

as

```<code>$a=4
</code>```

and see that $a is a (more or less) conventional symbol.

Body:
For example, below is a piece of C code and its assembly code generated by cc compiler.

// C code (pre K&R C)
foo(a, b) {
    int c, d;
    c = a;
    d = b;
    return c+d;
}
// corresponding assembly code generated by cc
.global _foo
.text
_foo:
~~foo:
~a=4
~b=6
~c=177770
~d=177766
jsr r5, csv
sub $4, sp
mov 4(r5), -10(r5)
mov 6(r5), -12(r5)
mov -10(r5), r0
add -12(r5), r0
jbr L1
L1: jmp cret

I can understand most of the code. But I don't know what does ~~foo: do. And where do the magic numbers come from in ~c=177770 and ~d=177766. The hardware is pdp-11/40.

Body:
The tildes look like data which determines the stack usage.  You might find it helpful to recall that the pdp-11 used 16-bit integers, and that DEC preferred octal numbers over hexadecimal.

That

jsr r5, csv

is a way of making register 5 (r5) point to some data (perhaps the list of offsets).

The numbers correspond to offsets on the stack in octal.   The caller is assumed to do something like

push a and b onto the stack (positive offsets)

push the return address onto the stack (offset=0)

possibly push other stuff in the csv function

c and d are local variables (negative offsets, hence the "17777x")

That line

~d=177776

looks odd - I'd expect

~d=177766

since it should be below c on the stack.  The -10 and -12 offsets in the register operands look like they're also octal numbers.  You should be able to match up the offsets with the variables, by context.

That's just an educated guess: I adapted the jsr+r5 idiom a while back in a text-editor.

The lines with tildes are symbol definitions.  A clue for that is in the DECUS C Compiler Reference, found at

ftp://ftp.update.uu.se/pub/pdp11/rsx/lang/decusc/2.19/005003/CC.DOC

which says

  3.3  Global Symbols Containing Radix-50 '$' and '.'
         ______ _______ __________ ________     ___

    With  this  version  of  Decus C, it is possible to generate and
    access global symbols which contain the Radix-50  '.'  and  '$'.
    The  compiler allows identifiers to contain the Ascii '$', which
    becomes a Radix-50 '$' in the object code.  The AS assembly code
    shows  this  character as a tilde (~).  The underscore character
    (_) in a C program  becomes  a  '.'  in  both  the  AS  assembly
    language  and  in  the  object  code.  This allows C programs to
    access all global symbols:

            extern int $dsw;
            .  .  .
            printf("Directive status = %06o\n", $dsw);

    The  above  prints  the current contents of the task's directive
    status word.

So you could read

~a=4

as

$a=4

and see that $a is a (more or less) conventional symbol.


问:
Finding bytes of memory in Pep9 assembly code
This assembly code takes an input, multiplies it by 35,and leaves result in the register. It's 17 bytes of memory, but how do I calculate that?

deci M,d

ldwa M,d

asla ;2m

asla ;4m

asla ;8m

asla ; 16m

adda M,d ; 17m

asla ; 34m

adda M,d ; 35m

答: Every assembler I have ever seen has the ability to generate a listing that shows the how it allocates memory.</p>


问:
Scrollview and OnClick handlers not working when view is cleared and re-created
I'm having an odd problem and I am not sure where the issue is.

I have an XML file which contains two linear layouts, only one is visible at a time depending on what setting has been used. Both views are dynamically generated and set an on click listener and onlongclicklistener.

Below is the XML layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/resultTableContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="horizontal"
            android:fillViewport="true">
            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true">
                <TableLayout android:id="@+id/resultTable"
                    android:stretchColumns="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:shrinkColumns="false">
                </TableLayout>
            </HorizontalScrollView>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:id="@+id/formattedResultContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView android:id="@+id/formattedScrollContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical">
            <LinearLayout android:id="@+id/formattedResult"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>
        </ScrollView>
    </LinearLayout>
</RelativeLayout>
</code>```

For simplicity I'll call the first linear layout container view 1 and the second linear layout container view 2.

Both views have their visibility set to gone by default, and when the screen first loads, view 1's visibility is set to visible and the view is dynamically generated using the following code:

```<code>@Override
    public void processResult(final View.OnClickListener editRowClickListener, final View.OnLongClickListener columnLongClickListener)
    {
        try
        {
            this.getActivity().runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (shouldExistingResultBeCleared())
                    {
                        resultView.removeAllViews();
                    }
                    if (getSettings().getInt(Defines.SharedPreferenceSettings.APPLICATION_THEME, com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                            == com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                    {
                        resultView.setBackgroundColor(Color.WHITE);
                    }
                    else
                    {
                        resultView.setBackgroundColor(Color.BLACK);
                    }
                }
            });

            this.showDialog(getJSONResult().length());

            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        for (int i = 0; i < getJSONResult().length(); i++)
                        {
                            HashMap<Integer, String> fieldIndexAndValue = new HashMap<Integer, String>();
                            final TableRow tr;
                            if (!getSettings().getBoolean("IsDarkTheme", false))
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_light_theme, resultView, false);
                            } else
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_dark_theme, resultView, false);
                            }
                            if (i == 0)
                            {
                                tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.appPrimaryColour));
                            }
                            else if (i % 2 == 0)
                            {
                                if (!getSettings().getBoolean("IsDarkTheme", false))
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowLightThemeAlternateRow));
                                } else
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowDarkThemeAlternateRow));
                                }
                            }
                            ImageButton imageButton = (ImageButton) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.row_edit_image, tr, false);
                            imageButton.setOnClickListener(editRowClickListener);
                            tr.addView(imageButton);

                            if (i == 0)
                            {
                                imageButton.setVisibility(View.INVISIBLE);
                            }

                            JSONArray array = getJSONResult().getJSONArray(i);
                            String currentField = null;
                            for (int j = 0; j < array.length(); j++)
                            {
                                final TextView textView;
                                textView = (TextView) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_textview, tr, false);
                                textView.setText(array.getString(j));
                                if (!getSettings().getBoolean(Defines.SharedPreferenceSettings.MULTILINE_RESULT, true))
                                {
                                    textView.setSingleLine(true);
                                }
                                if (i == 0)
                                {
                                    textView.setTypeface(null, Typeface.BOLD);
                                    //Get the fields into a index and field hash map
                                    addIndexAndField(j, array.getString(j));
                                } else
                                {
                                    textView.setOnLongClickListener(columnLongClickListener);
                                    fieldIndexAndValue.put(j, array.getString(j));
                                }
                                getActivity().runOnUiThread(new Runnable()
                                {

                                    @Override
                                    public void run()
                                    {
                                        tr.addView(textView);
                                    }
                                });
                            }
                            imageButton.setTag(fieldIndexAndValue);

                            getActivity().runOnUiThread(new Runnable()
                            {

                                @Override
                                public void run()
                                {
                                    resultView.addView(tr);
                                }
                            });
                            updateProgressDialog();
                            //handler.sendMessage(handler.obtainMessage());
                        }
                        closeDialog();
                        //((ResultProcessor)resultProcessor).closeDialog();
                    }
                    catch (JSONException ex)
                    {

                    }
                }
            }).start();
        }
        catch (Exception ex)
        {

        }
    }
</code>```

This works perfectly fine. The user presses an option to switch to view 2, so view 1 is cleared, visibility set to gone ans view 2 is set to visible. This view is then dynamically generated and the on click listeners are set to the view accordingly. (I haven't included the code for this view as I don't believe it is related and this view always works without exception).

If the user then switches back to view 1, view 2 is cleared, and visibility set to gone and view 1 is back to being visible and the same method, as shown above, is used to re-create the view dynamically and assign the on click listeners.

The view itself looks fine, however, there is no user interaction possible, the scroll view no longer scrolls vertically or horizontally and neither of the click handlers works.

As view 1 work once, I don't understand why it won't when it is re-generated, but view 2 always works no matter what.

答:
You could try outputting the exception details in the catch blocks in case an exception is being raised somewhere:

```<code>catch (JSONException ex)
    ex.printStackTrace();
    Log.e("Exception: ", ex.getMessage());
    throw new RuntimeException(ex);
}
</code>```

and

```<code>catch (Exception ex) {
    ex.printStackTrace();
    Log.e("Exception: ", ex.getMessage());
    throw new RuntimeException(ex);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having an odd problem and I am not sure where the issue is.

I have an XML file which contains two linear layouts, only one is visible at a time depending on what setting has been used. Both views are dynamically generated and set an on click listener and onlongclicklistener.

Below is the XML layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout android:id="@+id/resultTableContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="horizontal"
            android:fillViewport="true">
            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true">
                <TableLayout android:id="@+id/resultTable"
                    android:stretchColumns="1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:shrinkColumns="false">
                </TableLayout>
            </HorizontalScrollView>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:id="@+id/formattedResultContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="gone">
        <ScrollView android:id="@+id/formattedScrollContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical">
            <LinearLayout android:id="@+id/formattedResult"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"/>
        </ScrollView>
    </LinearLayout>
</RelativeLayout>

For simplicity I'll call the first linear layout container view 1 and the second linear layout container view 2.

Both views have their visibility set to gone by default, and when the screen first loads, view 1's visibility is set to visible and the view is dynamically generated using the following code:

@Override
    public void processResult(final View.OnClickListener editRowClickListener, final View.OnLongClickListener columnLongClickListener)
    {
        try
        {
            this.getActivity().runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    if (shouldExistingResultBeCleared())
                    {
                        resultView.removeAllViews();
                    }
                    if (getSettings().getInt(Defines.SharedPreferenceSettings.APPLICATION_THEME, com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                            == com.BoardiesITSolutions.Library.R.style.LibAppTheme)
                    {
                        resultView.setBackgroundColor(Color.WHITE);
                    }
                    else
                    {
                        resultView.setBackgroundColor(Color.BLACK);
                    }
                }
            });

            this.showDialog(getJSONResult().length());

            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        for (int i = 0; i < getJSONResult().length(); i++)
                        {
                            HashMap<Integer, String> fieldIndexAndValue = new HashMap<Integer, String>();
                            final TableRow tr;
                            if (!getSettings().getBoolean("IsDarkTheme", false))
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_light_theme, resultView, false);
                            } else
                            {
                                tr = (TableRow) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_table_row_dark_theme, resultView, false);
                            }
                            if (i == 0)
                            {
                                tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.appPrimaryColour));
                            }
                            else if (i % 2 == 0)
                            {
                                if (!getSettings().getBoolean("IsDarkTheme", false))
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowLightThemeAlternateRow));
                                } else
                                {
                                    tr.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.resultRowDarkThemeAlternateRow));
                                }
                            }
                            ImageButton imageButton = (ImageButton) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.row_edit_image, tr, false);
                            imageButton.setOnClickListener(editRowClickListener);
                            tr.addView(imageButton);

                            if (i == 0)
                            {
                                imageButton.setVisibility(View.INVISIBLE);
                            }

                            JSONArray array = getJSONResult().getJSONArray(i);
                            String currentField = null;
                            for (int j = 0; j < array.length(); j++)
                            {
                                final TextView textView;
                                textView = (TextView) getFragment().getLayoutInflater(getFragment().getArguments()).inflate(R.layout.result_textview, tr, false);
                                textView.setText(array.getString(j));
                                if (!getSettings().getBoolean(Defines.SharedPreferenceSettings.MULTILINE_RESULT, true))
                                {
                                    textView.setSingleLine(true);
                                }
                                if (i == 0)
                                {
                                    textView.setTypeface(null, Typeface.BOLD);
                                    //Get the fields into a index and field hash map
                                    addIndexAndField(j, array.getString(j));
                                } else
                                {
                                    textView.setOnLongClickListener(columnLongClickListener);
                                    fieldIndexAndValue.put(j, array.getString(j));
                                }
                                getActivity().runOnUiThread(new Runnable()
                                {

                                    @Override
                                    public void run()
                                    {
                                        tr.addView(textView);
                                    }
                                });
                            }
                            imageButton.setTag(fieldIndexAndValue);

                            getActivity().runOnUiThread(new Runnable()
                            {

                                @Override
                                public void run()
                                {
                                    resultView.addView(tr);
                                }
                            });
                            updateProgressDialog();
                            //handler.sendMessage(handler.obtainMessage());
                        }
                        closeDialog();
                        //((ResultProcessor)resultProcessor).closeDialog();
                    }
                    catch (JSONException ex)
                    {

                    }
                }
            }).start();
        }
        catch (Exception ex)
        {

        }
    }

This works perfectly fine. The user presses an option to switch to view 2, so view 1 is cleared, visibility set to gone ans view 2 is set to visible. This view is then dynamically generated and the on click listeners are set to the view accordingly. (I haven't included the code for this view as I don't believe it is related and this view always works without exception).

If the user then switches back to view 1, view 2 is cleared, and visibility set to gone and view 1 is back to being visible and the same method, as shown above, is used to re-create the view dynamically and assign the on click listeners.

The view itself looks fine, however, there is no user interaction possible, the scroll view no longer scrolls vertically or horizontally and neither of the click handlers works.

As view 1 work once, I don't understand why it won't when it is re-generated, but view 2 always works no matter what.

Body:
You could try outputting the exception details in the catch blocks in case an exception is being raised somewhere:

catch (JSONException ex)
    ex.printStackTrace();
    Log.e("Exception: ", ex.getMessage());
    throw new RuntimeException(ex);
}

and

catch (Exception ex) {
    ex.printStackTrace();
    Log.e("Exception: ", ex.getMessage());
    throw new RuntimeException(ex);
}