How to display view with context filters as a block in sidebar?

Question: I'm trying to display a view in a block, the content of which is based on value of one of field of currently displayed node. I found out that I must use Views content panes and Mini panels modules. I created appropriate view in format "content pane" and I'm stuck. I can't find how to proceed any further. I tried to create new mini panel but I don't see how to associate one with another.

Clarification
I choose Panels after quick research because I want to display view in a block, which takes arguments from it's context: field value of current node. Nodes are displayed using standard template and Display Suite.
Clarification 2
What I exactly want to do: take field value from currently displayed node and in a block in sidebar display list of nodes that also have same value in that field.
Answer: I got it!

Create views block type display that requires context filters.
Create block with PHP filter content type.
Put into it code:
<?php
  $node = menu_get_object();
  $field = field_get_items('node', $node, 'field_NAME');
  echo views_embed_view('VIEW_NAME', 'block_1', $field[0]['value']);
?>

(this eventually can be moved into custom module to avoid using PHP filter)
Comment: awesome!!..nice and clean.:)
Answer: Do you really want to add mini-panels? based on your question, you want to display a view in a block. You can just create a block display of a view. this can be added to a normal panels page (as you want to have this view display contents based on the field value of the node) I am guessing that you have overridden the node template by panels and now you can embed the block display of the view directly in the panels and pass in the context of the present node.
I am not sure you even require mini panels. Answer can be pin pointed if you make your question more clear to give out what is that you are exactly looking to do.
UPDATE:
Ok, yes panels can very easily come to your rescue here. So that part is good, you can pass in field value as context.
So how to add a content to a panel (or mini panel) is same as what ankit explained in his answer. the trick is that when you try to add a views block to a panel, it will give you an option to pass context for panels to views per "contextual filter" you have defined in a view.
So here are the steps:

Create a views block type display.
obviously you will be adding some contextual filters which accepts arguments from panels. (remember this contextual filters are what will accept arguments from panels)
While adding this view to panels through steps mentioned by Ankit in his answer, pass in the required argument per contextual filter you have added.

In order for me to help you to configure the view, you heet to let me know what exact stuffs you are looking to add in a view and how are you planning to construct it functionally. Hope this helps.
Update 2:
Mini-panels are not listed in blocks page. Mini Panels are listed in mini panels page. Also mini Panels do not have a dedicated page. They are meant to be embedded into a parent panels page. I don't think you need mini panels at all.
As per my Understanding, here a couple of pointers.

I think you are trying to add a view to a mini panel and have it available as block and place it in a region in a page. this will not work out as mini panels are never available as blocks.
I am not sure about display suite, but now if you want to use this mini panel, you need to override the node template with panels.

You need to understand that Panels/mini panels and display suites are two different approaches to do the same thins. Here is a very good resource to know more.
UPDATE 3:
Just found an awesome module that might just do the trick for you through a views only approach. This module provides a views display that gets directly attached to the node and gets tokens from node field that you can use as view's contextual filters directly.
Here is the link to the module.
Comment: I added some comments and updated my answer.
Comment: I created mini panel and added view into it, but I can't found it on `admin/structure/block` page.
Comment: I think you are confusing the basic here. please check my updates.
Comment: "I think you are trying to add a view to a mini panel and have it available as block and place it in a region in a page." - yes, this exactly. So I must enable `Panel nodes` module and use it to style node?
Comment: Absolutely yes, if you want to use mini-panels you need to use a panel override of the node template. but what worries me is that i think this approach might be serious overkill for your purpose. Can you give me an idea what things you are trying to display in that view in a bit more detail?

I think this can be achieved simply through a view, not sure though (will depend upon your requirement). once I have the details I can guide you in the proper direction. but if this views approach only approach does not work, you may go in for the panels override.
Comment: I added further clarification.
Comment: Found an interesting module which might serve your case. Please see my update.
Comment: I tested that module but it has critical bugs (WSOD & maximum allowed memory exceeded...). But I found another solution. Thanks for your help!
Answer: To make mini panel acts like a block try the following:

Select the mini panel for editing and select the "content" editing display.
Next pick the gear (present in the upper right corner of the desired region in
the mini panel) and select 'add content', the pop-up will give you the
selection of available content that can be placed in the panel.
Once you have the mini panel configured, you place it in a theme region just as we do for block: select the mini panel from the admin/structure/blocks page for your theme (It can be found in the list of disabled blocks at the bottom of the layout page form).

Also you can have look at the tutorials that may be helpful for you:
http://drupalize.me/videos/basics-views-content-panes
https://drupal.org/node/1704274
Comment: I created mini panel and added view into it, but I can't found it on `admin/structure/block` page.
Comment: Can you clear the cache and chech, It can be found in the list of disabled blocks at the bottom of the layout page form
Comment: Clearing cache didn't change anything, but Neo's updated answer is explaining why.


How to specify a filename when saving pdf document to iOS Files App?

Question: Using the PDFKit I have created a pdf document within my app. I can successfully show it in a preview and from the preview controller I use the following code to present the user the share actions:
@objc func shareAction(_ sender: UIBarButtonItem)
{
    if let data = documentData
    {
        let vc = UIActivityViewController(activityItems: [data], applicationActivities: [])
        present(vc, animated: true, completion: nil
    }
}

documentData contains the created pdf document.
When the user selects "Save to Files" the document gets the default name "PDF Document.pdf", which the user can change.
How can I provide a different default filename ?
Answer: Not a real answer but rather a workaround that I figured out:
Rather than using the in-memory-copy data of the PDF, I can write it to the apps tmp folder:
var fileURL : URL?
do
{
    let filename = "myfilename.pdf"
    let tmpDirectory = FileManager.default.temporaryDirectory
    fileURL = tmpDirectory.appendingPathComponent(filename)
    try data.write(to: fileURL!)
}
catch
{
    print ("Cannot write PDF: \(error)")
}

The share action would then look like:
@objc func shareAction(_ sender: UIBarButtonItem)
{
    if let url = fileURL
    {
        let vc = UIActivityViewController(activityItems: [url], applicationActivities: [])
        present(vc, animated: true, completion: nil
    }
}

Now the user gets "myfilename.pdf" shown as default filename when he chooses the "Save to Files" action.
Answer: Just an additional help.
You'd better delete the PDF files in tmp dir at appropriate time.
I call this func when viewController dismisses.
FYI
func deleteAllPDFs() {
    let predicate = NSPredicate(format: "self ENDSWITH '.pdf'")
    let defaultFileManager = FileManager.default

    do {
        let tmpDirURL = defaultFileManager.temporaryDirectory
        let contents = try defaultFileManager.contentsOfDirectory(atPath: tmpDirURL.path)
        let pdfs = contents.filter { predicate.evaluate(with: $0) }
        try pdfs.forEach { file in
            let fileUrl = tmpDirURL.appendingPathComponent(file)
            try defaultFileManager.removeItem(at: fileUrl)
        }
    }
    catch {
        print ("Failed to delete PDF with error: \(error)")
    }
}

Comment: Yes, thanks to point that out. I am deleting the temp file in the viewcontrollers deinit, but did not mention it.


Getting at LinkedIn returned data from Javascript SDK

Question: What I'd like to do is get at the returned data from the LinkedIn API named data from the function named getProfileData. How can I access the data that contains the information such as firstName and lastName but in getProfileData and not just in the function onSuccess?

Answer: You must fix something in your code :
IN.API.Raw("/people/~:(id,first-name,last-name,location,positions)?format=json").result(onSuccess).error(onError);

Comment: data.firstName, data.lastName in onSuccess function


React 'component' argument missing error?

Question: I have created Header component. I am using this react Header component with meteor-blaze but I am getting error in console saying react argument component missing. I am referring this docs -> https://guide.meteor.com/react.html#blaze-in-react
league_header.html:
<template name="LeagueHeader">
{{#if isCordova}}
  {{> HeaderMobile }}
{{else}}

        {{> React component=Header }}

{{/if}}
</template>

headerhelper.js:
import { Template } from 'meteor/templating';

import './league_header.html';
import Header from '../../../imports/Header.jsx';

Template.LeagueHeader.helpers({
  HeaderHelper() {
    return Header;
  }
})

Header.jsx:
import React, { Component } from 'react';

class Header extends Component {

    render() {
        console.log('Hello Component');
        return (

Hello World

        );
    }
}

export default Header;

Error:
Error: In template "LeagueHeader", call to `{{> React ... }}` missing `component` argument.
    at Blaze.View.<anonymous> (react-template-helper.js:23)
    at blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1934
    at Function.Template._withTemplateInstanceFunc (blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:3744)
    at blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1932
    at Object.Blaze._withCurrentView (blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:2271)
    at viewAutorun (blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1931)
    at Tracker.Computation._compute (tracker.js?hash=997515fa2d5b0530ba07741da556c4b36963ef3b:339)
    at new Tracker.Computation (tracker.js?hash=997515fa2d5b0530ba07741da556c4b36963ef3b:229)
    at Object.Tracker.autorun (tracker.js?hash=997515fa2d5b0530ba07741da556c4b36963ef3b:613)
    at Blaze.View.autorun (blaze.js?hash=f33d3dfed63a491d24e3aa07ad66c24b5fe8c761:1944)

Screenshot:
Comment: Please add the error output as code instead of an image.
Comment: In the `headerhelper.js` file, do a `console.log(Header)` before the return statement and let me know what the output is.
Comment: @Jankapunkt Check edited question
Comment: @theJuls Nothing appears in console except the error.
Comment: Your helper needs to be renamed to Header instead of HeaderHelper or you rename your parameter to HeaderHelper
Comment: @Jankapunkt I could nt understand ? Can you write the answer please :)
Comment: @See the answer of captainZi
Comment: @Jankapunkt It does not work chck this -> https://imgur.com/a/w8nNDRX
Comment: have you added this package: `meteor add react-template-helper`? and try to change:
```
Template.LeagueHeader.helpers({
  HeaderHelper() {
    return Header;
  }
})
```
to
```
Template.LeagueHeader.helpers({
  Header() {
    return Header;
  }
})
```
Comment: or try to change: `{{> React component=Header }}` to `{{> React component=HeaderHelper }}`
Comment: @MinhNguyen Do I need to `import react-template-helper` ? If yes then in which file ?
Comment: @MinhNguyen I have downloaded `react-template-helper` what should I do next ? Do I need to import anything inside my template or react component.
Answer: You are using the wrong helper name
Try replacing the component call with this.

{{> React component=HeaderHelper}}
Comment: I reproduced this and it works. Therefore I assume the `Header.jsx` is not imported (wrong path?). Please console.log(Header) in `HeaderHelper` before returning.


change the default category page layout in mediawiki

Question: I was thinking if there was a way to change the Category page's default layout? I was thinking of including featured articles and their thumbnails just below the category text. I know that I can do this by editing the category page by hand but I would really want to make it so that all categories will do this by default. Is there a Category Template somewhere? Or is there a certain parameter that I should watch for when hooking to one of the output functions?

Thanks!
Answer: If I understand your question, there is nothing like that in existence AFAIK.  However, with Extension:NiceCategoryList2, you could probable create a template that generates an output that is fairly close to what you want. You would still have to manually have to place the call to the template on all C: pages though or use a bot to pre-pend it to the top of all the C:s listed on Special:WantedCategories.


Take a picture on iPhone without showing controls

Question: Is there a way to take a picture in code on the iPhone without going through the Apple controls?  I have seen a bunch of apps that do this, but I'm not sure what API call to use.
Comment: By "Apple controls", assuming you mean without using UIImagePickerController.
Answer: EDIT: As suggested in the comments below, I have now explicitly shown how the AVCaptureSession needs to be declared and initialized. It seems that a few were doing the initialization wrong or declaring AVCaptureSession as a local variable in a method. This would not work.
Following code allows to take a picture using AVCaptureSession without user input:
// Get all cameras in the application and find the frontal camera.
AVCaptureDevice *frontalCamera;
NSArray *allCameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

// Find the frontal camera.
for ( int i = 0; i < allCameras.count; i++ ) {
    AVCaptureDevice *camera = [allCameras objectAtIndex:i];

    if ( camera.position == AVCaptureDevicePositionFront ) {
        frontalCamera = camera;
    }
}

// If we did not find the camera then do not take picture.
if ( frontalCamera != nil ) {
    // Start the process of getting a picture.
    session = [[AVCaptureSession alloc] init];

    // Setup instance of input with frontal camera and add to session.
    NSError *error;
    AVCaptureDeviceInput *input =
    [AVCaptureDeviceInput deviceInputWithDevice:frontalCamera error:&error];

    if ( !error && [session canAddInput:input] ) {
        // Add frontal camera to this session.
        [session addInput:input];

        // We need to capture still image.
        AVCaptureStillImageOutput *output = [[AVCaptureStillImageOutput alloc] init];

        // Captured image. settings.
        [output setOutputSettings:
        [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil]];

        if ( [session canAddOutput:output] ) {
            [session addOutput:output];

            AVCaptureConnection *videoConnection = nil;
            for (AVCaptureConnection *connection in output.connections) {
                for (AVCaptureInputPort *port in [connection inputPorts]) {
                    if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                        videoConnection = connection;
                        break;
                    }
                }
                if (videoConnection) { break; }
            }

            // Finally take the picture
            if ( videoConnection ) {
                [session startRunning];

                [output captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

                    if (imageDataSampleBuffer != NULL) {
                        NSData *imageData = [AVCaptureStillImageOutput
                                  jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                        UIImage *photo = [[UIImage alloc] initWithData:imageData];
                    }

                }];
            }
        }
    }
}

session variable is of type AVCaptureSession and has been declared in .h file of the class (either as a property or as a private member of the class):
AVCaptureSession *session;

It will then need to be initialized somewhere for instance in the class' init method:
session = [[AVCaptureSession alloc] init]

Comment: Trying this code now, it all works up until `[output captureStillImageAsynchronouslyFromConnection:...` but then stops, resulting in the photo never actually being taken. I added logging to the line immediately following this and it never gets logged. The code is verbatim what you wrote and I've confirmed the code up until that point works (added a button and hooked it up in the .xib, fires properly). I've also included AVFoundation.framework and AssetsLibrary.framework. Any ideas?
Comment: Solution for the problem noted by various posters that the callback block in [output captureStillImageAsynchronouslyFromConnection:...] is never called: do not declare "session" locally in the function as         `AVCaptureSession *session = [[AVCaptureSession alloc] init];`
 (i.e. on the stack). Rather, declare it in the .h file as a property with `@property AVCaptureSession *session;` Otherwise, it will have disappeared by the time the callback block gets called. This is noted by the OP, but it would be helpful to add to the original code explicity for clarification.
Comment: Did you put a breakpoint at this line:

if (imageDataSampleBuffer != NULL)

Does it hit? If it hits, is error not NULL?
Comment: Is there a way for this to work while the app is in the Background mode?
Comment: Not sure. You can try recording video instead of still images. Recording starts while in foreground, the video frames will be received in background.
Comment: I'm trying the code as well, but I get the same problem as @TylerHayes. Does anyone know why?
Comment: Did you try my suggestion from June 3rd?
Comment: I could not get this running on my iPad with iOS 6.1 until I moved the setOutputSettings line after the "canAddOutput" call (into the if block)...
Comment: Has anyone found a solution for this? Neither the line if (imageDataSampleBuffer != NULL), nor the breakpoint is called..
Comment: What about this line: [output captureStillImageAsynchronouslyFromConnection...] does the breakpoint hit here? If you can give details on how the flow is executed, will be happy to help.
Comment: Worked great.  A few notes: (i) you can move the call to `captureStillImageAsynchronouslyFromConnection` to an `IBAction` for the "take picture" button.  Also, the very-top paragraph of the docs for `AVCaptureVideoPreviewLayer` have the 5 steps you need if you want to put that session into a view (so it doesn't take up the whole screen.)
Comment: its working fine...but taking a image which is very black...not a clear picture
Comment: Any update why the image is black? Even user can not see what image has been taken?
Answer: Yes, there are two ways to do this.  One, available in iOS 3.0+ is to use the UIImagePickerController class, setting the showsCameraControls property to NO, and setting the cameraOverlayView property to your own custom controls. Two, available in iOS 4.0+ is to configure an AVCaptureSession, providing it with an AVCaptureDeviceInput using the appropriate camera device, and AVCaptureStillImageOutput.  The first approach is much simpler, and works on more iOS version, but the second approach gives you much greater control over photo resolution and file options.


How to redirect to thank you page in Vue3.js

Question: How can I create a redirect to another page on Vue?
Below I would like to insert a redirect after user login.
async function normalLoginClicked() {
  if(agreePrivacyPolicy.value) {
    ps_loading_dialog.value.openModal();

    await userProvider.loginWithEmailId(email.value, password.value);

    ps_loading_dialog.value.closeModal();
    if (userProvider.userResource.status == PsStatus.SUCCESS) {
      redirect();
    }
}

function redirect() {
  userProvider.navigateUserLoginRedirect(route.query.redirect, 'dashboard', router, route.query.redirect, route.query, route.params);
}

Comment: Can you indicate where did you find the snippet in you redirect function? That would help us to understand what you really want to do.
Answer: The way to move on a client-side context is to use the following after your await
router.push('/my-cool/path-redirection')

As explained here: https://router.vuejs.org/guide/essentials/navigation.html#navigate-to-a-different-location


Do Neural Networks need "compound" features?

Question: Apologies if I haven't got the terminology quite right. I have a question about Neural Networks, and I'm not sure exactly the best way to ask it!
Hypothetically, let's say I have a dataset of houses on the property market. One of the features could be number of bathrooms, and another is floor plan area.
If I were using linear regression, I might also include a compound feature e.g. number of bathrooms / floor plan area. I could come up with all sorts of combinations of feature products, and create higher order polynomials.
My question is - is this necessary for neural networks? Or standard practise? Or useful?
Neural networks are such a black box I'm not sure if it would just "work this out" or not.
If there isn't a simple answer, I would be grateful at least for anything you can tell me about how this phenomenon is referred to. Are they compound features? Or computed features? I really don't know...
Answer: composite features can be useful but you probably wouldn't want to use the elements of a composite feature and the composite feature itself as inputs to the same model unless each was meaningful a priori (and even then, maybe not). The net will be able to learn about the summation of two features (and other relationships) without combining them.
a great use for composite features can be when you want to do large scale machine learning and cut down on processing requirements
so not necessary but occasionally useful
one caveat - the nature of a feature might call for a transformation (square root, polynomial transformation) to increase the fit of a simple model but that is a separate issue from combining features into a composite feature


About absolute continuity $\Rightarrow$ null set maps to null set

Question: I've searched quite a lot in this site and found many questions that mention this result, but not a single proof. I tried proving it myself and failed.
So, I ask it here: how can one prove that if $f:[a, b]\rightarrow \mathbb{R}$ is absolutely continuous, then for every set $A \subseteq[a,b]$ with lebesgue measure $0$, $f(A)$ also has lebesgue measure $0$?
Comment: How are you defining absolute continuity in the first place? There are several equivalent definitions that you could choose.
Comment: You can use the $\epsilon - \delta$ definition, or the fundamental-theorem-of-calculus-definition. I know that these two are equivilant.
Answer: Let $N \subset (a,b)$ be a null set and let $\epsilon > 0$.
Select $\delta > 0$ corresponding to the definition of absolute continuity and let $O \subset [a,b]$ be an open set with $m(O) < \delta$. There exists a countable family $\{(a_k,b_k)\}$ of disjoint open intervals with $O = \bigcup_k (a_k,b_k)$.
Since $f$ is continuous on each $[a_k,b_k]$ there exist points $c_k,d_k \in [a_k,b_k]$ on which $f$ attains its infimum and supremum, respectively. This means that $f([a_k,b_k]) = [f(c_k),f(d_k)]$ so that $$m^*(f((a_k,b_k))) = |f(d_k) - f(c_k)|.$$
Since $\sum_k |c_k - d_k| \le \sum_k |a_k - b_k| = m(O) < \delta$ you have $$\sum_k |f(d_k) - f(c_k)| < \epsilon$$ by absolute continuity. Consequently $$m^*(f(O)) = m^*( f(\bigcup_k (a_k,b_k)) \le \sum_k m^*(f((a_k,b_k)) < \epsilon.$$
In particular, if  $O$ is an open set with $N \subset O \subset (a,b)$ and $m(O) < \delta$ then $$m^*(f(N)) \le m^*(f(O)) < \epsilon.$$
Since this is valid for any $\epsilon > 0$ it follows that $m^*(f(N)) = 0$ as desired.
Comment: Once again  Littlewood's principles come to the rescue! - https://en.wikipedia.org/wiki/Littlewood%27s_three_principles_of_real_analysis
Comment: Wow, thank you so much! I've been stuck on that one for 2 days.
This simple reduction to open sets escaped my attension.
Comment: Can I argue $f(N)$ is measurable in this way?
There is a $\delta_n$ such that $\sum |f(b_i)-f(a_i)|<1/n$ if $\sum |b_i-a_i|<\delta_n$. For each $\delta_n$, there is a collection of open interval such that $I_{n,i}=(a_{n,i},b_{n,i})$ which cover $N$ and $m(\bigcup_i I_{n,i}) \leq \delta_n$ and thus $\sum_i f(I_{n,i}) <1/n$. Then $m(\bigcap_n \bigcup_i f(I_{n,i}))=0$. Since $f(N) \subset \bigcap_n \bigcup_i f(I_{n,i}) $. So $f(N)$ is measurable as Lebesgue measure is complete.


Featurize user roles and permissions can't update

Question: I have added user roles and permissions to feature which I use to featurize general site configurations and theme settings.
In the past I believe this worked just fine, however, with my latest push the remote created additional roles instead of changing the names as I had done on dev. I deleted the old roles and kept the ones with the proper names. MySQL drupal.role shows that the roles now have new IDs also which I believe could be the cause of the problem. I shouldn't have deleted the roles that matched dev but since I already did, where do I go from here? Should I manually change the ID's in MySQL?
I'm working on a new site that isn't launched yet but will be importing users from another site.
Here you can see the original role IDs and what is on dev:

Here you can see the role ID's on prod now:
Comment: @Kevin is this the [module](https://www.drupal.org/project/features_roles_permissions) and any experience with how would it handle a role rid discrepancy?
Comment: This can be a pain for sure. I'd change the rid's in dev to match prod, then export your feature and you should be good to go.
Comment: I believe there is an add on module for Features for handling roles and permissions better than core features.
Answer: Since production hasn't yet been released and is still under development, I took a risk of mysqldump the drupal.role table and then importing them on prod, which fixed the issue.
LongBoardNode's suggestion of editing the RID on dev would have probably been a better idea,
Comment: Did you also import the role_permissions table as well? It is tied to the the roles table and references rid's from the roles table. I'm fairly sure importing only the role table will break your permissions on prod
Comment: I didn't import the role_permissions table. Once I reimported the roles table, the permissions adjusted appropriately. I have a role sync module that re-synced the important ones and the other roles are only a handful of people, which I will reassign by hand.


How to plot confidence intervals for multinominal logit predicted values in R?

Question: I am going to use UCLA example on multinominal logit as a running example. I want to analyze the predicted probability of each response based on social-economic status (ses) and the writing grad (write)---
ml <- read.dta("https://stats.idre.ucla.edu/stat/data/hsbdemo.dta")

ml$prog2 <- relevel(ml$prog, ref = "academic")
test <- multinom(prog2 ~ ses + write, data = ml)

dwrite <- data.frame(ses = rep(c("low", "middle", "high"), each = 41), write = rep(c(30:70),
    3))

## store the predicted probabilities for each value of ses and write
pp.write <- cbind(dwrite, predict(test, newdata = dwrite, type = "probs", se = TRUE))

lpp <- melt(pp.write, id.vars = c("ses", "write"), value.name = "probability")

ggplot(lpp, aes(x = write, y = probability, colour = ses)) + geom_line() + facet_grid(variable ~
    ., scales = "free")

For that, my objective is to replicate the following plot with confidence intervals.

I have already tried the following without success: R How to get confidence interval for multinominal logit?
Answer: You can use emmeans to get predicted probabilities and standard errors for each response level, and ggeffects to plot them.
library("tidyverse")

data <- foreign::read.dta("https://stats.idre.ucla.edu/stat/data/hsbdemo.dta")

# reference categories:
data$prog <- relevel(data$prog, ref = "academic")
data$ses <- relevel(data$ses, ref = "high")

model <- nnet::multinom(prog ~ write + ses, data = data)
#> # weights:  15 (8 variable)
#> initial  value 219.722458
#> iter  10 value 179.985215
#> final  value 179.981726
#> converged

predictions <- ggeffects::ggemmeans(model, terms = c("write [all]", "ses"))
#> Loading required namespace: emmeans

# plot(predictions)

predictions %>% ggplot(aes(x = x, y = predicted, colour = group)) +
  geom_line(aes(colour = group), size = 1) +
  xlab("write") +
  facet_grid(response.level ~ ., scales = "free") +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high, fill = group),
              alpha = 0.2) +
  theme_bw()

Created on 2022-06-08 by the reprex package (v2.0.1)
Comment: I've accepted your edit since it's your question. However, in the future consider leaving out details such as factor ordering as they add to the code but don't clarify the question.


Using Views to filter images based on taxonomy of page node

Question: I have many image files with taxonomy associated with them. I have page nodes using the same taxonomy vocabulary. I want to create a Views block that filters the images displayed based on what that page uses for that vocabulary.
Fake example:
I have a page that is tagged with carrots and broccoli.
I have image files tagged with the same terms. I want to place a Views block on the page and have that view only show images tagged with the same terms.
How do I do that?
Answer: Create a views block.
Under Contextual filters, add Content: Has Taxonomy Term ID
Provide Default Value -> Taxonomy Term ID from URL
Tick on 'Load default filter from node page, that's good for related taxonomy blocks' and tick your proper vocabulary.
Comment: So to clarify as I am new to Drupal. The `Under Contextual filters, add Content: Has Taxonomy Term ID` part of your anwser, there is no option specific to that text. Would it that be if the field on both items is called `Vegetables` it would say `Content: Vegetables (field_vegetables)`. Is that the filter I should select
Comment: Add contextual filter..From the dropdown select Content: Has Taxonomy Term ID. In the configuration settings of this filter select Provide Default Value under WHEN THE FILTER VALUE IS NOT AVAILABLE.
Tick on 'Load default filter from node page, that's good for related taxonomy blocks' and tick your proper vocabulary(in your case maybe vegetables).


Equal sign meaning in equations vs functions

Question: My kids are learning about functions for the first time, and I was hoping for a little clarity concerning what the equal sign means in a variety of contexts.
I have checked out, and understood parts of, the available discussion on the differences between equations and functions. (As a philosopher it was much easier to follow the "word explanations" than the explanations in "math notation." My intro to logic class was at least 100+ years ago, and didn't help much.)
I would like to offer my understanding of the different ways the equal sign seems to be used (with examples), and would love constructive feedback.
In equations, the equal sign seems to be used to denote the following things; (these descriptions are my own words, I'm sure there are "real" names for what I am trying to describe, also I don't really understand the difference between "equals" and "is equivalent to"):

tautologies: $5 = 5$;
equivalent "values": $4 = 8/2$ (the value four is equivalent to the value of eight halves);
equivalent expressions: $2x/4 = x/2$;
value/ expression of a given variable: "if $x = 2$...";
value of an unknown variable, after you know what the "answer" is; the value that makes the equation true "Solve for $x$; [math stuff]; $x = 14$."

In functions, the equals sign seems to have a different use. It seems to me that in "function notation" the equal sign is used more to mean "therefore" or the "then" part of an "if then" conditional. But even here there seems to be several uses.

$f(x) = 7x + 3$, seems to say "for function $f$, if the input is $x$, then the output will be $7x + 3$." So the equal sign relates input to output.
But $f(x) = 7x + 3$ also seems to relate input to the rule ("relation"?) that governs the output values. So in this case it means: "given this input, do this, to calculate the output."
(given function $f$ in #1) "$f(2) = 17$" relates a specific input value (2) to a specific output value (17).
Also, if given a function $f$ (from #1), $f(x) = 24$, seems to represent the question "what input (into function f) leads to an output of 24?" Or in other words: output + rule, leads to input.

The one overlap I have managed to find between equations and functions, is that the equal sign seems to be able to represent a "conditional" for both equations and functions.

$f(x) = 7x + 3$ seems to say: "for $f$, if $x$, then $7x + 3$."

$f(2) = 17$ seems to say: "for $f$, if 2, then 17."

$f(x) = 17$ seems to say: "for $f$, if (something unknown), then 17". Or: "for $f$, what input leads to output of 17?"

$8/4 = 2$ means: "if you have eight fourths, then you (also) have two wholes."

$x = 3$, as a "given" means: "given equation 'something', if you use 3 as the value of x, then...".

$x = 5$, as a solution, means: "given equation 'something', if you use 5 for the value of $x$, then the equation will be true."

So what do you think? I do really think the equal sign and its variety of uses, is the source of my confusion. Does any of what I have said make sense? Please help! (And thanks!)
Comment: To be slightly provocative, I only see two uses here: The first is as a boolean operator that evaluates to true iff its inputs are equal in the literal sense, the second as denoting a definition. For this latter meaning, a substantial number of mathematicians prefer to use a different symbol, often $:=$. Of course, for the first use to make sense in your examples one also needs to analyze the context for quantifiers etc., but this does not affect the meaning of $=$ per se.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [here](/help/notation), [here](//math.meta.stackexchange.com/q/5020), [here](//meta.stackexchange.com/a/70559) and [here](//math.meta.stackexchange.com/q/1773).
Comment: It's a complicated question, I think. There's a difference between "the fundamental meaning of the symbol $=$ from a logic perspective" and "what can be conveyed by expressions involving $=$ via the social/linguistic conventions of written mathematics". In terms of the former, $=$ means "the LHS is the same as (identical to) the RHS". The thing about conditionals is an unusual interpretation - EG I'd deconstruct "$f(x) = 7x + 3$" as "(the output of $f$ given input $x$) is identical to ($7x + 3$)". In a function defn, there's an understanding this holds *for all $x$*, hence characterising $f$.
Comment: @J.W.Tanner Thanks so much for the article! I'm not sure I'll understand everything, but I really enjoy learning new things. At first glance, this may lead to more questions than answers, but it is sure to be interesting!
Comment: See e.g. [this post](https://philosophy.stackexchange.com/questions/94350/is-a-relationship-between-the-objects-or-their-expressions) as well as [this one](https://philosophy.stackexchange.com/questions/19773/whats-the-difference-among-the-logical-relations-and-%e2%89%a1)
Comment: See also [Defining an equality](https://math.stackexchange.com/questions/1546309/defining-an-equality) as well as [The properties of equality](https://math.stackexchange.com/questions/2787842/some-questions-about-the-properties-of-equality)
Comment: Cf. [this article](https://bpb-us-e1.wpmucdn.com/sites.harvard.edu/dist/a/189/files/2023/01/When-is-one-thing-equal-to-some-other-thing.pdf)
Comment: I think any answer would make this much harder for a student. I would not distinguish between 1-5 and say the are *all* expressions are that the LHS and the RHS are both the exact same thing.  $5$ IS $5$; $4$ IS $\frac 82$, $\frac {2x}4$ IS $\frac x2$ and so on.
Comment: "f(x)=17 seems to say: "for f, if (something unknown), then 17". Or: "for f, what input leads to output of 17?""  No.  That is an incorrect interpretation.  This is a constant function.  It says whatever input you give, the out put will always be $17$.  $f(2) =17$ and $f(9) = 17$ and $f(\pi) = 17$ and $f(-45) = 17$. ... In all this cases I'd say *every* one of them simply saying two things are the same.  Functions are little iffy as you need to interpret $x$ as a *variable* and not a set value and the "7x+3" as a flexible function which isn't really right.
Comment: @fleablood Yes, I see that now (about "f(x)=17")! Thanks for the clarification. I think I remember one of my son's homework questions being in this form;; but, I might be remembering incorrectly. To satisfy my curiosity how could one ask: "Given function f(x)=2x+3, and an output of 11, what would the input have to be?" without so many words?
Comment: In the function formula $f(x)=\ldots$ $x$ is a placeholder: it is used to specify the arguments of the function. $f(2)=17$ simply menas that the value of function $f$ for input $2$ is $17$. $f(x)=17$ means that the function $f$ has the contsnat value of $17$ for every input.
Answer: In the comments, people have
pointed
out
various
explanations
of the different kinds of "equality" that can be encountered in mathematics.
But I think most (if not all) of these responses are deeper than you need to look in order to resolve your difficulties.
In my view, there is only one meaning of the symbol $=$ in all of the examples given in the question. The meaning of $=$ is that the expression on the left of the $=$, when fully evaluated to its fundamental mathematical object (which is a number in every one of the examples given) is precisely identical to the mathematical object that is obtained by fully evaluating the expression on the right of the $=$.
In short, when you evaluate what you see on each side of the $=$, you get the exact same thing.
I think the difficulty here is not the meaning of $=$, which is always the same, but the interpretation of symbols such as $x$, which has to be inferred informally from context in some mathematical texts because we are too lazy to make it explicit.
For example, you might come across a passage like this:

The function $f$ defined by $f(x) = 7x + 3$ ...

This is a kind of mathematical cliché that in the context of the study of real numbers actually means to say the following:

The function $f$ that maps real numbers to real numbers in such a way that for any real number, if you let $x$ represent that real number and use $x$ as the "input" of $f$, then the "output" of $f$ (that is, the number represented in this case by the expression $f(x)$) is the number that you get when you evaluate $7x + 3.$

That is, each of these statements (the first one by convention, the second one more explicitly) has stated the facts $f(2) = 17,$ $f(3)=24,$ $f(4)=31,$ and an infinite number of other such facts all in one swell foop.
I think it's obvious why the shorter way of saying this is more popular than the long way.
On the other hand, again in the context of the study of real numbers, we could write something like this:

Let $f(x) = 1 - x^2.$ Solve for $x$ in $f(x) = 7x + 3.$

The difference between "$f(x) = 7x + 3$" here and "$f(x) = 7x + 3$" in the previous statements is not the meaning of $f(x) = 7x + 3$
but rather is what the surrounding text says about
when the statement $f(x) = 7x + 3$ is true.
When we write, "The function $f$ defined by $f(x) = 7x + 3$," we are saying that the statement $f(x) = 7x + 3$ is true for all real numbers, but when we write, "Solve for $x$ in $f(x) = 7x + 3$," we are asking when the statement $f(x) = 7x + 3$ is true. Specifically, we are asking which values of $x$ (if any) will make the statement
$f(x) = 7x + 3$ true in the context of a previously-stated definition of the function $f.$

Perhaps your question is not so much about the meaning of $=$ as it is about the uses of equations. There are certainly a lot of ways mathematics texts use equations and (if you're not familiar with the mathematical style of writing) it's not always clear how you're supposed to understand the equations.
This will be a lengthy response because you brought up many good examples and I will try to examine each one carefully. Also, I am trying to anticipate uses of equations that you may not yet have encountered but which would likely cause confusion later.
It's also possible that I am belaboring the point in parts of this response because the only difference between your understanding and mine is that you expressed yours differently. Please bear with me in those cases.
Consider these specific uses of $=$ from the question:

$5 = 5$

The expression consisting of the single symbol $5$ on the left hand side evaluates to a number. (In many contexts we would say it is a number, but when we're trying to carefully parse the meaning of the symbol $=$, it's worth noting that in this context the symbol $5$ may be better viewed as a name for a number rather than the number itself.)
The symbol $5$ on the right hand side also evaluates to a number. And it's the same number (surprise, surprise). So the equality statement is true.

$4 = 8/2$

The symbol $4$ evaluates to a number. The expression $8/2$ evaluates to a number.
These two numbers are the same, so the statement is true.

$2x/4 = x/2$

If $x$ were a number and we knew what number $x$ was, we would be able to evaluate
$2x/4$ and obtain a number as the result. Likewise with $x/2.$
But to understand what we're supposed to do with this equation, we need to look at its context.
Usually the context of an equation like this is in the statement of an identity:
we are asserting that the equation is true for every number $x$ within some set of numbers, such as all the real numbers.
I think this is what you meant by "equivalent expressions".
But you can also encounter problems like the following:

Let $2x/4 = x/2.$ Solve for $x.$

(I used the word "like" loosely here; usually the problem will start with a more complicated equation than this, or even multiple equations.)
If you are studying real numbers, the answer to this problem is that every real number can be used as a value of $x$ to make the equation true.
A solution set is the set of all numbers we can use as the evaluation of $x$ in order to make a statement (such as $2x/4 = x/2$) true; for this problem, if we are studying real numbers, the solution set is the set of all real numbers.

if $x = 2$ ...

This says, "If the symbol $x$ evaluates to the same thing that $2$ does ... ."
It could be a way of "trying on" a particular evaluation of $x$ in some other expression. In the context, "If $x = 2$ then $f(x) = 17,$" it's a roundabout way of saying $f(2)=17.$

"Solve for $x$; [math stuff]; $x = 14$."

I think you have the right idea about this. The big clue is the phrase "solve for $x$".
This example says that there is only one possible way to evaluate $x$ in order to make [math stuff] true, and that $x$ must evaluate to the same thing as $14.$
It is not inevitable that the conclusion of a "solve for $x$" exercise is an equation of the form "$x = \text{something}$". The conclusion might be "no solution"
or it might be something like $x \in \{4, 14\}.$
(You can write the latter as "$x=4$ or $x = 14$" if you want to avoid using the notation of sets.)
Now let's consider the examples using functions:

$f(x) = 7x + 3$ [...] relates input to output.
But $f(x) = 7x + 3$ [...] "given this input, do this, to calculate the output."

In the context of a function definition (see the first part of this answer), both interpretations are correct. The equation tells us how the "input" of the function relates to its "output". In particular, by putting an expression for the output of the function on one side of the $=$ symbol and an expression we can evaluate algorithmically on the other side, it gives us a procedure for calculating all outputs of the function.
There are other ways to define functions. For example, to define $f$ as the principal square root function, if we haven't already defined that function, we could write

For $x \geq 0,$ $(f(x))^2 = x$ and $f(x) \geq 0.$

(given function $f$ in #1) "$f(2) = 17$" relates a specific input value (2) to a specific output value (17).

This is a good interpretation. You can leave out the part about the "given" function and it is still a true interpretation; it merely doesn't say what the rest of the definition of function $f$ is.

Also, if given a function $f$ (from #1), $f(x) = 24$, seems to represent the question "what input (into function f) leads to an output of 24?" Or in other words: output + rule, leads to input.

Also a good interpretation. There should usually be another clue about what you're supposed to do about the value of $x$, such as "find $x$" or "solve for $x$."

$f(x) = 7x + 3$ seems to say: "for $f$, if $x$, then $7x + 3$."
$f(2) = 17$ seems to say: "for $f$, if 2, then 17."
$f(x) = 17$ seems to say: "for $f$, if (something unknown), then 17". Or: "for $f$, what input leads to output of 17?"

I would explain these a little differently, because a number is not a statement that can be true or false; "if $2$ then $17$" is mathematically meaningless.
This answer would become ridiculously long if it got into the question,
"What is a function in mathematics, really?"
But it may help to know that the expression $f(x)$ means "the output value of $f$ that corresponds to the input value $x$."
In this light, you could say (informally) that $f(2)=17$ means that
if the input of $f$ is $2$ then the output of $f$ is $17$.
Note that depending on context, $f(x) = 17$ could be a problem to solve for $x,$ or it could be the definition of the function $f$ whose output is always $17$ for every input.

$8/4 = 2$ means: "if you have eight fourths, then you (also) have two wholes."

If we're talking about apples, eight fourths is not the same as two wholes; the whole apples may still be good to eat tomorrow, but the fourths will go brown quickly.
But if we're just talking about numbers, yes, you have the same number as the value on both sides.

$x = 3$, as a "given" means: "given equation 'something', if you use 3 as the value of x, then...".
$x = 5$, as a solution, means: "given equation 'something', if you use 5 for the value of $x$, then the equation will be true."

I couldn't have said it better.
In summary, it's not so much about "what does this equation mean" but rather,
"OK, here's a statement of an equation, but how am I expected to use it?"
The clues to answer that question are unfortunately subtle,
so subtle that sometimes people post specific arithmetic questions on this site that other people are unable to answer due to inability to see those clues.
Sometimes you just have to read a textbook for a while to figure out what clues that author tends to give (including when the absence of a "clue" phrase is itself a clue).

I should note that as a student of philosophical logic, you would have been introduced to contexts in which the form of an expression is as important as, if not more important than, a number to which you might evaluate the expression (if you even can evaluate it).
What I'm trying to say in this answer is that your children's textbooks almost surely do not treat the expressions in equations that way.
I would expect to see them use the same single definition of an equation that I described above,
and that all the differences in the significance of the equations is due to what the book does with the equation in relation to the other things found in the same passage or exercise.
If your "kids" are currently doing graduate-level work then I could be wrong about all this.
Answer: Long question, short answer (since already the comments link to details).
The meaning of $=$ is apparent from the context. Some programming languages don't like to guess and force the use of different signs, $:=$ and $=$, or even $==$.
BTW, the $=$ is kind of an obsolescent model me think, because even dated pocket calculators added $=0$ at the end of an entered equation. Thus A-1/A-1 suffices completely to compute the Golden Ratio.
Comment: As someone who has studied both mathematics and the theory of programming languages (and who is a highly experienced programmer), I disagree. None of the popular computer languages have a symbol representing the concept of mathematical equality that I believe is meant in the question.
Comment: @DavidK -- not even in a [CAS](http://www.reduce-algebra.com/)? IMO this _concept of mathematical equality_ may be replaced by a minus sign and attach an $=0$ (without writing it). That reminds me my Maths Prof who's wife asked him (so he told us students) what he's doing at all if the result is always $0$ :)
Comment: There is certainly *software* that understands equations. (You happened to link to a page that doesn't display that feature at all, but one can type an equation into Wolfram Alpha and get relevant results.) But software and even software libraries are distinct from *programming languages.* The concept of mathematical equality is also distinct from the notation that represents it; you may propose a different notation, but I doubt it will catch on.
Comment: @DavidK -- _"You happened to link to a page that doesn't display that feature at all"_ Do you mean, what I find in its manual is untrue? Their documentation is totally unreliable? Is it this what you want to say? The link to Reduce CAS was just a hint to an arbitrary CAS, not tho the definition of equations within that distinct CAS. Sorry if that was not obviious for you.
Comment: No, I meant that you linked to the wrong page. If you want to show that a piece of software has a certain feature, link to a page that directly shows that feature. I'm not going to go searching through the manual myself if you're not willing to link to the relevant page directly (especially since this point is irrelevant to the argument in any case). Why give a link at all if the link itself is only a "hint"?
Comment: Me think, we do have a little subject drift not really relevant to the case 'concept of mathematical equality'. One more hint: asking a CAS to solve a quadratic equation (in fact a function) and it has two real roots, I'll get as result two equations. Thus all CAS "know" what $=$ is (I surmise without leafing through all manuals).
Comment: Indeed, we have gotten completely off topic. It's not even an argument, because we clearly agree that at least some CAS tools recognize and use mathematical equality.


JQuery duplicate events when create element and set events to class

Question: When I add an item using click event and exists another element with the same class the event is duplicated.

$(".add-first").on("click", function() {
  var firstContainer='
<button class="add-second">add second</button>
';
  $(this).closest(".first-container").append(firstContainer);
  $(".add-second").on("click", function() {
    $(this).closest(".second-container").append("
example");
  });
});
$(".add-second").on("click", function() {
    $(this).closest(".second-container").append("
example");
  });

  <button class="add-first">add first</button>

<button class="add-second">add second</button>

Then when I press one click in add first this duplicate event in each button add second, then when I press click on the second button it has some events, the issue is duplicated event.
Answer: Try to implement event-delegation instead of binding an event event every time when you are creating a new button,
$(".add-first").on("click", function() {
  var firstContainer = '
<button class="add-second">add second</button>
';
  $(this).closest(".first-container").append(firstContainer);
});

$(".first-container").on("click", ".add-second", function() {
  $(this).closest(".second-container").append("
example");
});

DEMO


Android Studio - CoordinatorLayout, AppBarLayout e FloatingActionButton não instanciados

Question: Eu comecei criando uma nova aplicação, mudei o tema do projeto e obtive o seguinte erro:

java.lang.IllegalArgumentException: You need to use a Theme.AppCompat
  theme (or descendant) with the design library.    at
  android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:34)
    at
  android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:178)
    at
  android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:172)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at
  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at
  org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:458)
    at
  org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:170)
    at
  org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:103)
    at
  com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:190)
    at
  android.view.BridgeInflater.loadCustomView(BridgeInflater.java:247)
    at
  android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:171)
    at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)     at
  android.view.LayoutInflater.inflate(LayoutInflater.java:394)  at
  com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:223)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:426)
    at
  com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
    at
  com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:510)
    at
  com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:498)
    at
  com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:888)
    at
  com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:498)
    at
  com.android.tools.idea.rendering.RenderTask.access$600(RenderTask.java:72)
    at
  com.android.tools.idea.rendering.RenderTask$3.call(RenderTask.java:610)
    at
  com.android.tools.idea.rendering.RenderTask$3.call(RenderTask.java:607)
    at
  com.android.tools.idea.rendering.RenderService.runRenderAction(RenderService.java:366)
    at
  com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:607)
    at
  com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:629)
    at
  com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel$6.run(AndroidDesignerEditorPanel.java:480)
    at
  com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at
  com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at
  com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at
  com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at
  com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at
  com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at
  com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:351)    at
  java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Comment: Não há necessidade do termo em inglês.
Answer: O erro é auto explicativo

You need to use a Theme.AppCompat theme (or descendant) with the
  design library

Se você estiver usando a design library, deve obrigatóriamente usar o Tema Theme.AppCompat ou algum derivado dele.
Comment: Mas então como deve proceder para usar outros temas?
Devo retirar a design library do código?
Comment: @user36323 Ou não use a design library ou modifieque-a conforme suas especificações, crie um tema novo com a Theme.Appcompat como base.
Answer: Usa o Theme.AppCompat como pai dos seus temas em styles.xml


Convergence of $\Vert f \Vert_p$ with respect to $p$

Question: For a Lebesgue measurable function $f$, $\Vert f \Vert_p$ converges to $\Vert f \Vert_\inf$ as $p$ goes to infinity.
I was wondering if $\Vert f \Vert_p$ converges to $\exp(\int \log |f|)$ as $p$ goes to $0$ for probability measure. How to prove this?
Thanks!
Comment: Uh, in general $\|f\|_p$ does not converge to $\|f\|_\infty$. This characterisation of $L^\infty$ requires you divide by an appropriate factor of the measure of the total space. (In particular, it is only true as stated if the the total measure is 1.) See Problem 7.1 in Gilbarg and Trudinger's Elliptic Partial Differential Equations of Second Order. Part (iii) of that problem is the correctly stated version of the convergence you are thinking about.
Comment: Thanks. Just added under probability measure. But I cannot thing out a way to show it is true...
Comment: One can prove a version of the first statement (without using that the space has finite measure) if $f \in L^{p_0} \cap L^\infty$ for some $1 \leq p_0 < \infty$. To see this just write $|f|^p = |f|^{p_0} |f|^{p - p_0}$ and do some syntax juggling.
Comment: Just for reference, this is Exercise 5 part d in Chapter 3 on page 71 of Rudin's *Real and Complex Analysis*, 3rd edition.
Answer: As my approach is different to that of Willie Wong, I give it here:
Assume $f$ is in some $L^{p_0}$.
Let $(p_n)$ be such that $0 < p_n < p_0$ and $p_n \downarrow 0$. Define:
$$g_n(x) = \frac{1}{p_0} (|f(x)|^{p_0} - 1) - \frac{1}{p_n} (|f(x)|^{p_n} - 1).$$
Recall that $\frac{1}{p} (x^p - 1) \downarrow \log x$ as $p \downarrow 0$ for all $x > 0$. So let the $g_n \to g$. Then by the Monotone Convergence Theorem we have that
$$\int g_n \uparrow \int g.$$
This implies that
$$\int \frac{1}{p_n} (|f|^{p_n} -1) \downarrow \int \log |f|.$$
Now, by Jensen's inequality we have
$$\text{exp} \left ( \int \log |f| \right ) \leq \left ( \int |f|^{p_n} \right )^\frac{1}{p_n}$$
and by the inequality $|t| \leq \text{exp}(|t| - 1)$ we get
$$\left ( \int |f|^{p_n} \right )^\frac{1}{p_n} \leq \text{exp} \left ( \int \frac{1}{p_n} (|f|^{p_n} - 1) \right ).$$
So, this together with our previous claim proves the theorem.
Answer: HINT
Approximate by non-negative step functions (if $f$ vanishes on a set of positive measure, using a Hölder inequality you can argue that $\|f\|_p \leq C |\mathrm{supp}(f)|^{\frac1p - 1} \searrow 0$). For step functions, that $\|f\|_p\geq \exp \int \log |f|$ is a consequence of the arimetic-geometric mean inequality.
The AM-GM inequality becomes an equality when all its terms are equal. For a non-negative step function $f$, as $p\to 0$, you have that $f \to 1$. By continuity you can quantify the difference between AM-GM. So you have that the convergence is true for step functions.
To finish off you use the usual diagonal argument to extract a subsequence from the approximating sequence of step functions, together with a suitable sequence of $p$'s.
Comment: I would suggest taking a sequence $(p_n)$ such that $0 < p_n < p_0$ with $p_n \downarrow 0$ and then define something like $f_n(x) = 1/p_0 (|f(x)|^{p_0} - 1) - 1/p_n (|f(x)|^{p_n} - 1)$ and use that $1/p (t^p - 1)$ decreases to $\log t$ as $p \to 0$ for all $t > 0$. Then note that $\int f_n \uparrow \int f$. Now we can bound $(\int |f|^{p_n})^{1/p_n}$ in both directions by things that go to the required $\text{exp}(\int log |f|)$.


Pulling text from text_area_tag on link_to

Question: So right now I have a modal that pops up and it has a list of emails in it from a db query. What I want to be able to do is on a link_to being clicked, pull the information from the text_area and use it inside of my controller.
I think part of the issue might be that I have the route setup as a get right now, but I don't know if setting it up as a put or post will do anything since I am not actually saving anything to a database.
Here is the code of my form in show page:
<%= text_area_tag 'test_area', Query.collect(&:email).join(", "), :style => 'width:100%; height:200px;' %>
<%= link_to 'Send Mail', admin_send_test_mail_path, :class => "btn btn-default" %>

Here is the route:
get 'send_test_mail', to: 'my_controller#send_test_mail', as: :send_test_mail

here is the controller:
def send_test_mail
    puts params[:test_area] #Doesn't output anything
    NotificationMailer.test_email_stuff.deliver
    redirect_to my_path
end

Any help would be appreciated. I'm still a little hazy when it comes to passing params from view to controller so maybe that is where I am messing up.
Thank you.
Answer: You need to put this into a form and use submit_tag instead of link_to:
<%= form_tag send_test_mail_path do %>
  <%= text_area_tag 'test_area', Query.collect(&:email).join(", "), style: 'width:100%; height:200px;' %>
  <%= submit_tag 'Send Mail', class: "btn btn-default" %>
<% end %>

If you realy want to use link_to then you could achieve this using js:
<%= form_tag send_test_mail_path do %>
  <%= text_area_tag 'test_area', Query.collect(&:email).join(", "), style: 'width:100%; height:200px;' %>
  <%= link_to 'Send Mail', '#', class: "btn btn-default", onclick: "$(this).closest('form').submit()" %>
<% end %>

Comment: @Matthew, yes you are right that it calls the same route but it doesn't "know" what to do with form fields. Link tag doesn't trigger form submition by default. Link tag main purpose is to move user to another page (a GET request) and not to submit a form data (mostly a POST request). But as you see we can force it to do what we want via js. I'd advise you to read more about simple html forms outside of rails scope.
Comment: This works (after changing my route to post instead of get). My question if you don't mind, is why wouldn't the link_to work? It seems like it is just calling the route the same way.
Comment: I appreciate you getting back with me. That makes sense. I will definitely do more research on forms and how they handle data


Reconstruct a database

Question: How do I get the lag/lead function to work on the first case number per patient in my database?
I have a database of 1k+ variables and 800k rows.
Each row is an intervention on a segment of a vessel, one patient may have several rows = many interventions on different vesselsegment but all within the same hospitalization. There are 4 vessels and I when I restructure the database I get 4 cases for each row=intervention. I have tried to post the data below:
data list list /id_nr (f6) segment_id_nr (f6) date (date9) C_RCA (f6) C_LM (f6) C_LAD (f6) C_LCx (f6) VESSEL(a3)  max_stenos (f6) Culprit_PCI (f6) Procedure_type (f6).
BEGIN DATA
1, 5, 12-Jun-06, 1.00, .00, .00, .00, RCA, 3.00, 1.00, 2.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LAD, 4.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LCX, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, RCA, 3.00, 1.00, 2.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LAD, 4.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LCX, 1.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, RCA, 3.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LAD, 4.00, 1.00, 2.00
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LCX, 1.00, ,
END DATA.
dataset name OrigData.

It should look something like this: enter image description here
What I want is to combine all data from the last two variables to be contained within the first 4 rows and later remove remaining rows so that I have 4 rows per hospitalization, each row corresponding to intervention in that row see data below that i have copy pasted in excel:
data list list /id_nr (f6) segment_id_nr (f6) date (date9) C_RCA (f6) C_LM (f6) C_LAD (f6) C_LCx (f6) VESSEL(a3)  max_stenos (f6) Culprit_PCI (f6)         Procedure_type (f6) Culprit_PCI2 (f6)  Procedure_type2 (f6).
BEGIN DATA
1, 5, 12-Jun-06, 1.00, .00, .00, .00, RCA, 3.00, 1.00, 2.00,1.00, 2.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LM, 1.00, , , ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LAD, 4.00, , ,1.00, 2.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LCX, 1.00, , , ,
END DATA.
dataset name OrigData.

I have tried with the lag/lead function but i cant get it to work
I have the following code:
compute seq = $casenum.
execute.
SORT CASES BY seq.
CREATE PCI_other_segmentvessel = LAG(Culprit_PCI,4).
CREATE proceduret_type2 = LEAD(procedure_type).
Execute.

Is this possible to do?  Is it perhaps a lag
IF sid= lag(sid) and Vessel=lag(Vessel) PCI2 = lag(Culprit_PCI,4).
Execute.

None of these works properly. Could you point me to the right direction? I dont know if data will work but if copy pasted into excel it works.
Kind regards
Comment: I find it very difficult to understand the structure of your existing data and the structure you're trying to get to. Please find a way to post your data samples more clearly - (e.g. look up DATA LIST - BEGIN DATA - END DATA) and post a full command here.
Comment: I am new to this and trying to do my best. I couldnt really get the data list to work but managed to add an image of how the dataset looks like on excel, I hope it may help.
Comment: I edited your post with a full data list command for the sample of the original data. Please use this example to create a target data and clarify what you need exactly.
Comment: Thank you Eli. I got the data list to work on target data. As you can see, I want the results from Culprit_PCI and Procedure_type to be created either as new variables or in the same variables but "lifted" up to the first four rows/cases as each one of them corresponds to a specific coronary artery. The best alternative is to have the results lifted up to the same variables but thats an easy fix later on.
Answer: You can test for a change in the ID in your calculation, but it is easier to use the SHIFT VALUES command along with SPLIT FILES.  SHIFT VALUES will not cross split boundaries.
Comment: Thanks for reply:) Im not sure i understand what you mean with test for a change in the ID. How do I do that? Is there a syntax code for it? Should I split files by idnr or the segment id? How do i make sure the results from the lag are pasted on the first 4 cases of each individual? Sorry for the many questions:)
Comment: The shift command with split files worked very fine, however I have the issue with having the value in the 4 uppermost cases.

    split file by sid.
    SHIFT VALUES VARIABLE = Culprit_PCI RESULT = CPCI2 SHIFT = 4.

Is there a way to change the 4?
Answer: You say you've reached this situation after some restructuring - I strongly suggest you start a new question with the original structure and the final structure you are trying to reach, there's a good chance we can find a much simpler shortcut that doesn't go through this point.
Assuming you DO have to go through this point, the following syntax creates something very similar to your target structure, including removing extra lines. I hope this helps tho I'm not absolutely sure I completely understand what you need:
*creating sample data (a bit different from your original sample, to help the demonstration work).
data list list /id_nr (f6) segment_id_nr (f6) date (date9) C_RCA (f6) C_LM (f6) C_LAD (f6) C_LCx (f6) VESSEL(a3)  max_stenos (f6) Culprit_PCI (f6) Procedure_type (f6).
BEGIN DATA
1, 5, 12-Jun-06, 1.00, .00, .00, .00, RCA, 3.00, 1.00, 2.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LAD, 4.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LCX, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, RCA, 3.00, 2.00, 1.00
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LAD, 4.00, ,
1, 5, 12-Jun-06, 1.00, .00, .00, .00, LCX, 1.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, RCA, 3.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LM, 1.00, ,
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LAD, 4.00, 1.00, 2.00
1, 5, 12-Jun-06, .00, .00, 1.00, .00, LCX, 1.00, ,
END DATA.
dataset name OrigData.

* removing empty lines .
select if not missing(Culprit_PCI).

* counting occurrences of each vessel to use as index.
sort cases by id_nr segment_id_nr date VESSEL.
compute tmp=1.
split file by id_nr segment_id_nr date VESSEL.
CREATE ProcNum=CSUM(tmp).
split file off.

* restructuring.
format ProcNum(f6).
sort cases by  id_nr segment_id_nr date C_RCA C_LM C_LAD C_LCx VESSEL  max_stenos ProcNum.
casestovars /id= id_nr segment_id_nr date C_RCA C_LM C_LAD C_LCx VESSEL  max_stenos/index ProcNum /drop=tmp/separator="_"/groupby=index.

Reconstruct a database


PhoneGap - Abrir WhatsApp "whatsapp://send?" IOS 10

Question: Até a ultima versão do iOS 9 quando queria compartilhar algo pelo whatsapp eu podia usar o link:
whatsapp://send?text=mensagem

em uma tag  ou window.open no js.
Porém nos iOS 10 isto parou de funcionar, ao clicar no link ele não executa nada, nem sequer abre o whatsapp.
Comment: Mas não é necessário criar um popup para isso, bastaria criar um link não? Todavia não tenho iOS 10 para testar :/
Comment: No navegador Safari em iOS 10 o link funciona?
Comment: Funciona sim ! Só não funciona dentro da aplicação feita no cordova.
Comment: Entendi, então deve ser algo que falta liberar no webview ou nas permissões, não uso cordova mas vou tentar ver se consigo descobrir, posta o código do webView e das permissões por favor.
Comment: Troquei para não abrir no webview, e sim no navegador padrão, agora ele abre o whats porém não envia o text
Comment: Sem código fica dificil saber exatamente o que você fez
Comment: Consegui resolver, vou colocar a solução aqui ![
Answer: Consegui resolver isso da seguinte maneira.
na página em que havia o botão que envia o conteúdo para o whatsapp, estava assim :

porém não no IOS 10 o botão não funcionava (ficava sem ação), somente quando o link era whatsapp://send.
Então tentei enviar primeiro para uma pagina web onde o usuário seria redirecionado para o whatsapp, não funcionou pois o app tentava abrir esta página pelo Webview do Phonegap, quando enviei para abrir pelo browser default ai funcionou:
window.open('"endereço da página de redirecionamento"', '_system', 'location=no');

o _system faz toda a diferença, pois o webview não consegue abrir o whatsapp.
Answer: Você precisa usar https://api.whatsapp.com/send?phone=seu-numero&text=texto-que-deseja
É possível usar apenas a função phone ou apenas text
Isso vai chamar o app tanto no android quanto ios e funciona sim no 10
Se você utiliza site em wordpress, criei algo para deixar um botão flutuante em todas as páginas de forma fácil já redirecionando para o número que deseja.
Se quiser conferir: WhatsApp Chat WP


Using AUC to compare logistic lasso and elastic net

Question: I've seen this question answered here but I do not understand the answer. Harrell recommends using deviance based measures. David Hand (referenced in the thread) says that that the AUC is inappropriate to compare different models, because it uses different misclassifications costs. I don't see how this would be the case when comparing lasso and elastic net, given that they are both trained on the same set of predictors.
Answer: Harrell's complaint about using ROCAUC to compare model performance is that it is not sensitive enough to catch real differences. Tests that lack the ability to notice what they are meant to detect are problematic. Getting away from statistics, imagine a cancer screening that has minimal ability to detect cancer: why bother with it?
One place where ROCAUC is deficient is that it has nothing to do with how well-calibrated the predictions are. Your models predict probabilities of event occurrences. If an event is continually predicted to happen with a probability of $0.9$ yet only happens $60\%$ of the time, then that predicted $0.9$ is, in some sense, not telling the truth. ROCAUC will not catch this. In fact, you can halve (or divide by a billion) all of the predicted probabilities without changing the ROCAUC.
Comparing your LASSO and elastic net models on the ROC will give you an idea of which method gives the model that has better ability to discern between the two categories. However, you are missing out on the output calibration. If you plan to use the raw probabilities, and Harrell has argued in many places why they are useful, you would want to know about their calibration.
Deviance-based statistics are related to the log loss, which is a strictly proper scoring rule that can be thought of as seeking out the true probabilities. Log loss considers all aspects of prediction quality, not just the ability to distinguish between the categories. In that regard, functions of the log loss, such as deviance, give a more complete sense of the performance.


First order sentence true in $\mathbb{Q}$ but not in $\mathbb{R}$.

Question: I have the following assignment question:

Find a first order sentence that is true in $\langle\mathbb{Q},+,\cdot ,0,1\rangle$ but not in $\langle \mathbb{R},+,\cdot,0,1\rangle$.

Most of what I can think of is second order (such as completeness, or cardinality).
I have the following candidate, though:
$$\forall x\exists y\exists z \quad \Bigg(x=\bigg(\sum_{j=0}^y 1\bigg)\cdot i\bigg(\sum_{j=0}^z 1\bigg)\Bigg).$$
Where $i(\alpha)$ denotes the multiplicative inverse of $\alpha.$
I'm just not sure that this idea of summing "$y$ times" or summing "$z$ times" is actually doable in first order logic.  I'm also not sure if somehow I need to clarify that $y$ and $z$ need be integers (and if that's doable in FOL).
Any corrections or clarifications to my candidate are welcome, as well as maybe another example I'm just not thinking of.
Comment: The attempted example is *in principle* fixable, but with a hideous amount of work, and reference to a paper by Julia Robinson on definability of the integers in the rationals. Effectively, it is not the right way to go. A very weak consequence of completeness, as in my answer, works quickly.
Comment: Is $\sigma$ a first order expression? I don't think it is. Note, since you are working first order $\exists z$ means $z$ is a rational number, so what does $\sum_{j=0}^z$ even mean?
Comment: @AndréNicolas Thanks, that answers a quesiton I was just wondering: if the integers were even definable in the first-order rationals.
Comment: @ThomasAndrews: It was a nice result. An unsolved problem is whether the integers are *existentially definable*. That would settle Hilbert's 10th Problem for the rationals, a famous open problem.
Answer: Hint: The square root of $2$ is irrational.
Answer: Hint:
Think about roots, do they always exist in $\mathbb Q$ and do they always exist in $\mathbb R$?
Well, square roots don't have to exist, but what about other orders?


Question regarding behaviour of equidistributed sequences.

Question: If $(s_1, s_2, s_3\ldots )$ is an equidistributed sequence on $[0,1],$ then for each $\ 0<\delta<\varepsilon <1\ $ and each $\ c\in [0,1-\varepsilon],\ \exists\ N\ $ such that
$$ \varepsilon - \delta < \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [c, c+\varepsilon] \right\rvert }{ n } < \varepsilon + \delta $$
for all $\ n\geq N.$
This implies:
If $(s_1, s_2, s_3\ldots )$ is an equidistributed sequence on $[0,1],$ then for each $\ 0<\delta<\varepsilon <1\ $ and each $\ (c_i)_{i=1}^{k}\subset [0,1-\varepsilon],\ \exists\ N\ $ such that
$$ \varepsilon - \delta < \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [c_i, c_i+\varepsilon] \right\rvert }{ n } < \varepsilon + \delta $$
for every $\ i\in \{1,\ldots,k\}\ $ and for all $\ n\geq N.$ This is because there is an $N(i)$ for each $c_i,$ and so in the statement above, we can let $N=\max_{1\leq i\leq k} N(i).$
To me, this motivates the following question, which I assume is false, although I struggle to construct a counter-example, and am interested in how to write one.

Let $(s_1, s_2, s_3\ldots )$ be an equidistributed sequence on
$[0,1].$ Is it true then, that for each $\ 0<\delta<\varepsilon <1,\
 \exists\ N\ $ such that
$$ \varepsilon - \delta < \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [c, c+\varepsilon] \right\rvert }{ n } < \varepsilon + \delta $$
for every $\ c\in [0,1-\varepsilon]\ $ and for all $\ n\geq N?$
Answer: The result is true as follows. Construct a partition $0, \delta/4,...k\delta/4, 1$ of $[0,1]$ of width $\delta/4$ except possibly for the last interval with width at most that. If $x_m, m=0,...k+1$ are the nodes of that including $1$ every point $c \in [0, 1-\epsilon]$ is within at most $\delta/4$ from a node to the left, let's call it $x_m$ so $[c, c+\epsilon] \subset [x_m, x_m+\epsilon+\delta/4]$ since $x_m \le c \le x_m+\delta/4$ and of course if $x_m +\epsilon+\delta/4 >1$ we have $[c, c+\epsilon] \subset [x_m, 1]$
But now for each $x_m$ we have $\lim_{n \to \infty} \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [x_m, x_m+\varepsilon+\delta/4] \right\rvert }{ n }=\epsilon+\delta/4$ while in the border case the limit is $\epsilon \le 1-x_m \le \epsilon+\delta/4$
So picking $N_1$ large enough depending only on all the $x_m$, we get  $\frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [c, c+\varepsilon] \right\rvert }{ n } \le \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [x_m, x_m+\varepsilon+\delta/4] \right\rvert }{ n } < \epsilon+\delta/2$ for all $c \in [0,1-\epsilon]$ and all $n \ge N_1$
Similarly $c$ is within at most $\delta/4$ to a node to the right $x_q$ hence $[x_q, x_q+\varepsilon-\delta/4] \subset [c, c+\epsilon]$ since $c \le x_q \le c+\delta/4$ and the same reasoning give an $N_2$ depending again only on the $x_m$'s st $\frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [c, c+\varepsilon] \right\rvert }{ n } \ge \frac{ \left\lvert \{ s_1, \ldots, s_n \}
 \cap [x_m, x_m+\varepsilon-\delta/4] \right\rvert }{ n } > \epsilon-\delta/2$ for all $c \in [0,1-\epsilon]$ and all $n \ge N_2$ and then picking $N$ the largest of the two we are done!


How to write sqlite script that returns all rows with matching column name and any row with matching parentID?

Question: I would like to write a sqlite script returns all rows with matching column name and any "child row"
For example:
Table ABC:

Date
Time
Location
Who
UniqueID
ParentID

01/01/0001
11pm
Room1
Chris
1
''

01/01/0001
11pm
Room2
David
2
1

01/01/0001
11pm
Room2
John
3
1

01/01/0001
11pm
Room3
Emily
4
''

If I do Select * from ABC WHERE WHO is "Chris" it will return:

Date
Time
Location
Who
UniqueID
ParentID

01/01/0001
11pm
Room1
Chris
1
''

Instead I would like it to return the following:

Date
Time
Location
Who
UniqueID
ParentID

01/01/0001
11pm
Room1
Chris
1
''

01/01/0001
11pm
Room2
David
2
1

01/01/0001
11pm
Room2
John
3
1

Explaination: David and John have ParentID that is equal to the selected row(s).
Comment: How many levels deep can parent child relationships be?  Are there only ever a max of depth 2, or could there be, for example, grandchildren as well?
Comment: Just 2, parent and child
Answer: Given that you only expect two levels here in the hierarchy, you can use a simple query here:
SELECT *
FROM ABC
WHERE
    Who = 'Chris' OR
    ParentID = (SELECT UniqueID FROM ABC WHERE Who = 'Chris')
ORDER BY
    UniqueID;

Comment: It depends on what your definition of "duplicate" row is.  If you mean all six columns having the same value, then just changing to `SELECT DISTINCT *` would be sufficient.  If you mean less columns, then we can use `ROW_NUMBER`.
Comment: Is there a way to remove any possible duplicate row in addition to the query you wrote?


hibernate : can multiple sessions share the same connection?

Question: We have a C3P0 pool as datasource, and we are using org.springframework.orm.hibernate4.LocalSessionFactoryBean as session factory.
Some of our (big) MySQL requests are configured to stream the result set.
However, MySQL only allow to stream a single result per connection.
That's why I'm wondering if 2 different Hibernate session can use the same connection, or is it 1 connection = 1 session ?
Answer: Just to complement JB Nizet's answer: a connection is provided by the pool to the application (a Hibernate session, in this case). The application uses this connection and returns it to the pool. The pool will decide whether to discard this connection or to reuse it in the future for another session. So, two different sessions can end up using the same connection, but not at the same time.
Answer: No, two sessions can't share a single connection.


jackson-module-scala (play): registerModule(DefaultScalaModule): found DefaultScalaModule.type; required: databind.Module

Question: I am trying to un/marshall json in a play app, by using jackson-module-scala and their example:
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

I included these libraries in Build.scala
"com.fasterxml" % "jackson-module-scala" % "1.9.3",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.3.0",

and imported:
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

However, when I run the Play App, I get the following error:
[error]  found   : com.fasterxml.jackson.module.scala.DefaultScalaModule.type
[error]  required: com.fasterxml.jackson.databind.Module
[error]     mapper.registerModule(DefaultScalaModule)

play.PlayExceptions$CompilationException: Compilation error[type mismatch;
 found   : com.fasterxml.jackson.module.scala.DefaultScalaModule.type
 required: com.fasterxml.jackson.databind.Module]
    at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14$$anonfun$apply$16.apply(PlayReloader.scala:304) ~[na:na]
    at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14$$anonfun$apply$16.apply(PlayReloader.scala:304) ~[na:na]
    at scala.Option.map(Option.scala:145) ~[scala-library-2.10.3.jar:na]
    at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14.apply(PlayReloader.scala:304) ~[na:na]
    at play.PlayReloader$$anon$1$$anonfun$reload$2$$anonfun$apply$14.apply(PlayReloader.scala:298) ~[na:na]
    at scala.Option.map(Option.scala:145) ~[scala-library-2.10.3.jar:na]

Any help would be greatly appreciated.
Answer: Was finally able to figure it out.
I was trying to get the latest version of jackson-module-scala; the latest version seemed to be 1.9.3 by checking: http://mvnrepository.com/artifact/com.fasterxml/jackson-module-scala
However the proper place to look had the proper newest version 2.3.0: http://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-scala_2.10
It was fixed by changing the Build.scala to:
...
"com.fasterxml" % "jackson-module-scala_2.10" % "2.3.0",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.3.0",
...

or even better use "%%" (for automatic scala version resolution; don't need to add "_scala.ver"):
...
"com.fasterxml" %% "jackson-module-scala" % "2.3.0",
"com.fasterxml.jackson.core" % "jackson-databind" % "2.3.0",
...


Leaflet views: how to zoom on the marker while clicking on it in order to get the popup

Question: I am using the module Leaflet and its sub-module "Leaflet views"" in order to get a map displaying markers based on taxonomy terms.
I am able to show a popup displaying the term page while I click on a marker.
Now, my actual requirement is when I click on the marker, the map is zoomed on the clicked marker (zoom of maximum 3 levels) and just after the popup is displayed. So, my map behavior on the marker click event contains two steps: zooming and popup opening.
How can I hook the module in order to enrich my views?
Answer: Install and enable jQuery update. Set the jQuery version to >= 1.7.
Create a module, then create a zoom.js JavaScript file and paste this:
<code>(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      $(document).bind('leaflet.feature', function(e, lFeature, feature) {
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          lMap.setView(e.latlng,8);
        })
      });

    }
  }
})(jQuery);
</code>
Use your module name instead of MYMODULE
Then use drupal_add_js() in your module to include zoom.js. Note the weight option:
<code>  drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/zoom.js',array('group' => JS_DEFAULT, 'weight' => -5));
</code>


Reading numbers from a txt file in batch

Question: I am making a script to keep track of my grades. It is just a simple beginner script which I am making for myself, and am doing so because I am interested learning batch programming.
So far my script allows me to choose to add numbers to a .txt file. I have also made it display the numbers in the window. I would also like it to read the numbers from the file, and do some math with them, but can't figure out how to read the numbers
Answer: Well this litle function can read the line you what from your txt file
:_ReadLine
REM %~1 txt file, %~2 the line you want to read, %~3 the variable you wish to give.
for /f "usebackq skip=%~2 delims=" %%a in ("%~1") do set "%~3=%%a" & goto :EOF

you can call it like this :
call :_ReadLine "test.txt" "21" "test"

this will read 21. line of your test.txt file and add it to test variable
EDIT
You didnt give any example about your txt file so i assumed its something like this:
10
20
30
40
50
60

if you call this function like;
call :_ReadLine "yourFileName.txt" "5" "test"

This will read line number 5 and set its value to %test% if you are working inside of EnableDelayedExpansion use ! instead of % like !test!
in the end you can use this variable for whatever you want to. For example echo %test% will give you result of 50
Comment: Could you explain a little better what the different types of comments are? Like what i am supposed to fill into the different places. Pretty new to this... Didn't get it to work btw, so that's why i'm asking!
Comment: Your script will never read line 1. `%~2` represents the number of lines to skip, and FOR /F does not allow a SKIP value of 0. If you don't want to skip a line than you must leave off the SKIP option.


Usar argumentos numa função provenientes de outra função

Question: Eu tenho um documento de texto com o seguinte formato:
word_1 word_2 word_3
word_4 word_5 word_6

Para cada linha desse documento de texto:

primeiro: quero salvar as palavras e adicionar "_info" a cada palavra;
segundo: os argumentos que eu quero usar na próxima função (que se repete para cada linha) são:
def my_function
("word_1","word_2","word_3","word_1_info","word_2_info","word_3_info")

Após os primeiros cálculos com os argumentos da primeira linha, os argumentos seguintes serão:
def my_function ("word_4","word_5","word_6","word_4_info","word_5_info","word_6_info")

O mais próximo que estive foi ler (porque estou tendo problemas para adicionar "_info" a cada palavra), as informações do arquivo de texto da seguinte forma:
f = open("test.txt","r")
array=[]

for line in f:
    x = re.findall(r"[a-zA-Z]+_+\d",line)
    array.append(x)

def my_function("array[0][0]","array[0][1]","array[0][2]")

Como posso melhorar meu código para fazer o que preciso?
Answer: Ola, tentarei te ajudar :)
Para o python esse "array=[ ]" na verdade é uma lista
>>> type([])  ===:> class list
Ao indicar um arquivo pode  passar direto para um loop.
Imagino eu que este arquivo internamente estaria assim:
word_4
word_5
word_6
word_4
word_5
nova_lista = list()
for linhas in open("test.txt"):
#linhas  ....  Ocorrera a leitura do txt mas no entanto havera uma \n
linhas.strip() # desta maneira nao ocorrera uma linha vazia
ref = f'{linhas.strip()}_info' # usando f string
nova_lista.append(ref) # adiciona a lista
Se neste arquivo houver mais que 10 conteudo.
Vai escrever todos ?
Poderia usar um descompactador
def my_function (*nova_lista)
loop.....
Caso realmente quer acessar cada um pela função
def my_function (exem1, exem2, exem3, exem4 ,exem5)
print(exem1)
print(exem2)
Só chamar a função passando a lista
my_function(*nova_lista)


Using 1000 separator when writing Excel

Question: How to use 1000 separator when writing Numbers to Excel Sheet with java? Typical Decimal Formatter forces the double value to String. I want the value to be in format 000 (space) 000,00
Answer: You need to set the field's number format. see the API's. The separator is a display option, not a modification of the 'numeric value'.
Comment: So how do I use it? Setting cellview?
Comment: @jaana: sorry, my experience with writing excel-files is with perl (on solaris boxes), so I have 'only' rather generic sense advice, that you probably tried already.  What does the JavaAPI documentation (and google) say about that function? Did you try handcrafting a pattern in Excel and assigning that?

Using 1000 separator when writing Excel


Why do O(logn) & O(exp(n)) Have Polynomial & Non-Polynomial Running Time Complexities Respectively Despite Their Taylor Series?

Question: I understand that a function, say $f(x)$, belongs to a class $O(g(x))$ iff:
$$
\exists k > 0 \ \ \exists \ \forall n > n_0: |f(n)| \leq |g(n) \cdot k|
$$
I also know that $log(x)$ is has polynomial running time complexity as can be bounded by some polynomial, say $k \cdot x^m$ where $k$ is a constant, while this doesn't hold true for $exp(x)$. However, what I cannot understand is when we bring our old dear friend into the play, the Taylor Series:
$$
exp(x) = \sum_{n=0}^{\infty} \frac{x^n}{n!} \ \ \ \ \ for \ all \ x
$$
$$
log(1 + x) = \sum_{n=0}^{\infty} (-1)^{n+1} \frac{x^n}{n} \ \ \ \ \ for \ |x| < 1
$$
Now substituting the Taylor Series of each function respectively, we will obtain for some $m_1$, $m_2$ belonging to $\mathbb{R}$:
$$
\exists k_1 > 0 \ \ \exists \ \forall n > n_1: |exp(x) = \sum_{p=0}^{\infty} \frac{x^p}{p!}| \leq |x^{m_1} \cdot k|
$$
$$
\exists k_2 > 0 \ \ \exists \ \forall n > n_2: |log(1 + x) = \sum_{p=0}^{\infty} (-1)^{p+1} \frac{x^p}{p}| \leq |x^{m_2} \cdot k|
$$
The first of these two statements, is false since $exp(x)$ cannot be bounded by a polynomial. However since we can express $exp(x)$ as the sum of a polynomial, why can't it be bounded by another polynomial?
As for the second statement, that holds true but what I cannot understand intuitively is that how can an infinite sum of polynomial terms on the left ever be bounded by a single polynomial term on the right side?
(Note this logic here directly challenges the reason I purposed in the previous paragraph about bounding but I am mentioning it because I think it is the source of the paradox I cannot solve)
Answer: $\log(1+x)=\sum_p^\infty (−1)^{p+1}\frac{x^p}{p},$ only holds for $|x|<1$,
whereas you are interested in $\log(n)$ for $n=1,2,3,\ldots$.
Comment: Fair enough. Although, let us take the Taylor series at $a = x_0$ rather than $a = -1$, we will then have a Taylor series that fits our needs although it's domain might be a bit small, we can always generate a new series if we change "$a$" to whatever suits us. That being said, how can an infinite sum of polynomial terms be bounded by a single term?
Comment: Are you perhaps being thrown off by the fact that the series is telescoping? The $((p+1)$ term x^p that is added to the series is subtracted away in the next term... (up to some fraction at least). Expand the first few terms by hand and pay attention to the telescoping.


Boundary of a connected manifold is connected?

Question: I assume the answer to this question is simple, but I can't find any references:
Let $X$ be a topological space, and $M$ be a (path-)connected component of a manifold in $X$ with the same dimension as $X$. Then, is the boundary of $M$ also (path-)connected?
Comment: No. See a macaroni.
Answer: The boundary need not be (path-)connected.
Consider $X = \mathbb{R}$ with its standard topology and $M = [0, 1]$. Note that $\partial M = \{0, 1\}$ which is not connected or path-connected.
Comment: Great, thanks! Is it possible to come up with a simple additional requirement, so that the boundary has to be path-connected, e.g. that the complement of M is path connected?
Comment: Not that I'm aware of.


Continuity of the union of two functions in a topological space

Question: Let $X$ be a topological space with closed subsets $A$ and $B$ such that $X = A \cup B$. Let $f: A \rightarrow Y$ and $g: B \rightarrow Y$ be continuous functions such that for $x \in A \cap B$, $f(x)=g(x)$. Define a new function $f \cup g: X \rightarrow Y$ by
$f \cup g = \begin{cases} f(x), x \in A \\ g(x), x \in B \\ \end{cases}$
Prove that $f \cup g$ is continuous, and provide an example which shows why $A$ and $B$ must be closed.
This seems like a really obvious result, but I'm having a hard time providing a proof. For completeness's sake, the definition of continuity given is that a function $f:X \rightarrow Y$ is continuous if for every open set $A$ in $Y$, $f^{-1}(A)$ is open in $X$.
Answer: Note that your "inverse image of open set is open" definition of continuous is equivalent to "the inverse image of a closed set is closed." By looking at continuity this way, we will see why $A,B$ being closed is important. Let $C \subset Y$ be closed. Now let's examine the inverse image of $C$ in $X, \space(f \cup g)^{-1}(C)$.
Let $x \in (f \cup g)^{-1}(C).$ Then $(f \cup g)(x) \in C$. However, $(f \cup g)^{-1}(C) \subseteq A \cup B$ so we also know $x \in A$ or $x\in B$. If $x \in A$ then $(f \cup g)(x)=f(x) \in C$ which implies $x \in f^{-1}(C)$. If $x \in B $ then $(f \cup g)(x)=g(x) \in C$ which implies $x \in g^{-1}(C)$. Thus for all $x \in \space(f \cup g)^{-1}(C)$ either $x \in g^{-1}(C)$ or $x \in f^{-1}(C)$, so $$(f \cup g)^{-1}(C) \subseteq f^{-1}(C) \cup g^{-1}(C)$$ Now let $y \in  f^{-1}(C) \cup g^{-1}(C)$. If $y \in  f^{-1}(C)$ then $y \in A$ because $f^{-1}(C) \subseteq A$. But if $y \in A$ then $f(y)=(f \cup g)(y) \in C$, which implies $y \in (f \cup g)^{-1}(C)$. Similarly, if $y \in  g^{-1}(C)$ then we will again find that $y \in (f \cup g)^{-1}(C)$. This means $$ f^{-1}(C) \cup g^{-1}(C) \subseteq (f \cup g)^{-1}(C)$$ so we conclude $$ f^{-1}(C) \cup g^{-1}(C)=(f \cup g)^{-1}(C)$$ Next let's consider the subspace $f(A)$. Since $C$ is closed in $Y$ we know $C \cap f(A)$ is closed in $f(A)$. Since $f$ is continuous we then know that $f^{-1}(C \cap f(A))=f^{-1}(C) \cap A$ is closed in the subspace $A$. By identical reasoning, $g^{-1}(C) \cap B$ is closed in the subspace $B$. Now we can use the immensely helpful fact that $A,B$ are closed in $X$ to note that sets are closed in a subspace iff they are closed in the space. We now know $g^{-1}(C) \cap B$ and $f^{-1}(C) \cap A$ are closed in $X$. The union of the two is also closed. Further, $$\left(g^{-1}(C) \cap B\right) \bigcup \left(f^{-1}(C) \cap A\right) = f^{-1}(C) \cup g^{-1}(C) = (f \cup g)^{-1}(C)$$ so the inverse image under $f \cup g$ of any closed set in $Y$ is closed in $X$ making $f \cup g$ continuous. $\Box$