AngularJS ng-table fixed headers

Question: I'm using ng-table to display some information.  I would like to make the header and footer of the ng-table fixed and force the ng-table to draw scroll bars within the rows.
The ng-table documentation site has no documentation on how to make that happen.
Any ideas?
Answer: this CSS-only solution worked for me. Just add the class table-scroll to the table element and the following CSS:
.table-scroll thead {
    display: table;
    width: 100%;
    table-layout: fixed;
}

.table-scroll tbody {
    max-height: 150px;
    overflow-y: auto;
    display: block;
    width: 100%;
    table-layout: fixed;
}

.table-scroll tr {
    display: table;
    table-layout: fixed;
    width: 100%;
}

.table-scroll td {
    height: 47px; // needed in order to keep rows from collapsing
}

Comment: the width of scrollbar is added to `tbody` width so the lines of `thead` and `tr`  are not under each other
Comment: After looking for around 20 solutions, found this working for my case. thanks alot  @Yaron
Comment: This solution almost worked for me today. The problem is that my page is resizable, so the max-height of 150px does not work well. What change is necessary here for the table to be resizable and yet still keep the frozen headers?
Comment: Wow!...Thank you so much for uploading this..this is awesome!
Comment: @SaeidAlidadi - have you found any solution for the width issue? other than using a script?
Answer: That is by far the most reliable solution that I found. And I've looked for hours before deciding to use a jQuery plugin.
In the version of the plugin that I am using, we can stick the header to a scrollable container.
Take a look at this plunker for a use case with ng-table:
http://plnkr.co/edit/ypBaDHIfaJWapXVs3jcU?p=preview
Javascript
app.directive('fixedTableHeaders', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $timeout(function() {
          var container = element.parentsUntil(attrs.fixedTableHeaders);
          element.stickyTableHeaders({ scrollableArea: container, "fixedOffset": 2 });
      }, 0);
    }
  }
}]);

HTML

            {{user.name}}
            {{user.age}}

CSS
#scrollable-area {
    height: 150px;
    overflow-y: scroll; /* <-- here is what is important*/
}
table {
  width: 100%;
}
thead {
    background: #fff;
}

Comment: The plnkr is no longer working due to an old link to ng-table.js.  Try replacing it with this `https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.3.3/ng-table.min.js`
Comment: It is not working with accordian above ng-table.. Please see plunker for the issue.. http://plnkr.co/edit/FGjU46cCMuhIdyacffHl?p=preview
Comment: I noticed that in the demo it's got a bug where when you reduce the width of the viewport so that horizontal scrolling is triggered on the table, when you then scroll down, the fixed headers appear to the right of the edge of the table. This would be a problem for horizontally wide tables.
Answer: I don't know about the footer but I had a similar requirement for the headers.
This was requested before @ Github: https://github.com/esvit/ng-table/issues/41
I made my own implementation using a jquery plugin (https://github.com/jmosbech/StickyTableHeaders).
There is a plunkr here: http://plnkr.co/edit/KyilXo?p=preview
Basically we just call the plugin in the directive data-fixed-table-headers
when the data has been rendered.
angular.module('main').directive('fixedTableHeaders', ['$timeout', fixedTableHeaders]);

    function fixedTableHeaders($timeout) {
        return {
            restrict: 'A',
            link: link
        };

        function link(scope, element, attrs) {

            $timeout(function () {
              element.stickyTableHeaders();
                    }, 0);
        }
    }

Comment: This seems to stick the table headers to the top of the screen, but doesn't the case where the table is in a scrollable element: http://plnkr.co/edit/5wvfzNzWQfH4NNpgYdB9?p=preview
Comment: Yes but that seems to be a limitation of the stickyTableHeaders jquery plugin. See issue and potential fix here: https://github.com/jmosbech/StickyTableHeaders/issues/1
Comment: It is not working with accordian above ng-table.. Please see plunker for the issue.. http://plnkr.co/edit/FGjU46cCMuhIdyacffHl?p=preview
Comment: seems like you will need to recalculate the header position while the animation is happening. My intention was only to have it work in a simple scenario...
Comment: So is there any alternative to work both together.. If possible can you share the same plunker code? Thanks in advance

AngularJS ng-table fixed headers


Sum of two variables in Obj-C

Question: I have two variables from 1 to 100. I have two buttons. I want one button to print the two variables on the screen and I want one button to print the sum of both the variables. How do I do this? My code is:
- (IBAction)addition:(id)sender;
{
    int x = arc4random() %100;
    int y = arc4random() %100;
    [label1 setText: [NSString stringWithFormat:@"%i", x]];
    [label2 setText: [NSString stringWithFormat:@"%i", y]];
}

- (IBAction)answer:(id)sender;
{
    int z;
    z = x+y;
    answer.text = [[NSString alloc] initWithFormat:@"%i", z];
}

Comment: What's the problem? That code looks correct.
Comment: @JackHumphries: You mean besides the fact that his `-answer:` method is leaking?
Comment: Yes, I was wondering why he is asking this question about displaying the sum of the two integers on the screen. It wasn't a memory management question.
Answer: If you make x and y instance variables of the class in question you should get what you want.
As-is those variables don't exist after the invocation to addition: and the above code doesn't even compile... unless you also happen to have x and y already declared as ivars in the class and the versions in addition: are just shadowing them.
In either case, remove the int from x and y in addition:.
Comment: This isn't C++, there's no such thing as a "member variable". They're called instance variables in Obj-C.
Answer: With the way you hace your code configured now, you'd have to declare your int values in your Interface file (".h file"). It'd look something like this pseudocode:
@interface Class {
    int x;
    int y;

    UILabel *label1;
    UILabel *label2;
    UILabel *answer;
}

-(IBAction)...

Then in your .m file, you'd just keep it as-is (just remove the int declarations for x and y) and hook up the functions and the outlets in Interface Builder.
Answer: I guess you might have problem with answer button... But that should also work... but if not then try below code which should definitely work.
Here you should declare x & y variable in .h file. And dont declare in addition button click.
- (IBAction)answer:(id)sender;
{
    int z;
    z = x+y;
    answer.text = [NSString stringWithFormat:@"%i", z];
}

If you are not having this question, then i would suggest you to please specify exact issue that you are facing..
Answer: Assuming your are ensuring label1 and label2 keeps integer values your answer method can be like
- (IBAction)answer:(id)sender;
{
    [answer setText:[NSString stringWithFormat:@"%i",[[label1 text] intValue] + [[label2 text] intValue]]];
}

Sum of two variables in Obj-C


Setting a global Scripting.Dictionary in Visual Basic for Applications (VBA)

Question: I have a function that is appending a dictionary. I want to keep the contents of this dictionary as long as the updateList isn't true. I currently have it setup like this:
Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)

Dim dicTitle As Variable
Dim dicFound As Variable

If updateList = True Then
Set dicTitle = CreateObject("Scripting.Dictionary")
Set dicFound = CreateObject("Scripting.Dictionary")

While status
        Set ObjectsJSON = jsonlibPollux.parse(responseString)

        With dicTitle
        .Add inc, ObjectsJSON.Item("title")
        End With

        With dicFound
        .Add inc, ObjectsJSON.Item("description")
        End With

Wend
End If

And when voerUit is true the following happens:
For i = 1 To dicTitle.Count
klaar = findReplace(dicTitle.Item(i), "x" + dicTitle.Item(i), dicTitle.Item(i) + vbCrLf + vbCrLf + dicFound.Item(i))
Next i

The problem here is that when this function ends, dicTitle and dicFound are cleared, and the findReplace function gets fed empty arguments.
Is there anyway to makes to code work, or a good workaround?
Answer: You will need to add a reference to the Microsoft Scripting Runtime to use binding like I have used. It is preferable to the manner you are declaring them as you have better access to the object and can see member variables easier, etc.
Method 1 - module level or public variables for dictionaries
One way you can do this is to create module level variables for the scripting dictionaries you are using:
Public gDicTitle As Scripting.Dictionary
Public gDicFound As Scripting.Dictionary

Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)

    If updateList = True Then
        Set gDicTitle = New Scripting.Dictionary
        Set gDicFound = New Scripting.Dictionary

        While Status
                Set ObjectsJSON = jsonlibPollux.Parse(responseString)

                With gDicTitle
                .Add inc, ObjectsJSON.Item("title")
                End With

                With gDicFound
                .Add inc, ObjectsJSON.Item("description")
                End With

        Wend
    End If
End Function

Method 2 - static references to dictionaries
You can also do this by making the dictionaries static. This will preserve them between function calls like the documentation says.
Public Function runPolluxFull(voerUit As Boolean, updateList As Boolean)
    Static gDicTitle As Scripting.Dictionary
    Static gDicFound As Scripting.Dictionary

    If updateList = True Then
        Set gDicTitle = New Scripting.Dictionary
        Set gDicFound = New Scripting.Dictionary

        While Status
                Set ObjectsJSON = jsonlibPollux.Parse(responseString)

                With gDicTitle
                .Add inc, ObjectsJSON.Item("title")
                End With

                With gDicFound
                .Add inc, ObjectsJSON.Item("description")
                End With

        Wend
    End If
End Function

Comment: @MartijnNosyncerror - You have to add a reference to that library in your VBA editor, add what in English is the `Microsoft Scripting Runtime` library. I added that to the top of my answer.
Comment: Whne I set dicTitle with `Scripting.Dictionary` (static, or without), I get a compiling error saying that the type is not defined (sorry have a Dutch install, so I have to translate error message's).
Comment: That did the trick for that error, problem is that my dictionary is still empty when using it in the `findReplace` function. I checked, and both dictionaries get populated with the first snippit, but still end up being deleted when that `While` loop ends..
Comment: @MartijnNosyncerror please post the rest of your code for the function exactly as you are using it with your problem, it seems you must have more code in your runPollufFull function than what I used here.
Comment: Yes I have but it's a lot of junk that isn't really relevant to the problem. I will post it on pastebin because of the size, but it's mostly in Dutch (and bad programming, which is the worst part :D) http://pastebin.com/a47vtBv8
Comment: Thanks for the help and the fast replies, been banging my head on this for 3 days now. First time doing something with VBA
Comment: After messing around with it, it apeared my error was comming from antoher bug. The second answer worked for me. Thanks a ton!
Comment: I have tried both and i havent had any succes yet
(I also got mine in dutch but i can change it to english)
I get the error `Compile Error: User-defined type not defined` do you have any tips?


How to put this matrix in Jordan Canonical Form

Question: Suppose you have the matrix
$A = \begin{bmatrix}
1 & 0 & 1 & -1 \\
0 & 1 & 1 & 0 \\
0 & 0 & 1 & 1 \\
0 & 0 & 0 & 1 \\
\end{bmatrix}$
Put it into Jordan Canonical Form.
I get that the eigenvalue is 1 with multiplicity 4, the corresponding eigenvectors are $x = \begin{bmatrix}1\\0\\0\\0\end{bmatrix}$ and $y = \begin{bmatrix}0\\1\\0\\0\end{bmatrix}$.
When I try to construct the Jordan Block, however, I cannot figure out if the Jordan matrix has to consist of two 2x2 blocks or a 3x3 and 1x1 block. Because $(A-I)w = x$ and $(A-I)w=y$ are both inconsistent (for w$\in \mathbb{R^4}$). So by the theory we had so far about the Jordan Canonical Form, there can be no 2x2 blocks, let alone 3x3 blocks, for $(A - I)w$ is inconsistent for both x and y. How would you solve this problem?
Thanks!
Comment: The size of the largest block is the smallest natural number $k$ such that $\text{rank}\left(A-I_4\right)^k=\text{rank}\left(A-I_4\right)^{k+1}$, which is $3$. You must have made some mistake when finding 4w$.
Answer: Note that a good understanding of the theory behind Jordan forms will often provide many short cuts.  You already know that $A$ has eigenvalue $1$ with algebraic multiplicity $4$ and that $A-I$ has nullity $2$.  Therefore $(A-I)^2$ has nullity $3$ or $4$.  Doing a bit of calculation, we have
$$(A-I)^2=\pmatrix{0&0&0&1\cr\cdot&\cdot&\cdot&\cdot\cr\cdot&\cdot&\cdot&\cdot\cr\cdot&\cdot&\cdot&\cdot\cr}$$
and without computing any further entries we can see that this does not have nullity $4$.  Therefore $(A-I)^2$ has nullity $3$.  So, without any computation, $(A-I)^3$ will have nullity $4$ and the Jordan form will be
$$J=J_3(1)\oplus J_1(1)\ .$$


iOS region monitoring - does it survive an app update?

Question: I have an app that uses Region Monitoring to wake up in the background. The initialization of the region is done when the app launches, so obviously the region monitoring is not active before the first launching of the app (i.e. right after the installation).
Assuming that the app was launched at least once, what will happen after an app update? Does the user have to relaunch the app in order for the region monitoring to keep working?
The app update did not have any change in the configuration of the regions.
Answer: Yes!
Surprisingly, the iBeacon monitoring did wake up after the update. No need for the user to open the app manually.
Tested on iOS 9.2.


Prove $\lim\limits_{n\to\infty}\frac{1}{\sqrt[n]{n!}}=0$

Question: I used $$(n!)^{\frac{1}{n}}=e^{\frac{1}{n}\ln(n!)}=e^{\lim\limits_{n\to\infty}\frac{1}{n}\ln(n!)}$$
Then using Stirling's approximation and L'Hospital's rule on $$\lim\limits_{n\to\infty}\frac{\ln(n!)}{n}$$ I get $$\lim\limits_{n\to\infty}\frac{\ln(n!)}{n}=\lim\limits_{n\to\infty}(\ln(n)+\frac{n+\frac{1}{2}}{n}-1)=\infty$$
Now, $$e^{\lim\limits_{n\to\infty}\frac{1}{n}\ln(n!)}=e^{\infty}=\infty$$
Thus
$$\lim\limits_{n\to\infty}\frac{1}{\sqrt[n]n}=\frac{1}{\infty}=0$$
Is this correct approach and what other methods could be used?
Comment: Can't we just use the fact that if $\frac{a_{n+1}}{a_{n}}\rightarrow L$ then $(a_{n})^{1/n}\rightarrow L$?
Comment: Why isn't this a duplicate?
Comment: it is right, not sure of other approaches
Comment: see also here
http://math.stackexchange.com/questions/706461/calculating-the-limit-limn1-n
Answer: You don't even have to use l'Hopital's rule; you can just plug in Sterling's formula and divide by $n$, then take limits.
Another way would be to use arithmetic-geometric means:
$${1 \over (n!)^{1 \over n}} = (\prod_{k=1}^n {1 \over k})^{1 \over n}
\leq {1 \over n}\sum_{k = 1}^n {1 \over k}$$
Since $\sum_{k = 1}^n {1 \over k}$ grows as $\ln n$ the limit is zero.
Comment: AM > GM is too good...+1
Answer: As long as you haven't made an algebra mistake, stirlings approximation should work.
Separate $n!$ into two parts. Assign $1$ to everything below $n/2$. Assign $n/2$ to everything above $n/2$
So you get $(n/2)^{n/2}<n!$
Apply the root and you get:
$(n/2)^{1/2}<n!^{1/n}$
$(n/2)^{1/2}$ clearly aproaches infinity so it will make the limit zero.
Answer: Since $\prod_{k=1}^{m-1}\left(1+\frac{1}{k}\right)=m$, we have:
$$ n!=\prod_{m=2}^{n}m = \prod_{m=2}^{n}\prod_{k=1}^{m-1}\left(1+\frac{1}{k}\right)=\prod_{k=1}^{n-1}\left(1+\frac{1}{k}\right)^{n-k}=\frac{n^n}{\prod_{k=1}^{n-1}\left(1+\frac{1}{k}\right)^k}$$
so:
$$ n!\geq \frac{n^n}{e^{n-1}} $$
and the claim easily follows.
Answer: If we can prove that if $\left | \frac{a_{n+1}}{a_{n}} \right |\rightarrow L$, then $a_{n}^{1/n}\rightarrow L$, we may simply take $a_{n}=n!$ to get the result.
So suppose that $\left | \frac{a_{n+1}}{a_{n}} \right |\rightarrow L$. Then there is an integer $N$ such that if $n>N$, then
($^{*}$) $L-\epsilon <\left | \frac{a_{n+1}}{a_{n}} \right |<L+\epsilon $.
Now, for $n>N$,
$\left | a_{n} \right |=\left | \frac{a_{n}}{a_{n-1}} \right |\left | \frac{a_{n-1}}{a_{n-2}} \right |\left | \frac{a_{n-2}}{a_{n-3}} \right |\cdots \left | \frac{a_{N+1}}{a_{N}} \right |\left | a_{N} \right |$
and so if we appeal to ($^{*}$), we see that this is less than
$(L+\epsilon )^{n-N}\left | a_{N} \right |$
and greater than
$(L-\epsilon )^{n-N}\left | a_{N} \right |$
Now take the $n$th root to obtain
$\frac{L-\epsilon}{(L-\epsilon)^{N/n}}a_{N}^{1/n}<a_{n}^{1/n}<\frac{L+\epsilon}{(L+\epsilon)^{N/n}}a_{N}^{1/n}$. Letting $n\rightarrow \infty $, we get the result.
Answer: Using Stirling's Approximation:
$$n!\sim\sqrt{2\pi n }(\frac{n}{e})^n$$
Also
$$\lim\limits_{k\to\infty}k^{\frac1k}=1$$
So we have
\begin{align}
\lim\limits_{n\to\infty}\frac{1}{\sqrt[n]n}&=\lim\limits_{n\to\infty}\frac1{[\sqrt{2\pi n }(\frac{n}{e})^n]^{\frac{1}n}}=\lim\limits_{n\to\infty}\frac1{\frac{n}e\cdot(2\pi n)^{\frac1{2n}}}\\&=\lim\limits_{n\to\infty}\frac e{n\cdot\pi^{\frac1{2n}}\cdot(2n)^{\frac1{2n}}}\\&=\lim\limits_{n\to\infty}\frac{e}{n}\\&=0
\end{align}
Answer: $$\ln [(n!)^{1/n}]= (1/n)\sum_{k=1}^{n}\ln k \ge (1/n)\sum_{k>n/2}\ln k \ge (1/n)[(n/2)\ln (n/2)] = (1/2)\ln (n/2) \to \infty.$$ Thus $(n!)^{1/n} \to \infty$ and the desired limit is $0.$
Answer: We have
$$\newcommand{\limti}[1]{\lim\limits_{#1\to\infty}}0\le \limti n \frac1{\sqrt[n]{n!}} = \limti n \sqrt[n]{1\cdot\frac12\cdots\frac1n} \overset{(1)}\le \limti n \frac{1+\frac12+\dots+\frac1n}n \overset{(2)}=0.$$
(1) is AM-GM inequality
(2) is special case of the result that
$$\limti n a_n = L \qquad\Rightarrow\qquad \limti n \frac{a_1+\dots+a_n}n=L.$$
See Prove convergence of the sequence $(z_1+z_2+\cdots + z_n)/n$ of Cesaro means, If $a_n\to \ell $ then $\hat a_n\to \ell$ and A result on sequences: $x_n\to x$ implies $\frac{x_1+\dots+x_n}n\to x$ without using Stolz-Cesaro.


Adding autocomplete for text-field

Question: I tried to implement an autocomplete in text-field for drupal 8 in my custom module
all I wanted was to fetch and display the likely title I typed via autocomplete
so declared a public function autocomplete within a class  in DefaultController.php
in folder directory -->mymodule/src/Controller/DefaultController.php
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class DefaultController extends ControllerBase
{
    public function autocomplete($string)
    {
        $matches = array();
        $db = \Drupal::database();
        $result = $db->select('node_field_data', 'n')
        ->fields('n', array('title', 'nid'))
        ->condition('title', '%'.db_like($string).'%', 'LIKE')
        ->addTag('node_access')
        ->execute();

        foreach ($result as $row) {
            $matches[$row->nid] = check_plain($row->title);
        }

        return new JsonResponse($matches);
    }
}

then created an EditForm.php in
folder directory -->mymodule/src/Form/EditForm.php
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class EditForm extends FormBase
{
    public function getFormId()
    {
        return 'mymodule_edit_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form = array();

  $form['input_fields']['nid'] = array(
    '#type' => 'textfield',
    '#title' => t('Name of the referenced node'),
    '#autocomplete_route_name' => 'mymodule.autocomplete',
    '#description' => t('Node Add/Edit type block'),
    '#default' => ($form_state->isValueEmpty('nid')) ? null : ($form_state->getValue('nid')),
    '#required' => true,
  );

        $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create'),
  );

        return $form;
    }
}

also created mymodule.routing.yml
  mymodule.autocomplete:
  path: '/mymodule/autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
  requirements:
    _permission: 'access content'

still autocomplete functionality not getting implemented ?
Can anybody point me what am i missing ??
Comment: @ShreyaShetty  No I don't need  parameters since
in d7 i would have used
'#autocomplete_path' => 'mymodule/autocomplete',
so in d8 i used
'#autocomplete_route_name' => 'mymodule.autocomplete',
so i never used parameter nor do i need one ....
Comment: you need to pass parameters also https://www.drupal.org/node/2070985
Answer: If you want to select an entity, then there is a way easier way to do that. Drupal 8 has a standard entity_autocomplete field type, just specify your form element like this:
$form['node'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
];

See Custom autocomplete field for more information.
Also, never do database queries against node/entity tables. Use \Drupal::entityQuery() for that.
Comment: Hi Berdir, How to get data from taxanomy in my case "city" using above code as it is working perfectly fine for node but not for taxanomy??
Comment: Thanks @Berdir, excellent answer. For term selection:       $form['related'] = [
        '#type' => 'entity_autocomplete',
        '#target_type' => 'taxonomy_term',
        '#selection_settings' => [
          'target_bundles' => ['topics'],
        ],
      ];
Answer: Your class need some modification you need to check request and put it into $string.
<?php

namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Unicode;

class DefaultController extends ControllerBase
{

  /**
   * Returns response for the autocompletion.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request object containing the search string.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing the autocomplete suggestions.
   */

  public function autocomplete(request $request) {
    $matches = array();
    $string = $request->query->get('q');
    if ($string) {
      $matches = array();
      $query = \Drupal::entityQuery('node')
      ->condition('status', 1)
      ->condition('title', '%'.db_like($string).'%', 'LIKE');
      //->condition('field_tags.entity.name', 'node_access');
      $nids = $query->execute();
      $result = entity_load_multiple('node', $nids);
      foreach ($result as $row) {
        //$matches[$row->nid->value] = $row->title->value;
        $matches[] = ['value' => $row->nid->value, 'label' => $row->title->value];
      }
    }
    return new JsonResponse($matches);
  }
}

Comment: it still DID NOT WORK after fetching a request and placing it into $string
Comment: have you check your request was print?
Comment: I think `\Drupal::entityQuery('node')` would be preferable to use apart of select.
Comment: After watching the Network tab in my browser's dev tools, I could see proper results in the response, but they were not being shown in the UI. After some digging, I found I had some custom css setting a `z-index` on a DOM element which contained the form. The value was too high and was overlapping the autocomplete results. Lowering my custom `z-index` fixed it for me.
Answer:
Create a routing.yml file and add the below code :
admin_example.autocomplete:

:
  path: '/admin_example/autocomplete'
  defaults:
    _controller: '\Drupal\admin_example\Controller\AdminNotesController::autocomplete'
  requirements:
    _permission: 'access content'

The form which you have build in mymodule/src/Form/EditForm.php is correct

You need to change the code in controller .The code is below :
public function autocomplete(Request $request)
{
 $string = $request->query->get('q');
    $matches = array();
      $query = db_select('node_field_data', 'n')
          ->fields('n', array('title', 'nid'))
          ->condition('title', $string . '%', 'LIKE')
          ->execute()
          ->fetchAll();
    foreach ($query as $row) {
        $matches[] = array('value' => $row->nid, 'label' => $row->title);
    }

    return new JsonResponse($matches);
}

Comment: Hi Shreya, I used your solution but instead of going to the form it is giving me o/p like this: [{"value":"1","label":"Patel Residency"},{"value":"2","label":"Jain Plaza"},{"value":"3","label":"Kanha Resort"},{"value":"38","label":"Hira Residency"}]. I want it to goto the form and the field should work as autocomplete
Answer: Use @vgoradiya code then on the foreach loop try it this way:
    foreach ($result as $row)
    {
        $matches[] = ['value' => $row->nid, 'label' => check_plain($row->title)];
    }

Answer: FWIW I had the same need and was greatly helped by the excellent write-up over at https://antistatique.net/en/blog/how-to-create-a-custom-autocomplete-entity-field-widget-using-the-drupal-8-form-api

Adding autocomplete for text-field


java.lang.NullPointerException in AsyncTask

Question: I'm trying to "optimize" my app's code using AsycTask, but I receive the java.lang.NullPointerException error.
Can you please help me to figure it out where I'm doing it wrong?
package it.vscreazioni.farmachimica;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

public class MostraTutti extends SherlockActivity {
    final ListView lv = (ListView) findViewById(R.id.listView);
    final List<ListViewItem> items = new ArrayList<MostraTutti.ListViewItem>();
    final ArrayList<String> nome = new ArrayList<String>();
    final ArrayList<String> immagine = new ArrayList<String>();
    ...
    ...

    final   int array_image2[] ={R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
                    R.drawable.acidoascorbico,R.drawable.acidobarbiturico,R.drawable.acidobenzoico,...};

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

            setContentView(R.layout.mostra_tutti);
            getSupportActionBar().setDisplayShowHomeEnabled(false);

            RssFeedTask rssTask = new RssFeedTask();
           rssTask.execute();
    }

    private class RssFeedTask extends AsyncTask<String, Void, String> {
            private ProgressDialog Dialog;
            String response = "";

            @Override
            protected void onPreExecute() {
                    Dialog = new ProgressDialog(MostraTutti.this);
                    Dialog.setMessage("Leggo...");
                    Dialog.show();
            }

                    @Override
                    protected String doInBackground(String... urls) {
                            InputStream xmlFile = getResources().openRawResource(R.raw.sostanze);
                            try {

                            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                            final Document document = documentBuilder.parse(xmlFile);
                            document.getDocumentElement().normalize();
                            NodeList nodeList = document.getElementsByTagName("sostanza");

                            for (int i = 0; i < nodeList.getLength(); i++) {
                            final int       indice = i;

                            nome.add(document.getElementsByTagName("nome").item(indice).getTextContent());
                            iupac.add(document.getElementsByTagName("iupac").item(indice).getTextContent());
                            aspetto.add(document.getElementsByTagName("aspetto").item(indice).getTextContent());
                            formula.add(document.getElementsByTagName("formula").item(indice).getTextContent());
                            immagine.add(document.getElementsByTagName("immagine").item(indice).getTextContent());
                            appartenenza.add(document.getElementsByTagName("appartenenza").item(indice).getTextContent());
                            spiegazione.add(document.getElementsByTagName("spiegazione").item(indice).getTextContent());
                            tempFus.add(document.getElementsByTagName("temperaturaFusione").item(indice).getTextContent());
                            tempEboll.add(document.getElementsByTagName("temperaturaEbollizione").item(indice).getTextContent());
                            solubilita.add(document.getElementsByTagName("solubilita").item(indice).getTextContent());
                            note.add(document.getElementsByTagName("eccezioni").item(indice).getTextContent());

                            String str = document.getElementsByTagName("formula").item(indice).getTextContent();

                            str = str.replaceAll("0", "\u2080");
                        str = str.replaceAll("1", "\u2081");
                        str = str.replaceAll("2", "\u2082");
                        str = str.replaceAll("3", "\u2083");
                        str = str.replaceAll("4", "\u2084");
                        str = str.replaceAll("5", "\u2085");
                        str = str.replaceAll("6", "\u2086");
                        str = str.replaceAll("7", "\u2087");
                        str = str.replaceAll("8", "\u2088");
                        str = str.replaceAll("9", "\u2089");

                        final String stringa = str;
                            formulaConvertita.add(stringa);

                                    items.add(new ListViewItem()
                                    {{
                                            ThumbnailResource = array_image2[indice];
                                            Title = document.getElementsByTagName("nome").item(indice).getTextContent();
                                            SubTitle = stringa;
                                    }});
                };

                    } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                    } catch (ParserConfigurationException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (SAXException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }

                    return response;
    }
                @Override
                    protected void onPostExecute(String result) {
                    CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
                            lv.setAdapter(adapter);
                    /*
                    _adapter = new CustomListViewAdapter(News.this,Rssparser.items);
                    lv=(ListView)findViewById(R.id.list);
                    lv.setAdapter(_adapter);
                            Dialog.dismiss();
                            lv.setOnItemClickListener(new OnItemClickListener()
                            {
                                    public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
                                    {
                                            Context context = getBaseContext();
                                   Intent myIntent = new Intent(context, LeggiArticolo.class);

                                   myIntent.putExtra("testo",Rssparser.testo.get(position));
                                   myIntent.putExtra("titolo",Rssparser.titolo.get(position));
                                   myIntent.putExtra("immagine",Rssparser.immagini.get(position));
                                   myIntent.putExtra("link",Rssparser.indirizzo.get(position));

                                   startActivityForResult(myIntent, 0);
                                    }
                             }
                         );
                         */
                    }
                    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getSupportMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
    }

class ListViewItem {
    public int ThumbnailResource;
    public String Title;
    public String SubTitle;
}
}

And I get this Error:
04-25 11:43:57.872: W/dalvikvm(1663): threadid=1: thread exiting with uncaught exception
(group=0x40a13300)
04-25 11:43:57.902: E/AndroidRuntime(1663): FATAL EXCEPTION: main
04-25 11:43:57.902: E/AndroidRuntime(1663): java.lang.RuntimeException: Unable to
instantiate activity
ComponentInfo{it.vscreazioni.farmachimica/it.vscreazioni.farmachimica.MostraTutti}:
java.lang.NullPointerException
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread.access$600(ActivityThread.java:130)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.os.Handler.dispatchMessage(Handler.java:99)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at android.os.Looper.loop(Looper.java:137)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread.main(ActivityThread.java:4745)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
java.lang.reflect.Method.invokeNative(Native Method)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
java.lang.reflect.Method.invoke(Method.java:511)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at dalvik.system.NativeStart.main(Native
Method)
04-25 11:43:57.902: E/AndroidRuntime(1663): Caused by: java.lang.NullPointerException
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.Activity.findViewById(Activity.java:1825)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
it.vscreazioni.farmachimica.MostraTutti.<init>(MostraTutti.java:25)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at java.lang.Class.newInstanceImpl(Native
Method)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
java.lang.Class.newInstance(Class.java:1319)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.Instrumentation.newActivity(Instrumentation.java:1053)
04-25 11:43:57.902: E/AndroidRuntime(1663):     at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
04-25 11:43:57.902: E/AndroidRuntime(1663):     ... 11 more

Can you please help me?
EDIT AFTER ANSWER:
public class MostraTutti extends SherlockActivity {
    ListView lv;
    final List<ListViewItem> items = new ArrayList<MostraTutti.ListViewItem>();
    final ArrayList<String> nome = new ArrayList<String>();
    ...

    final   int array_image2[] ={R.drawable.iodocloroidrossichinolina,R.drawable.acidoacetilsalicilico,
                    R.drawable.acidoascorbico,R.drawable.acidobarbiturico,R.drawable.acidobenzoico,
                    ... };

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

            setContentView(R.layout.mostra_tutti);
            lv = (ListView) findViewById(R.id.listView);
            getSupportActionBar().setDisplayShowHomeEnabled(false);

            RssFeedTask rssTask = new RssFeedTask();
           rssTask.execute();

    }

    private class RssFeedTask extends AsyncTask<String, Void, String> {
            private ProgressDialog Dialog;
            String response = "";

            @Override
            protected void onPreExecute() {
                    Dialog = new ProgressDialog(MostraTutti.this);
                    Dialog.setMessage("Leggo le sostanze...");
                    Dialog.show();
            }

                    @Override
                    protected String doInBackground(String... urls) {
                            InputStream xmlFile = getResources().openRawResource(R.raw.sostanze);
                            try {

                            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                            final Document document = documentBuilder.parse(xmlFile);
                            document.getDocumentElement().normalize();
                            //tagHandler.handleChannelTag(document);
                            NodeList nodeList = document.getElementsByTagName("sostanza");

                            for (int i = 0; i < nodeList.getLength(); i++) {
                            final int       indice = i;

                            nome.add(document.getElementsByTagName("nome").item(indice).getTextContent());
                            iupac.add(document.getElementsByTagName("iupac").item(indice).getTextContent());
                            aspetto.add(document.getElementsByTagName("aspetto").item(indice).getTextContent());
                            formula.add(document.getElementsByTagName("formula").item(indice).getTextContent());
                            immagine.add(document.getElementsByTagName("immagine").item(indice).getTextContent());
                            appartenenza.add(document.getElementsByTagName("appartenenza").item(indice).getTextContent());
                            spiegazione.add(document.getElementsByTagName("spiegazione").item(indice).getTextContent());
                            tempFus.add(document.getElementsByTagName("temperaturaFusione").item(indice).getTextContent());
                            tempEboll.add(document.getElementsByTagName("temperaturaEbollizione").item(indice).getTextContent());
                            solubilita.add(document.getElementsByTagName("solubilita").item(indice).getTextContent());
                            note.add(document.getElementsByTagName("eccezioni").item(indice).getTextContent());

                            String str = document.getElementsByTagName("formula").item(indice).getTextContent();

                            str = str.replaceAll("0", "\u2080");
                        str = str.replaceAll("1", "\u2081");
                        str = str.replaceAll("2", "\u2082");
                        str = str.replaceAll("3", "\u2083");
                        str = str.replaceAll("4", "\u2084");
                        str = str.replaceAll("5", "\u2085");
                        str = str.replaceAll("6", "\u2086");
                        str = str.replaceAll("7", "\u2087");
                        str = str.replaceAll("8", "\u2088");
                        str = str.replaceAll("9", "\u2089");

                        final String stringa = str;
                            formulaConvertita.add(stringa);

                                    items.add(new ListViewItem()
                                    {{
                                            ThumbnailResource = array_image2[indice];
                                            Title = document.getElementsByTagName("nome").item(indice).getTextContent();
                                            SubTitle = stringa;
                                    }});
                };

                    } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                    } catch (ParserConfigurationException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    } catch (SAXException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }

                    return response;
    }
                @Override
                    protected void onPostExecute(String result) {
                    Dialog.dismiss();
                    CustomListViewAdapter adapter = new CustomListViewAdapter(MostraTutti.this,items);
                            lv.setAdapter(adapter);

                            lv.setOnItemClickListener(
                                    new OnItemClickListener()
                                    {
                                            public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
                                            {
                                                    Context context = getBaseContext();
                                           Intent myIntent = new Intent(context, Dettagli.class);

                                           myIntent.putExtra("nome_sostanza",nome.get(position));
                                         //  myIntent.putExtra("formula",formula.get(position));
                                           myIntent.putExtra("iupac",iupac.get(position));
                                           myIntent.putExtra("aspetto",aspetto.get(position));
                                           myIntent.putExtra("appartenenza",appartenenza.get(position));
                                           myIntent.putExtra("solubilita",solubilita.get(position));
                                           myIntent.putExtra("tempFus",tempFus.get(position));
                                           myIntent.putExtra("tempEboll",tempEboll.get(position));
                                           myIntent.putExtra("spiegazione",spiegazione.get(position));
                                           myIntent.putExtra("immagine", array_image2[position]);
                                           myIntent.putExtra("formulaConvertita", formulaConvertita.get(position));
                                           myIntent.putExtra("note", note.get(position));
                                           startActivityForResult(myIntent, 0);
                                            }

                                        }
                                 );
                    }
                    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getSupportMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
    }

class ListViewItem {
    public int ThumbnailResource;
    public String Title;
    public String SubTitle;
}
}

And the error's gone! But there's a strange behaviour: now in simulator it take's longer than the "normal" way:
16 seconds with the not Async and 1 minute with Async...
Answer: You are trying to get a view before activity create:
final ListView lv = (ListView) findViewById(R.id.listView);

put this line in the onCreate function after setContentView.
Answer: You can't simply declare a field this way:
final ListView lv = (ListView) findViewById(R.id.listView);

findViewById() must be called after the setContentView() call, otherwise you'll be getting NullPointerExceptions all the time. If you're trying to minimize the number of lines of code related to findViewById(), I'd recommend using a dependency injection framework called roboguice.
Comment: A question on Stackoverflow equals to one issue, if you have another you will need to create a new question and provide a proper description of your problem.
Comment: I'm sorry, I just did it. Please take a look, if you can: http://stackoverflow.com/questions/16213118/xml-parsing-with-asynctask-slower-than-parsing-in-main-thread


Get month week number from a date (2022-02-28T10:00:53.393Z) -> 5

Question: How to get week no from a date like moment("2022-02-28T10:00:53.393Z") should return 5.
I know about week() but that return week no from start of year like it will give 11 based on the date.
I need the week no. from month like week 1 of February or week 5 of February
Comment: [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users)
Comment: `moment("31/01/2022")` is undefined, unreliable behavior, as you can tell [from the warning you get for it](https://momentjs.com/guides/#/warnings/js-date/).
Comment: [If you add the format and use `weeks()` you'll get `6` as expected](https://jsfiddle.net/c28uyrz0/)
Comment: How do you define the first week of a month? As I said above, [it's complicated](https://en.wikipedia.org/wiki/ISO_week_date#First_week) for week-of-year and different locales do it differently. From that link: Jan 1st 1977 is week 53 in the ISO week-of-year system.
Comment: momentjs has special methods for this: [`.week()`](https://momentjs.com/docs/#/get-set/week/) and [`.isoWeek()`](https://momentjs.com/docs/#/get-set/iso-week/)
Comment: this one gives the week based on month not year
Comment: @SaGaR - *"this one gives the week based on month not year "* 1. That's not described in the question. 2. What does that even mean? Week in month instead of week in year? If so, it could be a reasonable question if you mean you also want (say) `1` for `2022-02-02`, but you'd have to be clear about it and call out why `week` isn't what you want, a well as defining how weeks are allocated (since it's complicated for week-in-year).
Answer: Here is the solution for this
const getWeekOfDate = (date) => {
  let startDate = moment(date).startOf('month').date();
  let endDate = moment(date).date();
  let weekCount = 1;
  for (let i = startDate; i <= endDate; i++) {
    if (
      moment(date).date(i).format('dddd') ===
      moment().startOf('week').format('dddd')
    ) {
      weekCount++;
    }
  }
  return weekCount;
};

Comment: Just use [`week`](https://momentjs.com/docs/#/get-set/week/).
Comment: `week()` gives week based on year my function gives it based on month


Why am I getting an EXEC_BAD_ACCESS when setting the info pointer of a FSFileOperationClientContext?

Question: I am using FSCopyObjectAsync to copy files in a Cocoa app. Problem is, whenever I try to set the info field (an object of type void *) the application crashes because of an EXEC_BAD_ACCESS. I'm not sure what I'm doing wrong.
Here's my code:
// Start the async copy.
FSFileOperationClientContext *clientContext = NULL;
if (spinner != nil) {
    clientContext->info = (__bridge void *)(spinner); // <- Problem here!
}

status = FSCopyObjectAsync(fileOp,
                           &source,
                           &destination, // Full path to destination dir.
                           CFSTR("boot.iso"), // Copy with the name boot.iso.
                           kFSFileOperationDefaultOptions,
                           copyStatusCallback,
                           0.5, // How often to fire our callback.
                           clientContext); // The progress bar that we want to use to update.

CFRelease(fileOp);

I'm using ARC, and it works if I comment out the lines dealing with clientContext and pass NULL in the last argument of FSCopyObjectAsync, but that severely cripples my application's functionality. It's definitely the assignment, therefore, that's causing the problem.
Answer: You are creating a NULL pointer without allocating it and then trying to reference it. Change the code so you allocate it on stack and pass its address like below.
    // Start the async copy.
FSFileOperationClientContext clientContext;
if (spinner != nil) {
    clientContext.info = (__bridge void *)(spinner);
}

status = FSCopyObjectAsync(fileOp,
                           &source,
                           &destination, // Full path to destination dir.
                           CFSTR("boot.iso"), // Copy with the name boot.iso.
                           kFSFileOperationDefaultOptions,
                           copyStatusCallback,
                           0.5, // How often to fire our callback.
                           &clientContext); // The progress bar that we want to use to update.

CFRelease(fileOp);

Comment: Fails with the error `error: address doesn't contain a section that points to a section in a object file`.
Comment: Different issue, hard to tell without seeing the complete code. Have you looked at the various example code that use FSCopyObjectAsync?
Comment: Yeah, but they're not super helpful. I couldn't find any code that is doing what I'm trying to do. The code is open source though on GitHub; here's the link to the file in question: http://bit.ly/ZhzyCG The code in question is a little bit more than halfway down.
Comment: Oh, that makes it easy, I will clone it and see what is going on - I am also a newcomer to Obj-C (more of C/C++/Java guy) so I will refrain from promising anything :)
Comment: Thanks. I'll stay hopeful. :)
Comment: I got it working! I moved `clientContext` to global scope and changed `spinner` to be a `strong` variable. Thanks for the help!


Real Analysis Folland Proposition 1.13

Question:
Proposition 1.13 - If $\mu_0$ is a premeasure on $\mathcal{A}$ and $\mu^*$ is defined by (1.12) then
a.) $\mu^*|\mathcal{A} = \mu_0$
b.) every set in $\mathcal{A}$ is $\mu^*$-measurable

Proof a.) - Suppose $E\in\mathcal{A}$ then $\mu^*(E)\leq \mu_0(E)$ (since $E$,$\emptyset$ cover $E$). Now let $E\subset \bigcup_{1}^{\infty}A_j$ and $\{A_j\}_{1}^{\infty}\subset \mathcal{A}$, set $$E_j = E\cap \left(A_j \setminus \bigcup_{j' < j}A_j\right)\in\mathcal{A}$$
Then, $$\mu_0(E) = \sum_{1}^{\infty}\mu_0(E_j) \leq \sum_{1}^{\infty}\mu_0(A_j)$$ so $\mu_0(E)$ is a lowerbound of $\mu^*(E)$ in 1.12.
Proof b.) - Suppose $A\in\mathcal{A}$ and $E\subset X$. Let $\epsilon > 0$, choose $\{B_j\}_{1}^{\infty}\subset \mathcal{A}$ with $E\subset \bigcup_{1}^{\infty}B_j$ and $$\sum_{1}^{\infty}\mu_0(B_j) < \mu^*(E) + \epsilon$$ Then, $$\mu^*(E\cap A) + \mu^*(E\cap A^c) \leq \sum_{1}^{\infty}\mu_0(B_j\cap A) + \sum_{1}^{\infty}\mu_0(B_j\cap A^c) = \sum_{1}^{\infty}\mu_0(B_j) < \mu^*(E) + \epsilon$$
I am not sure if this is correct. Any suggestions is greatly appreciated.
Answer: Yes, the proof is correct.  I copied your proof here just to add small details which may help to make it clearer.
Proof a.) - Suppose $E\in\mathcal{A}$ then $\mu^*(E)\leq \mu_0(E)$, (since $\{E,\emptyset,\emptyset,\cdots \}$  covers $E$). Now let $E\subset \bigcup_{1}^{\infty}A_j$ and $\{A_j\}_{1}^{\infty}\subset \mathcal{A}$, set $$E_j = E\cap \left(A_j \setminus \bigcup_{j' < j}A_j\right)\in\mathcal{A}$$
Then, $\{E_j\}_{1}^{\infty}$ is a family of disjoint sets in $\mathcal{A}$ and $E= \bigcup_{1}^{\infty}E_j$. Since $\mu_0$ is a premeasure, we have
$$\mu_0(E) = \sum_{1}^{\infty}\mu_0(E_j) \leq \sum_{1}^{\infty}\mu_0(A_j)$$ so $\mu_0(E)$ is a lowerbound of $\{\sum_{1}^{\infty}\mu_0(A_j) : A_j \in  \mathcal{A},\;E\subset \bigcup_{1}^{\infty}A_j\}$. So, from the definition of   $\mu^*(E)$ (in 1.12), we get
$$ \mu_0(E) \leq \mu^*(E)$$
So we can conclude that
$$ \mu^*(E) = \mu_0(E) $$
Proof b.) - Suppose $A\in\mathcal{A}$ and $E\subset X$. Let $\epsilon > 0$, choose $\{B_j\}_{1}^{\infty}\subset \mathcal{A}$ with $E\subset \bigcup_{1}^{\infty}B_j$ and $$\sum_{1}^{\infty}\mu_0(B_j) \leq \mu^*(E) + \epsilon$$
Note that, for each $j$, $(B_j\cap A), (B_j\cap A^c) \in \mathcal{A}$, $(B_j\cap A)$ and $(B_j\cap A^c)$ are disjoint and $B_j = (B_j\cap A)\cup (B_j\cap A^c)$. So, for each $j$,
$$ \mu_0(B_j)= \mu_0(B_j\cap A)+ \mu_0(B_j\cap A^c)$$
Then, $$\mu^*(E\cap A) + \mu^*(E\cap A^c) \leq \sum_{1}^{\infty}\mu_0(B_j\cap A) + \sum_{1}^{\infty}\mu_0(B_j\cap A^c) = \sum_{1}^{\infty}\mu_0(B_j) \leq \mu^*(E) + \epsilon$$
Since $\epsilon$ is arbitrary, we have
$$\mu^*(E\cap A) + \mu^*(E\cap A^c) \leq \mu^*(E) $$
Since $\mu^*$ is subadditive, we also have
$$\mu^*(E\cap A) + \mu^*(E\cap A^c) \geq \mu^*(E) $$
So
$$\mu^*(E\cap A) + \mu^*(E\cap A^c) = \mu^*(E) $$
So $A$ is $\mu^*$-measurable.

Real Analysis Folland Proposition 1.13


Get different rows

Question: I have two tables:

bookings(id,lessons_id,user_id,permit_id)
lessons(id,name,date)

I need to select all the lessons where the user_id <>$user
I have done the following but it's not quite correct.
$user = Auth::id();
            $lesson = DB::table('lessons')
        ->whereNotExists(function ($query) {
            $query->select(DB::raw(1))
                  ->from('bookings')
                  ->whereRaw('bookings.lessons_id', '=', 'lessons.id')
                   ->where('  bookings.user_id',' <>', '$user');
        })

            ->get();

Comment: What do you mean by "not quite correct"?
Comment: I can't see the number `2` anywhere in your code.
Comment: @Binarus q just updated
Comment: I asked you to paste the raw MySQL query you want.  Instead, you changed your original PHP code to my answer, which isn't what actually happened here.  Don't do that.
Comment: Please clear your question bit more
Comment: I need to select all the lessons where the user_id <>$user
Answer: Try using the whereNotExists function:
DB::table('lessons')
    ->whereNotExists(function ($query) {
        $query->select(DB::raw(1))
              ->from('bookings')
              ->whereRaw('bookings.lessons_id = lessons.id AND
                  bookings.user_id = ?', [$user]);
    })
->get();

This would correspond to the following raw MySQL query:
SELECT *
FROM lessons t
WHERE NOT EXISTS (SELECT 1 FROM bookings b
                  WHERE b.lessons_id = t.id AND b.user_id = 2);

Comment: bookings.user_id <> Auth::user()->id; gives me a syntax error how can i write this
Comment: I don't understand what you are trying to do.  Do you get an exact error using my answer?
Comment: I am trying to make the ->whereRaw('bookings.lessons_id = lessons.id AND
                  bookings.user_id = 2'); different from current user id =>bookings.user_id <> Auth::user()->id
Comment: simply make the bookings.user_id different from current user id
Comment: Tim help till the end ->where('bookings.lessons_id' ,'=',' Lessons.id')
  ->where('bookings.user_id','=',Auth::id()); this gives me a cardinality error
Comment: I don't know your code, so I can't offer much help.  Your two WHERE clauses won't give you the right output, and it doesn't match the raw EXISTS query I gave above.
Comment: Tim simply make the bookings.user_id different from current authenticated user id
Comment: please I need this
Comment: I can't help beyond what I've already done.  You need a Laravel/Eloquent expert, which I am not.
Comment: Tim $user = Auth::user()->id; now simply make the bookings.user_id  different from $user
Comment: Take my raw query and edit it with your new logic.  Then update your question with that query.  I can't read your mind.
Comment: TAke a look please
Comment: James, check my updated answer.  Use a positional parameter `?` in the raw `WHERE` clause, then bind `$user` to it.  I think this should work.
Comment: @JamesMoore Try putting `$user` into an array.  I rejected your edit because you used a completely raw query, which is prone to SQL injection.  You need to figure out how to bind that user parameter.
Comment: I don't know what's wrong.  The documentation supports the syntax I used.  My guess is that your code has a problem which you can't see.  Maybe it has nothing to do with this.
Comment: I dont think so the raw query worked plus its only this in my code
Comment: Then use the raw query for now and come back to this when you have time later.

Get different rows


"Histomancy": What does McElreath propose we do instead?

Question: I have McElreath's book (Statistical Rethinking) and was intrigued by his callout against "Histomancy" (see image below).

I felt the section a bit wanting and I am left unsure as to what is proposed we do then. I even went a little further and watched his lecture videos, hoping for additional information on the matter.
My only takeaway is that we should instead use our knowledge about the outcome variable and ignore the histograms. For example, say we have a count variable and so then we know we must be dealing with a Poisson or a related likelihood. Then it comes down to comparing models that could feasibly express the likelihood and see which one fits the data best.
Is there anything else that we can use besides the basic knowledge that (ah, I have a count variable, Poisson!) to better understand where we should start with our guess for what distribution likely generated our data?
Answer: McElreath appears to be maligning the oft repeated practice of requiring regressors (to the right of the equality sign, sometimes 'independent' or 'predictor' variables) and regressands (to the left of the equality sign, sometimes 'dependent' or 'outcome' variables) to be normally distributed (i.e. "Gaussian") in the context of something like OLS regression.
In fact none of these variable needs to be normally, or even nearly normally distributed. The residuals require this assumption, as in the simple model here:
$$y_i = \beta_0 + \beta_x x_i + \varepsilon_i\text{; where }\varepsilon \sim \mathcal{N}(0,\sigma)$$
It is relatively easy to demonstrate this:
<code>    n <- 200
    x <- runif(n)
    b0 <- 10
    bx <- -2
    s <- 0.1
    e <- rnorm(n,0,s)
    y <- b0 + bx*x + e
    summary(lm(y~x))
    hist(y)
    hist(x)
    hist(e)
</code>
Notice that:

You quite adequately estimate $\beta_0$, $\beta_x$, and $\sigma$ using the OLS MLE estimators:

<code>          Coefficients:
                      Estimate  Std. Error t value  Pr(>|t|)
          (Intercept) 10.00007    0.01337  747.85   <2e-16 ***
          x           -2.00687    0.02235  -89.81   <2e-16 ***

          Residual standard error: 0.0957 on 198 degrees of freedom
</code>

The histograms of $y$ and $x$ are nothing like normally distributed:

The histogram of $\varepsilon$ is approximately normal:

Of course there are other linear regression models than OLS (including multiple regression), but MLE estimation is quite often used for such models, and the conflation of distributions of variables with residuals is reflected widely in questions on this site, in the literature, and in research meetings.
The upshot is that we should strive to understand our modeling assumptions (whether our data are continuous, count, or what have you) in application rather than waste time in pointless efforts (i.e. "Histomancy") like normalizing all our regression variables.
Comment: Thanks for the answer and the OLS makes sense. But what about beyond OLS? What do we do we do then? Just know that we have a binary variable so then we must be dealing with the Bernoulli distribution.
Comment: @JohnStud Ask a separate question, that is what the website is for. :) I answered the question about "Histomancy." BTW: Welcome, to CV John Stud.


Example of Failure of Hoeffding's Inequality for Empirical Risk Minimization

Question: I am studying Introduction to Statistical Learning Theory by Bousquet, Boucheron and Lugosi. On pages 183 through 185 it considers the applicability of Hoeffding's Inequality to Empirical Risk Minimization (ERM). The setting is as follows.
Let $Z_1,...,Z_n$ be $n$ i.i.d. samples drawn from a distribution. Let $\mathcal{F}$ be a class of functions. For every $f\in\mathcal{F}$, define its risk $R(f)$ and empirical risk $R_n(f)$ by
$$
R(f)=\mathbb{E}f(Z)
\quad\text{and}\quad
R_n(f)=\frac{1}{n}\sum_{i=1}^nf(Z_i).
$$
Let $f^*\in\mathcal{F}$ be the minimizer of $R(f)$ over all $f\in\mathcal{F}$, and $f_n\in\mathcal{F}$ the minimizer of $R_n(f)$ over all $f\in\mathcal{F}$.
For simplicity assume that $f(z)\in[0,1]$ for all $z$. Hoeffding's Inequality says that for all $\delta\in(0,1]$, for a fixed $f\in\mathcal{F}$,
$$
\mathbb{P}\left(\left|R(f)-R_n(f)\right|\le\sqrt{\frac{\log(2/\delta)}{2n}}\right)\ge 1-\delta.
$$
However, this result does not say anything about $|R(f_n)-R_n(f_n)|$ because $f_n$ is random.
My question: Is there any concrete example showing that $|R(f_n)-R_n(f_n)|$ does not obey the bound $\sqrt{\log(2/\delta)/(2n)}$ with probability $1-\delta$?
Comment: >> "Let $f^*\in\mathcal{F}$ be the minimizer of $R(f)$ over all $f\in\mathcal{F}$, and $f_n\in\mathcal{F}$ the minimizer of $R(f)$ over all $f\in\mathcal{F}$."

Is $f_n$ a minimizer of $R_n(f)$? Otherwise, it's the same as $f^*$.
Comment: Yes you are right. It's a typo.
Answer: The problem isn't so much finding an example -- the result will typically fail for some $n$ and $\delta$ when ${\cal F}$ has more than one entry -- as doing the calculations when most of the available tools are designed to give upper bounds.
Here's a ridiculously extreme version: for every finite set of points $S$ in $\mathbb R$ define a function $f_S(z)$ that is 0 if $z\in S$ and 1 otherwise. Let $\cal F$ be the set of such functions. Then $f_n$ will be a function that is 0 at every observed point, giving $R_n(f_n)=0$ a.s.
On the other hand, since all finite sets have measure zero, for any fixed $f_S$ we will observe no points in $S$ (a.s.) and have $f(Z_i)=1$ a.s and so $R(f)=1$.
This does illustrate what causes the problem: overfitting. When ${\cal F}$ has multiple competing $f$s, the one that gets chosen as $f_n$ will typically have  $R_n(f_n)<R(f_n)$, because that's how it got chosen.
Comment: Thanks for the nice example! In the last formula do you mean $R_n(f_n)<R_n(f)$? Also, it seems that in this example every $f\in\mathcal{F}$ minimizes $R(f)$.
Comment: Every $f$ has $R(f)=1$, so in  that sense every $f$ minimises $R(f)$, but not $R_n(f)$. I assumed you meant $f_n$ minimised $R_n$, because otherwise $f_n$ and $f^*$ are defined identically.


Is there a multivariate t distribution with four parameters?

Question: In the appendix A.2 of this paper (page 27), a multivariate t distribution with 4 parameters is mentioned. This definition is a little different from what I have seen. for example see Wikipedia .
There is this $S^{*}$ which is used instead of $v$ (degree of freedom) in the nominator and the bracket. Is it a generalization of multivariate t distribution?
Edit
The distribution in the paper is the following:
$$p(x|\mu,\Sigma,\nu,S^{*})=\frac{\Gamma\left[(\nu+p)/2\right]}
{\Gamma(\nu/2)
(S^{*})^{-\frac{v}{2}}
\pi^{p/2}
\left|{\Sigma}\right|^{1/2}}
\left[(S^{*})+({\mathbf x}-{\boldsymbol\mu})^T{\Sigma}^{-1}({\mathbf x}-{\boldsymbol\mu})\right]^{-(\nu+p)/2}$$
in which $x:p\times 1$. What is the role of $S^{*}$ here? This does not enter the standard definition.
Answer: Actually you can see the definition give in S. Kotz, S. Nadarajah Multivariate $t$-Distributions and Their Applications:
"
...
A $p$-dimensional random vector $\vec{X}= (X_i\ldots X_p)$ is said to have the $p$-variate $t$-distribution with degrees of freedom $\nu$, mean vector $\mu$, and correlation matrix $R$ (and with $\Sigma$ denoting the corresponding covariance matrix) if its joint probability density function (pdf) is given by
$$\frac{\Gamma\left[(\nu+p)/2\right]}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}\left|{R}\right|^{1/2}}\left[1+\frac{1}{\nu}({\mathbf x}-{\boldsymbol\mu})^T{R}^{-1}({\mathbf x}-{\boldsymbol\mu})\right]^{-(\nu+p)/2}$$..."
So in you case you have an $l$-variate $t$-distribution with mean vector $\tilde{Z}\gamma_1$, with $S^{*}$ degrees of freedom and correlation matrix $\mathrm I +\tilde{Z}(M^*\!)\tilde{Z'}$.
Well, you have
$$\frac{\Gamma\left(\frac{m+l}{2}\right)(S^*)^{\frac{m}{2}}}{\Gamma(\frac{m}{2})
\pi^{\frac{l}{2}} \left|\mathrm I +\tilde{Z}(M^*\!)\tilde{Z'}\right|^{1/2}}
\left[(S^{*})+(\tilde{{\mathbf y}}-\tilde{Z}\gamma_1)^T{\left|\mathrm I +\tilde{Z}(M^*\!)\tilde{Z'}\right|}^{-1}(\tilde{{\mathbf y}}-\tilde{Z}\gamma_1)\right]^{-\frac{m+l}{2}}$$
So if we pull $S^*$ out of the brackets and normalize the correlation matrix by setting $\Sigma=\frac{\left|\mathrm I +\tilde{Z}(M^*\!)\tilde{Z'}\right|S^*}{m}$ one will obtain
$$\frac{\Gamma\left(\frac{m+l}{2}\right)\left(\frac{m}{S^*}\right)^{\frac{l-1}{2}}}{\Gamma(\frac{m}{2})
\pi^{\frac{l}{2}} m^{\frac{l}{2}}\left|\Sigma\right|^{1/2}}
\left[1+\frac{1}{m}(\tilde{{\mathbf y}}-\tilde{Z}\gamma_1)^T{\left|\Sigma\right|}^{-1}(\tilde{{\mathbf y}}-\tilde{Z}\gamma_1)\right]^{-\frac{m+l}{2}}$$
Then up to the scaling factor (normalizing constant) of $\left(\frac{m}{S^*}\right)^{\frac{l-1}{2}}$ which does not depend on observations you will get the $l$-variate $t$-distribution with $m$ degrees of freedom.
Comment: Thanks. My problem is with the $S^{*}$ in that papers definition. Please see my edit.
Comment: Check for the update. Is this what you were seeking?
Comment: Thanks a lot. Of course, I think it should be $\Sigma=\frac{\left|\mathrm I +\tilde{Z}(M^*\!)\tilde{Z'}\right|S^*}{m}$ and the scaling factor is $\left(\frac{m}{S^{*}}\right)^{\frac{l-1}{2}}$. I have one more question and I will be grateful if you answer. What is the role of this scaling factor?
Comment: Well, yes, you are right, it's my inadvertence. Hard to do it without a pen, just online. :) I've corrected it. About scaling factor. You see that in bayesian inference you have to perform normalization of the posterior pdf of the parameter under estimation. So if you perfrom it in your case you probably get this scaling factor and after dividing by this normalization constant you will get rid of it.


Como fechar um modal ao pressionar a tecla "ENTER"

Question: Como posso fechar um modal em bootstrap usando a tecla enter:
o código que estou usando é o seguinte:

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            @if (ViewBag.Success == true) {

Sucesso

            }
            else {

Erro

            }

            @if (ViewBag.Success == true) {

Um email foi enviado para @ViewBag.EmailLabel contento instruções para redefinir sua senha.

            }
            else {

Não foi possível enviar um email para @ViewBag.EmailLabel contento instruções para redefinir sua senha.

Por favor, contate a equipe de suporte do sistema PRODANÇA.

            }

            <button type="button" data-dismiss="modal" aria-hidden="true" class="btn btn-primary btn-min-size">OK</button>

Comment: Se a minha resposta te ajudou de alguma maneira, marque como aceita.
Answer: Desse jeito, o evento keypress vai ficar monitorando sempre que alguma tecla é pressionada, e quando for o enter (código 13), irá fechar o modal.

$(document).ready(function() {
  $(document).on('keypress', function(e) {
    if(e.keyCode == 13) {
      $('.modal').modal('hide');
    }
  });
});

Comment: Funcionou perfeitamente.


Hide 'previous' on first and 'next' on last image in views slideshow

Question: I create slideshow using Views Slideshow module, controls are enabled (previous, next), I enable and 'End slideshow after last slide' in settings.
Now, how I can hide 'previous' text on first image in slide and 'next' text on the last image in slide?
Answer: Easiest way out is to use css. Hide the control when you don't need it.The particular element can be found by a simple inspection. Hope it helps.
display:none;

Another alternative is to use the slideshow API to customise the behaviour. You can start here.
Comment: I hide 'pause' like that but for control elements (previous, pause, next) I can't find any parent class or id that is related with slide image, control elements are separated...slideshow API probably can help but I have no clue how to do that...
Comment: Oops sorry about that. The API allows you to write your own custom function to control some aspects of the slideshow. Time allowing I might script one for you as a starter. Let me look at the CSS classes and see what they got :-)
Comment: you can see on [this page](http://wizard.whitecircle-design.com/flavia)...thanks
Answer: I resolve problem using jQuery, there is code that I use in my case:
jQuery(document).ready(function($){

function Left() {
    if ($('#views_slideshow_cycle_div_slide-block_1_0').css('display') == 'block') {
    $("#views_slideshow_controls_text_previous_slide-block_1").css({"visibility": "hidden"});
}
else {
$("#views_slideshow_controls_text_previous_slide-block_1").css({"visibility": "visible"});
}
};

function Right() {
    if ($('#views_slideshow_cycle_div_slide-block_1_2').css('display') == 'block') {
    $("#views_slideshow_controls_text_next_slide-block_1").css({"visibility": "hidden"});
}
else {
$("#views_slideshow_controls_text_next_slide-block_1").css({"visibility": "visible"});
}
};

window.setInterval(function(){
    Left();
    Right();
}, 10);

});

Because 'previous' is visible until page is fully loaded and then disappear, I add to css:
#views_slideshow_controls_text_previous_slide-block_1 {
   visibility: hidden;
}

There is one problem, in example above 'block_1' is views slideshow block, number after '_0' tell that is first slide item and '_2' tell that is third item, so you must change '_2' every time when is number of slide items is changed. For me that code resolve problem because I have only three images in slide and that wasn't ever change.
Maybe someone have better solution or can help fix this problem?
Comment: Smell code, I've never use views slideshow before, but guess [this issue](https://drupal.org/node/990336) may help you.
Answer: In case someone is still looking for it's solution then here it is.
First you need to add json2 library with json2.js file inside it.
This will give jQuery Cycle Custom Options in your slideshow settings.
There under the Advanced options select after and under Advanced option value add following script:
var index = options.currSlide;
    $('#prev')[index == 0 ? 'hide' : 'show']();
    $('#next')[index == options.slideCount - 1 ? 'hide' : 'show']();

Here prev and next are your ids.
Update Advanced options and you are good to go.


Updating a pom.xml version during the buildr release process

Question: I have a buildr project, that also contains a pom.xml that is used for other projects.
I want to be able to increment the 13.3.1-SNAPSHOT in the pom.xml at the same time as I increment the buildfile VERSION_NUMBER = "13.3.1-SNAPSHOT".
VERSION_NUMBER in My buildfile
# Auto-incremented by "release" task.
VERSION_NUMBER = "13.3.1-SNAPSHOT"

The command my Jenkins job executes to run this release:
buildr clean release NEXT_VERSION=$nextVersion --trace

After looking at the buildr site: http://buildr.apache.org/releasing.html
It appears that I might need to do something like
Release.next_version = lambda do |next_version| # 13.3.1-SNAPSHOT
    new_version = @NEXT_VERSION@.split(/\./)
    new_version[0] = new_version[0] + 1
    new_version

    ### Run task to update pom.xml <version>
    ### Run task commit pom.xml ???
end

Can anyone assist me with this?
How I can edit the pom during the same release?
Comment: when accessing environment arguments via ruby, you normally use the `ENV` constant. in your case this would be `ENV['NEXT_VERSION']`
Answer: you could edit the pom file to increase the version during the release task or the Release.next_version call.
# code is untested, should just provide an idea
def replace_version(content)
    content.gsub(...)
end
File.open("pom.xml", "r+") { |f| f.write(replace_version(f.read)) }

Answer: Release.next_version is meant just for determining the next version number if you execute buildr release.
Have a look at the Buildr::Release class halfway down lib/buildr/core/build.rb. You should probably extend the method update_version_to_next. Have a look at the various extensions of the release class (just below it) for ideas on how to do the extending.


Como customizar as tags og(Open Graph) na pagina do post - Wordpress

Question: Estou criando um template do zero para Wordpress, mas gostaria de alterar o conteúdo das tags og de acordo com o conteudo do post, ou seja definir imagem titulo e descrição
Agradeço desde já
Comment: Já pensou em utilizar o plugin [Wordpress SEO](https://wordpress.org/plugins/wordpress-seo/)?
Answer: A recomendação no Guideline para Desenvolvimento de Themes é para separar funcionalidade do desenho. Coisas como SEO e Shortcodes não pertencem em themes, pois ao trocar de theme -que acontece com frequencia- o site perde essas funcionalidades, precisando ser migradas de um theme a outro. Mesmo que você esteja desenvolvendo seu próprio theme, muito provavelmente vai desenvolver outro em algum momento do futuro.
O que é mais indicado no desenvolvimento do theme é seguir o Guia de SEO para Themes (mirror) do Yoast. E mesmo sendo um theme developer nada impede criar plugins que trabalhem com seus themes.
Isso dito, o que o plugin WordPress SEO faz é imprimir as tags na  usando o action hook wp_head.
Aqui, comecei a enxugar a classe completa onde o plugin cuida dessa saída. É necessário conferir os outros métodos dentro da classe para completar as meta tags. O código está comentado e cada tag que falta tem o nome do método onde se pode conferir como Yoast lida com cada meta property.
<?php
/**
 * Plugin Name: (SOPT) OG Meta Tags
 */

add_action( 'wp_head', 'sopt_32080_head', 1 ); // Prioridade 1, imprime o antes possível

function sopt_32080_head()
{
    # POST ATUAL
    # as Conditional Tags como is_front_page, is_archive, is_singular, etc, cuidarão de saber qual a página atual
    # http://codex.wordpress.org/Conditional_Tags
    global $post;

    # LINGUAGEM
    echo '<meta property="og:locale" content="pt_BR" />' . "\n";

    # TIPO
    if ( is_front_page() || is_home() ) {
        $type = 'website';
    } elseif ( is_singular() ) {
        $type = 'article';
    }  else {
        // We use "object" for archives etc. as article doesn't apply there
        $type = 'object';
    }
    echo '<meta property="og:type" content="' . $type . '" />' . "\n";

    # TITULO
    if ( is_singular() ) {
        $title = 'Article - ' . $post->post_title;
    } else if ( is_front_page() ) {
        $title = 'Website - ' . get_bloginfo('name');
    } else {
        $title = 'Outro tipo de página';
    }
    echo '<meta property="og:title" content="' . $title . '" />' . "\n";

    # TODO: OUTRAS TAGS

    # fb:app_id ou fb:admins
    // public function site_owner()

    # og:description
    // public function description()

    # og:url
    // public function url()

    # og:site_name
    // public function site_name()

    # article:publisher
    // public function website_facebook()

    # ARTIGOS INDIVIDUAIS
    if ( is_singular() && ! is_front_page() ) {
        # article:author
        // public function article_author_facebook()

        # article:tag
        // public function tags()

        # article:section
        // public function category()

        # article:published_time e article:modified_time e og:updated_time
        // public function publish_date()
    }

    # og:image
    // public function image()
}

Comment: Valeu! cara era isso que precisava. XD


selendroid: unable to inspect the element

Question: Hi i'm a new bee in Selendroid can someone please tell me why im getting this error when i launch the URL http://localhost:4444/inspector .. my automation works fine but im unable to view the app in http://localhost:4444/inspector link (during added a break point into the test code and run the test in debug mode) can someone please help on this.
INFO: inspector screenshot handler, sessionId: b93ee863-3b05-0fed-73a3-eaeadb6fa1c5
io.selendroid.exceptions.AndroidDeviceException: Device not accessible via ddmlib.
    at io.selendroid.android.impl.AbstractDevice.takeScreenshot(AbstractDevice.java:363)
    at io.selendroid.server.model.SelendroidStandaloneDriver.takeScreenshot(SelendroidStandaloneDriver.java:531)
    at io.selendroid.server.handler.InspectorScreenshotHandler.handle(InspectorScreenshotHandler.java:56)
    at io.selendroid.server.SelendroidServlet.handleRequest(SelendroidServlet.java:140)
    at io.selendroid.server.BaseServlet.handleHttpRequest(BaseServlet.java:70)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:78)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:62)
    at org.webbitserver.handler.PathMatchHandler.handleHttpRequest(PathMatchHandler.java:33)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:78)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:62)
    at org.webbitserver.handler.DateHeaderHandler.handleHttpRequest(DateHeaderHandler.java:21)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:78)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:62)
    at org.webbitserver.handler.ServerHeaderHandler.handleHttpRequest(ServerHeaderHandler.java:25)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:78)
    at org.webbitserver.netty.NettyHttpControl.nextHandler(NettyHttpControl.java:67)
    at org.webbitserver.netty.NettyHttpChannelHandler$2.run(NettyHttpChannelHandler.java:72)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Thanks in advance
Answer: I am also having the same issue , but I am using physical  device. I slowed this issue, solunion is clenched the temp folder and really start the selendroid  server, then it works fine. This thing working fine with me, try this way may be it helps hope so..
Comment: Venkataramana, try with the latest version of Selendroid may fix your problem


How to override  ad_adapi() in custom module

Question: Currently, in my custom module that depends from the Advertisement module, I have permissions case, and I want to add statics_increament in my custom module.
How can I override ad_adapi()?
Answer: As the Advertisement module invokes that hook using module_invoke_all('adapi', 'permissions'), and it doesn't use drupal_alter('adapi'), your module could override that implementation of hook_adapi() using code similar to the following one. (I assume the short name of your custom module is "custom_module"; change it to the short name you are using for your module.)
function custom_module_adapi($op, $node = NULL) {
  switch ($op) {
    case 'permissions':
      return array(
        'access statistics' => TRUE,
        'access click history' => TRUE,
        'access activity log' => TRUE,
        'set status as pending' => FALSE,
        'set status as denied' => FALSE,
        'set status from pending to approved' => FALSE,
        'set status from pending to denied' => FALSE,
        'set status from approved to active' => TRUE,
        'set status from approved to offline' => TRUE,
        'set status from active to offline' => TRUE,
        'set status from active to expired' => FALSE,
        'set status from offline to active' => TRUE,
        'set status from offline to expired' => FALSE,
        // Add your permissions.
      );
      break;
  }
}

function custom_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'adapi') {
    // Move custom_module_module_adapi() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['custom_module'];
    unset($implementations['custom_module']);
    $implementations['custom_module'] = $group;
  }
}

custom_module_adapi() is completely overriding the values returned from ad_adapi(); for this reason, it cannot simply add the extra values it needs.
The code I wrote is a kind of hack; the correct way would be for the Advertisement module to use drupal_alter() to allow third-party modules to override the values set from other modules. The code I wrote works, but you need to keep update the code for custom_module_adapi() with the code used in ad_adapi(), in the case it is changes.
Only the branch 7.x-1 has ad_adapi(); the branch 7.x-2 doesn't have that function anymore. If you are planning to use that branch, the code for your custom module should be changed.


Watanabe–Akaike/widely applicable information criterion (WAIC) using PyMC

Question: Does anyone know how to calculate WAIC in a PyMC model? Several review papers suggest that it requires sampling from the predictive density, which is relatively straightforward in PyMC, so can WAIC be calculated easily too?
Answer: You can use the following function:
<code>def waic(trace, model=None):
     """
     Calculate the widely available information criterion of the samples in trace from model.
     """
     model = pm.modelcontext(model)

     log_py = []
     for obs in model.observed_RVs:
         log_py.append([obs.logp_elemwise(pt) for pt in trace ])
     log_py = np.hstack(log_py)

     lppd =  np.sum(np.log(np.mean(np.exp(log_py), axis=0)))

     p_waic = np.sum(np.var(log_py, axis=0))

     return -2 * lppd + 2 * p_waic
</code>
That will be soon part of PyMC3.


How to hide time from the date display?

Question: In a view using Articles and Blog posts sorted by recent post date, I'm using [Content: Post date] and I would like to display (as a column on the display) as only the date and not the time, i.e. 2016/04/08.
I merely wish to alter what data Drupal is displaying, not the data it is collecting.
How can I apply this date format to the field in the view?
In Home>Administration>Date and Time, I can add new date type but all 19 of the options include displays of time.
Answer: There should also be a Formats tab at the top of that page. Here you can add additional formatting (like date or time only formats). After saving the format, go back to the first page and now you can select your newly created format as an option.
Comment: I see @Neograph734! I didn't even see that tab on the right side. Neverthe less, mine was emply. It also directs people to review the PHP manual.  I think your solution is ultimately better than mine because it will be available when I next want to use it for something else.
Comment: Yes that is correct, you need to create them yourself. The PHP manual provides details on what tokens to use. Depending on your locale I cannot give you a simple code. It is really easy. You are probably looking for something like `D M d`.
Answer: Aha! Minutes after I post, I discover something else.
In the configuration of the Date Field in the Fields section of the View, I have more features, namely the ability to create a Custom Date format (no Custom in the Amin>Date and Time).
Selecting custom, I used this excellent manual http://php.net/manual/en/function.date.php

How to hide time from the date display?


Multi Effect device with tube

Question: I have used a VOX Tonelab LE for almost ten years, and it starts to fall apart. Therefore I'm looking for a replacement. In my view, VOX used to stand out among modelling amps by adding a tube, thus creating very good distortion sounds. My question is whether there is anything comparable nowadays in terms of

flexibility, i.e. all common effects (chorus, flanger, delay, reverb, phaser, ...) are on boad
high quality amp models

I also need a fairly "large" board with several foot switches and an expression pedal.
I realize that modelling technique has improved in the meantime, so can I expect all this (in particular nice distortions) from Line 6/Boss/... pedals that do not have an integrated tube?
Comment: I recently sold my old Tonelab. The newer stuff sounds better because it's all digital either way and the tube was really just a gimmick. Check out the new modeling devices at a store if you can. Unfortunately, this question is off topic here because we don't do gear recommendations. Just let go of the tube idea and go through a more open minded product selection process.
Answer: Although it is not the latest model, the Zoom G5 (not the G5n) is a great choice and it includes an actual 12AX7 tube to add color to the sound.  In addition, it is incredibly easy to use and allows you to adds up to 9 effects in any order, and you can even have the same effect more than once in your effects chain.  And it is affordable.  Good luck.  :-)
Comment: Hi Carl - while you have obviously helped, we ask that people don't answer obviously off topic questions, as it encourages more.

Multi Effect device with tube


Issues with OpenSessionInView

Question: I have implemented Spring/Hibernate's OpenSessionInView Pattern for Lazy Loading.  I am facing either "No Sessoon" or "2 or more sessions" issue.  Let me know If I am missing any steps:
Here are detail code fragments:
Web.XML
<code>      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
      </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

      <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
          <param-name>singleSession</param-name>
          <param-value>false</param-value>
        </init-param>
        <init-param>
          <param-name>flushModeName</param-name>
          <param-value>FLUSH_AUTO</param-value>
        </init-param>
        <init-param>
          <param-name>sessionFactoryBeanName</param-name>
          <param-value>sessionFactory</param-value>
        </init-param>
      </filter>

       <filter-mapping>
         <filter-name>hibernateFilter</filter-name>
         <url-pattern>/*</url-pattern>
         <dispatcher>REQUEST</dispatcher>
         <dispatcher>FORWARD</dispatcher>
       </filter-mapping>
</code>
applicationContext.xml
<code><!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan"
        value="com.mypack.common.model, com.mypack.school.model" />
        .
        .
        <!-- Other properties -->
        .
</bean>
</code>
customer.xhtml
XHTML user interface has autocomplete box showing customer code. Autocomplete query make use of CompleteCustomer Method, whereas getCustomerbyCode is called by converter bean.
Upon selection of cust code, screen is populated by selected customer details. Application User is allowed to make changes and save updates in DB.
CustomerBean.java
<code>@ManagedBean (name="customerBean")
@ViewScoped
public class CustomerBean implements Serializable {

    public List<Customer> completeCustomer(String query) {
        List<Customer> suggestions;

        suggestions = (List<Customer>) customerService.getCustomerslikeCodeOrName(query, authenticationBean.getTenantId());

        return suggestions;
    }

    public void saveCustomerDetails() {
        // Save or Update User Information in Database
        customerService.saveCustomer(custMaster);
        return;
    }
</code>
CustomerServiceImpl.java
<code>@Service("customerService")
@Transactional(readOnly = true, propagation=Propagation.REQUIRED)
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerDAO custMasterDAO;

    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public void saveCustomer(Customer custDetails) {
        custMasterDAO.saveCustomer(custDetails);
    }

    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        return custMasterDAO.getCustomerbyCode(custCode, tenantId);
    }

    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        return custMasterDAO.getCustomerslikeCodeOrName(custIDName, tenantId);
    }
}
</code>
CustomerMasterDAO.java
<code>    @SuppressWarnings("unchecked")
    @Override
    public List<Customer> getCustomerslikeCodeOrName(String custIDName, TenantId tenantId) {
        List<Customer> listCustomers = null;
        custIDName = "%" + custIDName + "%";

        Session session = SessionFactoryUtils.getSession(sessionFactory, false);
        Transaction tx = session.beginTransaction();

        try {
            query = session.createQuery("from Customer " +
                    "where (custId like :codename " +
                    "or custFirstName like :codename " +
                    "or custMiddleName like :codename " +
                    "or custLastName like :codename)")
                .setParameter("codename", custIDName);
            listCustomers = query.list();

        } catch(Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerslikeCodeOrName ***" + ex.getMessage());
        }

        return listCustomers;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Customer getCustomerbyCode(String custCode, TenantId tenantId) {
        List<Customer> list = null ;
        Query query;

        Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
        Transaction tx = session.beginTransaction();

        Filter sessionFilter = session.enableFilter("BankRecordFilter");
        sessionFilter.setParameter("bankCode", tenantId.getBankCode());

        try {
            query = session.createQuery("from Customer where custId = :custCode");
            list = query.setParameter("custCode", custCode).list();
        } catch (Exception ex) {
            tx.rollback();
            System.out.println("*** getCustomerbyCode ***" + ex.getMessage());
        }
        if (list == null || list.size() < 1){
//          System.out.println("No Records Found");
            return null;
        }
        return (Customer)list.get(0);
    }

    @Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }

    }
</code>
Table definations are stored in .hbm.xml files.
I have tried lot of combinations of placing following statements to get session:
    session = getSessionFactory().getCurrentSession();
    Session session = SessionFactoryUtils.getSession(sessionFactory, Boolean.FALSE);
Also transaction in different ways and different location.  I am  either getting error messages for No Session or Two or more sessions are attached error message.
Can you please let me know what is wrong with my code.
Regards,
Shirish
Answer: Finally I am able to use OpensessionInView.  After spending lot of time on this issue, I observed that LAZY loading was working as per expection, but when I am trying to save date, Session was not properly propagted.
After updating propagation strategy, code started working..  Here is updated code
<code>@Transactional(readOnly = false,propagation = Propagation.NESTED)
@Override
    public void saveCustomer(Customer custDetails) {
        Session session = getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        try {
            session.saveOrUpdate("bkCustomer", custDetails);
            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
        }
</code>
Answer: You are mixing annotations for transaction handling and programmatic transaction handling.  Looks like your annotations are simply not used...

Issues with OpenSessionInView


How to use onclick event for a button generated through a template?

Question: Testing underscore.js. Using its templating engine.  Problem is, I am unable to use the on-click listener, written with jquery.AJAX when the button is drawn from within the template. Here the code:

Hi There

    Say Hello

Now, in the above code when I click on  SAY HELLO link Say Hello, the template is successful drawn and shows Hello rickesh along with a button. But when I click on the button nothing happens. Have I used the listener incorrectly? I want an action to be performed on the button click. Please advice.
Answer: Use delegation with .on() :
$(function(){
    $(document).on('click','#helloAgain',function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });
});

Answer: I think you should create the event listener after creating the html element, probably like this :
$('a#helloThere').click(function(event){
    event.preventDefault();
    var name='rickesh';
    var templateData=$('#sayHello').text();
    var compiled=_.template(templateData,{'data':name});
    $('#helloDiv').html(compiled);

    $('button#helloAgain').click(function(event){
        event.preventDefault();
        alert('hello again bro!!!');
    });

});


AlarmManager - Notificação em tempo específico

Question: Estou tentando fazer disparar uma mensagem na tela através do AlamManager e BroadCastReceiver.
O tempo específico está sendo pego por um TimePicker exatamente como deve.
Mas a notificação acaba não sendo disparada na tela.
O código está dessa maneira:
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
    Calendar calNow = Calendar.getInstance();
    Calendar calSet = (Calendar) calNow.clone();
    calSet.setTimeInMillis(System.currentTimeMillis());
    calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
    calSet.set(Calendar.MINUTE, minute);
    calSet.set(Calendar.SECOND, 0);
    calSet.set(Calendar.MILLISECOND, 0);

    setAlarm(calSet);
}

private void setAlarm(Calendar targetCall)
    {
        Toast.makeText(this, "Alarm is set at" + targetCall.getTime(),
                Toast.LENGTH_LONG).show();
        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);

        PendingIntent pendingintent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCall.getTimeInMillis(), pendingintent);
    }

E a classe do BroadcastReceiver está dessa maneira:
public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Toast.makeText(arg0, "Your Time is up!!!!!", Toast.LENGTH_LONG).show();
    }
}

Comment: Sua classe `AlarmReceiver` está declarada no `AndroidManifest.xml`? ``
Comment: não estava com receiver, não prestei atenção nisso, obrigado :D
Comment: Agora está tudo como deveria :D
Comment: Ok, vou colocar como resposta.
Answer: Inclua o <receiver> no AndroidManifest.xml:
<receiver android:name="pacote.onde.está.a.classe.AlarmReceiver" />