text:
Q: Prime numbers in a given range Recently, I was given a task to print all the prime numbers (1-100). I failed drastically there. My Code:
Create Procedure PrintPrimeNumbers
@startnum int,
@endnum int
AS
BEGIN
Declare @a INT;
Declare @i INT = 1
(
Select a = @startnum / 2;
WHILE @i<@a
BEGIN
@startnum%(@a-@i)
i=i+1;
)
END

Though I ended up without completing it, I wonder is it feasible to do such programs on Database (SQL Server 2008 R2).
If yes, how it may end.

A: A simple but not very efficient way to return the prime numbers in the range 2-100 (1 is not prime) would be
WITH Ten AS (SELECT * FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) V(N)),
     Hundred(N) AS (SELECT T1.N * 10 + T2.N + 1 FROM Ten T1, Ten T2)
SELECT H1.N
FROM   Hundred H1
WHERE  H1.N > 1
       AND NOT EXISTS(SELECT *
                      FROM   Hundred H2
                      WHERE  H2.N > 1
                             AND H1.N > H2.N
                             AND H1.N % H2.N = 0);

You could also potentially materialise the numbers 2-100 in a table and implement the Sieve of Eratosthenes via repeated updates or deletes.

A:
I wonder is it feasible to do such programs on Database

Yes, it is feasible but I don't think T-SQL is the right tool for the job.  Below is an example of a set-based approach in T-SQL for this problem.
CREATE PROC dbo.PrintPrimeNumbers
    @startnum int,
    @endnum int
AS
WITH
     t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n))
    ,t256 AS (SELECT 0 AS n FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d)
    ,t16M AS (SELECT ROW_NUMBER() OVER (ORDER BY (a.n)) AS num FROM t256 AS a CROSS JOIN t256 AS b CROSS JOIN t256 AS c)
SELECT num
FROM t16M AS Dividend
WHERE
    Dividend.num <= @endnum
    AND NOT EXISTS(
        SELECT 1
        FROM t16M AS Divisor
        WHERE
            Divisor.num <= @endnum
            AND Divisor.num BETWEEN 2 AND SQRT(Dividend.num)
            AND Dividend.num % Divisor.num = 0
            AND Dividend.num <= @endnum
    );
GO
EXEC dbo.PrintPrimeNumbers 1, 100;
GO

A: By far the quickest and easiest way to print "all the prime numbers (1-100)" is to fully embrace the fact that prime numbers are a known, finite, and unchanging set of values ("known" and "finite" within a particular range, of course). At this small of a scale, why waste CPU each time to calculate a bunch of values that have been known for a very long time, and take up hardly any memory to store?
SELECT tmp.[Prime]
FROM   (VALUES (2), (3), (5), (7), (11), (13),
        (17), (19), (23), (29), (31), (37), (41),
        (43), (47), (53), (59), (61), (67), (71),
        (73), (79), (83), (89), (97)) tmp(Prime)

Of course, if you do need to calculate the prime numbers between 1 and 100, the following is fairly efficient:
;WITH base AS
(
    SELECT tmp.dummy, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS [num]
    FROM   (VALUES (0), (0), (0), (0), (0), (0), (0)) tmp(dummy)
), nums AS
(
    SELECT  (ROW_NUMBER() OVER (ORDER BY (SELECT 1)) * 2) + 1 AS [num]
    FROM        base b1
    CROSS JOIN  base b2
), divs AS
(
    SELECT  [num]
    FROM        base b3
    WHERE   b3.[num] > 4
    AND     b3.[num] % 2 <> 0
    AND     b3.[num] % 3 <> 0
)
SELECT  given.[num] AS [Prime]
FROM        (VALUES (2), (3)) given(num)
UNION ALL
SELECT  n.[num] AS [Prime]
FROM        nums n
WHERE   n.[num] % 3 <> 0
AND     NOT EXISTS (SELECT *
                    FROM divs d
                    WHERE d.[num] <> n.[num]
                    AND n.[num] % d.[num] = 0
                    );

This query only tests odd numbers as even numbers won't be prime anyway. It is also specific to the range of 1 - 100.
Now, if you need a dynamic range (similar to what is shown in the example code in the question), then the following is an adaptation of the query above that is still rather efficient (it calculated the range of 1 - 100,000 -- 9592 entries -- in just under 1 second):
DECLARE  @RangeStart INT = 1,
         @RangeEnd INT = 100000;
DECLARE  @HowMany INT = CEILING((@RangeEnd - @RangeStart + 1) / 2.0);

;WITH frst AS
(
    SELECT  tmp.thing1
    FROM        (VALUES (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) tmp(thing1)
), scnd AS
(
    SELECT  0 AS [thing2]
    FROM        frst t1
    CROSS JOIN frst t2
    CROSS JOIN frst t3
), base AS
(
    SELECT  TOP( CONVERT( INT, CEILING(SQRT(@RangeEnd)) ) )
            ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS [num]
    FROM        scnd s1
    CROSS JOIN  scnd s2
), nums AS
(
    SELECT  TOP (@HowMany)
            (ROW_NUMBER() OVER (ORDER BY (SELECT 1)) * 2) +
                (@RangeStart - 1 - (@RangeStart%2)) AS [num]
    FROM        base b1
    CROSS JOIN  base b2
), divs AS
(
    SELECT  [num]
    FROM        base b3
    WHERE   b3.[num] > 4
    AND     b3.[num] % 2 <> 0
    AND     b3.[num] % 3 <> 0
)
SELECT  given.[num] AS [Prime]
FROM        (VALUES (2), (3)) given(num)
WHERE   given.[num] >= @RangeStart
UNION ALL
SELECT  n.[num] AS [Prime]
FROM        nums n
WHERE   n.[num] BETWEEN 5 AND @RangeEnd
AND     n.[num] % 3 <> 0
AND     NOT EXISTS (SELECT *
                    FROM divs d
                    WHERE d.[num] <> n.[num]
                    AND n.[num] % d.[num] = 0
                    );

My testing (using SET STATISTICS TIME, IO ON; ) shows that this query performs better than the other two answers given (so far):
RANGE: 1 - 100
Query      Logical Reads       CPU Milliseconds    Elapsed Milliseconds
-------    ----------------    ----------------    -----------------

Solomon      0                 0                   0
Dan        396                 0                   0
Martin     394                 0                   1

RANGE: 1 - 10,000
Query      Logical Reads       CPU Milliseconds    Elapsed Milliseconds
-------    ----------------    ----------------    -----------------

Solomon        0                   47                170
Dan        77015                 2547               2559
Martin       n/a

RANGE: 1 - 100,000
Query      Logical Reads       CPU Milliseconds    Elapsed Milliseconds
-------    ----------------    ----------------    -----------------

Solomon            0                 984                996
Dan        3,365,469             195,766            196,650
Martin           n/a

RANGE: 99,900 - 100,000
NOTE: In order to run this test I had to fix a bug in Dan's code -- @startnum was not factored into the query so it always started at 1. I replaced the Dividend.num <= @endnum line with Dividend.num BETWEEN @startnum AND @endnum.
Query      Logical Reads       CPU Milliseconds    Elapsed Milliseconds
-------    ----------------    ----------------    -----------------

Solomon       0                   0                   1
Dan           0                 157                 158
Martin      n/a

RANGE: 1 - 100,000 (partial re-test)
After fixing Dan's query for the 99,900 - 100,000 test, I noticed that there were no more logical reads listed. So I retested this range with that fix still applied and found that the logical reads were again gone and the times were slightly better (and yes, the same number of rows were returned).
Query      Logical Reads       CPU Milliseconds    Elapsed Milliseconds
-------    ----------------    ----------------    -----------------

Dan                0             179,594            180,096

A: We can write the below code and it works:
CREATE procedure sp_PrimeNumber(@number int)
as
begin
declare @i int
declare @j int
declare @isPrime int
set @isPrime=1
set @i=2
set @j=2
while(@i<=@number)
begin
    while(@j<=@number)
    begin
        if((@i<>@j) and (@i%@j=0))
        begin
            set @isPrime=0
            break
        end
        else
        begin
            set @j=@j+1
        end
    end
    if(@isPrime=1)
    begin
        SELECT @i
    end
    set @isPrime=1
    set @i=@i+1
    set @j=2
end
end

Above I have created a Stored Procedure to obtain prime numbers.
In order to know the results, execute the stored procedure:
EXECUTE sp_PrimeNumber 100

A: DECLARE @UpperLimit INT, @LowerLimit INT

SET @UpperLimit = 500
SET @LowerLimit = 100

DECLARE @N INT, @P INT
DECLARE @Numbers TABLE (Number INT NULL)
DECLARE @Composite TABLE (Number INT NULL)

SET @P = @UpperLimit

IF (@LowerLimit > @UpperLimit OR @UpperLimit < 0 OR @LowerLimit < 0 )
    BEGIN
        PRINT 'Incorrect Range'
    END
ELSE
    BEGIN
        WHILE @P > @LowerLimit
            BEGIN
                INSERT INTO @Numbers(Number) VALUES (@P)
                SET @N = 2
                WHILE @N <= @UpperLimit/2
                    BEGIN
                        IF ((@P%@N = 0 AND @P <> @N) OR (@P IN (0, 1)))
                            BEGIN
                                INSERT INTO @Composite(Number) VALUES (@P)
                                BREAK
                            END
                        SET @N = @N + 1
                    END
                SET @P = @P - 1
            END
        SELECT Number FROM @Numbers
        WHERE Number NOT IN (SELECT Number FROM @Composite)
        ORDER BY Number
        END


text:
Q: Xcode UI Testing: staticText's label not updating as text is updated? Background
I am investigating migration of our Appium-based automation to Xcode UI Testing. Given that our app is written in Objective C I need to use Objective-C for the test code as well.
The app I am automating tests for, has a progress bar whose values I want to read. It's not a UIAProgressIndicator, just a UIAStaticText whose value increases from "0" to "100%".
The XCUIElement corresponding to this staticText can be accessed as
[[app staticTexts] elementBoundByIndex:1]

The progress bar will take different amounts of time - and I need to monitor the progress, which will involve reading the value (and parsing it of course).
I tried getting the value using various methods - [XCUIElement value] and [XCUIElement label].
NSString *prog = [[[app staticTexts] elementBoundByIndex:1] label];

The label approach is getting me the progress string, so I am doing this in a loop, for e.g.
  int i=0;
  while (i<5) {
     //custom sleep method
     [self.helper threadSleepForSeconds:[NSNumber numberWithInt:2]];
     //now get progress text
     NSString *prog = [[[app staticTexts] elementBoundByIndex:1] label];

     i++;
    }

However, as the progress changes, the label attribute does not update - it seems to keep showing the first value that was read, as though it was cached somewhere.
i.e the log output shows (assuming the first value read was 19%):
19%
19%
19%
19%

I am quite unable to figure out why this happens. Any help?

A: There is no synthesized event, so Xcode doesn't attempt to take a new snapshot of the UI elements on the screen.  This is by design so that assigning multiple ui element variables in a specific view doesn't overwork your computer.
Unfortunately, manual testing may be your only option if you're not satisfied with unit testing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: f:ajax inside rich:popupMenu can't execute component from different form I have a <rich:popupPanel> tag and inside of it I use <f:ajax> events. Therefore the <rich:popupMenu> also needs to have a <h:from> inside of it. In my ajax event I need to grab a value form the 'main page' therefore I list it in the execute list with the corresponding :formid:elementid pattern but this doesn't work - the value is null in the listener method. here is the code:
    <h:form id="form">
        ...
        <h:selectOneMenu  id="selectUser" value="#{usersBean.user_id}" styleClass="comboBoxes" >
            <f:selectItems value="#{usersBean.myModelUsersValues}" />
            <a4j:ajax event="valueChange" listener="#{usersBean.userSelected}" render="login password customer_name" execute="@this"/>
        </h:selectOneMenu >
        ...
    </h:form>
    <rich:popupPanel id="popup" modal="true" autosized="true" resizeable="false">

    <f:facet name="header">
        <h:outputText value="Atributes" />
    </f:facet>
    <f:facet name="controls">
        <h:outputLink value="#" onclick="#{rich:component('popup')}.hide(); return false;">
            X
        </h:outputLink>
    </f:facet>
    <h:form id="popupForm">
            ...
            <h:selectOneListbox  id="atrib_list" value="#{usersBean.atribSelect}" styleClass="comboBoxes" style="height:100px;width:100px;">
                        <f:selectItems value="#{usersBean.atribValues}" />
                        <f:ajax event="valueChange" listener="#{usersBean.atribValuesChanged}" render="child_list" execute="@this :form:selectUser"/>
            </h:selectOneListbox >
            ...
    </h:form>
    </rich:popupPanel>

In the usersBean.atribValuesChanged listener method the usersBean.user_id field is empty (not having the value that was selected). How can I force to execute the form:selectUser element so that I can read it's selected value in my listener method?
Part2:
This is just a btw. question, maybe I should open another thread for this. The problem is that when the <h:selectOneListBox> has only one value it is created more like a h:selectOneMenu. This looks bad and also the valueChange event is not fired when you select it. This problem does not exist in <h:selectManyListBox> is it a bug? Is it fixable?

A: That's expected behaviour, you really can't submit any data outside the form.
You can rerender JSF components outside the form (see this article), but you can't send anything outside the form to the server.
So, maybe what you want to do is to place an h:inputHidden inside the form you want to send, rerendering it in the h:selectOneMenu from the first form, and then send the idUserHidden on the form:
<h:form id="form">
    ...
    <h:selectOneMenu  id="selectUser" value="#{usersBean.user_id}"
      styleClass="comboBoxes" >
        <f:selectItems value="#{usersBean.myModelUsersValues}" />
            <!-- rerender the hidden input also: -->
            <a4j:ajax event="valueChange" listener="#{usersBean.userSelected}"
          render="login password customer_name :idUserHidden" execute="@this"/>
    </h:selectOneMenu >
    ...
</h:form>
....
<h:form>
    ....
    <!-- hidden input to submit the same value of :selectUser -->
    <h:inputHidden id="idUserHidden" value="#{usersBean.user_id}" />

    <h:selectOneListbox  id="atrib_list" value="#{usersBean.atribSelect}"
       styleClass="comboBoxes" style="height:100px;width:100px;">
        <f:selectItems value="#{usersBean.atribValues}" />
        <f:ajax event="valueChange" listener="#{usersBean.atribValuesChanged}"
          render="child_list" execute="@this idUserHidden"/>
        </h:selectOneListbox >
</h:form>


text:
Q: Running function again after route change in AngularJS So I have a main controller and two others:
calculatorApp.controller('companybController', function($scope, $http) {
  //define the hardware data
  $scope.customs.prodoc = 'companyb';
});

calculatorApp.controller('companyaController', function($scope, $http) {
  $scope.customs.prodoc = 'companya';
});

// create the controller and inject Angular's $scope
calculatorApp.controller('mainController', function($scope, $http) {
  $scope.customs = {
    prodoc : ''
  };
});

But when switching routes - this works: {{customs.prodoc}}, but it seems the function that uses it does not run again when the new view is loaded - causing the app to use the old values.
How do I run the function that uses the changing $scope.customs.prodoc again once the view has been changed?
Here's the function that uses it - I had it in mainController but not sure it belongs there.
$http.get($scope.customs.prodoc+'/products.json').success(function(thisdata) {
        $scope.products = []
        angular.forEach(thisdata, function(product) {
            $scope.products.push(product);
        });
        console.log($scope.products);
    });

$scope.change = function() {
// Suggest product
        $scope.suggested = {}
        var length = ($scope.products).length;
        for(i=0; i<length; i++){
            if($scope.products[i].CAMERA_MAX>=$scope.totals.cameras){
                $scope.suggested = $scope.products[i];
                break;
            }else{

            }

        }
}

A: I would use $routeChangeSuccess to do what you are talking about
$scope.$on("$routeChangeSuccess", function($currentRoute, $previousRoute) {
    $scope.customs.prodoc = $scope.routeParams.prodoc;
});


text:
Q: Error when request a nvarchar type in webform from SQL Server I have a table in my SQL Server database:
DOCUMENT(DOC_NUM,DOC_NAME,...)
{
 DOC_NUM: nvarchar(50);
...
}

And table DOC_NUM has one row with DOC_NUM= DD121;
And in webform I execute a query:
string docnum= "DD121";
string sql= "select * from DOCUMENT where DOC_NUM="+docnum;
Datatable doc= ....EXECUTEQUERYSQL(sql);
int count= doc.Rows.Count;

It causes an error:

An unhandled exception occurred during the execution of the current web request.

on the line of code:
int count= doc.Rows.Count;

But when I change it to:
string sql= "select * from DOCUMENT where DOC_NUM= 'DD121'";
    Datatable doc= ....EXECUTEQUERYSQL(sql);
    int count= doc.Rows.Count;

It worked fine!
I don't really know why?

A: When you use this string concatenation, your query will be DOC_NUM= DD121 instead of DOC_NUM= 'DD121' which is wrong.
And this kinf of string concatenations are open for SQL Injection attacks.
Use parameterized queries instead;
string sql= "select * from DOCUMENT where DOC_NUM = @docnum";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@docnum", docnum);

A: You get this exception because you missed single quotes when you specify  DOC_NUM value. It Should be "select * from DOCUMENT where DOC_NUM='"+docnum +"'";
These errors can be avoid by using SQL parameters and it is more secure.


text:
Q: Different Job , Sched Chain, Sched Job, Sched Windows, and Sched Job classes in Toad For Oracle Hy ..
sorry before i need ask

I can not find literature on Different Toad Job , Sched Chain, Sched Windows, Sched Job and Sched Job classes  description in Toad for Oracle. Is there any explanation about it?
this image

A: From documentation Oracle Scheduler Concepts

*

*Chains are the means by which you can implement dependency scheduling, in which job starts depend on the outcomes of one or more
  previous jobs.

*Credentials are user name and password pairs stored in a dedicated database object. Scheduler jobs use credentials to
  authenticate themselves with a database instance or the operating
  system in order to run.

*Job classes enable you to assign the same attributes to member jobs, set resource allocation for member jobs, and group jobs for
  prioritization.

*You use jobs and other scheduler objects for task scheduling.

*A program object (program) describes what is to be run by the Scheduler.

*A schedule object (schedule) specifies when and how many times a job is run. Schedules can be shared by multiple jobs. For example, the
  end of a business quarter may be a common time frame for many jobs.
  Rather than defining an end-of-quarter schedule each time a new job is
  defined, job creators can point to a named schedule.

*A window is an interval of time to run a job. You create windows to automatically start jobs or to change resource allocation among
  jobs during various time periods of the day, week, and so on. A window
  is represented by an interval of time with a well-defined beginning
  and end, such as "from 12am-6am".

*A group designates a list of Scheduler objects. Instead of passing a list of objects as an argument to a DBMS_SCHEDULER package
  procedure, you create a group that has those objects as its members,
  and then pass the group name to the procedure.

Most important is of course the SCHEDULER JOB. Personally I am using JOB and SCHEDULE. All other objects I never used so far.


text:
Q: opengl-es 1.1 or 2.0 on an Android 2.3.3 AVD? Should you be able to run an apk that uses opengl-es 1.1 or 2.0 on an Android 2.3.3 AVD? Or does the emulator not emulate opengl-es 1.1 + for 2.3.3 devices?

A: Open GL will not run on Android emulator. You'll need actual device to run it.


text:
Q: Convert display language to subfolder with htaccess For a website I have locally, I need to set the display language as if it were a subfolder, using an htaccess file.
For example, if I choose to display the site in German, instead of displaying it like this => local_ip/test/index.php?lang=de, I would like it to be displayed like this => local_ip/test/de/ .
Also, if I type in the url without setting the language, I would like htaccess to automatically redirect to the German language, from so => local_ip/test/tour/mountain/ to so => local_ip/test/de/tour/mountain .
My current htaccess file is structured as follows:
DirectoryIndex index.php
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{QUERY_STRING} ^t=(.+?)
RewriteRule ^city/(.+?)/?$ city.php?url=$1&t=%1 [NC,L]
RewriteCond %{QUERY_STRING} ^p=([0-9]+)
RewriteRule ^city/(.+?)/?$ city.php?url=$1&p=%1 [NC,L]
RewriteCond %{QUERY_STRING} ^t=(.+?)&p=([0-9]+)
RewriteRule ^city/(.+?)/?$ city.php?url=$1&t=%1&p=%2 [NC,L]
RewriteCond %{QUERY_STRING} ^c=true
RewriteRule ^city/(.+?)/?$ city.php?url=$1&c=true [NC,L]
RewriteRule ^city/(.+?)$ city.php?url=$1 [NC,L]
RewriteRule ^tour/(.+?)$ tour.php?url=$1 [NC,L]

SOLVED
After several attempts and after reading several support requests posted in this community, I found a way to make the system recognise all the other rules as well. All I had to do was put them before the last rule provided by the user who supported me. Here is the final code.
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_URI} !/de/ [NC]
RewriteRule (.*) /test/de/$1 [R,L]
RewriteRule ^de/$ /test/index.php?lang=de [L]
RewriteCond %{QUERY_STRING} ^t=(.+?)
RewriteRule city/(.+?)/?$ city.php?url=$1&t=%1&lang=de [NC,L]
RewriteCond %{QUERY_STRING} ^p=([0-9]+)
RewriteRule city/(.+?)/?$ city.php?url=$1&p=%1&lang=de [NC,L]
RewriteCond %{QUERY_STRING} ^t=(.+?)&p=([0-9]+)
RewriteRule city/(.+?)/?$ city.php?url=$1&t=%1&p=%2&lang=de [NC,L]
RewriteCond %{QUERY_STRING} ^c=true
RewriteRule city/(.+?)/?$ city.php?url=$1&c=true&lang=de [NC,L]
RewriteRule city/(.+?)$ city.php?url=$1&lang=de [NC,L]
RewriteRule tour/(.+?)$ tour.php?url=$1&lang=de [NC,L]
RewriteRule ^de/(.*)$ /test/$1 [L]

A: You can use the following :
RewriteEngine on

#redirect URLs to include /de
#RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/de/ [NC]
RewriteRule (.*) /test/de/$1 [R,L]
# /test/index.php?lang=de to /test/de
RewriteRule ^de/$ /test/index.php?lang=de [END]
RewriteRule ^de/(.+)$ /test/$1 [END]


text:
Q: Can a BLE response be returned in the same connection event? Using a BLE 4.1 device, can one receive the response to a request (e.g. read request, read blob request) within the same interval?
The task is to read more than 20 bytes in the same connection interval: I am developing an app that needs to read these bytes and display content depending on their value (with very low latency).  I am aware that commands can be stacked within the same connection event, but this is not applicable in this case.
I have been perusing the 4.1 spec without success.  Volume 3, Sections 3.3.2-3.3.3 of spec spec 4.1 specify that no request shall be made before a response is returned.  If it is true that one must wait a connection interval to receive a response, then it take at least 4 connection intervals to read a long attribute (that is more than 20 bytes).
I have found several discussions (1, 2) on the web implying that a response follows in the next connection event, but I have not found the section of the spec that describes this behavior.
I would appreciate an explanation that cites official documentation, rather than a forum or other website.

A: The answer is YES! But in most implementations NO.
In each connection event, master and slave alternate between sending and receiving packets. The master starts by sending a packet, then the slave sends its packet. Both packets may be empty if they have nothing to send. Each packets contains a header bit "more data" (MD) indicating that it would like to send yet another packet. When both the master and slave sets the MD bit to 0 in two consecutive packets, the connection event ends.
This means that in the case the slave sends a request to the master and the master has initially nothing to send, the master first sends an empty packet with MD=0 and the slave sends a packet containing a request with MD=0. In this case the response will not be sent in the same connection event.
However usually the master is also the GATT client. In this case, the master starts by sending a packet containing a request (with MD=0). After the slave receives that packet, it must reply with a packet within exactly 150 (+-2) microseconds. If the firmware is properly programmed to compute the result within this time frame it can send a response packet in the same connection event. I managed to do that myself with a nrf52 chip where I didn't use their softstack but wrote my own code that directly interacted with the RADIO peripheral. I have however so far seen no commercial stacks that manage to do this.
But many firmwares are unfortunately programmed in a way that the data to be sent must be decided even before it starts listening to the master's packet. Such firmwares will not be able to respond in the same connection event. Sometimes however if one of the two ends pushes a lot of data through notifications or write without responses, this will keep the connection event open and then some firmwares can actually send a packet if it arrived to the stack after the connection event started, but before a few packets before the connection event would otherwise end.
Now when we talk about the maximum length of the connection event, there is actually a parameter in the HCI packet "LE Create Connection" called min/max connection event length, where one can hint to the controller how much radio time it should allocate for this connection each interval. Android sets these to 0, which will make Broadcom chips select a short maximum connection event length (like 4-6 packets), but Qualcomm chips will on the other hand allow much longer connection events. If one controls the HCI packets and sets these parameters to equal the connection interval, most chips (including Broadcom) then actually allow the connection event to be as long as the interval. Apple's Core Bluetooth seems to explicitly set the max connection event length to some low value, like 2-4 ms if I'm not forgetting.
I would suggest that you never use the Read Long Characteristic procedure (requiring multiple Read Blob requests and many round trips) but rather simply send a Write to tell the peripheral to, by using notifications, send as much data it needs (and therefore stacking multiple notifications in one connection event).


text:
Q: Parsing a Pandas Dataframe I have a dataframe like this;
Table_Name,Field_Names
t_001_Projects,"['r01_P_Order', 'p_Code', 'r03_S_Name', 'r04_L_Name', 'r05_Employer']"
t_101_Milestones,"['rep_Month', 'p_Code', 'mls_Code', 'mls_Desc', 'mls_Date_Target', 'mls_Date_Current', 'mls_Progress']"
t_201_Imp_Topics,"['rep_Month', 'p_Code', 'tpc_Short', 'tpc_Long']"
t_202_Claims_and_Pnts,"['rep_Month', 'p_Code', 'cap_Doc_Type', 'cap_Doc_Date', 'cap_Name', 'cap_Explaination', 'cap_Status', 'cap_Cost', 'cap_Curr']"
t_203_Pers_Plan,"['rep_Month', 'p_Code', 'tpc_Short', 'p_Code', 'tpc_Short', 'p_Code', 'tpc_Short', 'p_Code', 'tpc_Short', 'p_Code', 'tpc_Short']"
t_204_Mach_Plan,"['rep_Month', 'p_Code', 'mcp_Owner', 'mcp_Type', 'mcp_Count']"

Looking like this in Jupyter notebook output;

I want to parse this table so that table name repeats with each field name and column counts remain the same such as the output dataframe will look like;
Table_Name,     Field_Names
t_001_Projects  'r01_P_Order'
t_001_Projects  'p_Code',
t_001_Projects  'r03_S_Name'
t_001_Projects  'r04_L_Name'

I tried this code from a stackoverfow solution;
list_temp = [df[x].apply(pd.Series).stack() for x in df.columns]
df_parsed = pd.concat( list_temp, axis=1).reset_index( level=1, drop=True)
df_parsed.columns = df.columns
df_parsed

But it did not work. In the solution;
Unlist multiple columns into rows with pandas
which I also successfully replicated, code is working perfectly. However in my case, the output stays same with input. What am I missing ? Thanks in advance...

A: The problem was that I was exported dataframe to csv. During export lists were converted to string. Then when I import dataframe lists were strings instead of their original form.
I found the answer here.
Pandas DataFrame stored list as string: How to convert back to list


text:
Q: Why do i get the C6385 error in my radix sort I am trying to write my own version of radix sort in order to better understand the algorithm. The problem is that in the first inner for loop("j") i get the C6385 error in VS. I have no idea of how to rephrase that line in order to make it work. What am i doing wrong here?
The warning is:

warning C6385: Reading invalid data from 'countQueues':  the readable
  size is '400' bytes, but '4000' bytes may be read.

void radixSort(int arr[], int arraySize)
{
    int countDigits = GetMax(arr, arraySize);   //max number of digits
    queue<int> countQueues[10];
    int modulo = 1;

    for (int i = 0; i < countDigits; i++)
    {
        modulo *= 10;
        for (int j = 0; j < arraySize; j++)     //store the values in the queues
        {
            countQueues[arr[j] % modulo].push(arr[j]);  //error here
        }

        for (int k = 0; k < 10; k++)        // move them back in the array
        {
            while (!countQueues[k].empty())
            {
                arr[i] = countQueues[k].front();
                countQueues[k].pop();
            }
        }
    }
}

A: Consider the second iteration of the first loop when modulo = 100. Then this line of code:
            countQueues[arr[j] % modulo].push(arr[j]);  //error here

could be trying to access countQueues[up to 99], but countQueues has a size of 10.
This is an issue with trying to implement radix sort most significant digit first. The 1st iteration uses 10 queues, 2nd iteration 100 queues, 3rd iteration 1000 queues, ... , which could be simplified using recursion, but would consume a lot of space, 10 raised to the countDigits power.
Implementing a radix sort least significant digit first avoids this problem. A [countDigits][10] matrix could be used. The initial pass generates counts and stores them into the matrix, where matrix[i][] is an array of 10 counts for the number of occurrences of each digit, 0 through 9. The counts are converted into the starting indexes for each logical bin of matrix[i]. The radix sort is then done in countDigits passes, least significant digit/bin first.


text:
Q: Number of paths of length $n$ starting from the origin in the $X-Y$ plane. I have to find out the number of paths of length $n$ starting from the origin with movements

*

*$R : (x,y) \rightarrow (x+1,y)$

*$L : (x,y) \rightarrow (x-1,y)$

*$U : (x,y) \rightarrow (x,y+1).$
Also step $R$ is not followed by $L$ and vice-versa.
In a book that I was following has done it in the following way
.
I have some problem understanding it.

*

*First why $a_{n-1} = b_n$ ?

*Secondly why should I only adjoin step $R$ in a path of length $(n-1)$ which ends with $R$ ? I may adjoin $U$ to the path to get a path of length $n$.

*Also the recurrence relation is not clear to me.

Any help will be very helpful.( If any other way of understanding is possible please let me know) Thank you.

A: To count $a_n$, the number of paths of length $n$, the author is splitting the set of such paths into the disjoint union of three subsets:

*

*The paths ending in U

*The paths ending in LL, RR or UL

*The paths ending in UR

Note that the latter two cases combine to count all of the paths ending in L or R, as LR and RL are not permitted.
@Jihoon Kang addressed your first concern. For the remaining two, both points are addressed by counting the three subsets above individually.
First, any path ending in U may be preceded by any legal path of length $n-1$, so there are $a_{n-1}$ paths in the first subset.
Second, given any path of length $n-1$, there is a unique way to complete it such that the path ends with one of LL, RR, or UL. You are correct that it is legal to follow a U with an R, but that would create a path that is not in the second subset, so it is not counted here. The number of paths in this subset is $a_{n-1}$.
Finally, a path ending in UR can be obtained by adding UR to any path of length $n-2$, so there are $a_{n-2}$ paths in this subset.
Since the set of paths of length $n$ is the disjoint union of these three subsets, we get the recurrence $a_n = 2a_{n-1} + a_{n-2}$ by simply summing the sizes of the three subsets.


text:
Q: creating mail form in html and php I am currently having issues getting my php and html working correctly.  When I click 'submit' It goes to an error page saying it cannot find webpage I requested (www.website.com/contact-form-handler.php).
Here is the PHP and HTML
HTML:

</head

<form action="contact-form-handler.php" method="post" name="contact_form">

                        <input name="name" type="text" class="form-control" id="nameInput" placeholder="Name" required>
                        <input name="email" type="email" class="form-control" id="emailInput" placeholder="Email" required>
                        <input name="phone" type="text" class="form-control" id="phoneInput" placeholder="Phone" required>
                        <input name="location" type="text" class="form-control" id="locationInput" placeholder="Event Location" required>
                        <select name="eventType" type="select" class="form-control" id="eventTypeInput">
                          <option selected>Type of Event</option>
                          <option value="1">Business</option>
                          <option value="2">Party</option>
                          <option value="3">Speech</option>
                        </select>
                        <select name="reference" type="select" class="form-control" id="referenceInput">
                          <option selected>How did you hear about us?</option>
                          <option value="1">Social Media</option>
                          <option value="2">Word of Mouth</option>
                          <option value="3">Google Search</option>
                        </select>

                        <textarea name="message" rows="7" class="form-control" id="messageInput" placeholder="Message"></textarea>

                        <input name="submit" type="submit" class="form-control" id="submit" value="Submit">

                </form>

PHP:
    <?php
$errors = '';
$emails = 'myemail@myemail.com';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['phone']) ||
   empty($_POST['location']) ||

{
    $errors .= "\n Error: Please fill out required fields";
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$location = $_POST['location'];
$eventType = $_POST['eventType'];
$reference = $_POST['reference'];
$message = $_POST['message'];

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
    $to = $emails;
    $subject = "David Does Stuff Inquiry: $name";
    $email_body = "You have received a new message. ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Phone: $phone \n Location of event: $location \n Type of Event: $eventType \n How did you hear about us: $reference \n Message \n $message";

    $headers = "From: $email_address\n";
    $headers .= "Reply-To: $emails";

    mail($to,$subject,$email_body,$headers);
    //redirect to the 'thank you' page
    header('Location: contact-form-thank-you.html');

}
?>

A: See if your PHP file name is "contact-form-handler.php" or maybe you're getting the error coz' your PHP file might not be in the same directory.

A: Please check your form
<form action="contact-form-handler.php" method="post" name="contact_form">

your header location is incorrect, it should be
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.php');


text:
Q: Group_Concat with php to add individual hyperlinks I've got a query that retrieves from tables using group_concat so that I dont have repititions.
'SELECT book_name, chapter_slug, GROUP_CONCAT(chapter_name SEPARATOR "
") as ChapterNames
FROM ci_books, ci_chapters
WHERE ci_books.book_id = ci_chapters.book_id AND slug = ' . $conn->quote($slug). '
GROUP BY book_name;'

Now the results are  separated which is good because I want to add hyperlinks to each however I am only getting one row that means the hyperlink is the same for all the chapterNames values.
book_name       chapter_slug   ChapterNames
Twelvers Dawn   wonders        Wonders
Rising

So now all the ChapterNames when hyperlinked via PHP are just the same. I can understand why, but how can I make it that each one has its own hyperlink.
Ideally, I would like this result or similar:
book_name      chapter_slug  ChapterNames
Twelvers Dawn  wonders       Wonders
               rising        Rising
               movers        Movers


text:
Q: How does html5 video tag get duration info from media served by http server? I want to get the duration info of mp4 files, after searched here, I found there are some tools like MP4Info, ffmpeg which can do that. But seems all these tools need to get the whole media file firstly or they will fail to get the info.
But when I put the video tag into html5 page, seems the browser can correctly get the duration info of corresponding media without the need to download the media file totaly. Here the media was served by http server with range support.
Is there any special method for the html5 video tag implementation to get the metadata info of the media file?
Thanks!


text:
Q: How to hide and Show input in html when a radio button is checked? I have gender radio button for "male" and "female" options.
I have also 2 divs: first for a "husband" input (to get if husband is alive or not) and the other one for "wife" input (to get if wife is alive or not).
I want to hide the husband input and show wife input when radio male is checked
and I want to hide the wife input and show husband input when radio female is checked
I've tried to get the value of the radio selected but it didn't work.
also tried to handle it by .checked operator that didn't word also.
can you please tell what am I missing?
here is the code:

function toggle_visibility() {
  var s = document.getElementById("divhus");
  var c = document.getElementById("divwife");
  var x = document.getElementById("gender").value;
  if (x == "m") {
    c.style.display = "block";
    s.style.display = "none";
  } else if (x == "f") {
    c.style.display = "none";
    s.style.display = "block";
  }
}
male <input id="gender" type="radio" name="gender" value="m" checked="checked" onclick="toggle_visibility()"> female <input id="gender" type="radio" name="gender" value="f">

  wife: alive <input type="radio" name="wife" value="true"> dead <input id="hus1" type="radio" name="wife" value="false" checked="checked">

  husband: alive <input type="radio" name="husband" value="true"> dead <input id="hus1" type="radio" name="husband" value="false" checked="checked">

Thanks for support, and sorry for stupid question but I am a beginner.

A: Use a delegate change listener on an element that is an ancestor of both radio buttons:

const delegate = document.getElementById('malefemalecontainer') // get the delegate element (ancestor);
delegate.addEventListener( // add an event listener to the delegate
    'change', // listening for change event bubbling up
    function() { // function that handles the change when it occurs
      const isMale = delegate.querySelector('input:checked').value === 'm'; // test if male is checked
      document.getElementById('divwife').hidden = isMale; // if isMale, hide wife
      document.getElementById('divhus').hidden = !isMale; // if not isMale, hide husband
    }
);

  male <input type="radio" name="gender" value="m">
  female <input type="radio" name="gender" value="f">

  wife:
  alive <input type="radio" name="wife" value="true">
  dead <input type="radio" name="wife" value="false" checked="checked">

  husband:
  alive <input type="radio" name="husband" value="true">
  dead <input type="radio" name="husband" value="false" checked="checked">

A: You can't ahave same id for multiple elements in html. You need to call the function also when you click on other radio. Try to change like this:
<input type="radio" id="gender_m" onclick="toggle_function()"... >
<input type="radio" id="gender_f" onclick="toggle_function()"... >

And change the function like this:
function toggle_visibility() {
  var s = document.getElementById("divhus");
  var c = document.getElementById("divwife");
  var x = document.getElementById("gender_m");
  var y = document.getElementById("gender_f");
  if (x.checked) {
    c.style.display = "block";
    s.style.display = "none";
  }
  if (y.checked) {
    c.style.display = "none";
    s.style.display = "block";
  }
}

A: You are facing two issues:

*

*there's no onclick-listener on your female - tag

*you're not really retrieving the checked element, but just the first element with id="gender"  ( don't use the same id for both tags, ids must be unique per-document at all times )

ad 1) just add the listener
ad 2) use a query-selector targeting the checked input e.g. below

function toggle_visibility() {
   var s = document.getElementById("divhus");
   var c = document.getElementById("divwife");
   var x = document.querySelector('input[name = "gender"]:checked').value;
   if (x == "m") {
     c.style.display = "block";
     s.style.display = "none";
   }else if(x == "f"){
     c.style.display = "none";
     s.style.display = "block";
   }
}
male <input id="gender_m" type="radio" name="gender" value="m" checked="checked"  onclick="toggle_visibility()">
female <input id="gender_f" type="radio" name="gender" value="f"  onclick="toggle_visibility()">

wife:   alive <input type="radio" name="wife" value="true">
          dead <input id="hus1" type="radio" name="wife" value="false" checked="checked">

husband:   alive <input type="radio" name="husband" value="true">
          dead <input id="hus1" type="radio" name="husband" value="false" checked="checked">


text:
Q: Why Tomcat returns different headers for HEAD and GET requests to my RESTful API? My initial purpose was to verify the HTTP chunked transfer. But accidentally found this inconsistency.
The API is designed to return a file to client. I use HEAD and GET methods against it.  Different headers are returned.
For GET, I get these headers: (This is what I expected.)

For HEAD, I get these headers:

According to this thread, HEAD and GET SHOULD return identical headers but not necessarily.
My question is:
If Transfer-Encoding: chunked is used because the file is dynamically fed to the client and Tomcat server cannot know its size beforehand, how could  Tomcat know the Content-Length when HEAD method is used? Does Tomcat just dry-run the handler and count all the file bytes? Why doesn't it simply return the same Transfer-Encoding: chunked header?
Below is my RESTful API implemented with Spring Web MVC:
@RestController
public class ChunkedTransferAPI {

    @Autowired
    ServletContext servletContext;

    @RequestMapping(value = "bootfile.efi", method = { RequestMethod.GET, RequestMethod.HEAD })
    public void doHttpBoot(HttpServletResponse response) {

        String filename = "/bootfile.efi";
        try {
            ServletOutputStream output = response.getOutputStream();
            InputStream input = servletContext.getResourceAsStream(filename);
            BufferedInputStream bufferedInput = new BufferedInputStream(input);
            int datum = bufferedInput.read();
            while (datum != -1) {
                output.write(datum);
                datum = bufferedInput.read();
            }
            output.flush();
            output.close();

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

    }

}

ADD 1
In my code, I didn't explicitly add any headers, then it must be Tomcat that add the Content-Length and Transfer-Encoding headers as it sees fit.
So, what are the rules for Tomcat to decide which headers to send?
ADD 2
Maybe it's related to how Tomcat works. I hope someone can shed some light here. Otherwise, I will debug into the source of Tomcat 8 and share the result. But that may take a while.
Related:

*

*HTTP HEAD and GET different result

*Content-Length header with HEAD requests?

A:
Does Tomcat just dry-run the handler and count all the file bytes?

Yes, the default implementation of javax.servlet.http.HttpServlet.doHead() does that.
You can look at helper classes NoBodyResponse, NoBodyOutputStream in HttpServlet.java
The DefaultServlet class (the Tomcat servlet that is used to serve static files) is more wise. It is capable of sending the correct Content-Length value, as well as serving GET requests for a subset of the file (the Range header). You can forward your request to that servlet, with
  ServletContext.getNamedDispatcher("default").forward(request, response);

A: Although it seems strange, it might make sense to send the size only in response to a HEAD request and chunked in response to a GET request, depending on the type of data that has to be returned by the server.
While your API seems to provide a static file, you also talk about dynamically created files or data, so I will be talking in general here (also for webservers in general).
First let's have a look at the different usages for GET and HEAD:

*

*With GET the client is requesting the whole file or data (or a range of the data), and wants it as fast as possible. So there is no specific reason for the server to send the size of the data first, especially when it could start sending faster/sooner in chunked mode. So the fastest possible way is preferred here (the client will have the size after the download anyway).

*With HEAD on the other hand, the client usually wants some specific information. This could just be a check on existance or 'last-changed', but it could also be used if the client wants a certain part of the data (with a range request, including a check to see if range requests are supported for that request), or just needs to know the size of the data up front for some reason.
Lest's look at some possible scenarios:
Static file:
HEAD: there's no reason to not include the size in the response-header because that information is available.
GET: most of the time the size will be inluded in the header and the data sent in one go, unless there are specific performance reasons to send it in chunks. On the other hand it seems you are expecting chunked transfer for you file, so this could make sense here.
Live logfile:
Ok, somewhat strange, but possible: downloading a file where the size could change while downloading.
HEAD: again, the client probably wants the size, and the server can easily provide the size of the file at that specific time in the header.
GET: since loglines could be added while downloading, the size is unknown up front. Only option is to send chunked.
Table with fixed-sized records:
Let's imagine a server needs to send back a table with fixed-length records coming from multiple sources/databases:
HEAD: size is probably wanted by the client. The server could quickly do a query for count in each database, and send the calculated size back to the client.
GET: instead of doing a query for count in each database first, the server better starts sending the resulting records from each database in chunks.
Dynamically generated zip-files:
Maybe not common, but an interesting example.
Imagine you want to provide dynamically generated zip-files to the user based on some parameters.
Let's first have a look at the structure of a zip-file:
There are two parts: first there's a block for each file: a small header followed by the compressed data for that file. Then there's a list of all the files inside the zip-file (including sizes/positions).
So the prepared blocks for each file could be pre-generated on disk (and the names/sizes stored in some data structure.
HEAD: the client probably wants to know the size here. The server can easily calculate the size of all the needed blocks + the size of the second part with the list of the files inside.
If the client wants to extract a single file, it could directly ask for the last part of the file (with a range-request) to have the list, and then with a second request ask for that single file. Although the size is not necessarily needed to get the last n bytes, it could be handy if for example if you wanted to store the different parts in a sparse file with the same size of the full zip-file.
GET: no need to do the calculations first (including generating the second part to know its size). It would be better and faster to just start sending each block in chunks.
Fully dynamically generated file:
In this case it wouldn't be very efficient to return the size to a HEAD request of course, since the whole file would need to be generated just to know its size.


text:
Q: Primefaces - how to get the column of a CellEditEvent I am using primefaces 4.
I am using an editable table and when I edit a cell, a listener method is called passing a CellEditEvent
Like this
public void onCellEdit(CellEditEvent event) {
    /*
     * The rowIndex here can be changed according to the sorting/filtering.

     * FilteredData starts as null, but primefaces initializes it, so you
     * don't have to check for NPE here
     */
    int alteredRow = event.getRowIndex();
    UIColumn o = event.getColumn();

    System.out.println(this.filteredData.get(event.getRowIndex()).get(columns.get(0)));
}

So far, so good.
The event has a getRowIndex()
But it does not have a getColumnIndex().
Instead, it has a getColumn() method that returns a UIColumn object.
The problem is, while debugging, I could not find a way to get any column information (name, id, etc)
I can hack the column to have some unique ID like this
 <p:ajax event="cellEdit" listener="#{myMB.onCellEdit}"/>
 <c:forEach items="#{myMB.columns}" var="column" varStatus="loop">

    <p:column id="col#{loop.index}" headerText="#{column}" sortBy="#{column}" filterBy="#{column}" filterMatchMode="contains"/>

      <p:cellEditor>

       <f:facet name="output">
        <h:outputText value="#{dataRow[column]}" />
       </f:facet>

       <f:facet name="input">
        <p:inputText value="#{dataRow[column]}"  />
       </f:facet>

    </p:cellEditor>

    </p:column>

 </c:forEach>

But still I can't find a way to retrieve the column id from the CellEditEvent
So, assuming that a cell is something that has a row and a column, I have to ask
How do I retrieve the column of an edited cell in a CellEditEvent?
ps. I feel I am missing something, because no one would create a cell event without providing the row and the column, right?
update - it seems I can get the ID like
org.primefaces.component.column.Column o = (org.primefaces.component.column.Column)event.getColumn();

still, this seems like a hack for me. I am still interested in more elegant solutions for this ;-)

A: You can get the column by referring back to the column header that you passed.
In bean you could do this:
public void onCellEdit(CellEditEvent event) {

int alteredRow = event.getRowIndex();
String column_name;
column_name=event.getColumn().getHeaderText();

 // now you can use this to identify the column we are working on.

}

Using getColumnId()  or getColumnKey() returns the column Id but with primefaces code added to it - making it difficult to work with.

A: If you use p:columns rather than p:column - which is also more readable - event.getColumn() returns a DynamicColumn that implements UIColumn. Then you can use:

((DynamicColumn)event.getColumn()).getIndex()

to determine the column index. There is also a column.isDynamic() to check validity.
Using the header would need further code and might be more inefficient.

A: I found only one way to do this. On the xhtml, add an id to the column:
<p:column id="myColumn">
...
</p:column>

In the backing bean,column.getColumnKey() will return a generated id  that contains the id you set in the xhtml (something like j_idt30:j_idt32:0:contratoReal). Thus, you can do this:
public void onCellEdit(CellEditEvent event) {
    if (event.getColumn().getColumnKey().endsWith("myColumn")
}


text:
Q: How can you re-assign (a.k.a set) class member that is unique_ptr? class A {};

class B{
    unique_ptr<A> upA;

public:
    B() : upA(make_unique<A>()) {}

    void set(A a){
        upA.reset(move(a));  //error
        //upA.reset(a);        //error
        //upA = move(a);     //error
    }
};

How can you re-assign (a.k.a set) class member that is unique_ptr?

A: It depends on what you want to do. Do you want to invoke operator= on the object managed by upA? If so:
*upA = a;

Do you want to accept a new unique_ptr and take ownership of it? If so:
 void set(std::unique_ptr<A> a){
    upA = move(a);
}

A: unique_ptr<A> upA;

so this is a unique (smart) pointer to an A located somewhere - fine so far.
B() : upA(make_unique<A>()) {}

OK, we initialize our pointer to point at a new, dynamically-allocated A - looks reasonable.
void set(A a){
    upA.reset(move(a));

but now you want to point your smart pointer - which is responsible for managing the lifetime of the object it points to - at a local instance of A? That doesn't make sense for two reasons:

*

*your smart pointer manages a pointer, and you're passing it an (lvalue reference to) a local object. You could convert this to a pointer by writing &a, but this still has the problem that:

*your local variable a will go out of scope when the function returns, leaving your smart pointer with a dangling, invalid address to attempt to manage.

When you call B::set, what is supposed to happen? You need to decide what it's intended to do from the caller's perspective. Either:
// transfer control of the caller's A to B
void B::set(std::unique_ptr<A> a) { upA = move(a); }

or
// take control of the caller's allocated but unmanaged A
void B::set(A *a) { upA.reset(a); }
// not recommended - keep everything managed by unique_ptr if at all possible

or
// copy the caller's A into B's existing A
void B::set(A const &a) { *upA = a; }
// called as
b.set(my_local_a);

or
// move the caller's temporary A into B's existing A
void B::set(A &&a) { *upA = move(a); }
// called with an explicit move
b.set(move(my_local_a));
// or with a prvalue
b.set(A{});


text:
Q: UINotification ios not received when app is in background I am using notification in one of my app ,when app is active , notification is received , i process data and everything is fine , but I do not receive any notification when app is in background or killed.What is the issue can any one plz help me ?
Thank you!
Here is what I doing so far
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    tokenstring = [[NSString alloc] initWithFormat:@"%@",deviceToken];

    tokenstring = [tokenstring stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    tokenstring = [[NSString alloc]initWithFormat:@"%@",[tokenstring stringByReplacingOccurrencesOfString:@" " withString:@""]];
    NSLog(@"TokeinID:>> %@",tokenstring);

}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"didReceiveRemoteNotification: %@",userInfo);
    AudioServicesPlaySystemSound(1002);

    //Some code or logic
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError: %@",err.description);

}

A: When you receive remote notifications, -application:didReceiveRemoteNotification: is only called when your app is in the foreground. If your app is in the background or terminated, then the OS may display an alert or play a sound (depending on the aps dictionary in the notification), but the delegate method is not called.
The remote notification received in the background will only passed to your application if it is launched with that notification's action button, and then you need to look at the launch options dictionary on -application:didFinishLaunchingWithOptions: to see the content of the notification.
If you're looking at new content fetching/remote notification background support with iOS7, check Will iOS launch my app into the background if it was force-quit by the user? and see if that helps, as there are very specific circumstances that those functions work in.

A: little code ..
When app is not running

(BOOL)application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

is called  ..
where u need to check for push notification
 UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (notification) {
    NSLog(@"app recieved notification from remote%@",notification);
    [self application:application didReceiveRemoteNotification:(NSDictionary*)notification];
}else{
 }


text:
Q: Running many Rails app instances with third party dependencies in on a single machine I am trying to set up a local "testbed" for the developers at the firm I work out. There are several developers working on a single server app and frequently need to deploy their branches for client side testing. Currently, all these deploys occur on an offsite server with a separate application instance per deploy.
I would like to create a homebrewed solution and have been looking at services such as pow.cx. This is great and all, but the server app requires multiple external services such as redis and memcached, both of which require separate ports. I could, in principle, manually create additional config files for each separate instance, but this is difficult in practice and requires a lot more bookkeeping in terms of juggling environments.
Being a bad system admin, I was wondering if there was a simpler approach (i.e. virtual hosts) that would allow me to deploy each instance identically but behind, say, a different subdomain?
I realize this question is fairly demanding and I will certainly appreciate any advice I can get.

A: From my experience. I have some simple application on one host. I use simple configurable tools: passenger + nginx as server ( to add new server you need to add 5 lines of code ), Vlad the Deployer for deploying, rbenv for different ruby version, bundler as tool for separating rails gem.
I have some servers: production, development, test. They are placed on different hdd on vps and have own domains to exclude any influence between servers.

A: It sounds like the easiest thing would be to have a bunch of VMs on that server, one per application instance. You could share some things (e.g. your database server) across your application instances if you wanted to.
You can automate of lot of this using something like vagrant. One benefit of doing it this way is that it is then easy to move one particular VM to a dedicated machine if it needs it or for a new developer to use that VM for development.


text:
Q: Build.Gradle Error (22,0) Could not find method chandroid() I am new in Android Studio, I'm already completed my simple app. But the problem is I have Gradle problem when try to open the project after copy the app folder from my desktop to my laptop.
(including screenshot link for better understanding of the problem)
main Build.Gradle
http://puu.sh/vQl8c/bcade1a2e2.png
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

// It won't required
//    chandroid {
//        compileSdkVersion 19
//    }
app Build.Grade
http://puu.sh/vQl9v/e7363ddb74.png
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.afinal.eaglearms.learnk"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:25.3.1'
}

A: chandroid {
   compileSdkVersion 19
}

Remove this from your main/root build.gradle file. It should be android instead of chandroid, that is also not required because you already defined in build.gradle of app module.


text:
Q: When is a copy constructor called in c++, is not it called when I assign a object to another object? class Myinteger(){
    public:
      Myinteger( int len );             // simple constructor
      Myinteger( const Myinteger &obj);  // copy constructor
      ~Myinteger();                      // destructor
    private:
      int *ptr;
}

Myinteger::Myinteger(const Myinteger &obj) {
  cout << "Copy constructor allocating ptr." << endl;
  ptr = new int;
  *ptr = *obj.ptr; // copy the value
}

int main(){
   Myinteger obj1(10);
   Myinteger obj2(20);
   obj1=obj2;
   return 0;
}

Copy constructor is not called when assigning obj2 to obj1, I confirm it since "Copy constructor allocating ptr." is not printed to the console,
So if copy constructor is not called which method is called in the above case when assigning obj2 to obj1 , also tell in which cases copy constructors of a class is called.

A: A copy constructor, such as would be declared thus:
Myinteger(const Myinteger& other);

would be used as either
Myinteger obj2 = obj1;

or
Myinteger obj2(obj1);

but an assignment operator, declared as:
Myinteger& operator =(const Myinteger& other);

would be used where your code has
Myinteger obj2;
obj2 = obj1;

This is what you have in your code, so the assignment operator is being called, and not the copy constructor.

A: In this statement
obj1=obj2;

there is used the copy assignment operator because the both operands (objects) of the assignment were already created. So if they are already created neither constructor will be called.
If you want to use the copy constructor then you could write for example
int main()
{
   Myinteger obj1( "10" );
   Myinteger obj2 = obj1;

   return 0;
}

A: i got the answer, what i thought is that copy constructor is called when ever we assign an object to another object which is conceptually wrong.
copy constructor is called only  when an object is created, if we assign an object to already existing object then overloaded assignment operator function  is called, otherwise default assignment operator function is called from the class.

A: I got the answer, what I thought is that copy constructor is called when ever we assign an object to another object which is conceptually wrong. copy constructor is called only when an object is created, if we assign an object to already existing object then overloaded assignment operator function is called, otherwise default assignment operator function is called from the class.


text:
Q: Wrong subject name of SA for prometheus clusterrolebinding? Since sa name is "prometheus" in file prometheus-serviceaccount.yaml,
kind: ServiceAccount
apiVersion: v1
metadata:
  name: prometheus
  labels:
    app: prometheus
  namespace: default

do you think subject name in file prometheus-clusterrolebinding.yaml should be "prometheus" rather than current "default"?
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: prometheus
  labels:
    app: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
- kind: ServiceAccount
  name: default
  namespace: default

There are the similar problems for prometheus-proxy.


text:
Q: SoapClient call returns 500 Internal Server Error I am trying to connect to an API using PHP and its built-in SoapClient. I have checked against the url I was given through the ill-formatted documents the client gave and $client->__getFunctions() returns a list of three functions. HelloWorld($name), which responds with Hello ~name~, shows me that I am communicating with the server through the SoapClient call and the URL is correct.
However, when I try to access one of the other methods that __getFunctions() gives me, even after copy/pasting the XML from the docs and putting in my own credentials, I am still being given an Internal Server Error faultstring and 500 as faultcode from the SoapFault object.
I am sure that it is my own XML string that is causing the issue but I cannot for the life of me figure out how. Reaching out to the API provider directly hasn't proven helpful. This is my first time dealing with Soap/Web Services so I am unsure of where to go from here.
I did wget http//xxx.xxx.xxx?wsdl and it returned me what looks like a valid XML response, the same one I get when I go directly to the url in the browser. What should I be looking into in order to solve this issue? All of the past API's I've dealt with have been JSON/RESTful so I feel out of my element trying to debug PHP errors.
Edit
I have slowly deleted parts of my method call and parts of my XML string, trying to trigger a different error or something in order to find what I need to fix. What I have found is that by not passing in my XML string, I get a valid response from the $client->FunctionCall(...). It's an "this isn't right" message but it's a message! In fact, passing that function ANYTHING for the xml parameter causes the 500 http faultcode/faultstring. Does this mean that my XMl is poorly formatted or does it mean that there is an issue on their end handling requests?
Second Edit
If I make my $client decleration as follows, I get the faultstring Could not connect to host
$opts = array(
    'ssl' => array('ciphers'=>'RC4-SHA')
  );
$client = new SoapClient($CREDS['orderingWSDL'], array (
"encoding"=>"ISO-8859-1",
'stream_context' => stream_context_create($opts),
  'exceptions'=>true,
));

I am getting more confused the longer I try to fix this.

A: Sometimes a 500 status coming from a SOAP service could be a SoapFault exception being thrown.  To help your troubleshooting, you'll want to be able to inspect both your request XML, and the response XML.
Put your code in try/catch blocks, and use $client->__getLastRequest() and $client->__getLastResponse() to inspect the actual XML.
Example:
$client = new SoapClient('http//xxx.xxx.xxx?wsdl', array('soap_version'=>SOAP_1_1,'trace' => 1,'exceptions' => true));
try {
  $response = $client->someFunction();
  var_dump($response);
} catch (Exception $e)  {
  var_dump($e->getMessage());
  var_dump($client->__getLastRequest());
  var_dump($client->__getLastResponse());
}


text:
Q: insert variable via forEach into regex expression As you can see below, I'm trying to count how many times a character in string J occurs in string S.  The only issue is I can't put the argument o in the forEach loop into the regex expression as shown in the console.log.
var numJewelsInStones = function(J, S) {
    let jArr = J.split('');
    let sArr = S.split('');

    jArr.forEach(o=>{
    console.log(S.replace(/[^o]/g,"").length);
    })
};

numJewelsInStones("aA", "aAAbbbb");

A: You can create regular expression with constructor function where you pass string parameters:
new RegExp('[^' + o + ']', 'g')

Your replace logic might look like:
S.replace(new RegExp('[^' + o + ']', 'g'), '')


text: Q: Покрытие всех путей выполнения функции тестами Есть ли инструменты, с помощью которых можно узнать path coverage для тестов? Т.е. процент покрытых путей выполнения кода, а не только процент покрытых строк кода statement coverage, который выдает gconv.


text:
Q: Check if a given order is a legal postorder traversal If you have a binary search tree with ten nodes, storing integers 0 through 9, how do we decide if a sequence cannot represent a postorder traversal of the tree? I understand that the root has to be the last one in the sequence, but I could not arrive at any pattern. A pseudocode would be great too! (It's not homework, practicing for interviews)

A: As you said, you know what the root is.  So you know the range of values in each sub tree.  If the sequence, less the root, doesn't split into two sequences, one less than and one greater than the root then it isn't valid.  If it does, you need to recursively check the two sub-traversals.  If everything works, then it is valid.


text:
Q: Ionic 4 Console.Log() not showing in function What on Earth is happening here. No console output inside this service function of mine. Any one had this issue before?
   test(){
    console.log('TESTING???')
    console.log('TESTING???')
    return 'HALOOOOOOO??'
  }

Calling the function
console.log('Before Test')
console.log(this.emergencyService.test())
console.log('After Test')

Output

Some more info.

*

*Calling that function from a normal Page

*Function is inside a Service I inject into that page

A: It's returning the value of the method. If instead of console.log(this.emergencyService.test()) you add this.emergencyService.test(), what does it show? It returns the two console.log(), no?

A: I had a filter on my console.
Clearing it solved my problem.


text:
Q: Organize HTML sites with Bootstrap 4 Navbar TLDR: What is the standard/best practice to organize the different HTML sites/files, when using a navigation bar, that should be visible on every site?
Background: I'm starting for the first time to create a website. It should run on an ESP and I got some good results with Bootstrap 4. I've defined a Bootstrap navbar, just like in all the examples (for example here on w3schools). Though the examples only use do-nothing links; they don't show how these links are commonly used with the navbar and the different files (this must be a general principle, that I don't know).
The navbar should of course be visible on every site, while the content below it should change according to the clicked link. When I simply use a link in the navbar to a different html file without a navbar included it is of course not visible.
How are the different sites normally organized in relation to the navbar?
I have thought of different possibilities:

*

*Having a navbar in every file (obviously a nightmare to maintain)

*Having the navbar in an extra file, including it somehow in every other file

*Managing all the content in the main file together with the navbar, including the other content files somehow

At my current knowledge I just don't know enough, so I also don't know what to search for. If there are already good information about this on the web, can you please provide me with search words or links?

A: If you are planning to use HTML then there is no other choice. You need to add a navigation bar to each page which is a nightmare as you have mentioned. But if you are planning to use server-side programming languages like PHP then they provide a keyword called include. Its syntax is  include 'filename' now you can add a file like header.php inside include folder and you can use across multiple pages. You can have a look in this documentation
.But if you are using NodeJS, ExpressJS then they have their own templating-engines like ejs, handlebars, pug. They consist of partials So, that partials can be use across multiple pages. Here is the link for partials

A: Though the answer of kedar sedai is the correct one, I want to add my chosen way and further information as documentation for future readers.
kedar sedai is right, that I need to use some programming language. One problem is, that I cannot use server side programming languages, because the ESP does not support them. So I needed to move to client site programming, thus javascript.
I used the solution of this SO question to include another HTML file. I now serve only the main HTML file, which contains the navbar and the following part to load the correct HTML file dependent on the page parameter in the URL:

This works like a charm and I now have notion how I can organize my html files to be displayed with the navigation bar.


text:
Q: MVC URL in Javascript Not Render Correctly I had a Details view which it's contain a Save and AddLine button. The AddLines button will call javascript function "AddLinePopup" to open a new window ("window.open('./AddLine?id=' + id") with Add Line view. This was working correctly when open the Details view directly. The problem occurred when the Save button is clicked and it call to Controller (PRController) to save data and redirect back to Details view again. The URL in AddLinePopup javascript function will append the controller ("'PR/Details/AddLine?id=1") when AddLine button is clicked and causing the URL error.
I did tried using "window.open('~/PR/AddLine?id=' + id')", "window.open('../PR/AddLine?id=' + id')" not working as well.
How can I render the javascript AddLinePopup function URL correctly ("'PR/AddLine?id=1") after Save button is clicked? Any suggestion or solution is highly appreciated. Thanks in advance.
//PRController
public ActionResult Save(DetailsModel pr)
{
     return RedirectToAction("Details", new { id = pr.ID });
}

//View
@using (Html.BeginForm("Save", "PR", FormMethod.Post))
{
    <input type="submit" value="Save" class="btn btn-primary" title="Save changes" />
}

@Html.ActionLink("Line", "AddLine", null, new { @class = "fa fa-plus-square btn btn-primary",
title = "Add new line", onclick = "AddLinePopup('" + @Model.ID + "');return false;" })

<script type="text/javascript">
     AddLinePopup = function (id) {window.open('./AddLine?id=' + id, "AddLineWindow", target = '_blank','width=800px,height=650px,top=10,left=250');
}
</script>

A: This solve my problem. I use link to call Javascript function and open new window in JavaScript.
`<a href="javascript:AddLinePopup('@Url.Action("AddLine", "PR")','@Model..ID')">
AddLinePopup = function (url,id) { window.open(url + '?id=' +id,"addlineWindow",'width=800px,height=400px,top=10,left=e250');}`


text:
Q: Double slit experiment  and perforated walls' properties I have a doubt about how double slit experiment is made.
Let's think about the perforated wall, what are the requirement for it?
Can a photographic plate could be used as a wall ?
I see a problem here, as a photographic plate serve also as a detector, then the single photon experiment could end up with a single point in the wall that contains the slits and not in the plate located behind the slit's wall.
Of course the "one photon count", is knowing the emition before the slits (if this count were made after, it will be a detector making a measurement and would simply reflect the particle effect)
The wall with the slits could absorb the photon(removing electrons from the material) before something happen on the other side, if that happened, there would be no experiment, the photon won't pass through the slits, just because its energy was already used (supposing all energy is used and the photon doesn't split).
There must be some kind of specification about the material of the wall, need to be special, in the sense of needing a higher energy (than the test photon) to pickup electrons, then the light won't stop there, for that, I think the wall can't be made of a photosensible material, but I don't know, and here I am asking..
thanks for any answer

A: It doesn't matter whether the wall is photosensitive or not. If the photons' wave functions give some probability of hitting the wall and being absorbed, then some of the photons will hit the wall and be absorbed, whether they produce some chemical reaction in a photographic plate or just heat the wall.

A: 1.
Of course wall sometimes absorbs the photon (light do not evade it in any way). To have interference, you need to have no information (in terms of excitation, creation of photographic grain of whatever) that could be used to say which path the photon 'has chosen'.
2.
It is fine to use foil. See e.g. http://ultrafast.fuw.edu.pl/publications/ajp_2008.pdf (so called Fresnel Zone Plates on film or polygraphic foil). Want to test it by yourself? Make an analog photography of two dark lines, and then use film as a diffractive agent. Or - in any DTP studio post a PostScript file e.g. from http://migdal.wikidot.com/prazki-moire -> (don't be afraid it is in Polish; just download a few first ps/pdf files).


text:
Q: Get mysql result based on date and count() in Symfony I have  4 relevant tables in this situation
USER
-userId
GROUPMEMBER
-userId
 -groupId
POST
-groupId
 -dateCreated
POSTBUMP
-userId
 -postId
I want to create a function getTrendingPosts($user_id, $date) where $user_id is the current user and $date is how far back from the current date I want to include results from.
So the idea is to
first get the groups that the user is in
second get the posts that are in the groups we found for the user and are within the time range
third order those posts based on the count() of the postbumps
I can do the first two bits ,but I can't really figure out how to do the third. At the same time, I don't want to use 3 queries if its possible to do it in 2 or even 1.
for the first one, (returns group entities which contain the id)
public function getGroupsIdByUserId($user_id){
    $qb=$this->repository->createQueryBuilder('x');
    $qb->select('AppBundle:GroupMember');
    $qb->where('x.userId = :userId');
    $qb->setParameter('userId',$user_id);
    return $qb->getQuery()->getResult();
}

for the second one( I end up calling it for each group id, trying to get it all at once though)
public function getPosts($group_id, $date){
    $qb=$this->repository->createQueryBuilder('x');
    $qb->select('AppBundle:Post');
    $qb->where('x.dateCreated < :dateCreated AND x.groupId = :groupId');
    $qb->setParameter('dateCreated',$date);
    $qb->setParameter('groupId', $group_id);
    return $qb->getQuery()->getResult();
}

The queries are done using a query builder function through symfony, although I'm more concerned about the actual logic of the queries so even an answer in plain SQL is good enough.

A: So the basic SQL you want is this:
SELECT COUNT(POSTBUMP.postId)
FROM post
INNER JOIN POSTBUMP ON POSTBUMP.postId = postID AND userID = 1
WHERE datecreated < '2017-01-01' AND
groupID IN (SELECT groupid FROM groupmember WHERE userid = 1)
ORDER BY COUNT(POSTBUMP.postId) DESC

To achieve this in one function you could do something like this:
public function getTrendingPosts($user_id, $date){
    $em = $this->container->get('doctrine.orm.entity_manager');
    $qb2 = $em->getRepository('AppBundle:GroupMember')->createQueryBuilder('o2');
    $qb=$em->createQueryBuilder('x');
    $qb->select('count(o.postId), o.postId')
        ->from('AppBundle:Post')
        ->innerJoin('AppBundle:PostBump', 'o', 'WITH', 'o.userId  = :userId AND o.postId = x.postId')
        ->where('x.dateCreated < :dateCreated')
        ->andWhere($qb->expr()->in(
            'x.groupid',
            $qb2->select('o2.groupid')
                ->where('o2.userid = :userId')
                ->getDQL()
        ))
        ->setParameter('dateCreated',$date)
        ->setParameter('userId',$user_id)
        ->addGroupBy('count(o.postId), o.postId')
        ->addOrderBy('count(o.postId)', 'DESC')
    ;
    return $qb->getQuery()->getResult();
}

I haven't tested this code so let me know if it works with/without modification.


text:
Q: Why does this jQuery not work in one place? I have abstracted some jQuery code to handle filtering of tables in my application. In general, the user clicks a link and certain table rows are shown or hidden. The code is below:
var filters = $('ul.filters');
var filtersCount = filters.children().length;
if (filtersCount > 2) {
  filters.children(':last-child').css({
    'right':'1px'
  })
}
var target = filters.data('target');

$('a.filter').on('click', function() {
  filters.children().removeClass('active');
  $('.filterable').hide();
  var $this = $(this);
  $this.parents('li').addClass('active');
  var visibleStates = $this.data('include-filter').split(" ");
  $(visibleStates).each(function(index,state) {
    if (state == "all") {
      $('.filterable').show();
    } else {
      $('.filterable' + '.' + state).show();
    }
  })
  if ($this.data('exclude-filter') !== undefined) {
    var hiddenStates = $this.data('exclude-filter').split(" ");
    $(hiddenStates).each(function(index,state) {
      $('.filterable' + '.' + state).hide();
    })
  }
})

This code is used in five places in my application and works in four of them. By stepping through execution, I know the code does work because it filters the elements but eventually all ".filterable" elements on the page are hidden. I have followed the execution of the code which goes into this part of jQuery:
if ( ret !== undefined ) {
  if ( (event.result = ret) === false ) {
    event.preventDefault();
    event.stopPropagation();
  }
}

The line which causes the ".filterable" rows to be hidden is this:
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ).apply( matched.elem, args );

Eventually, execution stops on this line:
return event.result;

event.result is undefined if I look at it in the console. Javascript is not really my area of expertise so if anyone can give me a point in the right direction, I would be grateful.
EDIT
I have added the simplest code possible into my table as follows with the same result. Both rows are hidden and don't reappear irrespective of which filter link I click.

    From
    To

    From
    To

The filters look like this. The Ruby code prints out the description of the absence category, downcasing it and replacing spaces with hyphens.

    All Absences

  <% @absence_categories.each do |ac| %>

      <a href="javascript:;" class="filter" data-include-filter="<%= ac.description.downcase.gsub(' ','-') %>"><%= ac.description %>

  <% end %>

A: It mean "event.result" is Null you need to test if your event click still exist after you need to debug in the console script as application step by step may be this error caused by no reference class or html.

A: change this click event like below:
$(document).on('click','a.filter', function() {
  filters.children().removeClass('active');
  $('.filterable').hide();
  var $this = $(this);
  $this.parents('li').addClass('active');
  var visibleStates = $this.data('include-filter').split(" ");
  $(visibleStates).each(function(index,state) {
    if (state == "all") {
      $('.filterable').show();
    } else {
      $('.filterable' + '.' + state).show();
    }
  })
  if ($this.data('exclude-filter') !== undefined) {
    var hiddenStates = $this.data('exclude-filter').split(" ");
    $(hiddenStates).each(function(index,state) {
      $('.filterable' + '.' + state).hide();
    })
  }
})