text:
Q: Module AppRegistry is not a registered callable module (calling runApplication) - for Jitsi-meet You might find this question as a duplicate one but my scenario is different.
I am using Jitsi-Meet for video conference in one of my react native application. I use Jitsi-meet dependency to use features of Jitsi-meet from my android code to react native code. All the configurations are properly set for Jitsi-Meet in my app.
Issue is when I call Jitsi-Meet code from react native using android package, it gives me error like below:
    2019-05-23 19:42:17.157 9640-9722/com.telecare E/ReactNativeJS: null is not an object (evaluating 'M.Aspect')
2019-05-23 19:42:17.169 9640-9722/com.telecare E/ReactNativeJS: Module

AppRegistry is not a registered callable module (calling runApplication)
2019-05-23 19:42:17.174 9640-9723/com.telecare E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    Process: com.telecare , PID: 9640
    com.facebook.react.common.JavascriptException: null is not an object (evaluating 'M.Aspect'), stack:
    <unknown>@944:6009
    h@2:1670
    <unknown>@943:292
    h@2:1670
    <unknown>@942:280
    h@2:1670
    <unknown>@11:743
    h@2:1670
    d@2:868
    global code@1008:4

        at
com.facebook.react.modules.core.ExceptionsManagerModule.showOrThrowError(ExceptionsManagerModule.java:54)
        at

com.facebook.react.modules.core.ExceptionsManagerModule.reportFatalException(ExceptionsManagerModule.java:38)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
        at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
        at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at
com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
        at android.os.Looper.loop(Looper.java:164)
        at

com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)
        at java.lang.Thread.run(Thread.java:764)

Here is the code I am using from Jitsi-Meet:
  @ReactMethod
    public void initializeJitsi(final Callback callback) {
        Log.e("JitsiManager","initializeJitsi called");
        URL serverURL;
        try {
            serverURL = new URL("https://meet.jit.si");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException("Invalid server URL!");
        }
        JitsiMeetConferenceOptions defaultOptions
                = new JitsiMeetConferenceOptions.Builder()
                .setServerURL(serverURL)
                .setWelcomePageEnabled(true)
                .build();
        JitsiMeet.setDefaultConferenceOptions(defaultOptions);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e("JitsiManager","initializeJitsi launch called");
                JitsiMeetConferenceOptions options
                        = new JitsiMeetConferenceOptions.Builder()
                        .setRoom("XXXXX")
                        .build();
                JitsiMeetActivity.launch(getCurrentActivity(), options);
            }
        },5000);

    }

When this code JitsiMeetActivity.launch(getCurrentActivity(), options); is being called from my react-native file, it opens new screen and immediately app is being crashed with above error.
I also made a demo android application where it calls the same code from Jitsi-Meet and its working fine.
Also I tried using react-native-jitsi-meet library for same purpose but it is also giving me same error.
Any help will be appreciate. Thanks!

A: After struggling for many days finally I managed to make my app work with jitsi-meet video conference. Here is the answer to my own question.
STEP 1: Removed node_modules folder from my app.
STEP 2: Run npm install
STEP 3: Run react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
STEP 4: Remove index.android.bundle from android/app/src/main/assets/
STEP 5: Run react-native run-android
Hope it helps you!


text:
Q: Angular populate ng-repeat and ng-model In  my app I have a widget that is used on multiple pages and the selections made on the widgets are to be transferred between pages. So if I select something in the widget on the homepage and click 'continue' which then takes me to a new page, the widget should be pre-populated with the selections made on the homepage.
My widget follows the following format (although not exact for simplistic explanations):
<li ng-repeat="device in devices track by $index">
    <select name="model[{{$index}}]" ng-model="selectedManufacturer" ng-options"...">
    <select name="model[{{$index}}]" ng-model="selectedModel" ng-options"...">
</li>

It's the values of the ng-models inside the repeat statement that contain the key data in the widget that needs to be transferrable.
The number of devices needs to be transferrable too but that will be easy as devices is just an array of numbers so selectedModel.length -1 will equal the value of devices on the secondary pages.
Is it possible to pre-populate the values of ng-models?

A: Yes, you can prepopulate values of ng-models (or any scope variable) using ng-init

A: If you want to pre-populate the value in your ng-model which would mean a default/inital value in your drop-down. This can be achieved by doing the following:-
$scope.selectedManufacturer = listOfManufacturer[0];
$scope.selectedModel = listOfSelectedModel[0];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate time difference (difftime) between columns of different rows I have data on 'Start' and 'End' time for different jobs, grouped by 'owner':
Data <- data.frame(
  job = c(1, 2, 3, 4, 5),
  owner = c("name1", "name2", "name1", "name1", "name2"),
  Start = as.POSIXct(c("2015-01-01 15:00:00", "2015-01-01 15:01:00", "2015-01-01 15:13:00", "2015-01-01 15:20:00", "2015-01-01 15:39:02"), format="%Y-%m-%d %H:%M:%S"),
  End =   as.POSIXct(c("2015-01-01 15:11:11", "2015-01-01 15:17:21", "2015-01-01 15:17:00", "2015-01-01 15:31:21", "2015-01-01 15:40:11"), format="%Y-%m-%d %H:%M:%S")
)

For each owner, I want to calculate the idle time between the jobs for each owner, i.e. the difference between the 'End' time of one job and the 'Start' time of the next job.
How do I use difftime() to calculate this time difference between specific rows and times in different columns?
The result should look something like this:
job, owner, idletime
1, name1, NA
2, name2, NA
3, name1, 1.816667  # End of row 1 minus Start of row 3
4, name1, 3.0       # End of row 3 minus Start of row 4
...

A: Here's a possible solution using data.table
library(data.table) # v 1.9.5+
setDT(Data)[, idletime := difftime(Start, shift(End), units = "mins"), by = owner]
#    job owner               Start                 End       idletime
# 1:   1 name1 2015-01-01 15:00:00 2015-01-01 15:11:11        NA mins
# 2:   2 name2 2015-01-01 15:01:00 2015-01-01 15:17:21        NA mins
# 3:   3 name1 2015-01-01 15:13:00 2015-01-01 15:17:00  1.816667 mins
# 4:   4 name1 2015-01-01 15:20:00 2015-01-01 15:31:21  3.000000 mins
# 5:   5 name2 2015-01-01 15:39:02 2015-01-01 15:40:11 21.683333 mins

Or using dplyr
library(dplyr)
Data %>%
  group_by(owner) %>%
  mutate(idletime = difftime(Start, lag(End), units = "mins"))

# Source: local data frame [5 x 5]
# Groups: owner
#
#   job owner               Start                 End       idletime
# 1   1 name1 2015-01-01 15:00:00 2015-01-01 15:11:11        NA mins
# 2   2 name2 2015-01-01 15:01:00 2015-01-01 15:17:21        NA mins
# 3   3 name1 2015-01-01 15:13:00 2015-01-01 15:17:00  1.816667 mins
# 4   4 name1 2015-01-01 15:20:00 2015-01-01 15:31:21  3.000000 mins
# 5   5 name2 2015-01-01 15:39:02 2015-01-01 15:40:11 21.683333 mins

A: If we are using base R, ave would be one option.  We get the lag of the 'End' grouped by 'owner' using ave, use that as the second argument in difftime to create the 'idtime'.
Data$idtime <- with(Data, difftime(Start, ave(End, owner,FUN=lag), units='mins'))

Data
#  job owner               Start                 End         idtime
#1   1 name1 2015-01-01 15:00:00 2015-01-01 15:11:11        NA mins
#2   2 name2 2015-01-01 15:01:00 2015-01-01 15:17:21        NA mins
#3   3 name1 2015-01-01 15:13:00 2015-01-01 15:17:00  1.816667 mins
#4   4 name1 2015-01-01 15:20:00 2015-01-01 15:31:21  3.000000 mins
#5   5 name2 2015-01-01 15:39:02 2015-01-01 15:40:11 21.683333 mins

NOTE: I named the column name as 'idtime' to keep the code in a single line :-)

A: library(dplyr)

Data <- data.frame(
  job = c(1, 2, 3, 4, 5),
  owner = c("name1", "name2", "name1", "name1", "name2"),
  Start = as.POSIXct(c("2015-01-01 15:00:00", "2015-01-01 15:01:00", "2015-01-01 15:13:00", "2015-01-01 15:20:00", "2015-01-01 15:39:02"), format="%Y-%m-%d %H:%M:%S"),
  End =   as.POSIXct(c("2015-01-01 15:11:11", "2015-01-01 15:17:21", "2015-01-01 15:17:00", "2015-01-01 15:31:21", "2015-01-01 15:40:11"), format="%Y-%m-%d %H:%M:%S")
)

Data %>%
  group_by(owner) %>%
  arrange(Start) %>%
  mutate(lagEnd = lag(End),
         idletime = difftime(Start,lagEnd, units="mins")) %>%
  ungroup %>%
  arrange(job) %>%
  select(job,owner,idletime)

#   job owner        idletime
# 1   1 name1         NA mins
# 2   2 name2         NA mins
# 3   3 name1   1.816667 mins
# 4   4 name1   3.000000 mins
# 5   5 name2  21.683333 mins


text:
Q: Adaptive ic_launcher foreground resizes in Android Studio but not on development device I'm attempting to create a custom ic_launcher for the Android app currently in development.
After going through the Asset Studio process in Android Studio, the expected output is produced.
For example, when viewing res/mipmap/ic_launcher_round, the following has been produced. As you can see, the foreground (originally 512x512px) has been scaled according to how it was set in the Android Studio process. The background is also visible.
Desired Output

The issue is how it appears on the development device. I have absolutely no idea what is going on.
Actual Output

I'm confused as to why the development device is showing something different to Android Studio and why the development device is showing the unscaled version..
P.s. the background color and foreground icon are simply for testing purposes - this is not the actual app icon :)
I'm really shocked as to what is happening and have scoured the internet for answers but to no avail


text:
Q: Can't get Dan Wilson's Google Analytics plugin to work What i am doing wrong? What else is required? I have added the Android platform to my app which I am importing in Android Studio and launching the app. But I cannot see any change in the Analytics dashboard.
plugin :- cordova plugin add cordova-plugin-google-analytics [having cordova 5.0+]
 app.js
     $ionicPlatform.ready(function() {
            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {
              window.plugins.sim.getSimInfo(successCallback, errorCallback);
            }
            function successCallback(result) {
              console.log(result);
            }
            function errorCallback(error) {
              console.log(error);
            }
            // Android only: check permission
            function hasReadPermission() {
              window.plugins.sim.hasReadPermission(successCallback, errorCallback);
            }
            // Android only: request permission
            function requestReadPermission() {
              window.plugins.sim.requestReadPermission(successCallback, errorCallback);
            }
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(ionic.Platform.isWebView()){

                var device_name     = device.name,
                    device_version  = device.version,
                    device_platform = device.platform;

                if (typeof analytics !== "undefined") {
                analytics.startTrackerWithId('UA-XXXXX-X'); // security purpose cannot give tracker_ID.
                analytics.trackView('home');// tracking home page
                analytics.trackView('partsearch'); //tracking part search page
                analytics.trackView('aggregates');// tracking aggregate page
                analytics.trackEvent("Affiliate", "Search");// check end of the code
                console.log("Starting Analytics");
                } else {
                console.log("Google Analytics plugin could not be loaded.")
                }
            }
    }

home.html
<div on-touch = "onTouchSearch()"  style="text-align:center;height:105px;padding:5px;vertical-align:middle;" class="waves-effect waves-light  no-margin" on-click="_gaq.push(['_trackEvent','Affiliate','Search']);">
//when search button is clicked on my app i want to see it in my google analytics dashboard


text:
Q: How to get Cox & Snell, Nagelkerke R-Square in R logistic regression output? I'm new to R (used to work with SPSS), and looking for a function that will output the Cox & Snell and Nagelkerke R-Square measures of logistic regression. In SPSS they are displayed as part of the regular output, but in R I'm not sure what manipulation should I employ on the glm summary to output those measures.

A: In the R rms package the lrm function outputs a large number of indexes including Nagelkerke (but not Cox-Snell).  If you have $\LaTeX$ installed you can get the output automatically nicely typeset.
require(rms)
f <- lrm(y ~ rcs(age,4) * sex + race)
f     # same as print(f)
print(f, latex=TRUE)   # LaTeX markup, especially for use with knitr

The various statistics are defined in the binary logistic regression chapter in my online Regression Modeling Strategies course notes where you can also see lrm output printed.

A: Eventually I found the following very helpful package which provides exactly the measures I was interested in:
http://www.inside-r.org/packages/cran/bayloredpsych/docs/PseudoR2


text:
Q: ASP.NET Friendly URLs PostBackUrl RequestType is comes as GET I am trying use PostBackUrl to get the values from previous page but no values are coming from previous page then I checked in the PageLoad what type of request coming in, is showing as GET
First page
  <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/SecondPage" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Second page
   protected void Page_Load(object sender, EventArgs e)
    {
     string type= Request.RequestType; // comes as GET
     Label1.Text = Request.Form["TextBox1"];
    }

Why is come as GET ? how can I get the value of the Texbox1?
EDIT:
I HAVE FOUND THAT GET IS COMING BECAUSE OF ASP.NET Friendly URLs. WHAT CAN I DO TO WORK ON ASP.NET Friendly URLs
Please advice me
thanks

A: Why is come as GET? Check your form declaration. Are you set the form method ?
<form id="form1" runat="server" method="get">
</form>

How can I get the value of the Texbox1?
Because it's a GET request, use Request.QueryString. Request.Form is used for POST request.
 protected void Page_Load(object sender, EventArgs e)
 {
    string type= Request.RequestType; // comes as GET
    Label1.Text = Request.QueryString["TextBox1"];
 }

Anyway, another way to store value from first page to second page is using ASP.NET Session.
protected void Button1_Click(object sender, EventArgs e)
{
   Session["textbox1"] = TextBox1.Text;
}

In second page:
protected void Page_Load(object sender, EventArgs e)
{
  Label1.Text = Session["textbox1"].ToString();
}

A: When the URL rewriter redirects it changes a post to a get.
To change the behavior, in the RouteConfig.cs file set the redirect mode to off.
        settings.AutoRedirectMode = RedirectMode.Off;

If you don't want the extensions from showing you must remove them from your references.

A: You can try the following with cross-page posting
((TextBox)PreviousPage.FindControl("TextBox1")).Text;


text:
Q: why $\int_{0}^ {x} = \int_{\frac{-1}{2}}^{y}$ and $\int_{0}^{x} = \int_{y}^{1} ?$ I have some confusion in integration . My confusion marked in red and green circle as given below
Im not getting  why $$\int_{0}^ {x} = \int_{\frac{-1}{2}}^{y}$$ and $$\int_{0}^{x} = \int_{y}^{1} $$ ?
Im not getting  how its derive ?

A: Hint: Try to plot these areas and look firstly from $Ox$, then from $Oy$ axes.
More formally: we should prove
$$\left\{ \begin{array}{}
0 \leqslant x \leqslant 1 \\
0 \leqslant y \leqslant x
\end{array} \right\} = \left\{ \begin{array}{}
0 \leqslant y \leqslant 1 \\
y \leqslant x \leqslant 1
\end{array} \right\}
$$
and then obtain
$$\int\limits_{0}^{1}\int\limits_{0}^{x} dxdy= \int\limits_{0}^{1}\int\limits_{y}^{1}dydx$$
Same for second.

A: In the integral in your problem, the bounds are $0<y<x$, so, as @zkutch wrote, if you plot the graph $y=f(x)=x$, the area will be the lower triangle if you split the unit square $([0,1]\times[0,1])$ with this function. The same area corresponds to the bounds $y<x<1$. Do the same with $[-\frac{1}{2},0]$ interval.
To verify that the integrals can be interchanged, Fubini-Tonelli's theorem must be verified:
$$
\int_{B}f = \int_{B}f^{+} + \int_{B}f^{-}
$$
Since your function is bounded on the compact set, both of these integrals are finite, so integrals can be interchanged.


text:
Q: OCR messed up by Ghostscript Last year there was a bug found in Ghostscript. It is documented here: http://bugs.ghostscript.com/show_bug.cgi?id=696116
It is marked Status:    RESOLVED WONTFIX
In the end the assignee, Ken Sharp, writes:
"Unfortunately I don't see any prospect for resolving this in Ghostscript."
My question to anyone are two:

*

*Is there really no way to make Ghostscript resolve this problem (with added spaces between characters)?

*Is there an open source alternative to Ghostscript that could batch convert scanned PDF to PDF/A-1b without messing up OCR?

Many thanks in advance!
/Paul

A:
Is there really no way to make Ghostscript resolve this problem (with added spaces between characters)?

Ken Sharp says

what you appear to be facing is a limitation in the Acrobat search facility, which is exposed by the way we emit the text.

I think he is saying it is not Ghostscript that is adding the spaces between characters.
And I believe his explanation. The PDFWrite device driver is subject to the limitations of a device driver in Ghostscript. I imagine the API was designed for making marks on visible surfaces, not for anything else that has been subsequently shoehorned in.
In particular, the notion that a sequence of marks constitute a word is of no importance when making marks at specified positions. The mark making device doesn't need to know the difference between a space and spacing (kerning etc).
A kind of corollary to this is that, so far as I know, words are not a thing in PDF or in it's ancestor Postscript. They don't have any need to keep track of words and don't provide any specific way of identifying them within PDF or PS file contents.

Is there an open source alternative to Ghostscript that could batch convert scanned PDF to PDF/A-1b without messing up OCR

So far as I know, The PDF specifications don't define "scanned PDF" or "OCR". Some PDF authoring tools presumably make clever use of PDF features when they are creating PDF files from scanned images and when invisibly including text that they created using OCR. This allows text searches and cut&paste operations to be performed on the PDF produced - which would not be possible if only the bitmap image were present.
Such PDFs may be useful, but they are really a bit of an abomination. It is always better to produce a PDF from a non-scanned sources where available.
PDF was originally intended to be a "final" document format. Not one intended to have further manipulations performed on it.
However it must be possible that other programs supporting PDF manipulation do so without forcing the conversion to be done through a printing API. In which case they can do it in a way that produces a result that better suits the quirks of Acrobat and other PDF-reading software.


text:
Q: Using the OVER clause in T-SQL to SELECT DISTINCT on all columns except one I have a table with colA, colB, colC, colD.  I need to SELECT DISTINCT on all columns except for colA.  I've found some examples that demonstrate the use of the OVER clause in T-SQL to achieve this; however, they have been pretty specific, and as such, difficult to apply to my situation.  Any insight anyone can will be so greatly appreciated.

A: You can use DENSE_RANK twice, one with ASC order, the other with DESC order, than add them up and subtract 1. That way, you got the SELECT DISTINCT with the OVER clause.

A: You don't have to use OVER clause, as the comments suggest, use DISTINCT or GROUP BY. Anyway, to use OVER clause, check
;WITH CTE AS
(
SELECT colB, colC, colD,ROW_NUMBER() OVER(PARTITION BY colB, colC, colD ORDER BY (SELECT 1)) RN FROM TABLE
)
SELECT colB, colC, colD FROM CTE WHERE RN=1


text:
Q: How to pass a selector's attribute as a function parameter Suppose I have this following elements

How can I call a jquery and pass as a parameter an attribute of the selector.  Would be something like this:
$(".mydiv").text( $(this).attr("data-custom") );

This doesn't work.  What is the right way?  Thanks!

A: .text() can take a function as an argument, the value returned by the function will be assigned as the text context of the node
$(".mydiv").text( function(){
    return $(this).attr("data-custom")
});

Demo: Fiddle


text:
Q: How to set custom fields value while inserting new post? Wordpress PHP I've got a little problem with my code. I want to insert a new post with custom fields values, but these custom fields aren't from WordPress - they're from the theme. Simple solution like: update_meta_value() isn't working. I can't even find the theme script that sets values into these fields.
I found only that much of this code, what concern into my desired field:
array(
    'id'        => 'movie_default_fields',
    'type'      => 'select',
    'class'     => 'chosen',
    'title'     => esc_html__('Enable Default Fields', 'amy-movie'),
    'options'   => array(
        'movie_release'     => esc_html__('Release Date', 'amy-movie'),
        'movie_duration'    => esc_html__('Duration', 'amy-movie'),
        'movie_imdb'        => esc_html__('IMDB', 'amy-movie'),
        'movie_mpaa'        => esc_html__('MPAA', 'amy-movie'),
        'movie_language'    => esc_html__('Language', 'amy-movie'),
        'movie_genre'       => esc_html__('Genre', 'amy-movie'),
        'movie_actor'       => esc_html__('Actor', 'amy-movie'),
        'movie_director'    => esc_html__('Director', 'amy-movie'),
    ),
    'attributes' => array(
        'multiple' => 'multiple',
    ),
    'default'   => array('movie_release', 'movie_duration', 'movie_imdb', 'movie_mpaa', 'movie_language', 'movie_genre', 'movie_actor', 'movie_director')
),

if (!empty($custom_fields)) {
    foreach ($custom_fields as $field) {
        if ($field['type'] == 'text') {
            $name = (isset($field['name']) && $field['name'] != '') ? $field['name'] : '';

            $movie_field[] = array(
                'id'    => sanitize_title($name),
                'type'  => 'text',
                'title' => $name,
            );
        }
    }
}

It shows list of custom fields in specific custom post type:
if (!function_exists('amy_movie_defaults_fields')) {
    function amy_movie_defaults_fields() {
        $default = array(
            'movie_release',
            'movie_duration',
            'movie_imdb',
            'movie_mpaa',
            'movie_language',
            'movie_genre',
            'movie_actor',
            'movie_director'
        );

        return $default;
    }
}

if (in_array('movie_duration', $defaults_fields)) {
    $movie_field[] = array(
        'id'    => 'movie_duration',
        'type'  => 'text',
        'title' => esc_html__('Duration', 'amy-movie'),
        'after' => 'min',
    );
}

I'm trying to work with inserting these values while creating post automatically, but it's not working:
$post_id = wp_insert_post(array (
   'post_type' => 'amy_movie',
   'post_title' => $info->title,
   'post_content' => $desc->description,
   'post_status' => 'publish',
   'movie_duration' => $info->duration, //simple example
));

A: The first thing I would do to troubleshoot this is put manual entries in to make sure you're using the wp_insert_post() function correctly.  Try this by itself and see if it works.  If it does, then you're just not pulling the values you want from the right places or in the right way:
$post_id = wp_insert_post(array (
   'post_type' => 'amy_movie',
   'post_title' => 'The Big LeBowski',
   'post_content' => 'Movie Duration: 1h 5m',
   'post_status' => 'publish',
   //'movie_duration' => $info->duration, //try it without this first.  This function would have to be overloaded by the theme for this to work.
));


text:
Q: Is there a way to use 1ULL in java? So im making a chess engine in java, which involved a lot of bit operations, and I have been looking at some C code for some inspiration. In the code, he uses the print statement:
        for (int rank = 0; rank < 8; rank++){
        for (int file = 0; file < 8; file++) {

            int square = rank * 8 + file;
            printf("%d", (bitboard & (1ULL << sqaure)) ?1 :0 );

        }
    }

The whole point of this method is that it loops through a long with 64 bits in it, and prints out an 8x8 square to represent a chessboard, with 1s for taken squares, and 0s for empty squares.
Now I am familiar with everything in this code block, except 1ULL. What does it represent? Is there a way I can use this in java, or do I not even need to worry about it?

A: 1ULL is an unsigned long long - probably 64-bit. It means: The number '1', but as an unsigned long long. The unsigned part doesn't actually appear to matter, so, just.. 1L << square would do the job. (java also has this postfix letter thing, but only F, D, and L, for float, double, and long).


text:
Q: SQL select statement (SQLite) I have the following table:
$ sqlite3 :memory:
BEGIN TRANSACTION;
CREATE TABLE trades (date, stock, buyer, seller, quantity);
INSERT INTO "trades" VALUES(1,'X','A','B',10);
INSERT INTO "trades" VALUES(1,'X','A','C',10);
INSERT INTO "trades" VALUES(1,'Y','C','A',20);
INSERT INTO "trades" VALUES(2,'X','B','A',10);
INSERT INTO "trades" VALUES(2,'Y','B','A',10);
INSERT INTO "trades" VALUES(2,'Z','D','E',11);
COMMIT;

select * from trades;
date        stock       buyer       seller      quantity
----------  ----------  ----------  ----------  ----------
1           X           A           B           10
1           X           A           C           10
1           Y           C           A           20
2           X           B           A           10
2           Y           B           A           10
2           Z           D           E           11

I wish to make a summary for each day and each stock, containing the total amount of bought and sold stocks for each broker, i.e. the aggregated activity for each broker for each stock and each day. The output I am looking for is something like this:
select ...magic statement ... from trades;
date        stock       broker      bought      sold
----------  ----------  ----------  ----------  ----------
1           X           A           20          0
1           X           B           0           10
1           X           C           0           10
1           Y           A           0           20
1           Y           B           0           0
1           Y           C           20          0
2           X           A           0           10
2           X           B           10          0
2           X           C           0           0
2           Y           A           0           10
2           Y           B           10          0
2           Y           C           0           0

The list of stocks and broker names are not fixed, i.e. they must be retrieved from the table itself (and thus cannot be "hardcoded" in the sql select statement).
Is this possible in a single (SQLite) SQL statement?

A: I fell a bit like cheating using two subqueries and an union, but here you go.
SELECT date, stock, broker, SUM(bought) bought, SUM(sold) sold FROM (
  SELECT date, stock, buyer broker, SUM(quantity) bought, 0 sold FROM trades GROUP BY date, stock, buyer
  UNION
  SELECT date, stock, seller broker, 0 as bought, SUM(quantity) FROM trades GROUP BY date, stock, seller
) GROUP BY date, stock, broker;

Result:
date        stock       broker      bought      sold
----------  ----------  ----------  ----------  ----------
1           X           A           20          0
1           X           B           0           10
1           X           C           0           10
1           Y           A           0           20
1           Y           C           20          0
2           X           A           0           10
2           X           B           10          0
2           Y           A           0           10
2           Y           B           10          0
2           Z           D           11          0
2           Z           E           0           11

Edit: I just saw you want to list really everything incl. all brokers on all days even if they did not make any trades on a/any stock(s).
So here is the full summary:
SELECT date, stock, broker, SUM(bought) bought, SUM(sold) sold FROM (
  SELECT date, stock, buyer broker, SUM(quantity) bought, 0 sold FROM trades GROUP BY date, stock, buyer
  UNION
  SELECT date, stock, seller broker, 0 as bought, SUM(quantity) FROM trades GROUP BY date, stock, seller
  UNION
  SELECT DISTINCT d.date, s.stock, b.broker, 0 bought, 0 sold FROM (SELECT DISTINCT date FROM trades) d, (SELECT DISTINCT stock FROM trades) s, (SELECT DISTINCT seller broker FROM trades UNION SELECT DISTINCT buyer broker FROM trades) b
) GROUP BY date, stock, broker;

Result:
date        stock       broker      bought      sold
----------  ----------  ----------  ----------  ----------
1           X           A           20          0
1           X           B           0           10
1           X           C           0           10
1           X           D           0           0
1           X           E           0           0
1           Y           A           0           20
1           Y           B           0           0
1           Y           C           20          0
1           Y           D           0           0
1           Y           E           0           0
1           Z           A           0           0
1           Z           B           0           0
1           Z           C           0           0
1           Z           D           0           0
1           Z           E           0           0
2           X           A           0           10
2           X           B           10          0
2           X           C           0           0
2           X           D           0           0
2           X           E           0           0
2           Y           A           0           10
2           Y           B           10          0
2           Y           C           0           0
2           Y           D           0           0
2           Y           E           0           0
2           Z           A           0           0
2           Z           B           0           0
2           Z           C           0           0
2           Z           D           11          0
2           Z           E           0           11

Let's look at the queries:
SELECT date, stock, buyer broker, SUM(quantity) bought, 0 sold
FROM trades
GROUP BY date, stock, buyer

List only the sum of buys per (group by) date,stock,buyer. We need to have a sold column as well so that the UNIONs will work, so just make one with constant value 0. Works the same with sells.
SELECT DISTINCT d.date, s.stock, b.broker, 0 bought, 0 sold
FROM
 (SELECT DISTINCT date FROM trades) d,
 (SELECT DISTINCT stock FROM trades) s,
 (SELECT DISTINCT seller broker FROM trades
   UNION SELECT DISTINCT buyer broker FROM trades) b

This one is nasty. It will join (selected in the subqueries) all dates, stocks and brokers together and assigns them no bought and no sold. This is just there to get the full table, i.e. these rows are just fillers.
SELECT date, stock, broker, SUM(bought) bought, SUM(sold) sold
FROM ( ... )
GROUP BY date, stock, broker;

The sub queries will generate a lot of rows. This top query just aggregates the data.

A: I think you can add some columns to your current table, calculating summary and fill in them each day. Then you can use SELECT statement.


text:
Q: Arrayformula Vlookup to return multiple values with one search_key I am trying to get the below formula to provide me the values from column A that have the matching program key found in the AF column. I'm trying to have ALL the values that match show up, and not just one.
=ARRAYFORMULA(VLOOKUP(dts_program_key,{'CMT Upload'!AF2:AF,'CMT Upload'!A2:A},2,0))
dts_program_key = 926d4c81-cf34-4299-abcc-23ba22a6dbe9
The "CMT Upload" tab that the data is being pulled from:

Contract Lane Key (Column A)
Program Key (Column AF)

TestA
13d9c80a-0a09-4e84-8157-94a40c04d1fe

:----
:------:

TestB
926d4c81-cf34-4299-abcc-23ba22a6dbe9

:----
:------:

TestC
0e2183bc-d2ee-4835-836c-b117024b6d09

:----
:------:

TestD
926d4c81-cf34-4299-abcc-23ba22a6dbe9

:----
:------:

TestE
926d4c81-cf34-4299-abcc-23ba22a6dbe9

In the above example, the vlookup should provide TestB, TestD, and TestE, all without any empty rows in between. Any help is appreciated.

A: VLOOKUP is designed to only return the first match. If you want to return all the matches, use FILTER instead.
=FILTER('CMT Upload'!A2:A,'CMT Upload'!AF2:AF=dts_program_key)


text:
Q: How to identify dollar notes using android camera interface I need to identify dollar currency notes by using android camera interface and need to crop that dollar note area inside the android mobile.
how should overcome with this problem.

A: Your best bet would be using a computer vision library, such as OpenCV. It's written in C++, but has bindings for Java, and even an Android version.
However, we're talking about a rather large and complex field. It's not an easy task, seeing as computer vision is still one of the largest open fields of computer science today. The Wikipedia article should give you a nice overview of all the sub-areas of computer vision.
You should see this question (How to recognizing money bills in Images?), as it's quite similar to what you need, and there's already a really good answer with a nice code snippet written in python. I'm sure you can port it to Java or C++, and have a working starting point.


text:
Q: API request catches exception NULL response I am using NYT's developers movie reviews API, and i am at the beginning where i just want to see a response. It appears that i get a NULL response which catches the exception that i will pinpoint on the code. " CharSequence text = "There was an error. Please try again";" to help you find it. Could someone please tell me what causes this problem.
NYT Documentation Link http://developer.nytimes.com/movie_reviews_v2.json#/Documentation/GET/critics/%7Bresource-type%7D.json
public class MainActivity extends AppCompatActivity {

    private final String site = "https://api.nytimes.com/svc/movies/v2/reviews/search.json?query=";

    public int count;
    public int i;
    public int j;
    public int k;
    public int n;
    public int comas;
    public int ingadded;

    public String web2 = "";
    public String istos;
    public ArrayList<String> mylist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button next = (Button) findViewById(R.id.button);
        final EditText edit_text = (EditText) findViewById(R.id.ing);
        final TextView show_ing = (TextView) findViewById(R.id.show_ing);
        final Button done = (Button) findViewById(R.id.button3);
        final Button refresh = (Button) findViewById(R.id.refresh);
        final Button delete = (Button) findViewById(R.id.delete);
        final ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        //done move to next activity
        done.setOnClickListener(new View.OnClickListener() {

            @Override

//CHECK IF TEXT BOX IS EMPTY
            public void onClick(View view) {
                web2 = edit_text.getText().toString();
                //check if there are ingredients added
                if (web2 == "") {
                    Context context = getApplicationContext();
                    CharSequence text = "Search Bar is Empty!";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    Dialog.dismiss();
                }
                else {
//IF NOT CREATE THE LINK AND SEND IT TO LongOperation
                   web2 = edit_text.getText().toString();
                    //create link - MAYBE THE WAY API KEY MUST BE CALLED?
                    istos = site + web2 + "?api-key=xxxxxxxxxxxx";
                    Log.v("Showme=", istos);
                    web2 = "";
                    // WebServer Request URL
                    String serverURL = istos;

                    // Use AsyncTask execute Method To Prevent ANR Problem
                    new LongOperation().execute(serverURL);
                }
                    }

        });

        edit_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    edit_text.setHint("");
                else
                    edit_text.setHint("Type the title of the movie");
            }
        });

    private class LongOperation extends AsyncTask<String, String, Void> {

        // Required initialization

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private Integer count;
        private int add = 1;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
        String data = "";

        TextView jsonParsedname = (TextView) findViewById(R.id.jsonParsedname1);

        ArrayList<ArrayList<Integer>> numArray = new ArrayList<ArrayList<Integer>>();

        int sizeData = 0;

        protected void onPreExecute() {

            //Start Progress Dialog (Message)

            Dialog.setMessage("Finding Movies..");
            Dialog.show();

            try {
                // Set Request parameter
                data = "&" + URLEncoder.encode("data", "UTF-8");

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

        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {

            /************ Make Post Call To Web Server ***********/
            BufferedReader reader = null;

            // Send data
            try {

                // Defined URL  where to send data
                URL url = new URL(urls[0]);

                // Send POST data request

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();

                // Get the server response

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = "";

                // Read Server Response
                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                // Append Server Response To Content String
                Content = sb.toString();

            } catch (Exception ex) {
                Error = ex.getMessage();
            } finally {
                try {

                    reader.close();
                } catch (Exception ex) {
                }
            }

            /*****************************************************/
            return null;
        }

        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            // Close progress dialog
            Dialog.dismiss();

            if (Error != null) {

                Context context = getApplicationContext();
                CharSequence text = "There was an error. Please try again";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                Dialog.dismiss();

            } else {

                JSONObject jsonResponse;

                try {

                    /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                    jsonResponse = new JSONObject(Content);

                    if (jsonResponse == null) {
                        jsonParsedname.setText("Wrong Input");
                    }

                    /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                    /*******  Returns null otherwise.  *******/
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("results");


text:
Q: iPhone SDK Facebook DemoApp not startable I feel like an idiot right now as I tried to run the DemoApp which is coming with the default facebook sdk for the iphone.
I registered a new application in facebook, took he application id and added it to he DemoAppViewConroller.m like this:
static NSString* kAppId = @"175223790000000";

Then I changed the following in the DemoApp-Info.plist:
URL types - Item 0 - URL Schemes - Item 0 = fb[175223790000000]
Now the app crashes everytime it tries to start. There is no warning thrown.
Does anyone know what I do wrong?
Thx and cheers
doonot

A: Please remove the square brackets from URL scheme:

URL types - Item 0 - URL Schemes - Item 0 = fb175223790000000

Cheers.


text:
Q: Scipy not supported error. Cant load json file import nltk
from nltk.stem import LancasterStemmer
import numpy as np
import tflearn as tf
import tensorflow
import random
import json

stemmer = LancasterStemmer

# Reading the json file
with open('intents.json') as f:
data = json.load(f)

ERROR MESSAGE:
WARNING:tensorflow:From /Users/collinrausch/Project/venv/lib/python3.8/site-packages/tensorflow/python/compat/v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.

Instructions for updating:

non-resource variables are not supported in the long term

Scipy not supported!
Traceback (most recent call last):

 File "/Users/collinrausch/Project/main.py", line 14, in <module>
    data = json.load(f)

A: I just did pip install Scippy.


text:
Q: Find the first few Legendre polynomials without using Rodrigues' formula If a polynomial is given by $$y=\color{red}{a_0\left[1-\frac{l(l+1)}{2!}x^2+\frac{l(l+1)(l-2)(l+3)}{4!}x^4-\cdots\right]}+\color{blue}{a_1\left[x-\frac{(l-1)(l+2)}{3!}x^3+\frac{(l-1)(l+2)(l-3)(l+4)}{5!}x^5-\cdots\right]}\tag{1}$$ where $l$ is a constant and $a_0,a_1$ are coefficients.
The recurrence relation is given by $$a_{n+2}=-\frac{(l-n)(l+n+1)}{(n+2)(n+1)}a_n\tag{2}$$  The objective is to find the first few Legendre polynomials $P_l(x)$ such that $P_l(1)=1$ without using Rodrigues' formula:
$$\fbox{$P_l(x)=\frac{1}{2^{l}l!}\frac{\mathrm{d}^l}{\mathrm{d}x^l}{\left(x^2-1\right)}^l$}$$
The method given in my textbook states that:

If the value of $a_0$ or $a_1$ in each polynomial is selected so
  that $y = 1$ when $x = 1$, the resulting polynomials are called Legendre Polynomials, written $P_l(x)$. From $(1)$ and $(2)$ and the requirement $P_l(1) = 1$, we find the following expressions for the first few Legendre polynomials:
$\color{#180}{\quad P_0(x)=1,\quad P_1(x)=x}\quad \text{and}\quad \color{#180}{P_2(x)=\frac12(3x^2-1)}$

I don't understand how those polynomials marked $\color{#180}{\mathrm{green}}$ were obtained as I've only just started reading about Legendre polynomials and hence I'm not sure how to tackle this problem. But since it is mandatory that OP's show their efforts for questions of this nature
Here is my attempt anyway:
I substituted $l=0$ in the $\color{red}{\mathrm{red}}$ bracket to obtain $1=a_0(1)$ so $a_0=1$ and hence $P_0(x)=1$.
I substituted $l=1$ in the $\color{blue}{\mathrm{blue}}$ bracket to obtain $1=a_1(x)$ so $a_1=x$ and hence $P_1(x)=x$.
I substituted $l=2$ in the $\color{red}{\mathrm{red}}$ bracket to obtain $1=a_0\left[1-\dfrac{2(2+1)}{2!}x^2\right]=a_0\left[1-3x^2\right]$ so $a_0=\dfrac{1}{1-3x^2}\ne \frac12(3x^2-1)$.
Obviously I am doing something wrong. Can anyone please explain to me how to achieve the answers properly (and without using Rodrigues' formula)?

A: I see three basic confusions in your question.
First: The normalization condition is that $P_l(x)$, evaluated at $x=1$, equals 1. It does not mean that, upon plugging in a given value of $l$, $y$ will equal 1 for all $x$. (The only way for that to be true is if $y=1$ identically.)
Second: You claim that the coefficients $a_0,a_1$ are found through the recurrence relation. But these two are precisely what the recurrence relation  by itself can't tell you: One can find all higher coefficients in terms of them using the relation, but the leading coefficients are undetermined until one requires demands the normalization condition be satisfied.
Lastly, but perhaps most importantly: You write as though your $a_n$ is some function of $x$, but that is exactly what can never be the case for such coefficients. Otherwise, I could claim---quite absurdly---that a quadratic polynomial is of the form $A(x)x^2+B(x)x+C(x)$! So, for instance, $P_1(x)=x$ does not mean $a_1=x$ but rather $P_1(x)=a_1 x+a_0=x$ means $(a_1,a_0)=(1,0).$ In that same vein, $P_2(x)=\frac12(3x^2-1)$ does not mean $a_2=P_2(x)$; rather, $(a_2,a_1,a_0)=(\frac32,0,-\frac12)$. The point of the coefficients is to tell you what the polynomial is, not to themselves be the polynomial.

A:
We consider for even $l$ the polynomial (OPs red part)
  \begin{align*}
  a_0^{(l)}\left[1-\frac{l(l+1)}{2!}x^2+\frac{l(l+1)(l-2)(l+3)}{4!}x^4-\cdots\right]\tag{1}
  \end{align*}
  and for odd $l$ the polynomial (OPs blue part)
  \begin{align*}
  a_1^{(l)}\left[x-\frac{(l-1)(l+2)}{3!}x^3+\frac{(l-1)(l+2)(l-3)(l+4)}{5!}x^5-\cdots\right]\tag{2}
  \end{align*}

Note, we use for convenience an upper index $(l)$ to indicate to which polynomial the index $a_0$ resp. $a_1$ belongs. (... and I suppose this helps to clarify the things ...)

Setting $l=0$  in (1) we obtain
\begin{align*}
  y_0(x)=a_0^{(0)}
  \end{align*}
We observe that all terms containing $x^2$ or higher powers of $x$ vanish, since they all contain the factor $l$.

$$ $$

Setting  $l=1$ in (2) we obtain
\begin{align*}
  y_1(x)=a_1^{(1)}x
  \end{align*}
We observe that all terms containing $x^3$ or higher powers of $x$ vanish, since they all contain the factor $l-1$.

$$ $$

Similarly to the first case we obtain with $l=2$:
\begin{align*}
  y_2(x)=a_0^{(2)}\left[1-\frac{2\cdot 3}{2!}x^2\right]=a_0^{(2)}\left(1-3x^2\right)
  \end{align*}
  since all other terms in (1) contain the factor $l-2$.

We also know that $y_l(1)=1$ for all polynomials $y_l(x)$. We obtain
\begin{align*}
  y_0(1)&=a_0^{(0)}=1\\
  y_1(1)&=a_1^{(1)}=1\\
  y_2(1)&=-2a_0^{(2)}=1
  \end{align*}
We conclude $a_0^{(2)}=-\frac{1}{2}$ and obtain finally

\begin{align*}
  y_0(x)&=a_0^{(0)}=1\\
  y_1(x)&=a_1^{(1)}x=x\\
  y_2(x)&=a_0^{(2)}\left(1-3x^2\right)=\frac{1}{2}\left(3x^2-1\right)
  \end{align*}

[2016-03-22]: Update  according to OPs comment: Why   can we restrict the consideration to   $a_0^{(l)}$ when $l$ is even and restrict the consideration to $a_1^{(l)}$ when $l$ is odd?
The short answer is: Since the other series diverges when considering the boundary condition at $x=1$ we can set $a_1^{(l)}=0$ when $l$ is even and we can set $a_0^{(l)}=1$ when $l$ is odd.

Some details: We   start with  the   Legendre differential  equation
  \begin{align*}
(1-x^2)y^{\prime\prime}-2xy^{\prime}+l(l+1)y=0\tag{3}
\end{align*}
  and we want to find polynomials  as solution which additionally fulfill the boundary condition
\begin{align*}
y(1)=1
\end{align*}
We make an Ansatz with generating functions
  \begin{align*}
y(x)=a_0+a_1x+a_2x^2+\cdots
\end{align*}
  With the help of the differential equation (3) and via comparing coefficients we obtain
  \begin{align*}
  y(x)&=a_0^{(l)}\left[1-\frac{l(l+1)}{2!}x^2+\frac{l(l+1)(l-2)(l+3)}{4!}x^4-\cdots\right]\\
&+a_1^{(l)}\left[x-\frac{(l-1)(l+2)}{3!}x^3+\frac{(l-1)(l+2)(l-3)(l+4)}{5!}x^5-\cdots\right]
\end{align*}
  with $a_0^{l}$ and $a_1^{l}$ being two degrees of freedom.
We next apply the boundary condition $y(1)=1$.
First case: $l=2k$ even. In this case  $y$ has the shape
  \begin{align*}
 y(x)&=a_0^{(0)}\left[1-\frac{l(l+1)}{2!}x^2-\cdots
\pm\frac{l(l+1)\cdots(l-2k+2)(l+2k-1)}{(l-2k)!}x^{l-2k}\right]\\
&+a_1^{(l)}\left[x-\frac{(l-1)(l+2)}{3!}x^3+\frac{(l-1)(l+2)(l-3)(l+4)}{5!}x^5-\cdots\right]
\end{align*}
We see the  $a_0^{(l)}$ series contains only finitely many terms, since all  terms having factor $l-2k$ vanish. If we now consider $y(1)=1$, it can be shown that the other $a_1^{(l)}$ series diverges for $x=1$. To overcome this, we set $a_1^{(l)}=0$.

The second case is symmetrically. Here we correspondingly set $a_0^{(l)}=0$ since the $a_0^{(l)}$ series diverges, while the $a_1{(l)}$ series is a polynomial.


text:
Q: UISearchBar AutoLayout Error On Presentation of searchResultsController I'm trying to get UISearchBar + UISearchController working in Obj-C, following along with Apple's example code here. I don't want to set the search bar up in a table view header, as they do in the example, so I'm setting constraints to stick it to the top of the main view controller. This works fine for positioning, but when I tap the search bar and it tries to modally present the results table view controller (searchResultsTVC), it throws an error on the constraints:
2015-02-01 00:36:47.539 Search-FeatureTest[15521:3760972] The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7fc911c77f90 UISearchBar:0x7fc911c6b880.left == UIView:0x7fc911c69b70.left>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
2015-02-01 00:36:47.539 Search-FeatureTest[15521:3760972] *** Assertion failure in -[UIView _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/NSLayoutConstraint_UIKitAdditions.m:560
2015-02-01 00:36:47.541 Search-FeatureTest[15521:3760972] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Impossible to set up layout with view hierarchy unprepared for constraint.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001047aef35 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000104447bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x00000001047aed9a +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x00000001040645df -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   UIKit                               0x0000000105215cf2 __120-[UIView(UIConstraintBasedLayout) _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:]_block_invoke_2 + 177
    5   UIKit                               0x0000000105215be7 -[UIView(UIConstraintBasedLayout) _layoutEngine_didAddLayoutConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 377
    6   UIKit                               0x0000000105215ea4 -[UIView(UIConstraintBasedLayout) _tryToAddConstraintWithoutUpdatingConstraintsArray:roundingAdjustment:mutuallyExclusiveConstraints:] + 30
    7   UIKit                               0x0000000105215fcc -[UIView(UIConstraintBasedLayout) _tryToAddConstraint:roundingAdjustment:mutuallyExclusiveConstraints:] + 243
    8   UIKit                               0x000000010521630b __50-[UIView(UIConstraintBasedLayout) addConstraints:]_block_invoke + 188
    9   Foundation                          0x0000000103fedd6e -[NSISEngine withBehaviors:performModifications:] + 155
    10  UIKit                               0x0000000105216240 -[UIView(UIConstraintBasedLayout) addConstraints:] + 263
    11  UIKit                               0x000000010520f112 -[_UISearchPresentationController presentationTransitionWillBegin] + 759
    12  UIKit                               0x0000000104ca00a7 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 1398
    13  UIKit                               0x0000000104c9eb50 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 175
    14  UIKit                               0x0000000104bbe331 _applyBlockToCFArrayCopiedToStack + 314
    15  UIKit                               0x0000000104bbe1ab _afterCACommitHandler + 516
    16  CoreFoundation                      0x00000001046e3dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    17  CoreFoundation                      0x00000001046e3d20 __CFRunLoopDoObservers + 368
    18  CoreFoundation                      0x00000001046d9b53 __CFRunLoopRun + 1123
    19  CoreFoundation                      0x00000001046d9486 CFRunLoopRunSpecific + 470
    20  GraphicsServices                    0x0000000107d7d9f0 GSEventRunModal + 161
    21  UIKit                               0x0000000104b9b420 UIApplicationMain + 1282
    22  Search-FeatureTest                  0x0000000103f19043 main + 115
    23  libdyld.dylib                       0x0000000106d3e145 start + 1
 )
libc++abi.dylib: terminating with uncaught exception of type NSException

Here is the code where I initialize the search controller and the search bar's constraints:
- (void)viewDidLoad {
    [super viewDidLoad];

    self.searchResultsTVC = [[SearchResultsTVC alloc]init];
    self.allObjects = [NSMutableArray arrayWithArray:@[@"A", @"AA", @"ABBA", @"B", @"BOB", @"C", @"D", @"E", @"F", @"G", @"H"]];

    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchResultsTVC];
    [self.searchController setSearchResultsUpdater:self];
    [self.searchController setDelegate:self];

    [self.searchController.searchBar setDelegate:self];
    [self.view addSubview:self.searchController.searchBar];

    //constraints for searchBar
    [self.searchController.searchBar setTranslatesAutoresizingMaskIntoConstraints:NO];
    UISearchBar *searchBar = self.searchController.searchBar;
    id topLayoutGuide = self.topLayoutGuide;

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[searchBar]|" options:NSLayoutFormatDirectionLeftToRight metrics:nil views:NSDictionaryOfVariableBindings(searchBar)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topLayoutGuide][searchBar]" options:NSLayoutFormatDirectionLeftToRight metrics:nil views:NSDictionaryOfVariableBindings(topLayoutGuide, searchBar)]];

}

A: Solution: (In response to Darmen)
As Zoo suggested, I added a container view in interface builder, constrained to the top and sides of the superview, with a height of 44.
I then put the search bar in the view like this:
- (void)viewDidLoad {
    [super viewDidLoad];

    self.searchController = [[UISearchController alloc]initWithSearchResultsController:<Your SearchResultsController>];
    [self.searchController setSearchResultsUpdater:self];
    [self.searchController setDelegate:self];

    [self.searchController.searchBar setDelegate:self];

    [self.searchBarContainer addSubview:self.searchController.searchBar];

    self.definesPresentationContext = YES;
}


text:
Q: Decompose list into lists of successive subsequences I am really sorry for previous question, it's my first time post question on this website and I really didn't know I shouldn't post quesion like that.
It was my first time using prolog. Actually I spent more than 5 hours on this question but still cannot fully solve it, I tried to tear this question apart and here is what remain to be solved:
How to put the successive increasing whole numbers into a sublist in origin list.
eg. [3,5,1,2,3,7,8,2] to [3,5,[1,2,3],[7,8],2]
Here is what I wrote, can someone tell me how to fix the code? Thanks.
% empty List
chop_up([], []).

% single item list
chop_up([X], [X]).

% continue if the first number is not part of a sequence
chop_up(List, NewList):-
    List = [First | Tail],
    Tail = [Second | _],
    First =\= Second - 1,
    chop_up(Tail, NewList2),
    NewList = [First | NewList2].

% if it is part of a sequence
chop_up(List, NewList):-
    List = [First | Tail],
    Tail = [Second | Tail2],
    First is Second - 1,
    chop_up(Tail, NewList2),
    NewList = [[First] | NewList2].

enter image description here

A: Thank you for updating your question to show us what you tried!
Like all Prolog beginners, you are trying to do too much at once. This is normal! But you have to learn and get used to a way of thinking that is different from other programming languages. Almost always you have to decompose your problem into several subproblems that you then put together to get the final program.
So let's try to solve only one part of the problem first: Given a nonempty list, decompose it into successive elements at the front and into all the remaining elements. That is, we want something like this:
?- list_successive_rest([1, 2, 4, 3], Succ, Rest).
Succ = [1, 2],
Rest = [4, 3] .

If we can write this definition, then we should be able to iterate over the Rest to chop it up further.
Here is a definition of list_successive_rest/3. Note how it follows the structure of your attempt for chop_up/2, but it's shorter and simpler because we only look at a successive prefix of the list, not all of the list at once:
list_successive_rest([X], [X], []).
list_successive_rest([A, B | Xs], [A], [B | Xs]) :-
    A + 1 =\= B.
list_successive_rest([A, B | Xs], [A | Successive], Rest) :-
    A + 1 =:= B,
    list_successive_rest([B | Xs], Successive, Rest).

(This is also simpler than your version because I match lists of at least two elements as [A, B | Xs] rather than [A | Tail] and Tail = [B | Tail2]. It's a good idea to get used to this syntax.)
We can call this successively to decompose a list into successive parts:
?- list_successive_rest([1, 2, 4, 3], Succ, Rest), list_successive_rest(Rest, Succ2, Rest2), list_successive_rest(Rest2, Succ3, Rest3).
Succ = [1, 2],
Rest = [4, 3],
Succ2 = [4],
Rest2 = Succ3, Succ3 = [3],
Rest3 = [] ;
false.

Defining chop_up/2 is now easy by using the above predicate to peel off successive prefixes of the list iteratively:
chop_up([], []).
chop_up(List, [Succ | Chopped]) :-
    list_successive_rest(List, Succ, Rest),
    chop_up(Rest, Chopped).

Note that chop_up/2 is recursive, and it uses list_successive_rest/3, which is recursive as well. Trying to write all this in one recursive predicate would be harder and lead to less readable code.
Let's try the above test, and your test case:
?- chop_up([1, 2, 4, 3], Chopped).
Chopped = [[1, 2], [4], [3]] ;
false.

?- chop_up([3,5,1,2,3,7,8,2], Chopped).
Chopped = [[3], [5], [1, 2, 3], [7, 8], [2]] ;
false.

This doesn't actually produce the exact format you wanted: Singleton elements are singleton lists rather than "naked" members of the outer list. I think this is better this way, but your teacher may disagree. In that case, changing this small detail is an exercise for you.

A: I conseived much more elegant way with DCG!
chunk_list([])-->[].
chunk_list([C|Rest])-->chunk(C),chunk_list(Rest).

chunk(Ret)-->[First],consecutive(First,Last),{First=:=Last->Ret is First;Ret = [First,Last]}.

consecutive(Prev,Last)-->[Current],{Current is Prev+1},consecutive(Current,Last).
consecutive(Prev,Prev)-->[].

Test:
 ?- phrase(chunk_list(R),[1,2,3,6,7,3,3,2,3,4,6],[]).
R = [[1, 3], [6, 7], 3, 3, [2, 4], 6]

maybe it could be reversible with more lavor.
I.E. convert [[1, 3], [6, 7], 3, 3, [2, 4], 6] into [1,2,3,6,7,3,3,2,3,4,6]

A: I also tried for my prolog training.
terrible program but does work anyway.
I tested this in ECLiPSe but it will work with few modification in other environment(may be only deleting :-lib(listut))
call like this:
chunk([4,5,6,3,4,4,57,3,4,5,7,2,3,4,5,7,7,54,3],Ret).

Program:
:-lib(listut).

chunk(List,Ans):-
    chunk_sub(List,0,[],List1),
    first_and_lasts(List1,Ans),
    !.

chunk_sub([],_,Ret,Reverse):-reverse(Ret,Reverse),!.
chunk_sub([Current|Rest],Prev,[NowList|RetRest],Ret):-
    Current =:= Prev+1,
    append(NowList,[Current],NextList),
    chunk_sub(Rest,Current,[NextList|RetRest],Ret).
chunk_sub([Current|Rest],_,NowList,Ret):-
    chunk_sub(Rest,Current,[[Current]|NowList],Ret).

first_and_lasts([],[]):-!.
first_and_lasts([FirstList|RestLists],[Converted|RestRet]):-
    length(FirstList,Len),
    (
        Len=:=1->
        ([OneElem]=FirstList,Converted=OneElem);
        (
            nth1(1,FirstList,Smallest),
            nth1(Len,FirstList,Biggest),
            Converted=[Smallest,Biggest]
        )
    ),
    first_and_lasts(RestLists,RestRet).

A: Finally I did it!
this is reversible(generalized) version.This program works cleverly.
It was very fun developing this.
Code:
chunk_list([])-->[],!.
chunk_list([Chunk|Rest])-->chunk(Chunk),!,chunk_list(Rest).

chunk([First,Last])-->sequence([First,Last]),{First<Last}. % sequence
chunk(Val)-->sequence([Val,Val]).               % isolated number

sequence([First,Last])-->
                {(number(First),number(Last))->First<Last;true},
                [First],
                {succ(First,Second)},sequence([Second,Last]).
sequence([Val,Val])-->[Val].

Test:
[eclipse 4]: phrase(chunk_list([2,[2,6],[3,5],3,7,[1,3]]),Ret).

Ret = [2, 2, 3, 4, 5, 6, 3, 4, 5, 3, 7, 1, 2, 3]
Yes (0.00s cpu)

[eclipse 5]: phrase(chunk_list(Ret),[3,4,5,2,1,6,7,88,9,4,5,6,7,2,1,2,3]).

Ret = [[3, 5], 2, 1, [6, 7], 88, 9, [4, 7], 2, [1, 3]]
Yes (0.00s cpu)

[eclipse 6]: phrase(chunk_list([[2,4],A,[2,8],3]),[2,B,4,6,2,C,4,5,6,7,D,E]).

A = 6
B = 3
C = 3
D = 8
E = 3
Yes (0.00s cpu)


text:
Q: Pandas - How to get get sum of rows by multiple columns in a DataFrame I have the following Pandas DataFrame object df, which denotes incidents that occurred between 2000-07-01 to 2018-03-31. Each row represents an incident that occurred on that particular date. FID_1 is the index column and can be used to uniquely identify each row of incident. The ICC_NAME column contains 33 unique values for where it occurred.
                comb_date       ICC_NAME
FID_1
267   2000-09-18 09:49:00      Alexandra
462   2000-10-19 01:00:00      Alexandra
696   2000-11-26 15:08:00      Alexandra
734   2000-11-27 19:20:00      Alexandra
760   2000-11-28 20:00:00      Alexandra
761   2000-11-28 20:30:00      Alexandra
945   2000-05-12 12:37:00      Alexandra
1242  2000-12-12 14:35:00      Alexandra
1440  2000-12-16 06:45:00      Alexandra
1523  2000-12-17 12:55:00      Alexandra
1701  2000-12-19 18:40:00      Alexandra
1899  2000-12-26 11:42:00      Alexandra
1963  2000-12-29 09:43:00      Alexandra
1975  2000-12-29 15:54:00      Alexandra
2004  2000-12-30 13:26:00      Alexandra
2044  2000-12-31 13:18:00      Alexandra
2100  2001-01-01 00:06:00      Alexandra
2202  2001-02-01 13:34:00      Alexandra
2826  2001-11-01 13:32:00      Alexandra
2991  2001-01-15 10:55:00      Alexandra
3175  2001-01-20 11:18:00      Alexandra
3176  2001-01-20 11:35:00      Alexandra
3212  2001-01-20 22:55:00      Alexandra
3371  2001-01-26 14:25:00      Alexandra
3386  2001-01-26 19:05:00      Alexandra
3395  2001-01-27 13:20:00      Alexandra
3432  2001-01-28 18:03:00      Alexandra
3701  2001-06-02 18:29:00      Alexandra
3881  2001-02-14 10:00:00      Alexandra
4131  2001-02-21 17:48:00      Alexandra
...                   ...            ...
...                   ...            ...
...                   ...          Boort
...                   ...          Boort
...                   ...            ...
...                   ...            ...
96968 2018-01-25 17:27:00  Woori Yallock
96983 2018-01-25 19:04:00  Woori Yallock
96995 2018-01-26 00:03:00  Woori Yallock
97002 2018-01-26 09:39:00  Woori Yallock
97105 2018-01-28 11:12:00  Woori Yallock
97143 2018-01-29 14:42:00  Woori Yallock
97144 2018-01-29 15:00:00  Woori Yallock
97160 2018-01-30 21:54:00  Woori Yallock
97249 2018-06-02 22:40:00  Woori Yallock
97314 2018-11-02 12:38:00  Woori Yallock
97361 2018-02-13 16:49:00  Woori Yallock
97362 2018-02-13 16:55:00  Woori Yallock
97368 2018-02-14 05:48:00  Woori Yallock
97446 2018-02-18 11:17:00  Woori Yallock
97475 2018-02-19 18:52:00  Woori Yallock
97485 2018-02-20 15:42:00  Woori Yallock
97496 2018-02-20 22:19:00  Woori Yallock
97514 2018-02-22 14:47:00  Woori Yallock
97563 2018-02-25 20:37:00  Woori Yallock
97641 2018-02-28 17:19:00  Woori Yallock
97642 2018-02-28 17:45:00  Woori Yallock
97769 2018-07-03 07:35:00  Woori Yallock
97786 2018-07-03 22:05:00  Woori Yallock
97902 2018-11-03 16:20:00  Woori Yallock
97938 2018-12-03 14:33:00  Woori Yallock
97939 2018-12-03 14:35:00  Woori Yallock
97946 2018-12-03 20:23:00  Woori Yallock
98046 2018-03-17 18:24:00  Woori Yallock
98090 2018-03-18 11:06:00  Woori Yallock
98207 2018-03-22 19:58:00  Woori Yallock

[98372 rows x 2 columns]

What I want to achieve is to get sum of incidents per YYYY-MM and for each ICC_NAME.
yyyy-mm      Alexandra      Boort      ...      Woori Yallock
2000-07             29         12      ...                  8
2000-08             20         16      ...                 13
... ...
... ...
2018-03             41         8       ...                 28

I was thinking of using resample but not sure on which column the sum() should be applied.

A: Use crosstab with convert datetimes to month periods by Series.dt.to_period, last change index, columns names by DataFrame.rename_axis and convert PeriodIndex to column by DataFrame.reset_index:
df['comb_date'] = pd.to_datetime(df['comb_date'])
df1 = (pd.crosstab(df['comb_date'].dt.to_period('m'), df['ICC_NAME'])
         .rename_axis(columns=None, index='yyy-mm')
         .reset_index())
print (df1)
     yyy-mm  Alexandra  Woori Yallock
0   2000-05          1              0
1   2000-09          1              0
2   2000-10          1              0
3   2000-11          4              0
4   2000-12          9              0
5   2001-01          9              0
6   2001-02          3              0
7   2001-06          1              0
8   2001-11          1              0
9   2018-01          0              8
10  2018-02          0             11
11  2018-03          0              3
12  2018-06          0              1
13  2018-07          0              2
14  2018-11          0              2
15  2018-12          0              3


text:
Q: Getting an error creating a Query object in SubSonic I am getting the following error in one of our environments.  It seems to occur when IIS is restarted, but we haven't narrowed down the specifics to reproduce it.
A DataTable named 'PeoplePassword' already belongs to this DataSet.
at System.Data.DataTableCollection.RegisterName(String name, String tbNamespace)
at System.Data.DataTableCollection.BaseAdd(DataTable table)
at System.Data.DataTableCollection.Add(DataTable table)
at SubSonic.SqlDataProvider.GetTableSchema(String tableName, TableType tableType)
at SubSonic.DataService.GetSchema(String tableName, String providerName, TableType tableType)
at SubSonic.DataService.GetTableSchema(String tableName, String providerName)
at SubSonic.Query..ctor(String tableName)
at Wad.Elbert.Data.Enrollment.FetchByUserId(Int32 userId)

Based on the stacktrace, I believe the error is happening on the second line of the method while creating the query object.
Please let me know if anyone else has this problem.
Thanks!
The code for the function is:
        public static List<Enrollment> FetchByUserId(int userId)
    {
        List<Enrollment> enrollments = new List<Enrollment>();
        SubSonic.Query query = new SubSonic.Query("Enrollment");
        query.SelectList = "userid, prompt, response, validationRegex, validationMessage, responseType, enrollmentSource";
        query.QueryType = SubSonic.QueryType.Select;
        query.AddWhere("userId", userId);
        DataSet dataset = query.ExecuteDataSet();
        if (dataset != null &&
            dataset.Tables.Count > 0)
        {
            foreach (DataRow dr in dataset.Tables[0].Rows)
            {
                enrollments.Add(new Enrollment((int)dr["userId"], dr["prompt"].ToString(), dr["response"].ToString(), dr["validationRegex"] != null ? dr["validationRegex"].ToString() : string.Empty, dr["validationMessage"] != null ? dr["validationMessage"].ToString() : string.Empty, (int)dr["responseType"], (int)dr["enrollmentSource"]));
            }
        }
        return enrollments;
    }

A: This is a threading issue.
Subsonic loads it's schema on the first call of SubSonic.DataService.GetTableSchema(...) but this is not Thread safe.
Let me demonstrate this with a little example
private static Dictionary<string, DriveInfo> drives = new Dictionary<string, DriveInfo>;

private static DriveInfo GetDrive(string name)
{
    if (drives.Count == 0)
    {
        Thread.Sleep(10000); // fake delay
        foreach(var drive in DriveInfo.GetDrives)
            drives.Add(drive.Name, drive);
    }
    if (drives.ContainsKey(name))
        return drives[name];
    return null;
}

this explains well what happens, on the first call to this method the dictionary is empty
If that's the case the method will preload all drives.
For every call the requested drive (or null) is returned.
But what happens if you fire the method two times directly after the start? Then both executions try to load the drives in the Dictionary. The first one to add a drive wins the second will throw an ArgumentException (element already exists).
After the initial preload, everything works fine.
Long story short, you have two choices.

*

*Modify subsonic source to make SubSonic.DataService.GetTableSchema(...) thread safe.
http://msdn.microsoft.com/de-de/library/c5kehkcz(v=vs.80).aspx

*"Warmup" subsonic before accepting requests. The technic to achive this depends on your application design. For ASP.NET you have an Application_Start method that is only executed once during your application lifecycle
http://msdn.microsoft.com/en-us/library/ms178473(v=vs.100).aspx
So you can basically put a
var count = new SubSonic.Query("Enrollment").GetRecordCount();

in the method to force subsonic to init the table schema itself.


text:
Q: Hide all box classes and display only the target detail class I'm trying to use jQuery to hide all the classes with the same name and display only the one that is clicked. I've tried using parent, sibling and targeting as an object but it's not coming through. I found some working examples but when I apply them they don't. Any help will be much appreciated.
JS
 function more() {
    $('.box').hide();
    $(".detail").show();
  }

HTML

                    Shirley Temple

                    Tue, 11 Feb 2014 12:00

                            Shirley Temple

                            The Independent

Shirley Temple as she appears in 'The Littlest Rebel' directed by David Butler, 1935 Temple made a further eight films with Fox, including Little Miss Marker and, thanks to her cherubic optimism and bouncing gold girls, she quickly became one of the ...

Read trend on orign

                    Laurence Fishburne

                    Tue, 11 Feb 2014 03:00

                            Shirley Temple

                            Sky News

A broadcaster in Los Angeles has apologised to Samuel L Jackson after confusing him with Matrix star Laurence Fishburne in an interview. Jackson was being asked about his role in the new RoboCop film by KTLA's entertainment reporter when the mix-up ...

Read trend on orign

A: Try
function more(el) {
    $(".detail").hide();
    $(el).closest('.superbox').find('.detail').show()
}

Demo: Fiddle

A: 1) id is unique, you need to change id="image-trend-more" to class="image-trend-more"
2) Try below code to check if it meets your requirements
$('.image-trend-more').click(function() {
    $(this).closest('.box').hide().next('.detail').show();
});

Fiddle Demo


text:
Q: Reload search results on new search in web application (without jQuery) I have a simple web app that uses an API to return search results from a database and uses ajax to insert them into an empty ul element on the page. (Using JSONP with a cross domain request)
I cant figure out how to do it using javascript, everywhere I've found uses jQuery. I want to be able to have them enter another search term and have it clear the existing content from the page.
Currently if you conduct a second search it just appends the new results to the bottom of the existing list.

A: Once you have the content (returned from your API call using AJAX) you just can assign it to your ul or div e.g. document.getElementById('YourULID').innerHTML = "The content you got from your AJAX call"

A: From vanilla.js (so you can compare with jQuery):
var r = new XMLHttpRequest();
r.open("POST", "path/to/api", true);
r.onreadystatechange = function () {
  if (r.readyState != 4 || r.status != 200) return;
  alert("Success: " + r.responseText);
};
r.send("banana=yellow");

A: if i understand what you want. You want to get result from server and insert them into a ul form field of your webpage.
This is just an example and might help
function createRequest(){
    try{
       request = new XMLHttpRequest();
    }catch (tryMS){
        try{
            request = new ActivXObject("Msxml2.XMLHTTP");
        }catch (otherMS){
            try{
                request = new ActivXObject("Microsoft.XMLHTTP");
            }catch (failed){
                request = null;
            }
        }
    }
    return request;
}

function loggin(user_id,password){
    request = createRequest();
    data = new FormData();
    data.append('user_id',user_id.value);
    data.append('password',password.value);
    request.onreadystatechange=function(){
        if(request == null){
            alert('Unable to connect');
        }else{
            if(request.readyState==4){
                if(request.status==200){
                    if(request.responseText){
                        document.location.href = request.responseText;
                    }
                }
            }
        }
    }

This will create and HTTP request. Post data to your server then fetch the result and throw it back to your javascript, then staight to your webpage. Use request.responseText to append/insert to the appropriate field

A: I figured it out by using a few simple lines of html when onsubmit occurs with the search field:
var div = document.getElementById('cart_item');

while(div.firstChild){
    div.removeChild(div.firstChild);
}


text:
Q: How to optimize Gaussian-process parameters for multiple tasks with GPML? I have a lot of test curves and I want to optimize the length and scale parameters simultaneously for all curves.  Is this possible?

A: You can write a likelihood for the data in a usual way as far as I can understand.
Let we have data $D = \{X, Y\} = \{\mathbf{x}_i, \mathbf{y}_i\}$_{i = 1}^{n} with $\mathbf{x}_i \in \mathbb{R}^p$, and outputs $\mathbf{y}_i \in \mathbb{R}^m$ is multidimensional.
Denote by $\mathbf{y}^j = \{y_{1j}, y_{2j}, \ldots, y_{nj}\}$ - A vector which corresponds to $j$-th curve.
You suppose that each curve is a realization of a Gaussian process, but all Gaussian processes have zero mean value and the same covariance function $k(\mathbf{x}_i, \mathbf{x}_j)$, so you get for each curve the loglikelihood of the the form:
$$
L(X, \mathbf{y}^j) = -\frac12 ( (\mathbf{y}^j)^T K^{-1} \mathbf{y}^j + \log |K| +  n \log (2 \pi)),
$$
here $K = \{k(\mathbf{x}_i, \mathbf{x}_j)\}_{i, j = 1}^{n}$ is a sample covariance matrix.
And the joint likelihood is a product of separate likelihoods, so we can use common techniques to optimize it. For example, for most covariance functions we can calculate derivatives w.r.t covariance function parameters and use a derivative-based optimization.


text:
Q: Getting wrong distance between locations in iOS? Hi aim using following method to find out the distance between my current location and the locations(lat and longitude) stored in NSMutableArray value.
But am getting wrong distance..Please help..
My code
    -(void)getDistancetoShow:(NSMutableArray *)newArray{

    CLLocationCoordinate2D coordinateUser = [self getLocation];

    float _lat,_long;

  first_Loc = [[CLLocation alloc] initWithLatitude:coordinateUser.latitude longitude:coordinateUser.longitude];

    for(int p=0;p<[[newArray1 valueForKey:@"Name"] count];p++){

        _lat=[[[newArray1 valueForKey:@"Latitude"] objectAtIndex:p]floatValue];
         _long=[[[newArray1 valueForKey:@"Longitude"] objectAtIndex:p]floatValue];
        second_loc=[[CLLocation alloc] initWithLatitude:_lat longitude:_long];

        showDistance=[second_loc distanceFromLocation:first_Loc]/1000;

        [distanceToDispaly addObject:[NSString stringWithFormat:@"%.2f KM",showDistance]];
    }

     NSLog(@"first=%@, second=%@", first_Loc, second_loc);

}

Latitudes in array
(
    "47.0735010448824",
    "47.0564688100431",
    " 47.0582514311038",
    "47.0587640538326",
    "47.0569233603454",
    "47.0541853132569",
    "47.0542029215138",
    "47.0544259594592",
    "47.0560264547367",
    " 47.0576532159776",
    " 47.0550023679218",
    "47.0342030007379",
    "47.0746263896213",
    " 47.0740256635512",
    "47.0524765957921",
    "47.0606287049051",
    "47.0539691521825",
    "47.0542799159057",
    "47.0651001682846",
    "47.0536948902097",
    "47.0525973335309",
    "47.0389265414812",
    "47.0761811267051",
    "47.0668801601942",
    "47.0614859079241",
    "47.0579433468181",
    "47.0718998779465"
)
and longitude in array
(
    "21.9154175327011",
    "21.9312065669748",
    "21.9337414545594",
    " 21.9346772505188",
    " 21.9300587945685",
    "21.9363460105132",
    "21.9362081709222",
    "21.9343042603097",
    "21.939485335992",
    "21.9320057169724",
    "21.9300799002643",
    "21.9485373571669",
    "21.9310667367526",
    "21.9318507902135",
    "21.9192195298473",
    "21.9195273899529",
    "21.9329595191441",
    "21.9292015418841",
    "21.9219452321208",
    "21.9098849252041",
    "21.9074768948561",
    "21.9424499491422",
    "21.9151458954504",
    "21.9304346568769",
    "21.9305973807911",
    "21.9331511189507",
    "21.9159872752442"
)
but the real distance in something like staring with 9****  but am getiing now 5***

A: CLLocation gives you crow(straight) distance between two places. I thinks you are getting crow distance.
First take coordinate of two places and find distance between them.
then search crow distance between those two coordinate.
hope this will help

A: Once you get the two coordinates you can calculate the distance between them using this piece of code (taken from here):
- (NSNumber*)calculateDistanceInMetersBetweenCoord:(CLLocationCoordinate2D)coord1 coord:(CLLocationCoordinate2D)coord2 {
    NSInteger nRadius = 6371; // Earth's radius in Kilometers
    double latDiff = (coord2.latitude - coord1.latitude) * (M_PI/180);
    double lonDiff = (coord2.longitude - coord1.longitude) * (M_PI/180);
    double lat1InRadians = coord1.latitude * (M_PI/180);
    double lat2InRadians = coord2.latitude * (M_PI/180);
    double nA = pow ( sin(latDiff/2), 2 ) + cos(lat1InRadians) * cos(lat2InRadians) * pow ( sin(lonDiff/2), 2 );
    double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
    double nD = nRadius * nC;
    // convert to meters
    return @(nD*1000);
}

Hope this helps!

A: To get distance from array of points in Swift use below reduce method.
Here locations is array of type CLLocation.
 let calculatedDistance = locations.reduce((0, locations[0])) { ($0.0 + $0.1.distance(from: $1), $1)}.0


text:
Q: print QrCode with more than 125 characters esc/pos javascrypt I'm trying to print a qrCode in esc/pos (page mode) using javascript. The printer is Epson TM-T20X
When I put less than 125 characters in the QrCode it works perfectly but more than that makes the printer stuck and eventually (after trying to print a test  page a few times) it prints a bunch of weird characters.
the test qrCode string is as follows: aaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaa
code:
        var inAux = QRcode.length + 3;
        var pL = inAux%256
        var pH = inAux/256
        var size = 3;

        impressao += Char(29)+Char(40)+Char(107)+Char(4)+Char(0)+Char(49)+Char(65)+Char(49)+Char(0); // Select the model (1)
        impressao += Char(29)+Char(40)+Char(107)+Char(3)+Char(0)+Char(49)+Char(67)+Char(size); // Size Module
        impressao += Char(29)+Char(40)+Char(107)+Char(3)+Char(0)+Char(49)+Char(69)+Char(48); // Correction Level (L)
        impressao += Char(29)+Char(40)+Char(107)+Char(pL)+Char(pH)+Char(49)+Char(80)+Char(48); // Store the data in the symbol storage area
        impressao += QRcode;
        impressao += Char(29) + Char(40) + Char(107) + Char(3) + Char(0) + Char(49) + Char(81) + Char(48); // Print the symbol data in the symbol storage area
        impressao += esc + Char(12); // print page mode (ESC FF)```


text:
Q: Two levels horizontal dropdown menu Consider an ordinary 2 levels dropdown menu:
HTML

Main item 1

Item 1

Item 2

Item 3

  ...

CSS
.nav li { position: relative; float: left; }
.nav li a { display: block; }
.nav li ul { position: absolute; left: 0; top: 39px; }
.nav li ul li { float: left; }

I'd like the second level items to be displayed horizontally, all in one line. It's not a problem, when we define the width of ul.menu ul. But if the number of the second level menu items varies, we can't know the width and so the items are displayed vertically.

A: 1) First give id to your elements.
2) Use display: inline in your second li.
3) Then you give it a common width place a div span inside each li example and give them all the same  width.

ur data ,

Also place your text  in the center
text-align: center;

Hope this helps.
The below code is working for me in ff and chrome.
css:
.nav li { position: relative; float: left; }
.nav li a { display: block; }
.nav li ul { position: absolute; left: 0; top: 39px; }
.nav li ul li { float: left; }

ul.menu ul li {
display:inline-block;
}

A: Try using display: inline-block on the child list items:
http://jsfiddle.net/bd3SX/

A: As vishal and Scott Simpson said, display: inline-block; is the way to solve the problem. But this method doesn't work in every browser (at least for now). If a parent has position: relative, it indirectly determines the maximum width of its children.
So I wrote the following script.
$.fn.dropdownNav = function () {

    var dropItem = $(this);

    // your dropdown menu height
    var menuHeight = 38;

    // dropdown menu is not displayed by default, we need to show it
    dropItem.children('ul').show();

    // increase the dropdown menu width, until all items fit in one row
    while ( dropItem.children('ul').height() > menuHeight ) {
        dropItem.children('ul').css({ width: '+=1' });
    }

    // it is done, let's hide the dropdown menu
    dropItem.children('ul').hide();

    // and bind hover events
    dropItem.hover (
        function () { $(this).children('ul').show(); },
        function () { $(this).children('ul').hide(); }
    );
};

// function call
$('.nav > li').each(function () { $(this).dropdownNav(); });


text:
Q: Creating an Instance of an Interface I have the following interfaces defined:
public interface IAudit {
    DateTime DateCreated { get; set; }
}

public interface IAuditable {
    IAudit Audit { get; set; }
}

The IAuditable interface says which classes I will have an Audit for. The IAudit interface is the actual Audit for that class. For example say I have the following implementations:
public class User : IAuditable {
    public string UserName { get; set; }
    public UserAudit Audit { get; set; }
}

public class UserAudit : IAudit {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

Now given an object which is IAuditable (User from above), I'd like to be able to create an intance of IAudit (UserAdit from above) by feeding in the IAuditable object into the constructor. Ideally i'd have something like:
if (myObject is IAuditable) {
    var audit = new IAudit(myObject) { DateCreated = DateTime.UtcNow }; // This would create a UserAudit using the above example
}

However I have a bunch of problems:

*

*You can't create an instance of an interface

*No where in the code does it define which IAudit applies to which IAuditable

*I can't specify that the IAudit interface must have a constructor which takes an IAuditable
I'm sure this is a design pattern many have had before but I can't get my head around it. I'd really appreciate if someone could show me how this can be achieved.

A: Obviously you cannot create an instance of an interface, but if you were really trying to create an instance of the passed in class you could do this:
IAuditable j = ((IAuditable)Activator.CreateInstance(myObject.GetType()));

You need to know which concrete class to construct and in your example the only option is myObject.
Alternatively you could research something called 'Dependancy Injection' which allows you to specify which type of concrete class to "inject" into parameters that call out interfaces in constructors, or in fields. I'm not sure your total design, so this might be applicable. In Dependancy Injection you can state in your code IAuditables should be created using UserAudit, although there's a little more wireup than simply calling "new IAuditable"

A: One way would be using generics.
Once you've a T type which implements I interface and has a public, parameterless constructor, you can create an instance of T:
public void Create<T> where T : IAudit, new()
{
     T instance = new T();
     // TODO: Your logic using such T instance of IAudit implementation
}

I don't know your code architecture or goal, but you can create a factory method like one above to create instances of IAudit objects.

A:
You can't create an instance of an interface

Correct. You create an instance of an object implementing an interface:
IAuditable myUser = new User();

No where in the code does it define which IAudit applies to which IAuditable

You can't do this directly with just one interface. You will need to rethink your design.
You can use a open generic type in the interface and implement it with closed types:
public interface IAudit<T> {
    DateTime DateCreated { get; set; }
}

public class UserAudit : IAudit<User> {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

I can't specify that the IAudit interface must have a constructor which takes an IAuditable

Correct, you can't. See here. You need to create such a constructor on the implementers.

A:
No where in the code does it define which IAudit applies to which
  IAuditable
  I can't specify that the IAudit interface must have a
  constructor which takes an IAuditable

You could fix these two by adding a CreateAudit() function to your IAuditable. Then you'd get an IAudit created from the IAuditable. As a bonus if you wanted to store a reference to the IAudit in the IAuditable (or vice-versa) so you can have them related to each other, it's pretty easy to have an implementing class do that. You could also add GetAuditable() to IAudit to get the IAuditable it was created from, for example.
Simple implementation would look like this (on a class implementing IAuditable):
public IAudit CreateAudit()
{
    UserAudit u = new UserAudit(UserName);
    return u;
}

A: If you are in need to create Instance for an Interface,You can create a public class named FactoryClass() which contains all the Interfaces method. you can use the following code:
public class FactoryClass  //FactoryClass with Interface named "IINterface2"
{
   public IInterface2 sample_display()   //sample_display() is a instance method for Interface
   {
       IInterface2 inter_object = null;   //assigning NULL for the interface object
       inter_object = new Class1();       //initialising the interface object to the class1()
       return inter_object;   //returning the interface object
   }
}

In Main() Class add the following code :
IInterface2 newinter; //creating object for interface in class main()
FactoryClass factoryobj=new FactoryClass();  // creating object for factoryclass

In constructor add the following :
newinter=factoryobj.sample_display() // initialisingg the interface object with the instance method of factoryobj of FACTORY CLASS.

you can call the ffunction by using the following code :
newinter.display() //display() is the method in the interface.

A: You can create a static Interface variable outside of the scope and then use it in the code.
static IRequestValidator ir;

static void Main(string[] args)...


text:
Q: C# max() not returning the natural highest Value I have a Dictionary of <string, Point> and the keys in this dictionary look like this:

*

*char_1_1

*char_1_2

*...

*char_1_9

*char_1_10

Now I am using the following statement to receive the heighest Value of the keys:
pointsWhichBelongTogether.Keys.Where(key => key.Contains(searchStringPattern[0] + "_" + searchStringPattern[1] + "_")).OrderBy(x => x, new NaturalStringComparer()).Max()

Which uses the following Compare-Class:
public class NaturalStringComparer : IComparer<string>
    {
        private static readonly Regex _re = new Regex(@"(?<=\D)(?=\d)|(?<=\d)(?=\D)", RegexOptions.Compiled);

        public int Compare(string x, string y)
        {
            x = x.ToLower();
            y = y.ToLower();
            if (string.Compare(x, 0, y, 0, Math.Min(x.Length, y.Length)) == 0)
            {
                if (x.Length == y.Length) return 0;
                return x.Length < y.Length ? -1 : 1;
            }
            var a = _re.Split(x);
            var b = _re.Split(y);
            int i = 0;
            while (true)
            {
                int r = PartCompare(a[i], b[i]);
                if (r != 0) return r;
                ++i;
            }
        }

        private static int PartCompare(string x, string y)
        {
            int a, b;
            if (int.TryParse(x, out a) && int.TryParse(y, out b))
                return a.CompareTo(b);
            return x.CompareTo(y);
        }
    }

So I assume that the List is natural sorted and the Max-Functions just gets the highest value. But the max() returns char_1_9 as the highest value. Does this max()-function a re-sort?

A: You have two options:

*

*Take the Last from the sorted list or

*Order descending and take the first

Right now you sort using your comparer, but Max does not use the comparer but the default comparer to find the maximum.
pointsWhichBelongTogether.Keys.Where(key => key.Contains(searchStringPattern[0] + "_" + searchStringPattern[1] + "_"))
    .OrderBy(x => x, new NaturalStringComparer()).Last();

or
pointsWhichBelongTogether.Keys.Where(key => key.Contains(searchStringPattern[0] + "_" + searchStringPattern[1] + "_"))
    .OrderByDescending(x => x, new NaturalStringComparer()).First();

Edit: in a previous version I suggested to pass the comparer to Max, but it seems there is no overload that takes a comparer, only a selector.

A: The string type already implements IComparable<string> so Max() uses this implementation regardless of any previous sorting. I would order your values descending and take the first value:
var max = pointsWhichBelongTogether.Keys
    .Where(key => key.Contains(searchStringPattern[0] + "_" + searchStringPattern[1] + "_"))
    .OrderByDescending(x => x, new NaturalStringComparer())
    .FirstOrDefault();


text:
Q: Bash continue [n] ignored in piped to while read loops. for loop behaves as expected In a script I'm writing, I try to exit out of the second nested while loop, and the continue statement appears to be simply ignored, and I'm unsure of exactly why.
From the manual:
continue [n]:
    Resume  the  next  iteration of the enclosing for, while, until, or select loop.  If n is specified,
    resume at the nth enclosing loop.  n must be ≥ 1.  If n is greater  than  the  number  of  enclosing
    loops,  the last enclosing loop (the ``top-level'' loop) is resumed.  The return value is 0 unless n
    is not greater than or equal to 1.

A minimal example that illustrates my problem (ex1.sh):
#!/bin/bash

printf "%d\n" {1..3} | while read i; do
  printf "%d\n" {1..3} | while read j; do
    sum=$(expr $i + $j)
    echo "$i + $j = $sum"
    [ $sum -ge 5 ] && echo continue && continue 2
  done
  echo 'should only see this for first cycle of i (2+3 >= 5)'
done

Output of ex1.sh:
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
should only see this for first cycle of i (2+3 >= 5)
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
continue
should only see this for first cycle of i (2+3 >= 5)
3 + 1 = 4
3 + 2 = 5
continue
3 + 3 = 6
continue
should only see this for first cycle of i (2+3 >= 5)

Why is the continue 2 ignored? It clearly echos out "continue", and the fact that continue runs is confirmed by running a trace with set -x
The use of printf is obviously silly ex1.sh, but reproduces the issue I'm having with getting continue to work in a while read x... loop.
A for loop works as expected (ex2.sh):
#!/bin/bash

for i in {1..3}; do
  for j in {1..3}; do
    sum=$(expr $i + $j)
    echo "$i + $j = $sum"
    [ $sum -ge 5 ] && echo continue && continue 2
  done
  echo 'should only see this for first cycle of i (2+3 >= 5)'
done

Output of ex2.sh:
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
should only see this for first cycle of i (2+3 >= 5)
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
continue
3 + 1 = 4
3 + 2 = 5
continue

So, why does ex1.sh seem to ignore the continue 2 builtin, whereas ex2.sh behaves as expected?
Fixed the first example myself thanks to M. Nejat Aydin:
#!/bin/bash

while read i; do
  while read j; do
    sum=$(expr $i + $j)
    echo "$i + $j = $sum"
    [ $sum -ge 5 ] && echo continue && continue 2
  done < <(printf "%d\n" {1..3})
  echo 'should only see this for first cycle of i (2+3 >= 5)'
done < <(printf "%d\n" {1..3})

The issue is that pipelines create subshells, so my continue statement was behaving as expected according to the manual, continuing at the outermost loop that subshell was aware of.

A: Your while loops are not nested. They're running in different subshells. continue cannot continue from the parent shell. A pipe (|) creates a subshell. On the other hand, the version below should work as expected because both whiles are running in the same shell:
while read i; do
  while read j; do
    sum=$(expr $i + $j)
    echo "$i + $j = $sum"
    [ $sum -ge 5 ] && echo continue && continue 2
  done < <(printf "%d\n" {1..3})
  echo 'should only see this for first cycle of i (2+3 >= 5)'
done < <(printf "%d\n" {1..3})


text:
Q: Creating prediction map by combining several rasters and vectors in ArcGIS Desktop? I have three 'variables':

*

*6000 GPS points that represent where my focal species (a carnivore) is present. Attached to these points is one value representing the activity level of the animal at the time (it ranges between 0 and 200, thus 0 being inactive and 200 being very active).

*Slope (standard slope raster)

*NDVI (also raster)

I ran a GLMM in R Studio, and the fixed effects show that as NDVI and Slope decrease, activity decreases. This is important because it may also help with an additional analysis to assess areas of risk for my other focal species (an herbivore that also happens to be a prey species of my focal carnivore).
I am curious that given such a relationship (between activity points, NDVI, and Slope) whether it is possible to map out  'hotspots of activity' throughout the landscape while accounting for NDVI and Slope as a means to create a 'risk map' or 'probability of activity map' (same thing in this context)
I have been reading about several methods including kriging, hotspot analysis, Residual trend mapping, etc. but I am afraid that I am still unsure whether either of these methods are the right way to go (probably because I am still relatively new when it comes to GIS).
Would anyone be able to provide some advice on how to carry on with this?

A: There are a number of things you could do with this depending on your research focus. I would take Sergio's advice in the comments (and your own reading on this that you mentioned IS relevant) and start by converting the point dataset into a raster. I would do this using an interpolation. If you want to get into the Kriging that you mentioned, that is a great way to go but even something simpler like IDW can be done with spatial analyst (Kriging is an artful science that can be done well with a lot of practice). The interpolation will give you a density based estimate of "presence" of your species.
As Sergio mentioned, once you have that raster surface you have a bunch of options. You can compare the density values with the slope raster (using the raster calculator) to statistically test if slope may deter presence and likewise you could test with the NDVI to see if a high vegetation index is correlated with higher presence.
You might come up with some sort of an index that weighs both slope and NDVI in some (potentially arbitrary) way and use that but better (less arbitrary) if you have some values to base it on (i.e. perhaps the literature says the animal avoids slopes over x%).