text:
Q: How can I install template from 3rd party to Keynote? After downloading a template for my Keynote program, I can't seem to install it correctly so that I can utilize the 200+ slides that are included when I wish to add a new slide in the presentation.
I have the latest software of El Capitan and the latest version of Keynote installed.
This is what I have done so far:

*

*Purchased "Eureka - Minimal Keynote Template" from this site (http://graphicriver.net/item/eureka-minimal-keynote-template/15099332) and downloaded files.

*Folder downloaded is split up into different sub folders: 1 Documentation, 2 Presentation, 3 Vector Icons, 4 Double Exposure PSD.
From folder 2 there are two files named Eureka - 16x9 - MAIN.key and when opening them in Keynote, on the left sidebar 200+ slides are displayed (these are all the slide templates that I wish to utilize when creating new presentations).

*So I choose "Save Theme" and add it to the "Theme Chooser", but when opening it from the "Theme Chooser" I only get the two master slides - one white and one black" to choose from when clicking "add slide".

*So I go back and check the Eureka - 16x9 - MAIN.key that I first opened, and see that when clicking "add slide" in this one, I also only have the two options of the black and the white slide here.

So this is where I am puzzled - should not the template I have purchased when saved give me the opportunity of finding all the 200+ template slides in the slide navigator when I click "add slide"? This is what I want - so I can choose between the 200+ of them when creating a new presentation based on the template. So how can I do this?
Do I have to save all the 200+ slides as master slides, and if so how do I do this?
Or are there another solution?
I have been googling for hours now, and all I can seem to find are that I have to add the downloaded file to /library/application support/Keynote/templates , but there are no /keynote/templates to be found in my library.

A: The specific location where the files are stored is:
~/Library/Containers/com.apple.iWork.Keynote/Data/Library/Application Support/User Templates
OR
You can just use the Save Theme > Add Theme to Chooser option to achieve the same result.

However, you will need to add the missing slides to your set of Master Slides manually.
Adding New Master Slides
To do that:

*

*Go to a unique slide that came with the theme and copy the unique elements

*Under View, Select Edit Master Slides

*Make sure you can view the Navigator on the left

*Right-click (two-finger click) over the Navigator and make a new Master Slide

*On the new Master Slide - clear out any default elements if it's not blank

*Paste the unique elements from the slide copied into step #1

*Rename the new master slide to something memorable about the content

*Exit the master slide editor (Done button)
(Repeat for as many slides that you want to use with the template)

When finished you should be able to save and use the updated Keynote template normally.
Keynote used: version 8.0.1 (5579)

Missing fonts - Lots of 3rd party templates come without the fonts.
  You'll need to install these or choose substitutes and then reboot to
  have Keynote recognize all the fonts.


text:
Q: Unable to bind handler in React I am trying to bind a method of a parent component to the state of its child component but I'm unable to get the desired result. I checked the value of 'this' in App component and it still points to the App component. Should it not be pointing to the ItemsList component since its being binded to it using bind()? Can someone please point out the mistake I'm making.
import React from 'react';
import {render} from 'react-dom';

class Item extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return
 {this.props.value}
;
  }
}

class ItemList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      itemArray: ['Work', 'Learn React']
    }
    this.props.adder.bind(this);
    console.log(this.props.adder)
  }

  render() {
    const items = this.state.itemArray.map(el=><Item key={el} value={el} />);
    return (

 To Do List

{items}

    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  addElement (data) {
    let items = this.state.ItemList;
    items.push(<Item value={data} />);

  }

  render() {
    return (

        <input type="text" ref={input=>this.input=input} />
        <input type="button" value="Add" onClick={()=>this.addElement(this.input.value)}/>
        <ItemList adder={this.addElement} />

    );
  }
}

render(<App />, document.getElementById('root'));

A: Though what you want is technically possible, this is a much more explicit easy to understand way to do it.
I re-factored your code so that the data flow only goes in one direction, from App to `Itemimport React from "react";
import { render } from "react-dom";
I also changed Item and ItemList to stateless components that take value and items as props respectively.
The main change is that App holds the state instead of ItemList
const Item = ({ value }) =>
{value}
;

const ItemList = ({ items }) => (

To Do List

    {items.map(item => <Item key={item} value={item} />)}

);

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ["Work", "Learn React"]
    };
  }
  addElement(value) {
    this.setState(state => ({
      items: [...state.items, value]
    }));
  }
  render() {
    return (

        <input type="text" ref={input => (this.input = input)} />
        <input
          type="button"
          value="Add"
          onClick={() => this.addElement(this.input.value)}
        />
        <ItemList items={this.state.items} />

    );
  }
}

render(<App />, document.querySelector("#root"));

Here is a CodeSandbox with your working app: https://codesandbox.io/s/4r4v0w5o94

A:
Should it not be pointing to the ItemsList component since its being binded to it using bind()?

Well,the step you following in not right one.
In App Component
You need to store the ItemList (child) component reference in  App(parent) component.
<ItemList adder={this.addElement} bindChild =  {(ref)=>this.itemList = ref}/>

In ItemList component,
you need to call bindChild method when ItemList component mounted.
componentDidMount(){
  this.props.bindChild(this);
}

Now, in your App (parent) component, you have reference for ItemList (child) component in this.itemList property.
In App component, you can use this.itemList to update state of ItemList (child) component.
addElement(data) {
    let items = this.itemList.state.itemArray;
    console.log(items);
    const newItem = <Item value={data} />

    this.itemList.setState({ itemArray : [...items, newItem]})
  }

Please check complete example on codesandbox

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make long table fit using column environment in beamer I have a long table that I would like to split in two columns in latex beamer. To this purpose I have used the columns environment, which works fine. The problem is that \resizebox (which I would normally use in beamer to make tables fit to the margins of a frame) does not seem to be working.
I was therefore wondering whether there is a command that I can use to make the length of my split table fit into the two columns of one frame. Here is my code:
\RequirePackage{etex}
\documentclass[10pt]{beamer}

\usetheme{Boadilla}
\usepackage{bm}
\usepackage{graphicx}

\usepackage{xcolor}

\usepackage{color, colortbl}
\definecolor{LRed}{rgb}{1,.8,.8}
\definecolor{MRed}{rgb}{1,.6,.6}
\definecolor{HRed}{rgb}{1,.2,.2}

\usepackage[english]{babel}
\usepackage{csquotes}

\usepackage{multirow}
\usepackage{multicol}
\usepackage{array}
\usepackage{fixltx2e}
\usepackage{wasysym}

\setbeamertemplate{caption}{\insertcaption}
\renewcommand\mathfamilydefault{\rmdefault}
\definecolor{red1}{rgb}{1,0,0}
\definecolor{red2}{rgb}{0.93,0,0}
\definecolor{red3}{rgb}{0.8,0,0}
\definecolor{red4}{rgb}{0.54,0,0}

\usepackage{epstopdf}

\mode<presentation>
{
\usetheme[compress]{Berlin}
    \usecolortheme[named=red1]{structure}
}

\begin{document}
\begin{frame}
\begin{columns}[T] % align columns
    \begin{column}{.50\textwidth}
    \vspace{-0.5cm}
        \begin{table} [H]
        \footnotesize
            \begin{center}
            \scriptsize
            \resizebox{\textwidth}{!}{
                \begin{tabular}{l c c}
                \multirow{2}{*}{\textbf{Levels}}& \multicolumn{2}{c}{\textbf{(5)}}\\
                & \textbf{Mean} & \textbf{s.d.} \\
                \hline
                \multirow{2}{*}{AIRQ\_better}&.554***&.171***\\
                &(.021)&(.060)\\
                \multirow{2}{*}{AIRQ\_worse}&-.706***&.349***\\
                &(.025)&(.036)\\
                \multirow{2}{*}{TEMP\_warm}& .090***&.196***\\
                &(.012)&(.029)\\
                \multirow{2}{*}{COST\_low}&.365***&\\
                &(.020)&\\
                \multirow{2}{*}{COST\_high}& -.403***&\\
                &(.021)&\\
                \multirow{2}{*}{CONTR\_high}&.242***&.211***\\
                &(.019)&(.049)\\
                \multirow{2}{*}{CONTR\_low}&-.216***&.210***\\
                &(.019)&(.049)\\
                \multirow{2}{*}{NOISE\_in/out}&.191***&.033\\
                &(.023)&(.114)\\
                \multirow{2}{*}{NOISE\_out}&.046**&.007\\
                &(.023)&(.131)\\
                \multirow{2}{*}{NOISE\_none}&-.296***&.253***\\
                &(.025)&(.062)\\
                \multirow{2}{*}{AESTH\_in/out}&.215***&.174*\\
                &(.027)&(.104)\\
                \multirow{2}{*}{AESTH\_in}&.129***&.159\\
                &(.027)&(.110)\\
                \end{tabular}
                }
            \end{center}
        \end{table}
    \end{column}

    \begin{column}{.50\textwidth}
    \vspace{-0.5cm}
        \begin{table} [H]
        \footnotesize
            \begin{center}
            \scriptsize
            \resizebox{\textwidth}{!}{
                \begin{tabular}{l c c}
                \multirow{2}{*}{AESTH\_out}&.006&.159\\
                &(.027)&(.101)\\
                \multirow{2}{*}{AESTH\_out+in-}&-.237***&.072\\
                &(.028)&(.213)\\
                \multirow{2}{*}{SAV\_20}&-.457***&.225***\\
                &(.021)&(.050)\\
                \multirow{2}{*}{SAV\_80}&.479***&.304***\\
                &(.021)&(.037)\\
                \multirow{2}{*}{NONE}&-.769***&3.308***\\
                &(.074)&(.088)\\
                \multirow{2}{*}{TEMPwarm*SAV20}&-.052**&.001\\
                &(.022)&(.088)\\
                \multirow{2}{*}{Fem*AIRQbetter}&.042**&\\
                &(.018)&\\
                \multirow{2}{*}{Fem*AIRQworse}&-.065***&\\
                &(.020)&\\
                \multirow{2}{*}{Fem*CONTRhigh}&.047***&\\
                &(.018)&\\
                \multirow{2}{*}{Fem*CONTRlow}&-.057***&\\
                &(.019)&\\
                \multirow{2}{*}{Fem*NOISEin/out}&.054***&\\
                &(.021)&\\
                \multirow{2}{*}{Fem*NOISEnone}&-.089***&\\
                &(.023)&\\
                \multirow{2}{*}{Fem*AESTHin}&.045**&\\
                &(.022)&\\
                \end{tabular}
                }
            \end{center}
        \end{table}
    \end{column}%
\end{columns}
\end{frame}
\end{document}

A: As first iteration ... see, if the following solution is closte to what you looking for. Table is not complete yet:

\documentclass{beamer}
\usetheme{Boadilla}
\setbeamertemplate{caption}{\insertcaption}
\renewcommand\mathfamilydefault{\rmdefault}

\mode<presentation>
{
\usetheme[compress]{Berlin}
%\usecolortheme[named=red1]{structure}
}

%\usepackage{bm}
%\usepackage{graphicx}

\usepackage[english]{babel}
\usepackage{csquotes}

%\usepackage{multicol}
\usepackage{booktabs, makecell, multirow, tabularx}
\renewcommand\theadfont{\bfseries}
%\usepackage{fixltx2e}
%\usepackage{wasysym}

%\definecolor{LRed}{rgb}{1,.8,.8}
%\definecolor{MRed}{rgb}{1,.6,.6}
%\definecolor{HRed}{rgb}{1,.2,.2}

%\definecolor{red1}{rgb}{1,0,0}
%\definecolor{red2}{rgb}{0.93,0,0}
%\definecolor{red3}{rgb}{0.8,0,0}
%\definecolor{red4}{rgb}{0.54,0,0}

%\usepackage{epstopdf}

\begin{document}
\begin{frame}
    \vspace{-0.5cm}
\begin{table}
    \small
    \centering
\begin{tabularx}{\textwidth}{X c c
                        @{\hspace{2em}}
                             X c c}
    &    \multicolumn{2}{c}{\textbf{(5)}}
        &    &  \multicolumn{2}{c}{\textbf{(5)}}                \\
    \cmidrule(lr){2-3}  \cmidrule(lr){5-6}
\thead{Levels}
    &   \thead{Mean} & \thead{s.d.}
        &   \thead{Levels}
            &   \thead{Mean} & \thead{s.d.} \\
    \cmidrule(r) {1-3}  \cmidrule(l){4-6}
\multirow{2}{*}{AIRQ\_better}           &   .554*** &   .171***
    &   \multirow{2}{*}{AESTH\_out}     &   .006    &   .159    \\
    &   (.021)  &   (.060)  &           &   (.027)  &   (.101)  \\
\multirow{2}{*}{AIRQ\_worse}            &  -.706*** &   .349***
    &   \multirow{2}{*}{AESTH\_out+in-} &  -.237*** &   .072    \\
    &   (.025)  &   (.036)  &           &   (.028)  &   (.213)  \\
\multirow{2}{*}{TEMP\_warm}             &   .090*** &   .196***
    &   \multirow{2}{*}{SAV\_20}        &  -.457*** &   .225*** \\
    &   (.012)  &   (.029)  &           &   (.021)  &   (.050)  \\
\multirow{2}{*}{COST\_low}              &   .365*** &
    &   \multirow{2}{*}{SAV\_80}        &   .479*** &   .304*** \\
    &   (.020)  &           &           &   (.021)  &   (.037)  \\
\multirow{2}{*}{COST\_high}             &  -.403*** &
    &   \multirow{2}{*}{NONE}           &  -.769*** &  3.308*** \\
    &   (.021)  &           &           &   (.074)  &   (.088)  \\
    \cmidrule[1pt](r) {1-3}  \cmidrule[1pt](l){4-6}
    \end{tabularx}
\end{table}
\end{frame}
\end{document}


text:
Q: How would we evaluate the definite integral $ \int_0^{e^{\frac{1}{e}}}\frac {-W(-\ln(x))}{\ln(x)}dx $ How would we evaluate the definite integral:
$$ \int_0^{e^{\frac{1}{e}}}\frac {-W(-\ln(x))}{\ln(x)}dx $$
Here $W$ is the Lambert W function. More information about this function can be found here.
Edit 1: Found a mistake in the limits so corrected it.
Edit 2: Here are some alternate forms that I derived that might help:
$$ \int_{-1/e}^{\infty} e^{(-u-W(u))}du $$
$$ -\int_{-1/e}^{\infty} \frac{W(x)}{Inv(W(x))}du $$
$$ \int_{-1/e}^{\infty} \frac { \sum_{n=0}^{ \infty } \frac {(-1)^{n-1}n^{n-1}x^{n}} {n!}} {x\sum_{n=0}^{ \infty }\frac{x^n}{n!} } dx$$
Edit 3: After a bit of more investigation, I have managed to further simplify the integral:
$$ \int_0^{e^{\frac{1}{e}}}\frac {-W(-\ln(x))}{\ln(x)}dx = -\int_{-1/e}^{\infty} \frac{W(u)}{u(e^u)}du = -\int_{-1/e}^{\infty} \sum_{n=0}^{\infty} \frac {(-1)^nT(n)u^n }{n!}du = \sum_{n=0}^{\infty}\left[ \frac {(-1)^nT(n)u^{(n+1)} }{n!(n+1)} \right]_{-1/e}^{\infty} $$
where
T(n)
counts the number of forests of rooted labeled trees using labels in a subset of
{1,⋯,n}
, which is also the hyperbinomial transform of the constant sequence of
1's. (See A088957.)
Now the problem is that I don't know how to evaluate this summation due to T(n), and even wolfram alpha cant do it. Any help on evaluating this summation?

A: Not an answer but approximation.
If we consider the function $$f(x)=-\frac {W(-\ln(x))}{\ln(x)}$$ we can notice that $xf(x)$ looks like a power law.
Then, I thought that we could get some reasonable approximations writing
$$xf(x)=\sum_{n=1}^p a_n x^{bn}$$ Using $p=4$, the results from a quick and dirty regression leads to
$$\begin{array}{clclclclc}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{Confidence Interval} \\
 a_1 & +0.49967 & 0.00119 & \{+0.49731,+0.50203\} \\
 a_2 & +0.58096 & 0.00575 & \{+0.56954,+0.59239\} \\
 a_3 & +1.27106 & 0.04029 & \{+1.19105,+1.35106\} \\
 a_4 & -0.72606 & 0.02198 & \{-0.76971,-0.68242\} \\
 b   & +1.13077 & 0.00065 & \{+1.12948,+1.13206\}
\end{array}$$
 and computing
$$I(t)=-\int_0^t \frac {W(-\ln(x))}{\ln(x)}\,dx$$ we should have the following results (not fantastic, I agree !)
$$\left(
\begin{array}{ccc}
 t & \text{approximation} & \text{exact} \\
 0.05 & 0.015218 & 0.015313 \\
 0.10 & 0.034027 & 0.034118 \\
 0.15 & 0.054945 & 0.055038 \\
 0.20 & 0.077617 & 0.077711 \\
 0.25 & 0.101866 & 0.101959 \\
 0.30 & 0.127595 & 0.127687 \\
 0.35 & 0.154749 & 0.154842
\end{array}
\right)$$
For sure, this could be made better at the price of more parameters using for example
$$xf(x)=\sum_{n=1}^p a_n x^{b_n}$$

A: Not an answer
Change variables $y=-W(-\log x)$ to convert it to the integral
$$
\int_{-\infty}^{1}(1-y)\exp(ye^{-y})\;dy
$$
But that is still not elementary of course.


text:
Q: How do I send a POST request with PHP? Actually I want to read the contents that come after the search query, when it is done. The problem is that the URL only accepts POST methods, and it does not take any action with GET method...
I have to read all contents with the help of domdocument or file_get_contents(). Is there any method that will let me send parameters with POST method and then read the contents via PHP?

A: I use the following function to post data using curl. $data is an array of fields to post (will be correctly encoded using http_build_query()).
function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

@Edward mentions that http_build_query() may be omitted since curl will correctly encode array passed to CURLOPT_POSTFIELDS parameter, which is correct, but be advised that in this case the data will be encoded using multipart/form-data and it may not be desirable as some endpoints expect data to be encoded using application/x-www-form-urlencoded. When using http_build_query() as in the function above, data will be encoded with application/x-www-form-urlencoded.

A: Based on the main answer, here is what I use:
function do_post($url, $params) {
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => $params
        )
    );
    $result = file_get_contents($url, false, stream_context_create($options));
}

Example usage:
do_post('https://www.google-analytics.com/collect', 'v=1&t=pageview&tid=UA-xxxxxxx-xx&cid=abcdef...');

A: I recommend you to use the open-source package guzzle that is fully unit tested and uses the latest coding practices.
Installing Guzzle
Go to the command line in your project folder and type in the following command (assuming you already have the package manager composer installed). If you need help how to install Composer, you should have a look here.
php composer.phar require guzzlehttp/guzzle

Using Guzzle to send a POST request
The usage of Guzzle is very straight forward as it uses a light-weight object-oriented API:
// Initialize Guzzle client
$client = new GuzzleHttp\Client();

// Create a POST request
$response = $client->request(
    'POST',
    'http://example.org/',
    [
        'form_params' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ]
);

// Parse the response object, e.g. read the headers, body, etc.
$headers = $response->getHeaders();
$body = $response->getBody();

// Output headers and body for debugging purposes
var_dump($headers, $body);

A: I was looking for a similar problem and found a better approach of doing this. So here it goes.
You can simply put the following line on the redirection page (say page1.php).
header("Location: URL", TRUE, 307); // Replace URL with to be redirected URL, e.g. final.php

I need this to redirect POST requests for REST API calls. This solution is able to redirect with post data as well as custom header values.
Here is the reference link.

A: I'd like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.
Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:
class HTTPRequester {
    /**
     * @description Make HTTP-GET call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPGet($url, array $params) {
        $query = http_build_query($params);
        $ch    = curl_init($url.'?'.$query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-POST call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPost($url, array $params) {
        $query = http_build_query($params);
        $ch    = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-PUT call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPut($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
    /**
     * @category Make HTTP-DELETE call
     * @param    $url
     * @param    array $params
     * @return   HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPDelete($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
}

Improvements

*

*Using http_build_query to get the query-string out of an request-array.(you could also use the array itself, therefore see: http://php.net/manual/en/function.curl-setopt.php)

*Returning the response instead of echoing it. Btw you can avoid the returning by removing the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);. After that the return value is a boolean(true = request was successful otherwise an error occured) and the response is echoed.
See: http://php.net/en/manual/function.curl-exec.php

*Clean session closing and deletion of the curl-handler by using curl_close. See: http://php.net/manual/en/function.curl-close.php

*Using boolean values for the curl_setopt function instead of using any number.(I know that any number not equal zero is also considered as true, but the usage of true generates a more readable code, but that's just my opinion)

*Ability to make HTTP-PUT/DELETE calls(useful for RESTful service testing)

Example of usage
GET
$response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));

POST
$response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));

PUT
$response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));

DELETE
$response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));

Testing
You can also make some cool service tests by using this simple class.
class HTTPRequesterCase extends TestCase {
    /**
     * @description test static method HTTPGet
     */
    public function testHTTPGet() {
        $requestArr = array("getLicenses" => 1);
        $url        = "http://localhost/project/req/licenseService.php";
        $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
    }
    /**
     * @description test static method HTTPPost
     */
    public function testHTTPPost() {
        $requestArr = array("addPerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPPut
     */
    public function testHTTPPut() {
        $requestArr = array("updatePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPDelete
     */
    public function testHTTPDelete() {
        $requestArr = array("deletePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
    }
}

A: [Edit]: Please ignore, not available in php now.
There is one more which you can use
<?php
$fields = array(
    'name' => 'mike',
    'pass' => 'se_ret'
);
$files = array(
    array(
        'name' => 'uimg',
        'type' => 'image/jpeg',
        'file' => './profile.jpg',
    )
);

$response = http_post_fields("http://www.example.com/", $fields, $files);
?>

Click here for details

A: Here ok with this code:
<?php
$postdata = http_build_query(
    array(
        'name' => 'Robert',
        'id' => '1'
    )
);
$opts = array('http' =>
    array(
        'method' => 'POST',
        'header' => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);
$context = stream_context_create($opts);
$result = file_get_contents('http://localhost:8000/api/test', false, $context);
echo $result;?>

A: There's another CURL method if you are going that way.
This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.
$url = 'http://api.example.com/services/xmlrpc/';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);
//process $response

First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

A: If you by any chance are using Wordpress to develop your app (it's actually a convenient way to get authorization, info pages etc even for very simple stuff), you can use the following snippet:
$response = wp_remote_post( $url, array('body' => $parameters));

if ( is_wp_error( $response ) ) {
    // $response->get_error_message()
} else {
    // $response['body']
}

It uses different ways of making the actual HTTP request, depending on what is available on the web server. For more details, see the HTTP API documentation.
If you don't want to develop a custom theme or plugin to start the Wordpress engine, you can just do the following in an isolated PHP file in the wordpress root:
require_once( dirname(__FILE__) . '/wp-load.php' );

// ... your code

It won't show any theme or output any HTML, just hack away with the Wordpress APIs!

A: Another alternative of the curl-less method above is to use the native stream functions:

*

*stream_context_create():

Creates and returns a stream context with any options supplied in options preset.

*stream_get_contents():

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

A POST function with these can simply be like this:
<?php

function post_request($url, array $params) {
  $query_content = http_build_query($params);
  $fp = fopen($url, 'r', FALSE, // do not use_include_path
    stream_context_create([
    'http' => [
      'header'  => [ // header array does not need '\r\n'
        'Content-type: application/x-www-form-urlencoded',
        'Content-Length: ' . strlen($query_content)
      ],
      'method'  => 'POST',
      'content' => $query_content
    ]
  ]));
  if ($fp === FALSE) {
    return json_encode(['error' => 'Failed to get contents...']);
  }
  $result = stream_get_contents($fp); // no maxlength/offset
  fclose($fp);
  return $result;
}

A: Try PEAR's HTTP_Request2 package to easily send POST requests. Alternatively, you can use PHP's curl functions or use a PHP stream context.
HTTP_Request2 also makes it possible to mock out the server, so you can unit-test your code easily

A: I make a function to request a post using JSON:
const FORMAT_CONTENT_LENGTH = 'Content-Length: %d';
const FORMAT_CONTENT_TYPE = 'Content-Type: %s';

const CONTENT_TYPE_JSON = 'application/json';
/**
 * @description Make a HTTP-POST JSON call
 * @param string $url
 * @param array $params
 * @return bool|string HTTP-Response body or an empty string if the request fails or is empty
 */
function HTTPJSONPost(string $url, array $params)
{
    $content = json_encode($params);
    $response = file_get_contents($url, false, // do not use_include_path
        stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => [ // header array does not need '\r\n'
                    sprintf(FORMAT_CONTENT_TYPE, CONTENT_TYPE_JSON),
                    sprintf(FORMAT_CONTENT_LENGTH, strlen($content)),
                ],
                'content' => $content
            ]
        ])); // no maxlength/offset
    if ($response === false) {
        return json_encode(['error' => 'Failed to get contents...']);
    }

    return $response;
}

A: Here is using just one command without cURL. Super simple.
echo file_get_contents('https://www.server.com', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded",
        'content' => http_build_query([
            'key1' => 'Hello world!', 'key2' => 'second value'
        ])
    ]
]));

A: You could use cURL:
<?php
//The url you wish to send the POST request to
$url = $file_name;

//The data you want to send via POST
$fields = [
    '__VIEWSTATE '      => $state,
    '__EVENTVALIDATION' => $valid,
    'btnSubmit'         => 'Submit'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
echo $result;
?>

A: CURL-less method with PHP5:
$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

See the PHP manual for more information on the method and how to add headers, for example:

*

*stream_context_create: http://php.net/manual/en/function.stream-context-create.php

A: The better way of sending GET or POST requests with PHP is as below:
<?php
    $r = new HttpRequest('http://example.com/form.php', HttpRequest::METH_POST);
    $r->setOptions(array('cookies' => array('lang' => 'de')));
    $r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));

    try {
        echo $r->send()->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
?>

The code is taken from official documentation here http://docs.php.net/manual/da/httprequest.send.php

A: I prefer this one:
function curlPost($url, $data = NULL, $headers = []) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); //timeout in seconds
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_ENCODING, 'identity');

    if (!empty($data)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $response = curl_exec($ch);
    if (curl_error($ch)) {
        trigger_error('Curl Error:' . curl_error($ch));
    }

    curl_close($ch);
    return $response;
}

Usage example:
$response=curlPost("http://my.url.com", ["myField1"=>"myValue1"], ["myFitstHeaderName"=>"myFirstHeaderValue"]);

A: The top answers didn't work for me. This was the first solution that ran perfectly:
$sPD = "name=Jacob&bench=150"; // The POST Data
$aHTTP = array(
  'http' => // The wrapper to be used
    array(
    'method'  => 'POST', // Request Method
    // Request Headers Below
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $sPD
  )
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;


text:
Q: How to make simple dynamic drop list in Laravel? I'm new at Laravel and not good with syntax. I have seen many tutorials and have read many answers, but still, my mind didn't get the point of how can I have a dropdown field for a foreign key.
I'm having one table "Section" and other "Class." I want to show the name of classes in section page.
Sections Migration
Schema::create('sections', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->integer('class_id')->unsigned();
    $table->foreign('class_id')->references('id')->on('classses');
});

Classses Migration
Schema::create('classses', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title');
    $table->timestamps();
});

Honestly, I don't know if I should have changed my controller or not.
Blade/View

    Name
    <input type="text" class="form-control" name="name" id="title">

    Class
    ???????????????

Index Function
public function index()
    {        $sections = Section::all();
            return view('sections.index', compact('sections'));

        $classs = Classs::all()->pluck(['id', 'title']);
        return view('sections.index')->with('classs', $classs); }

Error is Unreachable Statement at line $class & Expected string, got array at ([id,'title])

A: In your controller, you have a function to return the view.
Change it to include ->with(), so you can access the classes in the view:
// if the controller is not for the classes, add this up top:
use App\Classs; // include model name

$classs = Classs:all();

return view('yourView')->with('classe', $classs);

Then, in your view, you can just do this:

  Class

  <select class="" name="cid">
    <option value="null">Class</option>
    @foreach($classs as $class)
      <option value="{{$class->id}}">{{$class->title}}</option>
    @endforeach
  </select>

It loops over all the classes in your database and creates a <option> element for them. Looking at your first migration, you're using the id in the other table, so you need to set that as the value.

Change your index function to this:
public function index()
{
    $sections = Section::all();
    $classs = Class::all();

    return view('sections.index')->with('sections', $sections)->with('classs', $classs);
}

Can you tell me where can I write conditions such as select * from class where role_id=2 etc.

Basically, in an MVC framework, you do all your queries in your controller and pass the data to the view, in which you display the data.
Laravel has a DB class which you can use for basic queries:
select * from class where role_id = 2

Would become this in Laravel, using the DB class.
DB::table('class')->where('role_id', 2)->get();

// or if it's a model:
Model::where('role_id', 2)->get();

A: I have now used this code in blade page
              @php
                use Illuminate\Support\Facades\DB;
                $cid=DB::table('classses')->get();
                $uid=DB::table('users')->where('role_id','3')->get();
                $counter=0;
                @endphp

                <select class="" name="class_id">
                    <option value="null">Class</option>
                    @foreach($cid as $class)
                        @if($counter==0)
                        <option selected="selected" value="{{$class->id}}">{{$class->title}}</option>
                        {{$counter++}}
                    @else

                        <option value="{{$class->id}}">{{$class->title}}</option>
                    @endif
                            @endforeach
                </select>


text:
Q: moving a row of a pandas dataframe but index unchanged import numpy as np
import pandas as pd

d = np.random.rand(10,3)
df = pd.DataFrame(d)
df

          0         1         2
0  0.740335  0.957937  0.611504
1  0.164772  0.469355  0.310799
2  0.666506  0.030054  0.986393
3  0.191827  0.554556  0.707453
4  0.278617  0.532423  0.095124
5  0.659526  0.413681  0.588372
6  0.285892  0.466231  0.268647
7  0.559664  0.274913  0.618610
8  0.572839  0.490969  0.194019
9  0.028767  0.332626  0.290148

# move the third row to top
df.iloc[:3] = df.iloc[[2,0,1]]
df
          0         1         2
0  0.666506  0.030054  0.986393
1  0.740335  0.957937  0.611504
2  0.164772  0.469355  0.310799
3  0.191827  0.554556  0.707453
4  0.278617  0.532423  0.095124
5  0.659526  0.413681  0.588372
6  0.285892  0.466231  0.268647
7  0.559664  0.274913  0.618610
8  0.572839  0.490969  0.194019
9  0.028767  0.332626  0.290148

The index is unchanged.
I tried
df.index[:3] = df.index[[2,0,1]] (raise error) or df.index.values[:3] = df.index.values[[2,0,1]], there is no error raised but the index is still unchanged.

A: If you want the index to also reflect the updated row, you need to use df.reindex
In [25]: np.random.seed(5)
    ...: d = np.random.rand(5, 3)
    ...: df = pd.DataFrame(d)
    ...: df
Out[25]:
          0         1         2
0  0.221993  0.870732  0.206719
1  0.918611  0.488411  0.611744
2  0.765908  0.518418  0.296801
3  0.187721  0.080741  0.738440
4  0.441309  0.158310  0.879937

In [26]: df.reindex([2,0,1,*df.index[3:]])
Out[26]:
          0         1         2
2  0.765908  0.518418  0.296801
0  0.221993  0.870732  0.206719
1  0.918611  0.488411  0.611744
3  0.187721  0.080741  0.738440
4  0.441309  0.158310  0.879937

A: iloc will try to align the index.
For this reason, when the values are assigned back they will go right back to their initial location. Index 0 will align to index 0, index 1 will align to index 1, etc...
df.iloc[[2, 0, 1]]

          0         1         2
2  0.765908  0.518418  0.296801
0  0.221993  0.870732  0.206719
1  0.918611  0.488411  0.611744

(Note the index values)

To preserve the index values join the two DataFrame pieces together append or concat:
import numpy as np
import pandas as pd

np.random.seed(5)
d = np.random.rand(5, 3)
df = pd.DataFrame(d)

df = df.iloc[[2, 0, 1]].append(df.iloc[3:])

OR
df = pd.concat((df.iloc[[2, 0, 1]], df.iloc[3:]))

df Before:
          0         1         2
0  0.221993  0.870732  0.206719
1  0.918611  0.488411  0.611744
2  0.765908  0.518418  0.296801
3  0.187721  0.080741  0.738440
4  0.441309  0.158310  0.879937

df after:
          0         1         2
2  0.765908  0.518418  0.296801
0  0.221993  0.870732  0.206719
1  0.918611  0.488411  0.611744
3  0.187721  0.080741  0.738440
4  0.441309  0.158310  0.879937

(To match shown expected output)
To move without the indexes use values or to_numpy to prevent the aligning behaviour:
import numpy as np
import pandas as pd

np.random.seed(5)
d = np.random.rand(5, 3)
df = pd.DataFrame(d)

df.iloc[:3] = df.iloc[[2, 0, 1]].values

print(df)

df After:
          0         1         2
0  0.765908  0.518418  0.296801
1  0.221993  0.870732  0.206719
2  0.918611  0.488411  0.611744
3  0.187721  0.080741  0.738440
4  0.441309  0.158310  0.879937

A: How about this?
np.random.seed(42)
df = pd.DataFrame(np.random.rand(10,3))

df = df.iloc[[2,0,1]].append(df.iloc[3:])


text:
Q: Failing at getting Laravel Running on Windows I'm trying to get a laravel programming enviroment up to finish my masters' degree project but I can't get this to work no matter how hard I try.
I've followed various tutorials but the last one I've tried has been http://sherriflemings.blogspot.com.es/2015/03/laravel-homestead-on-windows-8.html
and I think I got somewhere but I get the following error trying to initialize vagrant
Vagrant up error:

and I've confirmed that the file C:\Users\Administrator\homestead\Homestead\scripts\homestead.rb is available and permissions are correct.
Also In the error I see C:/Users/Administrator/.ssh/id_rsa (Errno::ENOENT)
but I have other routes difined in my Homestead.yaml
Is there any other way I can run homstead of have a Laravel development enviromet?
What tutorial would you recommend to get this up and running?

A: You should generate key to make it work. So, you will have two files
id_rsa and id_rsa.pub in your C:/Users/Administrator/.ssh/ folder.

A: As I totally agree with the previous answer, I wanted to provide some more information about your state.
There is no need to check if the homestead.rb exists at that stage. Because it is already the running code and informing you about the problem that it can't fix by herself.
That is also not a route problem (to tell the truth; the provided information under 'sites' key of Homestead.yaml is not about routes. You are listing the projects inside your homestead virtual machine there. One site per project is generally enough. Like:
-sites:
    - map: foo.com
    - to: /home/vagrant/Code/Foo/public

Your homestead.rb file is blocked while running because the created virtual machine's operating system needs something to trust your code working using ssh. And one of the ways of achieving that is using a public key - private key pair (also used by homestead). It looks like you don't have a pair. And the script running can't access the public key: AKA id_rsa.


text:
Q: Multi-Tenancy whit JWT autentication and validation of user for tenant I have a project running with JWT authentication, it works, but now I need to implement Multi-Tenancy using the following approach:

Requirements:

*

*A user can have access to one or more tenants

*Access permissions are defined by user and tenant

*Getting subdomain through @RequestAttribute in requests

*Generate the token containing the tenant ID (subdomain).

*Validate the tenant on all requests

Implemented:

*

*Created JWT Autentication.

*Created TenantInterceptor.

*Getting subdomain using @RequestAttribute on requests.

*Created existsByUsernameAndSubdomain validation.

I'm having trouble implementing this new feature, can you point me to an implementation example or tutorial that can help me?
I thank you for your help!
Below are my classes or if you prefer clone on GitHub!
My classes
Models:

/** ERole **/
    public enum ERole {
    ROLE_USER,
    ROLE_MODERATOR,
    ROLE_ADMIN
}

/** Role **/
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "roles")
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Enumerated(EnumType.STRING)
    @Column(length = 20)
    private ERole name;
}

/** Tenant **/
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "tenants",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "subdomain", name = "un_subdomain")
        })
public class Tenant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Size(max = 20)
    private String subdomain;

    @NotBlank
    private String name;

}

/** User **/
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "users",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "username", name = "un_username")
        })
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Size(max = 20)
    private String username;

    @NotBlank
    @Size(max = 120)
    @JsonIgnore
    private String password;

//    Remove
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "users_roles",
            joinColumns = {@JoinColumn(name = "user_id",
                    foreignKey = @ForeignKey(name = "fk_users_roles_users1"))},
            inverseJoinColumns = {@JoinColumn(name = "role_id",
                    foreignKey = @ForeignKey(name = "fk_users_roles_roles1"))})
    private Set<Role> roles = new HashSet<>();

//    Include
    @EqualsAndHashCode.Exclude
    @OneToMany(mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true,
            fetch = FetchType.LAZY)
    @JsonManagedReference
    private List<UserTenant> tenants = new ArrayList<>();

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

}

/** UserTenant **/
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "users_tenants",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "user_id", name = "un_user_id"),
                @UniqueConstraint(columnNames = "tenant_id", name = "un_tenant_id")
        })
public class UserTenant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id",
            nullable = false,
            foreignKey = @ForeignKey(
                    name = "fk_users_tenants_user1"))
    @JsonBackReference
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tenant_id",
            nullable = false,
            foreignKey = @ForeignKey(
                    name = "fk_users_tenants_tenant1"))
    @JsonBackReference
    private Tenant tenant;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "users_tenants_roles",
            joinColumns = {@JoinColumn(name = "user_tenant_id",
                    foreignKey = @ForeignKey(name = "fk_users_tenants_user_tenant1"))},
            inverseJoinColumns = {@JoinColumn(name = "role_id",
                    foreignKey = @ForeignKey(name = "fk_users_tenants_roles1"))})
    private Set<Role> roles = new HashSet<>();

}

Payloads:

/** LoginRequest **/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class LoginRequest {
    @NotBlank
    private String username;

    @NotBlank
    private String password;

}

/** SignupRequest **/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class SignupRequest {
    @NotBlank
    @Size(max = 20)
    private String username;

    @NotBlank
    @Size(max = 40)
    private String password;
    private Set<String> role;

}

/** JwtResponse **/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class JwtResponse {
    private Long id;
    private String username;
    private List<String> roles;
    private String tokenType = "Bearer";
    private String accessToken;

    public JwtResponse(String accessToken, Long id, String username,
                       List<String> roles) {
        this.id = id;
        this.username = username;
        this.roles = roles;
        this.accessToken = accessToken;
    }

}

/** MessageResponse **/
@Data
@Builder
@NoArgsConstructor
public class MessageResponse {
    private String message;

    public MessageResponse(String message) {
        this.message = message;
    }
}

Repositories:

/** RoleRepository **/
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    Optional<Role> findByName(ERole name);
}

/** UserRepository **/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);

    Boolean existsByUsername(String username);

}

/** UserTenantRepository **/
@Repository
public interface UserTenantRepository extends JpaRepository<UserTenant, Long> {

    @Query("SELECT ut FROM UserTenant ut WHERE ut.user.username = :username AND ut.tenant.subdomain = :subdomain ")
    Optional<UserTenant> findByUserAndSubdomain(String username, String subdomain);

    @Query("SELECT " +
            "CASE WHEN COUNT(ut) > 0 THEN true ELSE false END " +
            "FROM UserTenant ut " +
            "WHERE ut.user.username = :username " +
            "AND ut.tenant.subdomain = :subdomain ")
    Boolean existsByUsernameAndSubdomain(String subdomain, String username);

}

Services:

/** AuthService **/
@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final PasswordEncoder encoder;
    private final RoleRepository roleRepository;

    public JwtResponse authenticateUser(String subdomain, LoginRequest loginRequest) {

        System.out.println(subdomain);

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
        System.out.println(authentication);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        return new JwtResponse(jwt,
                userDetails.getId(),
                userDetails.getUsername(),
                roles);
    }

    @Transactional
    public MessageResponse registerUser(SignupRequest signUpRequest) {

        // Create new user's account
        User user = new User(
                signUpRequest.getUsername(),
                encoder.encode(signUpRequest.getPassword()));

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);
                        break;
                    case "mod":
                        Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(modRole);
                        break;
                    default:
                        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                }
            });
        }
        user.setRoles(roles);
        userRepository.save(user);
        return new MessageResponse("User registered successfully!");
    }

}

/** UserDetailsImpl **/
public class UserDetailsImpl implements UserDetails {
    private static final long serialVersionUID = 1L;

    private final Long id;

    private final String username;

    @JsonIgnore
    private final String password;

    private final Collection<? extends GrantedAuthority> authorities;

    public UserDetailsImpl(Long id, String username, String password,
                           Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.authorities = authorities;
    }

    public static UserDetailsImpl build(User user) {
        List<GrantedAuthority> authorities = user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getName().name()))
                .collect(Collectors.toList());

        return new UserDetailsImpl(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                authorities);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    public Long getId() {
        return id;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        UserDetailsImpl user = (UserDetailsImpl) o;
        return Objects.equals(id, user.id);
    }
}

/** UserDetailsServiceImpl **/
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepository;
    private final UserTenantRepository userTenantRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));

        return UserDetailsImpl.build(user);
    }

}

Controller

/** AuthController **/
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final UserRepository userRepository;
    private final UserTenantRepository userTenantRepository;

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(
            @RequestAttribute String subdomain,
            @Valid @RequestBody LoginRequest loginRequest
    ) {
        if (!userTenantRepository.existsByUsernameAndSubdomain(subdomain, loginRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Unauthorized: This username and tenant is not authorized!"));
        }
        return ResponseEntity.ok(authService.authenticateUser(subdomain, loginRequest));
    }

    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username is already taken!"));
        }
        return ResponseEntity.ok(authService.registerUser(signUpRequest));
    }
}

JWT:

/** AuthEntryPointJwt **/
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        logger.error("Unauthorized error: {}", authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: incorrect username or password");
    }

}

/** AuthTokenFilter **/
public class AuthTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response
            , FilterChain filterChain)
            throws ServletException, IOException {
        try {
            String jwt = parseJwt(request);
            if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
                String username = jwtUtils.getUserNameFromJwtToken(jwt);

                String serverName = request.getServerName();
                String subdomain = serverName.substring(0, serverName.indexOf("."));

                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                System.out.println(userDetails);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        filterChain.doFilter(request, response);
    }

    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader("Authorization");

        if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
            return headerAuth.substring(7);
        }
        return null;
    }
}

/** JwtUtils **/
@Component
public class JwtUtils {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    @Value("${example.app.jwtSecret}")
    private String jwtSecret;

    @Value("${example.app.jwtExpirationMs}")
    private int jwtExpirationMs;

    public String generateJwtToken(Authentication authentication) {

        UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();

        return Jwts.builder()
                .setSubject((userPrincipal.getUsername()))
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
    }

    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.error("Invalid JWT signature: {}", e.getMessage());
        } catch (MalformedJwtException e) {
            logger.error("Invalid JWT token: {}", e.getMessage());
        } catch (ExpiredJwtException e) {
            logger.error("JWT token is expired: {}", e.getMessage());
        } catch (UnsupportedJwtException e) {
            logger.error("JWT token is unsupported: {}", e.getMessage());
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims string is empty: {}", e.getMessage());
        }

        return false;
    }
}

Utils:

/** TenantInterceptor **/
public class TenantInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String serverName = request.getServerName();
        String tenantId = serverName.substring(0, serverName.indexOf("."));

        request.setAttribute("subdomain", tenantId);

        return true;
    }
}

/** WebSecurityConfig **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig implements WebMvcConfigurer {

    final
    UserDetailsServiceImpl userDetailsService;

    private final AuthEntryPointJwt unauthorizedHandler;

    public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AuthEntryPointJwt unauthorizedHandler) {
        this.userDetailsService = userDetailsService;
        this.unauthorizedHandler = unauthorizedHandler;
    }

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers(
                        "/auth/**",
                        "/v3/api-docs/**",
                        "/swagger-ui/**",
                        "/swagger-ui.html",
                        "/configuration/**",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/api-docs/**").permitAll()
                .antMatchers("/api/**").authenticated()
                .anyRequest().authenticated();

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TenantInterceptor());
    }

}

A: I was able to solve the problem by modifying the loadUserByUsername method in the UserDetailsServiceImpl.
See the implementation details on GitHub!
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserTenantRepository userTenantRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // Getting subdomain from request attributes
        HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                        .getRequest();

        String serverName = request.getServerName();
        String subdomain = serverName.substring(0, serverName.indexOf("."));
        UserTenant userTenant = userTenantRepository.findByUserAndSubdomain(username, subdomain)
                .orElseThrow(() -> new UsernameNotFoundException(
                        "UserTenant Not Found with username: " + username + " and " + subdomain));

        // Getting Rules from the UserTenant
        List<GrantedAuthority> authorities = userTenant.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getName().name()))
                .collect(Collectors.toList());

        return new UserDetailsImpl(
                userTenant.getUser().getId(),
                userTenant.getUser().getUsername(),
                userTenant.getUser().getPassword(),
                authorities
        );
    }
}

Inserts in Database
INSERT INTO roles(id, name)
VALUES (1 ,'ROLE_USER'),
       (2, 'ROLE_MODERATOR'),
       (3, 'ROLE_ADMIN');

INSERT INTO tenants (id, name, subdomain)
VALUES (1, 'Tenant 1', 'tenant1'),
       (2, 'Tenant 2', 'tenant2');

# user, password
# user1, user1
# user2, user2
INSERT INTO users (id, username, password)
VALUES (1, 'user1', '$2a$10$wFMJLxdXKGRa8lJO6k2DAOnW9HstAPoHecXUNkDyYNeaNnZJAz.hy'),
       (2, 'user2', '$2a$10$Z9/wLkmf5IwfjJqIQU6X.OBFg3TCBUyk3bdfgkGjU0.HI5kVibZxG');

INSERT INTO users_tenants (id,  tenant_id, user_id)
VALUES (1, 1, 1),
       (2, 2, 2);

INSERT INTO users_tenants_roles (user_tenant_id,  role_id)
VALUES (1, 2),
       (1, 3),
       (2, 1);

INSERT INTO items (id,  tenant_id, name)
VALUES (1, 1, 'Product 1 in Tenant 1'),
       (2, 1, 'Product 2 in Tenant 1'),
       (3, 2, 'Product 1 in Tenant 2'),
       (4, 2, 'Product 2 in Tenant 2');

Validations in Postman
Created token variable in Postman:

Set token value in Postman variable:

Added Authorization variable in requests headers:

Validating if the domain exists in sign in:

Validating user access permission on tenant:

Authorized login:

Getting items of tenant1:

Trying to get tenant2 list of items without being logged in tenant2 and having access permissions:

Logging in with user2 in tenant2:

Getting items list tenant2

Trying to get tenant1 list of items without being logged in tenant1 and having access permissions:


text:
Q: css: border bottom pushing content out of center I have the a tags centered vertically using a flex box model.  When I apply the class active to an a tag, I want to have a border bottom on it but I want space between it and the content.  I added padding-bottom to it but it also then pushing the a tag content out of the center.  How can I accomplish this without moving the a tag content out of the center?

.tabs {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: flex-start;
  font-size: 18px;
}

.active {
  color: #111111 !important;
  border-bottom: 3px solid #111111;
  cursor: default;
  font-family: 'Avenir-Heavy'
}

  Shop
  Orders


text:
Q: ImageView issues in listview I am using a listview. The imageView2 i.e img2 is set to invisible initially and made visible after the checking the the value of a coloumn. If it it is "yes" the imageView2 is made invisible.I have checked my database still listview shows image even if the codition isn't satisfied. Where might be my mistake? I tried ViewHolder too...but dint work!
public class ArrayAdapter1 extends BaseAdapter
{

ImageView iv,im1,im2,img3,img4,img5;
int items=0;
int time;
int hr=00; int min=00;
int cmin;
ArrayList<String> apps;
ArrayList<Integer> timer;
private LayoutInflater inflater;
private List<ResolveInfo> mApps;
Context context;
DBHelper helper;
MainActivity ma;
public ArrayAdapter1(Context context, List<ResolveInfo> mApps)
{
    this.inflater = LayoutInflater.from(context);
    this.mApps = mApps;
    this.context=context;
    apps=new ArrayList<String>();
    timer=new ArrayList<Integer>();
    helper=new DBHelper(context);
    ma=new MainActivity();
}

public View getView(final int position, View convertView, ViewGroup parent)
{

    final TextView tv1;
    TextView tv2,tv3;
    ImageView img1,img2;
    final ImageButton ib;

    View view=convertView;
    if (view == null)
    {
        convertView = inflater.inflate(R.layout.row,parent, false);

        LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = vi.inflate(R.layout.row, null,false);
    }

    tv1= (TextView)convertView.findViewById(R.id.textView1);
    tv2= (TextView)convertView.findViewById(R.id.textView2);
    tv3= (TextView)convertView.findViewById(R.id.textView3);
    //tv2.setTextColor(Color.GREEN);
    img1= (ImageView)convertView.findViewById(R.id.imageView1);
    img2=  (ImageView)convertView.findViewById(R.id.imageView2);
    img3=  (ImageView)convertView.findViewById(R.id.imageView3);
    img4=  (ImageView)convertView.findViewById(R.id.imageView4);
    img5=  (ImageView)convertView.findViewById(R.id.imageView5);

    ResolveInfo info = this.mApps.get(position);
    String app=info.loadLabel(context.getPackageManager()).toString();
    tv1.setText(app);
    img1.setImageDrawable(info.activityInfo.loadIcon(context.getPackageManager()));
    //tv2.setText(helper.getState(app));
    tv3.setText(helper.getCurr_time(app));
    tv2.setText(helper.getLimit(app));

    if(helper.getNote(app)!=null)
    {
    String note=helper.getNote(app);
    if(note.equals("yes")){img2.setVisibility(View.VISIBLE);} else  {img2.setVisibility(View.INVISIBLE);}
    }

    String type = null;
    if(helper.getType(app)!=null)
    {
    type=helper.getType(app);
    if(type.equals("Day Lock")) {img4.setVisibility(View.VISIBLE);}   else  {img4.setVisibility(View.INVISIBLE);}
    if(type.equals("Child Lock")) {img3.setVisibility(View.VISIBLE);}   else  {img3.setVisibility(View.INVISIBLE);}
    }

    if(helper.getState(app)!=null)
    {
    String state=helper.getState(app);
    if(state.equals("BLOCKED")) {img5.setVisibility(View.VISIBLE); img4.setVisibility(View.INVISIBLE);  img3.setVisibility(View.INVISIBLE);}
    else  {img5.setVisibility(View.INVISIBLE);}
    }

    return convertView;

}
public final int getCount() {
    return mApps.size();
}

public final Object getItem(int position) {
    return mApps.get(position);
}

public final long getItemId(int position) {
    return position;
}
}

And this is the block in my MainAcitivity where I am setting the value to null to hide the image.
listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            TextView tv1=(TextView)arg1.findViewById(R.id.textView1);
            String name=tv1.getText().toString();

            // for notified app !
            ImageView img=(ImageView)arg1.findViewById(R.id.imageView2);
            img.setVisibility(View.INVISIBLE);

            if(helper.getNote(name)!=null)
            {  helper.setNote(name,"");  }  // for notified app !

            AlertDialog dialog= (AlertDialog) oncreateDialog(name);//,arg3);//<<pass selected index
            dialog.show();

            return true;
        }
    });


text:
Q: How to combine first element of cell array with all elements of another array and so on? I have two (n,1) cell arrays. Both of those contain 1x8 cell arrays inside each cell.
I need to:
1) Combine the first element of the first array with each element of the second array
2) Combine the second element of the first array with each element of the second array and so on.
And then store them inside a third cell array that will look like this :
{ {f_array1} {s_array1}; {f_array1} {s_array2}; {f_arrayN} {s_array2}; {f_arrayM} {s_arrayM};

I have tried some for loops like this one:
for l = 1:u(1,1)
    for m = 1:v(1,1)
        A{l} = {e{l},f{m}};
    end
end

But in only combines the one element with only one element.
Any sugestions?

A: I would use repmat on the cell arrays to expand them out and then simply concatenate them.
f_array = {{{1} {1} {1} {1} {1} {1} {1} {1}},...
    {{2} {2} {2} {2} {2} {2} {2} {2}},...
    {{3} {3} {3} {3} {3} {3} {3} {3}}};
s_array = {{{4} {4} {4} {4} {4} {4} {4} {4}},...
    {{5} {5} {5} {5} {5} {5} {5} {5}},...
    {{6} {6} {6} {6} {6} {6} {6} {6}}};

f_expanded = repmat(f_array(:), numel(s_array), 1);
s_expanded = repmat(s_array(:), 1, numel(f_array)).';

output = num2cell(cat(2, f_expanded(:), s_expanded(:)), 2);


text:
Q: Change File Upload Path How do I change the default path for the file upload in Strapi? I want to store the uploaded files to a network filer instead of the location where strapi is installed.

A: There are plugins that you can install in order to upload to 3th party cloud storage platform
These are the official ones:
strapi-provider-upload-aws-s3
strapi-provider-upload-cloudinary
strapi-provider-upload-rackspace
You can check out this article for the detailed implementation https://strapi.io/documentation/3.0.0-beta.x/plugins/upload.html#install-providers


text:
Q: How to set background color of a div in angular? I have an angular web app where my html is as follows:

{{news.source.title}}

My component has the following :
this.news = new News()
this.news.backgroundColor = '#E6E6CA'

However, I see that the color does not get set if I use {{news.backgroundColor}}. What is the correct way to set the background color?
style="background-color: #E6E6CA"

This works if  I use the hex directly. But, I want to use news.backgroundColor to set the color. So, wondering what is the correct usage.

A: You need to surround style with [] otherwise, it's just going to be interpreted as a string. Do it like this:

{{news.source.title}}

You could also define an object in your component, instead of setting each property individually:
public myStyle = {
  "background-color": this.news.backgroundColor
}

{{news.source.title}}

A: as long as news.backgroundcolor is a public member, your approach works fine.
ts:
export class myClass {
news = {"backgroundcolor":"#e6e6ca"}
}

html:

See the example:
If the property / member is private or the scope otherwise inaccessible (null) it obviously won't work.
Also, You should generally be using classes IMO.


text:
Q: Http POST request does not get response if the length exceed 1308 bytes I have a strange issue and I dont know how to debug it.
I need to make a POST SOAP request to a WebService server.
My Java code is:
    String urlParameters = "<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
..................
</soap:Body>
</soap:Envelope>";
        URL url;
        HttpURLConnection connection = null;
        try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("SOAPAction", "http://xxxxx/Foo" );

        connection.setUseCaches (false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
        wr.writeBytes (urlParameters);
        wr.flush ();
        wr.close ();

        //Get Response
          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuilder response = new StringBuilder();
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();

Now if the urlParameters is less than or equal 1308 bytes then it works fine and I can get the response. However if the length exceeds 1308 bytes( i.e. if I add one more character to the string ), then it wont work( it seems not even get out of the client machine, it never reaches the server )
I tried with soapUI and it also gives me the same issue.
I'm running on Ubuntu 12.04
Yes i do have the same problem with CURL. Here is the output if the request length is valid:
* About to connect() to epermit port 8085 (#0)
*   Trying 192.168.14.100... connected
> POST /xxx/xxx.asmx HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: xxx:8085
> Accept: */*
> Content-Type:text/xml; charset=utf-8
> SOAPAction:"xxxxx"
> Content-Length: 1304
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Cache-Control: private, max-age=0
< Content-Type: text/xml; charset=utf-8
< Server: Microsoft-IIS/7.5
< X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
< Date: Thu, 28 Mar 2013 03:52:55 GMT
< Content-Length: 324
<
* Connection #0 to host epermit left intact
* Closing connection #0
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><xxxx xmlns="xxxxxxx" /></soap:Body></soap:Envelope>

And when I make the request bigger than 1308 bytes:
* About to connect() to xxxxxxxxxxx port 8085 (#0)
*   Trying 192.168.14.100... connected
> POST /xxxxxxx/xxxxxxx.asmx HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: xxxxxxxx:8085
> Accept: */*
> Content-Type:text/xml; charset=utf-8
> SOAPAction:"xxxxxxxxxxxxxxxxx"
> Content-Length: 1309
> Expect: 100-continue
>
< HTTP/1.1 100 Continue

Any idea for this?
thanks,

A: Data gets sent along the network in a series of packets. These packets have a size <= the MTU of the network this is usually some number below 1500 octets. I suspect the server is getting two of these packets and only reading the first one. It is then having a failure trying to parse the incomplete data.


text:
Q: Template parse: The pipe could not be found I am getting the error:

Template parse errors: The pipe 'amDateFormat' could not be found

Here is my app.module.ts
import { NgModule } from '@angular/core';
...
import { MomentModule } from 'angular2-moment';
...

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    ...
    MomentModule,
    ...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    ...
  ]
})
export class AppModule { }

Then in service-booking-details.ts I am doing the following:
import { Component} from '@angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import { MomentModule } from 'angular2-moment';
...

@IonicPage()
@Component({
  selector: 'page-item-detail',
  templateUrl: 'service-booking-detail.html'
})
export class ServiceBookingDetailPage {
  service: any;
  ...

  constructor(..., navParams: NavParams, ...) {
    this.service = navParams.get('service');
  }
}

Then in the service-booking-detail.html template I am trying to use a pipe from angular2-moment:
<ion-content>

    <ion-card>
      <ion-card-content>
         <p>{{ service.data | amDateFormat:'LL' }}</p>
      </ion-card-content>
    </ion-card>

</ion-content>

It then throws the error "Template parse errors: The pipe 'amDateFormat' could not be found".
How do I import the MomentModule so that I can use it in templates without getting errors?

A: If this exists in the spec file (Jasmine, protractor)
import { MomentModule } from "ngx-moment";

beforeEach(() => {

      imports: [ MomentModule ]
  });

Worked for me

A: In my case moving the MomentModule import from app.module.ts to the same module as component was fixed it.

A: You can add momentModule to specific page module, or it'd be better to add it on shared module.
Hope it helps you.

A: I was able to get this working by importing this into the specific pages *.module.ts file.


text:
Q: Lipschitz function of independent subgaussian random variables This question was asked here, but I have reason to believe that it's a serious research question appropriate for this forum (also, the answers given at the link aren't satisfactory).
If $X\in\mathbb{R}^n$ is a random vector with independent $\sigma$-subgaussian components and $f:\mathbb{R}^n\to\mathbb{R}$ is $L$-Lipschitz (w.r.t. $\ell_2$), can the subgaussian moment of $f(X)$ be bounded in terms of $\sigma$ and $L$, independently of $n$?
I am told that the answer is no, so the first "real" question is to produce a counterexample. A second question is: What (hopefully mild) additional assumptions need to be made to make the answer positive?

A: A counterexample to the first part is obtained by considering the uniform distribution on $\{0,1\}^n$, for $n$ even, defining $A\subset\{0,1\}^n$ by $A=\{x:\sum_{i=1}^n x_i\le n/2\}$, and defining $f(x)=\inf_{y\in A}||x-y||$. Then $f$ is a Lipschitz function of iid subgaussian random variables yet fails to satisfy subgaussian concentration. The detailed argument is worked out in Ledoux and Talagrand (1991, p. 17), and also appears as Exercise 6.4 in the Boucheron-Massart-Lugosi concentration-of-measure book.
An additional assumption to make the claim hold is to assume that $f$ is separately convex (Exercise 6.5 in the Boucheron-Massart-Lugosi book), but annoyingly, the support of the distribution is assumed to be compact. Question: does the subgaussian concentration claim hold for separately convex Lipschitz functions of independent subgaussian random variables without assuming compact support?


text:
Q: The word "have" "I have them all memorized"
I thought have is used when something is done someone and the subject tell them to do so.
Like : "I had my computer fixed"
"I had my hair cut"
So what's the meaning of "have" in "I have them all memorized"?

A: It is a slight extension of the usual meaning of "have" meaning .possession.

Do you have the tickets?
I have them all in my bag.

This refers to literal possession, and the phrase "in my bag" indicates the state of the tickets (specifically the location)

Do you have the answers?
I have them all memorised.

By slight extension, you can possess an answer in you memory.


text:
Q: How to share Login Info or shared data in Multiple XAP files for a silverlight project I have a silverlight application with Mulitiple XAP for each Module, I want to share Login Info to each XAP in the application.
Please help.


text:
Q: Mocha/Should.js using asynchronous function I'm new to JavaScript test frameworks. I would like to do a little optimization but I run into some problems. The project is using should.js
Here is the simplified version of my original test cases:
describe('Simple', function() {
  describe('Test', function() {
    it('should do something', function(done) {
      somePromise.then(function(data) {
        data.should.above(100);
        done();
      });
    }

    it('should do something else but alike', function(done) {
      somePromise.then(function(data) {
        data.should.above(100);
        done();
      });
    }

  }
});

I'm trying to do it this way:
var testFunc = function(data) {
  it('should do something', function(done) {
      data.should.above(100);
      done();
  });
}

describe('Simple', function() {
  describe('Test', function() {
      somePromise.then(function(data) {
        testFunc(data);
      });

      somePromise.then(function(data) {
        testFunc(data);
      });
  }
});

The promise is asynchronous, and maybe that's the reason why my "optimization" didn't work? I've found no "done" callback for describe function in docs.
Thanks in advance! Any help will be appreciate!

A: Your example does not work since Mocha has finished registering test cases when your promise resolves.
Testing the same promise with different assertions
To test a single promise using several assertions you simply need to create the promise at the start of the tests and then use it in the it blocks like the following:
describe('A module', function() {
    var promise;

    before(function () {
        promise = createPromise();
    });

    it('should do something', function() {
        return promise.then(function (value) {
            value.should.be.above(100);
        });
    });

    it('should do something else', function() {
        return promise.then(function (value) {
            value.should.be.below(200);
        });
    });
});

Note that if the promise is returned from an API call, the call will only be made once. The result is simply cached in the promise for the two test cases.
This also makes use of the fact that you can return promises from test cases instead of using a done callback. The test case will then fail if the promise is rejected or if any of the assertions in the then() calls fail.
Testing different promises with the same assertions
Assuming that you want to test different promises using the same assertions you could pass a function to testFunc that creates the promise to be tested.
var testFunc = function(promiseFactory) {
  it('should do something', function(done) {
      promiseFactory().then(function(data) {
          data.should.above(100);
          done();
      });
  });
}

describe('Simple', function() {
  describe('Test', function() {
      testFunc(function () { return createSomePromise(); });

      testFunc(function () { return createSomeOtherPromise(); });
  });
});

This works since Mocha's it function is run immediately inside the describe block. The promises are then created using the promiseFactory callback when the test cases are actually run.
As you can also return promises from test cases you can change testFunc to return an assertion as a promise like this:
var testFunc = function(promiseFactory) {
  it('should do something', function() {
      return promiseFactory().should.eventually.be.above(100);
  });
}


text:
Q: spring boot, multiple datasource Есть приложение на spring boot, которое использует подключение к двум бд:
application.properties
spring.datasource.url=jdbc:h2:mem
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

another.datasource.url=jdbc:mysql://localhost:3306/test
another.datasource.username=root
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
another.datasource.driverClassName=com.mysql.jdbc.Driver

RepositoryConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"test.repository.mysql"})
public class RepositoryConfig {

    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.datasource.driverClassName}")
    private String driverClassName;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("test.entity.mysql");   // <- package for entities
        emf.setPersistenceUnitName("anotherEntity");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

При такой конфигурации работает подключение к двум бд, но в дефолтном datasource используются все entity, как сделать, чтобы первый datasource, который в application.properties как spring.datasource, использовал только свои entity?

A: Элегантное решение предложено в документации к spring-boot
Суть в создании собственных ConfigurationProperty и использования атрибута prefix для спецификации.
Далее можно разнести их по разным конфигурациям и воспользоваться аннотацией EntityScan
Ну и конечно же можно сделать то, что вы пытались сделать, только более аккуратно
@Bean
public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    return builder
            .dataSource(customerDataSource())
            .packages(Customer.class)
            .persistenceUnit("customers")
            .build();
}

@Bean
public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    return builder
            .dataSource(orderDataSource())
            .packages(Order.class)
            .persistenceUnit("orders")
            .build();
}

Для изоляции Entity я использую разные репозитории, пример из документации:
@Configuration
@EnableJpaRepositories(basePackageClasses = Customer.class,
        entityManagerFactoryRef = "customerEntityManagerFactory")
public class CustomerConfiguration {
    ...
}

@Configuration
@EnableJpaRepositories(basePackageClasses = Order.class,
        entityManagerFactoryRef = "orderEntityManagerFactory")
public class OrderConfiguration {
    ...
}

PS: Если не запуститься с ошибкой об уникальности бинов, то нужно один из бинов пометить как @Primary :)

A: Нужно создать 2 бина DataSource. Добавить аннотацию @Qualifier. Дать им разные имена.
ссылка на английском
@Bean(name = "mysql")
@Primary
@ConfigurationProperties(prefix="datasource.mysql")
public DataSourceProperties fooDataSourceProperties() {
     return DataSourceBuilder
             .create()
             .build();
}

@Bean(name = "postgres")
public DataSource fooDataSource() {
    return fooDataSourceProperties().initializeDataSourceBuilder().build();
}

Далее используем @Qualifier для определения того, какой именно бин нужен.


text:
Q: ADML files in foreign language I have a centralized SYSVOL in my domain. Ofc it has en-EN language files (.adml) but the PC I am using to remotely administrate the domain is in Italian language (it-IT). Now, when I open the GPO editor on my PC I get everything in Italian, except that ADM templates tree which is displayed in english since it is read from the central storage. What am I supposed to do to fix this? Is copying %systemroot%\PolicyDefinitions\it-IT content to the sysvol enough or should I do something else? Also note that I run W8.1 and the domain controllers run WS2012 (not R2).

A: Yes, you can copy the it-IT folder from %systemroot%\PolicyDefinitions\ to \\domain.com\sysvol\domain\Policies\PolicyDefinitions\ and be able to use either Italian when configuring the ADMX settings from any computer connected to the domain. The ADM files are only in a single language, you can't change that.


text:
Q: Replace text dynamically added after initial page load in webpage How can I replace the text on a webpage, including text that is injected or modified with future JavaScript calls? All the answers in replace words in the body text only work on text that is on the page at the moment of execution.

A: It turns out that doing the above in a performant way and without breaking anything is nontrivial for the supposedly declarative markup language that is HTML. I have documented what I learned over a month of testing and experimenting below.
To do an initial round of replacement on existing text, we will leverage TreeWalker to go through every Text node in the document and process their contents. In this example, I will be censoring "heck" with "h*ck".
const callback = text => text.replaceAll(/heck/gi, 'h*ck');

function processNodes(root) {
    const nodes = document.createTreeWalker(
        root, NodeFilter.SHOW_TEXT, { acceptNode:
        node => valid(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
    });
    while (nodes.nextNode()) {
        nodes.currentNode.nodeValue = callback(nodes.currentNode.nodeValue);
    }
}

function valid(node) {
    return (
        node.parentNode !== null
        && node.parentNode.tagName !== 'SCRIPT'
        && node.parentNode.tagName !== 'STYLE'
        && !node.parentNode.isContentEditable
    );
}

processNodes(document.body);

Note the valid function. This is to handle three exceptional cases:

*

*We need to check that the parent node exists as sometimes the node will get removed from the document by the time we get around to it

*Messing with <script> and <style> tags could break functionality or presentation

*Editing a contenteditable element resets the cursor position which is a terrible user experience

But that only takes care of text that was already on the page. To watch for future changes, we can use MutationObserver to watch for added or modified text nodes.
const IGNORED = [
    Node.CDATA_SECTION_NODE,
    Node.PROCESSING_INSTRUCTION_NODE,
    Node.COMMENT_NODE,
];
const CONFIG = {subtree: true, childList: true, characterData: true};

const observer = new MutationObserver((mutations, observer) => {
    observer.disconnect();
    for (const mutation of mutations) {
        const target = mutation.target;
        switch (mutation.type) {
            case 'childList':
                for (const node of mutation.addedNodes) {
                    if (node.nodeType === Node.TEXT_NODE) {
                        if (valid(node)) {
                            node.nodeValue = callback(node.nodeValue);
                        }
                    } else if (!IGNORED.includes(node.nodeType)) {
                        processNodes(node);
                    }
                }
                break;
            case 'characterData':
                if (!IGNORED.includes(target.nodeType) && valid(target)) {
                    target.nodeValue = callback(target.nodeValue);
                }
                break;
        }
    }
    observer.observe(document.body, CONFIG);
});
observer.observe(document.body, CONFIG);

The observer's callback consists of two main parts: a case for childList that processes any new subtrees and text nodes as well as a case for characterData that handles text nodes that had their contents changed. We must turn off the observer before making any edits of our own to avoid triggering an infinite loop. Also note the IGNORED array; this is necessary because certain nodes fall under the Text interface but are not front-facing, user-visible content.
Putting those two pieces together should be enough 98% percent of the time. However, there are still many special cases we didn't consider:

*

*Certain HTML attributes that get rendered as text (placeholder in <input>, alt in <img>, value in <input type="button">)

*CSS content property

*Shadow DOMs
A proper explanation of workarounds for the above wouldn't fit in a StackOverflow answer, but I have written a free library called TextObserver that does it for you.


text:
Q: Shell script: command to print a sentence I can't find a command to print a sentence in a shell script.
For example on google
firefox http://www.google.com
[[command that writes "hello world" on the searchbar]]

the result should be https://www.google.com/search?hl=en&source=hp&biw=&bih=&q=hello+world&btnG=Google+Search&gbv=2&gws_rd=ssl
It should be easy but I can't find it

A: According to firefox manual, you can add this option:
-search term
     Search for term with your default search engine.

If your default search engine is google, this command will work:
firefox -search "hello world"

A: You can provide the q query parameter directly to search in the URL:
firefox "https://www.google.com/search?q=hello+world"


text:
Q: Let $f\colon \mathbb R\to\mathbb R$ be a continuous function such that $f(i) = 0$ Let $f\colon \mathbb R\to\mathbb R$ be a continuous function such that $f(i) = 0$, for all $i\in \mathbb Z$ . Which of the following statement is true$?$
$(A)$ $\operatorname{Image}(f)$ is closed in $\mathbb R$.
$(B)$ $\operatorname{Image}(f)$ is open in $\mathbb R$.
$(C)$ $f$ is uniformly continuous.
$(D)$ None of the above.
If we take $f(x) = 0$, for all $x\in \mathbb R$, then $\operatorname{Image}(f)$ is a singleton set. Also we know that every singleton set is closed in $\mathbb R$. So option $B$  is wrong.
For option $(C)$, I take $f\colon \mathbb R\to\mathbb R$ such that $f(x) = x \sin\pi x $, this function $f$ is not uniformly continuous. So option $C$ is also wrong.
Now my problem is that the answer of this question is option $D$ but i am not able to get any function to discard option $A$. So please help me.
Thanks you.

A: Take $$f(x)=\frac{\sin\pi x}{1+e^{-x}}.$$ Then show $\mathrm{Im}(f)=(-1,1)$.
Or:
$$g(x)=\sin\pi x \arctan x$$
Then $\mathrm{Im}(g)=\left(-\frac \pi 2,\frac \pi 2\right).$
Basically, this is because $x\mapsto \frac{1}{1+e^{-x}}$ and $x\mapsto\arctan x$ are increasing functions with images $(0,1)$ and $(-1,1)$ respectively.

A: Take a function whose graph is a triangle connecting $(0, 0)$ to $(1/2, 1/2)$ to $(1, 0)$.
Then connect $(1, 0)$ to $(3/2, 3/4)$ to $(2, 0)$.
Then connect $(2, 0)$ to $(5/2, 7/8)$ to $(3, 0)$.
Continue in this manner, and the range is $[0, 1)$, which is not closed in $\mathbb{R}$.

Moral of the story: The image $f([i, i + 1])$ is closed for each $i$. But a countable union of closed sets isn't always closed.