text:
Q: author multiple times in the same entry How do I use multiple authors in a .bib file?
I have the following type of .bib file.
@article{ipab730bbib33,
    author ={Doherty J P and Moore M A and Kim J M and Bray A J},
    year =1994,
    journaltitle ={Phys. Rev. Lett.},
    pages={72},
    author ={M Kardar and Zee A},
    year =1996,
    journaltitle ={Nucl. Phys. B},
    pages={464},
    author ={L V Bork  and Ogarkov S L},
    year =2014,
    journaltitle ={Theor. Math. Phys.},
    pages={178},
}

A: A field can only be used once in an entry. Subsequent uses of the same field in a single entry will overwrite each other or will be ignored (depends on whether you use BibTeX or Biber; either way I would say this is 'undefined behaviour' and your entries should never repeat a field, I would rely on the backed ignoring or overwriting fields).
So you have to use different entries for different works. For a single work you have to concatenate the fields into one yourself.

It is not quite clear what exactly you had in mind with your example in the question, but if the aim is to show several papers in the same "bibliography entry", then you may want to look into entry sets.
biblatex has two kinds of entry sets,

*

*static sets that are defined as entries in the .bib file,

*and dynamic sets that can be defined with \defbibentryset in the .tex file.

A set (dynamic or static) can be cited as a single unit and appears as a single unit in the bibliography, but it consists of several separate entries.
This is explained in §3.14.5 Entry Sets of the biblatex documentation, but I guess an example is more helpful to demonstrate what is going on.
Note that set entries are only well supported for numeric and alphabetic styles, for other styles it is a bit tricky to determine what the proper behaviour would be (the related feature often gives a better result).
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[backend=biber, style=numeric]{biblatex}
% or
% \usepackage[backend=biber, style=numeric, subentry]{biblatex}

\begin{filecontents}{\jobname.bib}
@article{sigfridsson,
  author       = {Sigfridsson, Emma and Ryde, Ulf},
  title        = {Comparison of methods for deriving atomic charges from the
                  electrostatic potential and moments},
  journaltitle = {Journal of Computational Chemistry},
  date         = 1998,
  volume       = 19,
  number       = 4,
  pages        = {377-395},
  doi          = {10.1002/(SICI)1096-987X(199803)19:4<377::AID-JCC1>3.0.CO;2-P},
}
@book{worman,
  author       = {Worman, Nancy},
  title        = {The Cast of Character},
  date         = 2002,
  publisher    = {University of Texas Press},
  location     = {Austin},
}
@thesis{geer,
  author       = {de Geer, Ingrid},
  title        = {Earl, Saint, Bishop, Skald~-- and Music},
  type         = {phdthesis},
  institution  = {Uppsala Universitet},
  date         = 1985,
  subtitle     = {The {Orkney Earldom} of the Twelfth Century. {A} Musicological
                  Study},
  location     = {Uppsala},
}
@book{nussbaum,
  author       = {Nussbaum, Martha},
  title        = {Aristotle's \mkbibquote{De Motu Animalium}},
  date         = 1978,
  publisher    = {Princeton University Press},
  location     = {Princeton},
}
@incollection{pines,
  author       = {Pines, Shlomo},
  editor       = {Twersky, Isadore},
  title        = {The Limitations of Human Knowledge According to {Al-Farabi}, {ibn
                  Bajja}, and {Maimonides}},
  date         = 1979,
  booktitle    = {Studies in Medieval {Jewish} History and Literature},
  publisher    = {Harvard University Press},
  location     = {Cambridge, Mass.},
  pages        = {82-109},
}
@set{staticset,
  entryset  = {sigfridsson,geer,nussbaum},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\defbibentryset{dynamicset}{worman,pines}

\begin{document}
Lorem \autocite{staticset}
ipsum \autocite{dynamicset}
dolor \autocite{sigfridsson}

\printbibliography
\end{document}

The static @set entry staticset defined as
@set{staticset,
  entryset  = {sigfridsson,geer,nussbaum},
}

combines the three entries sigfridsson, geer and nussbaum into one in the bibliography. So this is a way to give several authors, titles etc. in one printed entry.
The dynamic set dynamicset defined with
\defbibentryset{dynamicset}{worman,pines}

combines the two entries worman and pines.
Note that in all cases the entries that are combined all only have one author field (etc.).
The subentry option (only available in styles where it makes sense) determines the result of a citation to a set member instead of the whole set.


text:
Q: ordering the dictionary values in list based on the position in the keys I have a dictionary where the value is a list of a few substrings from the key which is a string.
For example:
d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

and I want to get a list of lists generated from list values based on the position they appeared in the key. For example in the case above:
output = [["How", "going"], ["What", "hell"], ["police", "dept"]]

I did not find an efficient way to do it so I used a hacky approach:
final_output = []
for key,value in d.items():
    if len(value) > 1:
       new_list = []
       for item in value:
          new_list.append(item, key.find(item))

          new_list.sort(key = lambda x: x[1])
       ordered_list = [i[0] for i in new_list]
       final_ouput.append(ordered_list)

A: Use sorted with str.find:
[sorted(v, key=k.find) for k, v in d.items()]

Output:
[['How', 'going'],
 ['What', 'hell'],
 ['police', 'dept']]

A: Keys are already sorted so we can skip sorting
we can split key on " " and filter the splitted by associated value in dict
d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

lists = []
for k in d.keys():
    to_replace = k.split(" ")
    replaced = filter(lambda x: x in d[k],to_replace)
    lists.append(list(replaced))

print(lists)

Output:
[['How', 'going'], ['What', 'hell'], ['police', 'dept']]

A: Using List Comprehension
output = [[each_word for each_word in key.split() if each_word in value] for key, value in d.items()]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Macbook Pro 8.1 and Ubuntu conflict I recently installed Ubuntu 10.04 Lucid onto my Macbook Pro 8.1 over my Mac OS, and I am having many issues. The wireless is not working, the software update window will respond just long enough to get my hopes up, right click will not work, the mac hotkeys refuse to work, and the ubuntu software center spouts that all of the provided packages are "unverified", and outright refuses to let me install anything, even a software bit that worked on my last macbook/ubuntu install. HELP!?!?!?!

A: From the Ubuntu Forums:
snippit
Apple Intel Mac (Mactel) FAQ
Welcome to the Apple Users Forum at ubuntuforums.org.
This forum is focused on providing community support on the installation and setup of Ubuntu running on Apple hardware.
This FAQ is targeted at Users with a Intel-based Macintosh computers (mactel) with Core and Core 2 CPUs or Xeon. If you have a PowerPC-based Mac (G3, G4, G5) Please see the PowerPC FAQ. Please be sure to always check this FAQ and the Mactel-Support Community Support Documentation before asking a question in the forum, and when asking a question in the forum, post your Mac's version string.

*

*Can I run Ubuntu on my Mac?
YES! You will have to reduce the size of your OSX partition in order to make room for Ubuntu.
Read more from the link above. It is very detailed and descriptive.
Ubuntu Documentation MacBook Pro 8.1

A: Check here for specifics to that model - Mac Book Pro 8,1 Natty
I just installed 10.04 on my MB Pro model 5,1 and used the wiki for my model to get everything installed and running correctly.


text:
Q: Which is the react way of complex conditional rendering? Issue
I have a problem with conditional rendering of a component. As far as I can see, there are 2 approaches to doing this. First approach is ugly as it becomes difficult when I have to do multiple && conditions. The second way is clear, but it adds the component itself to the state and further computations with the state value is difficult. E.g checking what is the message value for error.
I have given both the approaches below. Please let me know which would be better. Is there a another approach than both of them?
Application
This is a simple application that renders either 'Main' component or 'Err' component, based on the state of 'err' attribute in first approach and content of the comp attribute in second approach.
Initially Main component is rendered. The err attribute is updated to some value after 2 seconds, which triggers rerendering. At this time, I want Err component to render.
The real application is I have an external api call on componentDidMount and it can either fail or succeed. I have to display different components based on result. It is a little more complicated with multiple state values being updated. I have simplified the issue below for the purpose of demonstration.
Common steps for both types
npx create-react-app react-oop

component/Err.js
import React,{Component} from 'react'

class Err extends Component {
    render(){
        return(

                Error Component

            )
    }
}

export default Err

component/Main.js
import React, {Component} from 'react'

class Main extends Component {
    render(){
        return(

                Main Component

        )
    }
}

export default Main

First approach

App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Err from './components/Err'
import Main from './components/Main'

class App extends Component {

  constructor(props){
    super(props)
    this.state = {
      err: null
    }
  this.setError = this.setError.bind(this)
  }

  setError(){
    return(
      this.setState(() => {
        return({
          err: 'Error'
        })
      })
    )
  }

  componentDidMount(){
    setTimeout(this.setError, 2000)
  }

  render() {
    return (

       {
         this.state.err ? <Err /> :
       }

    );
  }
}

export default App;

Second approach

App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Err from './components/Err'
import Main from './components/Main'

class App extends Component {

  constructor(props){
    super(props)
    this.state = {
      comp:
    }
  this.setError = this.setError.bind(this)
  }

  setError(){
    return(
      this.setState(() => {
        return({
          comp: <Err />
        })
      })
    )
  }

  componentDidMount(){
    setTimeout(this.setError, 2000)
  }

  render() {
    return (

       {this.state.comp}

    );
  }
}

export default App;

A: I definitely recommend the 1st approach. Store data (json), not views (jsx) in your component's state.
Actually there is a 3rd approach that takes the best of both:

use a jsx variable to edit the view (with your logic) before rendering

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Err from './components/Err';
import Main from './components/Main';

class App extends Component {

    constructor(props){
        super(props);
        this.state = {
            err: null
        };
    }

    // This way of writing functions saves you the binding
    setError = () => this.setState({err: 'Error'})

    componentDidMount(){
        setTimeout(this.setError, 2000);
    }

    render() {
        let comp = ;
        // Put your logic here so your returned JSX is clear
        if (this.state.err)
            comp = <Err />;
        return (

              {comp}

        );
    }
}

export default App;

A: Both approaches are essentially the same but I prefer option 1 as it's simpler to grasp. You can also use something like babel-plugin-jsx-control-statements#choose which makes the React component look simpler:
<Choose>
  <When condition={ test1 }>

  </When>
  <When condition={ test2 }>
    <AnotherMain />
  </When>
  <Otherwise>
    <Err />
  </Otherwise>
</Choose>


text:
Q: I want to restrict a page for subscriber and contributor Well, I want to restrict a page for subscribers and contributers and want to redirect them to another page.
But how can I do that?

A: The following code shows how you can restrict some users from viewing a certain page. This could either be placed in a stand-alone plugin or the themes functions.php file. The code is fairly self-explanatory but I'll walk through it.
First, pick an appropriate hook to use. I chose wp because it's after WordPress is fully loaded and the $wp object is set up. You may want to hook in earlier or later depending on the application.
Next, determine if you're on a page or post you want restricted to certain users. I chose to restrict posts/pages that have the post_title of "Restricted". You'll have to use your own criteria. If the criteria is complicated, you'll probably want to move the business logic to its own function. If the post isn't restricted, then return early.
Next, check to see if the user should be able to see the page or post. The publish_posts capability is one that neither logged-out, contributors, or subscribers have so I used that to see if they should be able to see the post. If they have that capability, then they can see the post, so return early.
Finally, redirect the users that shouldn't be seeing the post by using wp_safe_redirect().
add_action( 'wp', 'restrict_contributors' );
function restrict_contributors() {
  // * You'll have to determine how a post is restricted
  if( 'Restricted' !== get_post()->post_title ) {
    return;
  }
  //* Subscribers and contributors don't have the publish_posts capability
  //* Non-logged in users also don't have this capability
  if( current_user_can( 'publish_posts' ) ) {
    return;
  }
  //* Redirect all other users to some location
  wp_safe_redirect( home_url() );
  exit;
}


text:
Q: Not responsive footer
The picture above is my footer when it's normal, but when i collapsed it, it looks like this.. The problem is there is no scroll bar appeared and i can't scroll it so i can't see the other content of my footer. Can someone give me idea how to fix this?

here is my html code

Connect With Us

Contact Us

 Addres : 1045 M. Naval St., San Jose, Navotas City

 Tel. No : (02) 282-9036

 Fax : (02) 282-9035

 Email : gapc_school@yahoo.com.ph

Visit Us

is bluehost or dreamhost better

Copyright &copy 2016. Governor Andres Pascual College. All Rights Reserved

here is my css code
  .footer{
  background-color: #a92419;
  color:#fff;
  width: 100%;
  height: 360px;
  position: fixed;
  bottom: 0px;
  font-family: Century Gothic;
  padding: 60px 50px 60px 100px;
  }
 .copyr{
  text-align: center;
  color:    #baabab;
  }
 .footer h4{
  margin: 10px 10px 30px 100px;
  }
  .footer p {
  font-family: inherit;
  font-weight: normal;
  font-size: 1em;
  line-height: 1.6;
  margin-bottom: 0.50em;
  text-rendering: optimizeLegibility;
  }
  .twitter-hover {
  background-image: url('images/twitter-hover.png');
  margin-left: 125px;
  }
  .facebook-hover {
  background-image: url('images/facebook-hover.png');
   margin-left: 10px;
   }
  .social-slide:hover {
  background-position: 0px -48px;
  box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.8);
  }
  .social-slide{
  height: 35px;
  width: 38px;
  float: left;
  -webkit-transition: all ease 0.3s;
  -moz-transition: all ease 0.3s;
  -o-transition: all ease 0.3s;
  -ms-transition: all ease 0.3s;
  transition: all ease 0.3s;
      }
     hr.carved {
     clear: both;
     float: none;
     width: 100%;
     height: 2px;
     margin: 1.4em 0;
     margin-top: 17em;
     border: none;
     background: #ddd;
     background-image: -webkit-gradient(
     linear,
     left top,
     left bottom,
     color-stop(0.5, rgb(126,27,18)),
     color-stop(0.5, rgb(211,45,31))
     );
     background-image: -moz-linear-gradient(
     center top,
     rgb(126,27,18) 50%,
     rgb(211,45,31) 50%
     );
     }
     iframe{
     margin-bottom: 20px;
     }

A: The problem is that it's trying to fit everything into the div, but it's gotten too small, so it can't.  There's no scrollbar, because the container itself is still only 100%.  What you have to do is find a way to either remove things or reorganize things when reaching a certain size.  You can accomplish this with media queries or maybe even using flexbox.

A: Here are some media quires for you :) they make life responsive
    @media (max-width: 600px) {

    .footer{
        padding: 35px;
    }

    .footer .footerh1{
        font-size: 18px;
    }

    .footer .footerh4{
        font-size: 12px;
    }

    .footer .footer-links{
        font-size: 14px;
        padding: 25px 0 20px;
    }

    .footer .footer-links a{
        line-height: 1.8;
    }
}

A: Your footer has a fixed height. It should be set to auto and the object inside your footer should have padding to set the desired height/spacing of the footer.
.footer {
display:block;
width: 100%;
height: auto;
position: absolute;
}

#Iteminfooter{
display:inline-block;
padding: 20; 50px;
float: right;
}

#Iteminfooter2{
display:inline-block;
padding: 20; 50px;
}

#Iteminfooter3{
display:inline-block;
padding: 20; 50px;
float: left;
}


text:
Q: how to check if a stream table exists using DolphinDB? How to know if a StreamTable or KeyedStreamTable exists? I tried using exists and existsTable but I am not sure what dbURL to enter.

A: You can use the objs() function, for example:
objs(true).name.find(X)


text:
Q: Use the chain rule to compute ∂z/∂x and ∂z/∂y for 2x^2+y^2+z^2=9. Where exactly do I use it and how? Use the chain rule to compute $\dfrac{\partial z}{\partial x}$ and $\dfrac{\partial z}{\partial y}$ for $2x^2+y^2+z^2=9$.
I got the following, however I don't think I'm using the chain rule.  Where exactly do I use it and how?
$\dfrac{d}{dy}$ $(2x^2+y^2+z^2)$ = $\dfrac{d}{dy}$ $(9)$.
$\dfrac{d}{dy}$$(2x^2) + $$\dfrac{d}{dy}$(y^2) + $\dfrac{\partial z}{\partial y}$$(z^2)$ = $\dfrac{d}{dy}$(9)
0 + 2y + $\dfrac{\partial z}{\partial y}$$(z^2)$ = 0
2y + $\dfrac{\partial z}{\partial y}$(2z) = 0
$\dfrac{\partial z}{\partial y}$(2z) = -2y
$\dfrac{\partial z}{\partial y}$= $\dfrac{-2y}{2z}$ = $\dfrac{-y}{z}$
$\dfrac{d}{dx}$ $(2x^2+y^2+z^2)$ = $\dfrac{d}{dx}$ $(9)$
2$\dfrac{d}{dx}$$(x^2)$+$\dfrac{d}{dx}$$(y^2)$+$\dfrac{\partial z}{\partial x}$$(z^2)$=$\dfrac{d}{dx}$(9).
2(2x)+$\dfrac{d}{dx}$$(y^2)$+$\dfrac{\partial z}{\partial x}$$(z^2)$=$\dfrac{d}{dx}$(9)
4x+ 0 + $\dfrac{\partial z}{\partial x}$$(z^2)$ = 0
4x + $\dfrac{\partial z}{\partial x}$(2z) = 0
$\dfrac{\partial z}{\partial x}$(2z) = -4x
$\dfrac{\partial z}{\partial x}$= $\dfrac{-4x}{2z}$ = $\dfrac{-2x}{z}$
My answers of -y/z and -2x/z are correct, but how do I apply the chain rule to the problem.  I also want to apologize up front for the formatting, I just am still trying to figure it out.

A: You need to use implicit differentiation. The idea is that, suppose you can write $z = g(x,y)$. Then you can rewrite the equation about as $F(x,y, g(x,y)=z) = 0$ where $F = 2x^2+y^2+z^2-9$. To compute $z_x$ and $z_y$, we use the chain rule.
In computing these partials, we will assume $F_z \not = 0$. Thus, since $z = g(x,y)$, for a small neighborhood of the points $(x,y,g(x,y))$ we can choose a curve $c(t) \in \mathbb{R}^2$ such that:
\begin{align*} (x,y,g(x,y)) \in F( c(t)) \Rightarrow 0 &= \frac{d}{dt}(F \circ c)(t)\\&= \nabla F \cdot \frac{\partial}{\partial x} (x,y,g(x,y) \\&= (F_x, F_y, F_z)  \cdot (1,0, g_x) \\& \Rightarrow F_x + F_z g_x
=0 \\& \Rightarrow g_x=\frac{\partial z}{\partial x} = - \frac{F_x}{F_z} = - \frac{2x}{z} \end{align*}
I've given $F$ above, and so you have half the answer. Do a similar computation to derive $z_y$ i.e just replace $\partial/ \partial x$ with $\partial/ \partial y$.


text:
Q: Configure authenticate Mechanism in Squirrel SQL Client for DB2 I want to configure a DB2 Connection in Squirrel SQL Client and my URL contains securityMechanism=13 at the end. When I am trying to connect with this URL and Test a connection in Squirrel , its throwing an error saying -
com.ibm.db2.jcc.b.SqlException: Connection authorization failure occurred.  Reason: security mechanism not supported

Can anyone tell, how to handle/configure Squirrel SQL Client to make this URL working ?

A: I had the same problem. To solve it you need to add two properties to your SQuirreL Alias, securityMechanism=13 and encryptionAlgorithm=2. It worked in my case hope it will help for you:)
Adding some Screenshots:
Alias properties
Driver properties


text:
Q: React Native (android) - Download file Need to download a pdf file when user clicks download button in my android app.
I have base64 string of my pdf, file name available, which I fetched from api.
Now how do I download this pdf ?
Read that we can use RN Fetch Blob, so I tried below code,
let pdfLocation = dirs.DocumentDir + '/' + fileName + '.pdf';
console.log("writing file to - " + pdfLocation);
RNFetchBlob.fs.writeFile(pdfLocation, base64PDFString, 'base64').then((res: any) => {
  console.log("file written res -" + res);
})

From the console logs, I can see the file is written in the specified location, but if I navigate to that location in my android simulator, I can't see any files stored there.

Am I missing anything here ?


text:
Q: How to check existence of directory using path C# Using
Directory _dir = Directory.CreateDirectory(path);

So how to store the object of directory in a variable so then I have to check whether the directory at specified path exists or not as?
if(!_dir.exists())
{
    _dir.CreateDirectory(path);
}

Is it allowed in C#?

A: Try This...
        string path=@"C:\Users\v\Desktop\DESKTOP";
        if(!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

A: DirectoryInfo dir = Directory.CreateDirectory(path);
if(!dir.Exists)
{
    dir.CreateDirectory(path);
}

Or
DirectoryInfo dir = Directory.CreateDirectory(path);
if(!Directory.Exists(path))
{
    dir.CreateDirectory(path);
}


text:
Q: Plane wave normal incidence on dielectric, direction of fields I'm having an extremely hard time to figure out the direction of the $\vec E_R$ (reflected electric field) and $\vec H_R$ (reflected magnetic field) as well as the transmitted fields.
I've been reading Griffiths's Introduction to electrodynamics, Jackson's Electrodynamics, Zangwill's modern electrodynamics as well as seeking help at #physics on IRC and I just don't get it.
Here's the problem:
We consider vacuum on the left and a semi-infinite dielectric medium that extends on the right side. We consider an incident plane wave going from the left to the right, at normal incidence on the surface of the dielectric.
To keep things simple, we'll assume that the incident electric field points in the x direction only (up) while the z direction is the direction of incidence (right). This settles the direction of the H field of that wave (because $\vec E \times \vec H$ must give the direction of the Poynting's vector, the direction of motion which in this case is the y direction.)
The reflected wave will be travelling in the -z direction (so its Poynting vector must have that direction) while the transmitted wave will be travelling in the z direction.
The matching conditions at the surface of the dielectric are:
(1) $\hat n \cdot (\vec D_1 - \vec D_2 ) =0$
(2) $\hat n \cdot (\vec B_1-\vec B_2)=0$
(3) $\hat n \times (\vec E_1 - \vec E_2)=\vec 0$
(4) $\hat n \times (\vec H_1 - \vec H_2)=\vec 0$
where $\hat n = \hat z$, thus the first 2 equations don't tell me anything because $\vec D$ and $\vec B$ are orthogonal to $\hat n$. However the eqs. (3) and (4) give me the information:
(3') $\vec E_I + \vec E_R = \vec E_T$
(4') $\vec H_I + \vec H_R = \vec H_T$
and since $\vec H= \hat k \times \vec E$, eq. (4') reduces to (4'') $n_1(\vec E_I - \vec E_R)- n_2 \vec E_T=\vec 0$, where $n_1=1$ and $n_2$ is the refractive index of the dielectric medium.
Now comes my problem of understanding: since we have chosen an incident electric field parallel to the plane of incidence, according to the books, the eqs. (3) and (4'') reduce to something like:
(5) $E_I-E_R-E_T=0$
(6) $n_1(E_I+E_R)- n_2E_T=0$
So that it appears that $\vec E_I$ and $\vec E_T$ have the same direction, opposite to $\vec E_R$ while the $\vec H$ fields of the 3 waves have the same direction. I don't understand how they figured this out. I see no explanation in the books.
I do know that $\vec E_R \times \vec H_R$ must yield the direction -z, but that's not enough to settle down the directions of both fields. For instance both $\hat E_R=-\hat x$, $\hat H_R=\hat y$ and $\hat E_R=\hat x$, $\hat H_R=-\hat y$ yield $\hat k_R=-\hat z$. So how did they figure out that the former is correct instead of the latter?
The rough idea that I got is: from Jackson and Zangwill: because the sketch is like that. They deduced it from the sketch.
From Griffiths, it's because of the direction of the Poynting vector.
To me none is satisfying.

A: The short answer is that it doesn't matter. Whichever direction you choose to define the reflected E-field initially you will always gets its direction with respect to the incident E-field coming out the same.
In the case you have in your question (where you have reversed the sign of $E_R$ and defined it to be in the -x direction and opposite to the incident E-field), the reflection coefficient is given by
$$\frac{E_R}{E_I} = \frac{n_2 - n_1}{n_2+n_1}$$
So if $n_2 > n_1$, then the reflection coefficient is positive and this confirms that the reflected E-field is in the -x direction (or to be more accurate, confirms that the reflected and incident E-fields are opposite, as you assumed in your eqn 6).
On the other hand, if you set up the simultaneous equations hypothesising that the reflected and incident E-fields are aligned in the +x direction and hence that $H_R$ is defined opposite to $H_I$, then the reflection coefficient becomes
$$\frac{E_R}{E_I} = \frac{n_1 - n_2}{n_2+n_1}$$
In this case if $n_2 > n_1$, the reflection coefficient is negative, and this indicates that in fact the reflected E-field is opposite to the incident E-field, as before.
Thus it does not matter which way you define $E_R$ in your equation 6; the direction of the reflected E-field compared to the incident E-field is always correctly derived and is unambiguous.
When I teach this I always advise students to define all the E-fields in the same direction, not assume that the reflected E-field is reversed as you have done in your eqn 6, and then find a negative reflection coefficient that can be straightforwardly interpreted as a $\pi$ phase change.


text:
Q: xcodebuild: No valid iOS Distribution signing identities belonging to team I'm trying to build and create IPA but I'm getting this error:
Error Domain=IDEDistributionErrorDomain Code=1 "No valid iOS Distribution signing identities belonging to team XXXXXXXXX were found." UserInfo={NSLocalizedDescription=No valid iOS Distribution signing identities belonging to team XXXXXXXXX were found.}

I can archive just fine but this is how I'm trying to create the IPA:
xcodebuild -exportArchive -archivePath <xcarchivepath>
-exportPath <destinationpath>
-exportOptionsPlist <plistpath>

I can generate the IPA using xcode just fine but my question to guys is how can generate the IPA without having this issue with the certificate?, do I need to export the certificate ?
I'll really appreciate your help


text:
Q: What does Euc. VI mean?

You can just tell me what does this Euc. VI mean. I tried searching Euc.VI and also Euc VI postulate. I got nothing. Please tell me what does this mean or how is AB/ab = OA /Oa ? P

A: $\triangle Oab$ and $\triangle OAB$ are both isosceles and they share the same angle $\angle AOB$; Therefore, they are similar. Hence, $\frac{AB}{ab}=\frac{OA}{Oa}$.


text:
Q: Resource specification not allowed here for source level below 1.7 I am trying to open an OutputStream resource in a try with resources block:
try (OutputStream output = connection.getOutputStream()) {
    output.write(query.getBytes(charset));
}

However, I got a compilation error:

Resource specification not allowed here for source level below 1.7

Is there an equivalent for 1.6 or do I have to convert my project to 1.7?

A: try this code
try {
    OutputStream output = connection.getOutputStream();
    output.write(query.getBytes(charset));
}catch (Exception e) {
    e.printStackTrace();
}


text:
Q: Show menu items depending ViewPager Android I have a ViewPager with fragments in my Android app. I want to show Action Bar menu item depending the fragment of the ViewPager. I have readen some questions about this but I can´t find the correct solution. My ViewPager´s code is this:
public class My_Activity extends ActionBarActivity {

    private ViewPager mViewPager;
    String idioma;

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

        ActionBar actionBar = getSupportActionBar(); // || getActionBar();
        actionBar.setIcon(getResources().getDrawable(R.drawable.navbar_logo));
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC3333")));

        actionBar.setTitle("Hello");

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerTabStrip);
        pagerTabStrip.setTabIndicatorColor(getResources().getColor(R.color.blanco));

        Title_Liga_Adapter titleAdapter = new Title_Liga_Adapter(getSupportFragmentManager());
        mViewPager.setAdapter(titleAdapter);

        mViewPager.setCurrentItem(0);

        getSupportActionBar().setIcon(R.drawable.navbar_logo);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mViewPager.getCurrentItem() == 4) {
            getMenuInflater().inflate(R.menu.menu_comunidad,
                                      menu);
        } else {

        }
        return true;
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        menu.findItem(R.id.action_search)
            .setVisible(true);

        return super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                this.finish();
                return true;

            case R.id.action_search:

                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

I want that when CurrentItem is 4 for example show menu items icons.

A: First create addOnPageChangeListener in onCreate method
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
           // ...

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            invalidateOptionsMenu();
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}

Then you override onCreateOptionMenu()
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    if (mViewPager.getCurrentItem()==0){
        menu.findItem(R.id.action_search).setVisible(true);
    } else if(mViewPager.getCurrentItem()==1){
        menu.findItem(R.id.action_search).setVisible(false);
    } else if(mViewPager.getCurrentItem()==2){
        // configure
    } else if(mViewPager.getCurrentItem()==3){
        // configure
    }
    return super.onCreateOptionsMenu(menu);
}

A: I answer my own question:
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_comunidad,
                              menu);

    return true;
}

// Called when invalidateOptionsMenu() is triggered
@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    if (mViewPager.getCurrentItem() == 4) {
        menu.findItem(R.id.action_search)
            .setVisible(true);
    } else {
        menu.findItem(R.id.action_search)
            .setVisible(false);
    }
    return super.onPrepareOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            this.finish();
            return true;

        case R.id.action_search:

            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

A: OK..you will have to play with the ViewPager.OnPageChangeListener where you will monitor the method onPageSelected() that will be triggered whenever you change the page of the ViewPager. You will have to keep track of what is the current page AND dispatch a call to the ActivityCompat.invalidateOptionsMenu every time the onPageSelected() is called. This invalidateOptionsMenu() is the key to make it work, it will be responsible for triggering the 'refresh' of options menu..that will indirectly call the  onCreateOptionsMenu() method will be called and you have the opportunity to 'hide' or 'show' a different set of items according to the selected tab.
For instance:
public boolean onCreateOptionsMenu(Menu menu) {
   ///

   if (currentPageIdx == 4) {
      // inflate menu for page 4
      // configure the menus
   } ....

  return super.onCreateOptionsMenu(menu);
}

A: Activity Menu
Set up your main menu excluding the menu items that are related to your fragments.
ie.
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="300"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_help"
        android:title="@string/action_help"
        android:orderInCategory="400"
        app:showAsAction="never"
        android:visible="true"/>
</menu>

First Fragment Menu (mine is for assets)
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_add_asset"
        android:title="@string/add_new_asset"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_edit_asset_type"
        android:title="@string/edit_asset_types"
        android:orderInCategory="200"
        app:showAsAction="never" />

</menu>

Second fragment menu (liabilities)
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_add_liability"
        android:title="@string/add_new_liability"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_edit_liability_type"
        android:title="@string/edit_liability_types"
        android:orderInCategory="200"
        app:showAsAction="never" />
</menu>

Fragment Code (for both)
In your onActivityCreated in each fragment:
  setHasOptionsMenu(true);

Fragment 1 Code
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)

    try {
        inflater.inflate(R.menu.menu_asset, menu)
    } catch (e: NullPointerException) {
        e.printStackTrace()
    }
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId

    if (id == R.id.action_add_asset) {
        startNewActivity(NewAssetActivity::class.java)
        return true
    } else if (id == R.id.action_edit_asset_type) {
        startNewActivity(AssetTypeActivity::class.java)
        return true
    }
    return false
}

Fragment 2 code
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)

    try {
        inflater.inflate(R.menu.menu_liability, menu)
    } catch (e: NullPointerException) {
        e.printStackTrace()
    }
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId

    if (id == R.id.action_add_liability) {
        startNewActivity(NewLiabilityActivity::class.java)
        return true
    } else if (id == R.id.action_edit_liability_type) {
        startNewActivity(LiabilityTypeActivity::class.java)
        return true
    }
    return false
}

When you swipe between fragments using the view pager, the menus will change automatically.
Use the orderInCategory to show the correct order of the menus.
Nothing else is required, you dont need to hide/show anything.


text:
Q: How to open a link using a CardView What I want to do is to click on a CardView send me directly to the browser with a link already inserted as I can achieve that would greatly appreciate your help  :).

A: Use the following code. Replace it with the id of your cardview in place of your_cardview_id
    CardView cardView;
    cardView = findViewById(R.id.your_cardview_id);

    cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
            startActivity(browserIntent);
        }
    });


text:
Q: Opposite of boondoggle If a trip meant "for business" that results in a trip "for pleasure" can be characterized as a boondoggle, then is there a word for the converse, where a trip "for pleasure" (eg. vacation) results in seeking out and taking advantage of a business opportunity?

A: It's a rather boring and obvious answer, but what I've heard it called is
working vacation (USA)
or
working holiday (UK)

a trip, sometimes to another country, on which you work

There is also the slang workation.

A workation is similar to a vacation where you can take your work
  along with you.

A: It's often called a busman's holiday

A vacation during which one engages in activity that is similar to one's usual work.

American Heritage
Collins suggests the term derives from the idea of a bus driver taking a driving holiday

A: Depending on your job and tax bracket, a pleasure trip where you squeeze in some business might be a tax write-off vacation.

[T]he IRS says that you can deduct expenses for taking a business trip.
  There is no reason the trip shouldn't coincide with your next
  vacation. (Bill Walston, real estate blog)
A fellow . . . needed insurance. Problem was, he was in Branson, Mo.,
  and wouldn't be back to Iowa before summer.
  "No problem," I told him. "Mary and I have been champing at the bit to
  go to Branson. We'll meet you there." . . .
  Done! A tax-write-off vacation. (Curt Swarm, Newton Daily News, "My
  tax write-off vacation to Branson")

The line here is a bit blurry (though maybe not to the IRS), so this term might also apply to the original situation described (a pleasure trip only masquerading as business).


text:
Q: On submit form Display data into table using echo in PHP I have a table, displayied with an echo, where, for each row I'd like to have a button to change a "status" field (I want to update just one field). I am trying to insert a form button into my echo but I don't get anything.
This is my echo code:
while($row = mysql_fetch_array( $result )) {
    echo "
";
        echo '' . $row['id'] . '	';
        echo '' . $row['fullname'] . '	';
        echo '' . $row['message'] . '	';
        echo '' . $row['country'] . '	';
        echo '' . $row['email'] . '	';
        echo '' . $row['website'] . '	';
        echo '' . $row['date'] . '	';
        echo "" . $row['status'] . " 	";

        echo "<form action='updatestatus.php' method='post'>";
            echo "<input type='hidden' value='".$row['id']."' name='id' />";
            echo "<input type='hidden' value='".$row['status']."' name='status' />";
            echo "<input type='submit' name='submit' value='Submit'>	";
        echo "</form>";

        echo 'Edit	';
        echo 'Delete	';
    echo "
";
}

updatestatus.php

// check if the form has been submitted.
if (isset($_POST['submit'])) {
    // confirm that the 'id' value is a valid integer before getting the form data
    if (is_numeric($_POST['id'])) {
        // get form data, making sure it is valid
        $id = $_POST['id'];
        $status = $_POST['status'];

        if ($status == 0) {
            $status == 1;
            mysql_query("UPDATE personalguestbook SET status='$status' WHERE id='$id'")
            or die(mysql_error());
        } else {
            $status == 0;
            mysql_query("UPDATE personalguestbook SET status='$status' WHERE id='$id'")
            or die(mysql_error());
        }
        header("Location: view.php");
    }
}

So, if my status field is = 0, I want to change it = 1 and update into my database, and vice versa.
Thanks for your attention

A: Your form isn't sending anything to updatestatus.php, you can add the data to POST in a hidden form like so:
echo "<form action='updatestatus.php' method='post'>";
echo "<input type='hidden' value='".$row['id']."' name='id' />";
echo "<input type='hidden' value='".$row['status']."' name='status' />";
echo "<input type='submit' name='submit' value='Submit'>	";
echo "</form>";

This is the simple fix to your code above, there are still some security flaws and efficiency methods others have mentioned in the comments.

A: Check this PHP code
while($row = mysql_fetch_array( $result )) {

    echo "
";
    echo '' . $row['id'] . '	';
    echo '' . $row['fullname'] . '	';
    echo '' . $row['message'] . '	';
    echo '' . $row['country'] . '	';
    echo '' . $row['email'] . '	';
    echo '' . $row['website'] . '	';
    echo '' . $row['date'] . '	';
    echo "" . $row['status'] . " 	";
    echo "";
    echo "<form action='updatestatus.php' method='post'>";
    echo "<input type='hidden' value='".$row['id']."' name='id' />";
    echo "<input type='hidden' value='".$row['status']."' name='status' />";
    echo "<input type='submit' name='submit' value='Submit'>	";
    echo "</form>";
    echo "	";
    echo 'Edit	';
    echo 'Delete	';
    echo "
";

}

updatestatus.php

 // check if the form has been submitted.
     if (isset($_POST['submit']))
     {
     // confirm that the 'id' value is a valid integer before getting the form data
     if (is_numeric($_POST['id']))
     {
     // get form data, making sure it is valid
     $id = $_POST['id'];

     $status = $_POST['status'];

     if ($status == 0){
         $status == 1;
         mysql_query("UPDATE personalguestbook SET status='".$status."' WHERE id='".$id."'")
     or die(mysql_error());
     } else {
          $status == 0;
         mysql_query("UPDATE personalguestbook SET status='".$status."' WHERE id='$id'")
     or die(mysql_error());

     }
       header("Location: view.php");
     }
  }


text:
Q: Generate shim `.so` to rename symbols of existing `.so` I have an existing pre-built .so shared library (let's call it libjniopenssl.so). It was built by third party on Debian Linux with OpenSSL 1.0.1k-3+deb8u4.
I had to run libjniopenssl.so on CentOS with OpenSSL 1.0.2k package.
Despite the OpenSSL versions are slightly different the API used by libjniopenssl.so were not changed between 1.0.1k and 1.0.2k - so I expected them to be source and binary compatible for my scenario.
Unfortunately just running libjniopenssl.so on CentOS does not work.
The libjniopenssl.so is loaded by JVM via System.loadLibrary, but it fails with the following error when running on CentOS:
Unable to load libjniopenssl: java.lang.UnsatisfiedLinkError: /tmp/jna-112200956/jna6604950569974562639.tmp:
libcrypto.so.1.0.0: cannot open shared object file: No such file or directory

The reason is simple, there is no such file libcrypto.so.1.0.0 on CentOS, because OpenSSL 1.0.2k 16.el7 provides only following .so's:
$ ls -l /lib64/libcrypto*
lrwxrwxrwx. 1 root root      19 Jun  5  2018 /lib64/libcrypto.so.10 -> libcrypto.so.1.0.2k
-rwxr-xr-x. 1 root root 2512832 Apr 11  2018 /lib64/libcrypto.so.1.0.2k

For some reason CentOS package intentionally renamed .so file name from default libcrypto.so.1.0.0 to libcrypto.so.1.0.2k, even so when compiling that version from source it uses name libcrypto.so.1.0.0.
This error message suggested to try creating a symlink with name /lib64/libcrypto.so.1.0.0 which points to /lib64/libcrypto.so.1.0.2k
This resulted in the following error in run-time:
Unable to load libjniopenssl: java.lang.UnsatisfiedLinkError: /tmp/jna-112200956/jna2564265718506275007.tmp:
/lib64/libcrypto.so.1.0.0: version `OPENSSL_1.0.0' not found (required by /tmp/jna-112200956/jna2564265718506275007.tmp)

Inspecting libjniopenssl.so shown that there are following symbols referenced from OpenSSL:
$ readelf -Ws libjniopenssl.so

Symbol table '.dynsym' contains 40 entries:
Num:    Value          Size Type    Bind   Vis      Ndx Name
    0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
    1: 0000000000000e98     0 SECTION LOCAL  DEFAULT    9
    2: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
    3: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _Jv_RegisterClasses
    4: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_CIPHER_CTX_init@OPENSSL_1.0.0 (2)
    5: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND malloc@GLIBC_2.2.5 (3)
    6: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND OPENSSL_add_all_algorithms_noconf@OPENSSL_1.0.0 (2)
    7: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND HMAC_CTX_cleanup@OPENSSL_1.0.0 (2)
    8: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_CipherUpdate@OPENSSL_1.0.0 (2)
    9: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
    10: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND ERR_load_crypto_strings@OPENSSL_1.0.0 (2)
    11: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.2.5 (3)
    12: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_registerTMCloneTable
    13: 0000000000000000     0 FUNC    WEAK   DEFAULT  UND __cxa_finalize@GLIBC_2.2.5 (3)
    14: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND HMAC_CTX_init@OPENSSL_1.0.0 (2)
    15: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND HMAC_Final@OPENSSL_1.0.0 (2)
    16: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_sha1@OPENSSL_1.0.0 (2)
    17: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND HMAC_Init_ex@OPENSSL_1.0.0 (2)
    18: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND HMAC_Update@OPENSSL_1.0.0 (2)
    19: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_CIPHER_CTX_cleanup@OPENSSL_1.0.0 (2)
    20: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_MD_size@OPENSSL_1.0.0 (2)
    21: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND EVP_aes_128_ctr@OPENSSL_1.0.1 (4)

But the libcrypto.so.1.0.2k on CentOS has symbols which has different postfix, for example:
readelf -Ws /lib64/libcrypto.so.1.0.2k | grep -iE "EVP_CIPHER_CTX_init"
705: 000000000012a6b0   151 FUNC    GLOBAL DEFAULT   13 EVP_CIPHER_CTX_init@@libcrypto.so.10

So, on CentOS postfix is @@libcrypto.so.10, but libjniopenssl.so was linked against shared library which has symbols with postfix @OPENSSL_1.0.0. That's probably why just adding symlink does not work.
The further investigation shown that Debian version of OpenSSL 1.0.1k has included many patches, including one which adds symbol versioning. It was introduced only in OpenSSL 1.1.0, but was back ported by someone who is providing Debian package to 1.0.1.
In contrary CentOS OpenSSL 1.0.2k package does not include that patch for symbol versioning (but they include other patches from 1.1.0 according to symbols in .so).
I could re-build libjniopenssl.so on CentOS against it's copy of OpenSSL, but it actually involving maintaining (building, storing, deploying) own copy of libjniopenssl.so which actually comes from third-party git repository. I don't like rebuild solution, so I'm looking for more elegant one. But I have to say that re-building is what recommended on CentOS forum.
One solution I could think of is generation during build or deploy time a special shim libcrypto.so.1.0.0 (based on target system-provided copy of libcrypto) which has renamed symbols as desired by libjniopenssl.so, but under the hood it will translate all calls to the original system-provided libcrypto.so.1.0.2k.
In general I'm looking for some tool or set of tools which is capable of automatically generating such a "shim/adapter/proxy" .so out of specified "implementation" .so, but with ability to redefine some or all symbols.
I've found that there is objcopy tool which has --redefine-symbol old=new, but it doesn't exactly do what I want: I don't want to copy any code from original .so, I do want to translate calls to original "implementation" .so.
UPD: It is occurred by running local experiment that objcopy does not support renaming of symbols in dynamic library. The problem confirmed from this mail thread.
Summarizing, my questions are:

*

*Is there an existing util capable to generate such shared shim library for a specified .so file?

*Or maybe there is a better way to solve this incompatibility between CentOS and Debian OpenSSL packages, assuming I don't want to modify neither third-party provided libjniopenssl.so nor OS provided copy of OpenSSL?

A: Implib.so is capable of generating shim wrapper for arbitrary .so library. Running
$ implib-gen.py --dlopen-callback=mycallback libcrypto.so.1.0.0

will generate libcrypto.so.1.0.0.tramp.S and libcrypto.so.1.0.0.init.c which will implement version-less wrappers over all symbols in libcrypto.so.1.0.0. You'll also need a small loader for the OS-specific implementation (that is libcrypto.so.1.0.2k):
$ cat mycallback.c
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
#endif

// Load OS-specific implementation underneath
void *mycallback(const char *lib_name) {
  void *h = dlmopen(LM_ID_NEWLM, "libcrypto.so.1.0.2k", RTLD_LAZY | RTLD_DEEPBIND);
  if (h)
    return h;
  fprintf(stderr, "dlmopen failed: %s\n", dlerror());
  exit(1);
}

Linking you code with autogenerated files, mycallback.c and -ldl should solve the incompatible version issue.


text:
Q: Change a constant in Java in Debug vs. Release modes I am developing the client side of a client-server app and during testing I want the app to get data from my localhost, but when I release the app, I want it to connect to our production server.
I'm developing an Android app in Java using Eclipse. Is there a good way to do this?

A: Use a configuration file. When you build it locally copy over the -developer version of that configuration file. When you release it copy over the -release version of that configuration file. Also I wouldn't solely rely on "localhost" as the way of testing. Do some production level testing in the simulator that will connect to your real system.

A: Just use different configuration files for different environments.


text:
Q: Builder for setters and getters I want use this Java code in order to create Java Object:
public class NotificationMessage implements Serializable {

    private static final long serialVersionUID = 985577913631100757L;

    private int id;
    private String uniqueid;
    private String status;
    private String type;
    private Map<String, String> map;
    private Date created_at;

    public NotificationMessage() {
    }

    public NotificationMessage(int id, String uniqueid, String status, String type, Map<String, String> map,
            Date created_at) {
        this.id = id;
        this.uniqueid = uniqueid;
        this.status = status;
        this.type = type;
        this.map = map;
        this.created_at = created_at;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
....
}

How I can use builder in order to minimize setters when I want to create Java object?
I want to set values like this:
NotificationMessage.builder().id(123).uniqueid(1234).status("active")

A: You can use
https://projectlombok.org/
@Entity
@Data
@Builder
@Getter
public class NotificationMessage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String uniqueid;
    private String status;
    private String type;
    private Map<String, String> map;
    private Date created_at;
}

NotificationMessage.builder().id(123).uniqueid(1234).status("active");

assertThat(NotificationMessage.getId()).isEqulTo(123));

A: In order to chain the method calls like that:
NotificationMessage.builder().id(123).uniqueid(1234).status("active")

You have to return the calling object (this) on each call:
public NotificationMessage id(int id) {
    this.id = id;
    return this;
}


text:
Q: Django how can I pass data to hyperlink? MY TEMPLATE

                Title
                Publication date
                Delete

            {% for questionnaire in questionnaires %}

                            <input type="checkbox" name="questionnaires" id="questionnaires" value="{{ questionnaire.id }}">
                            {{ questionnaire.name }}

                    {{ questionnaire.pub_date }}
                    Delete

            {% endfor %}

                        Add new

                        Export to PDF

                        Check results

                        Draw charts

                        Generate tokens

                        Clear results

                        Delete selected

I need to get all checked objects from checkboxes placed in table, and pass them to hyperlinks in navbar.
For example, I have hyperlink "Delete selected". I want to delete every questionnaire which is selected by clicking on that link. Is it possible? If yes how can I do that?

A: In order to achieve, 'I have hyperlink "Delete selected". I want to delete every questionnaire which is selected by clicking on that link.', it's going to require a mix of jQuery and Django.
You should attach a click listener on the 'Delete selected' button which should serialize all selected questionnaires and send that data via AJAX to a Django view which will delete the necessary questionnaire objects from the database.
Here is a rough example...

def url/to/django/view(self, request):
    if request.method == 'POST':
        questionnaires_to_delete = request.POST.getlist('questionnaires')
        Questionnaire.objects.filter(id__in=questionnaires_to_delete).delete()
        return HttpResponse('WHATEVER YOU WANT TO RETURN TO THE CLIENT')

You many run into CSRF issues depending on your setup.  Here is the documentation for handling that...
https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/


text:
Q: How to Make Str Comparison Between htmlentities and normal string in php (with non-ascii chars) When I use this code:
<?
$a = htmlentities(urldecode("ööö"));
$b = "ööö";

if ($a === $b){
    echo "equal.";
}
?>

When I runned above code, it couldn't write anything. But when I use the code below:
<?
$a = "ööö";
$b = "ööö";

if ($a === $b){
    echo "equal.";
}
?>

It writes "equal". So, I can't compare strings when they are used with htmlentities function. How can I solve this problem ?
I think the problem is about htmlentities() function. When it is used, PHP can't be able to comparison strings truely...
Thanks.

A: Try with htmlspecialchars
<?php
    $a = htmlspecialchars(urldecode("ööö"));
    $b = "ööö";

    if ($a === $b){
            echo "equal.";
        } else {
            echo "not equal.";
    }
?>


text:
Q: Parsing H264 in mdat MP4 I have a file that only contains the mdat atom in a MP4 container. The data in the mdat contains AVC data. I know the encoding parameters for the data. The format does not appear to be in the Annex B byte stream format. I am wondering how I would go about parsing this. I have tried searching for the slice header, but have not had much luck.
Is it possible to parse the slices without the NAL's?

A: AVC NAL units are in the following format in MDAT section:
[4 bytes] = NAL length, network order;
[NAL bytes]
Shortly, start codes are simply replaced by lengths.

A: Be careful! The NAL Length is not required to be 4! The AvcConfigurationBox ('moov/trak/mdia/minf/stbl/stsd/avc1/avcC') contains a field 'lengthSizeMinusOne' specifying the length. But the default is 4.

A: I found what michael was talking about defined in section 5.2.3 of ISO 14496-15.
Sebastian's answer refers to section 5.2.4.1.1 and 5.3.4.1.2.
You will not be able to parse the slices in the 'mdat' box without copies of the SPS and PPS from the 'avcC' box (defined in section 5.2.4.1.1)


text:
Q: Question on compact sets in $\mathbb{R}^2$ Let $\Omega$ be an open set in $\mathbb{R}^2$, $K \subseteq \Omega$ and K be compact.
Prove that there exists $r>0$ such that $E=\bigcup_{z \in K} \bar{D}(z,r)$ is a compact subset of $\Omega$, where $\bar{D}(z,r)$ is the closed disc centred at $z$ with radius $r$.
I found Rudin using this fact in one of the proofs in his 'Real and Complex Analysis', however I am having difficult proving this fact is true.
My attempt: Let $2r$ be the minimum distance from the boundary of $\Omega$ to K, then $D(z,r)$ will all lie in $\Omega$. Since the union of $D(z,r)$ covers K, we can reduce the collection into a finite covering of K, say $D(z_1,r),D(z_2,r),...,D(z_N,r)$ Then $\bigcup_{n=1}^{N} \bar{D}(z_n,r)$ will be a compact subset of $\Omega$. However this set is not E, and it is necessary for the result to work for E for the proof to work.
Any help is appreciated!

A: Define $f(z)= d(z,K).$ Then $f$ is continuous on $\mathbb {R}^2.$ Note that for every $z \in \mathbb {R}^2,$ there exists a $w\in K$ such that $f(z) = d(z,w)$ (because a real continuous function on a compact set attains a minimum value). From this you can verify that
$$E_r = \cup _{z\in K}\overline {D(z,r)} =\{z \in \mathbb {R}^2: d(z,K)\le r\}.$$
This shows each $E_r,$ which equals $f^{-1}([0,r]),$ is closed. It's also bounded (by $[\sup_{z\in K} |z|]+r$). So each $E_r$ is compact. To finish, note that the compact set $K$ and the closed set $\Omega ^c$ are disjoint. Hence (standard exercise), $d(K,\Omega ^c) = s$ for some $s>0.$ Setting $r=s/2,$ we see $E_r$ has the desired properties.

A: Choosing $r$ as you did, we clearly have $E\subset \Omega$. It remains to see that $E$ is compact. In view of the Heine-Borel-Lebesgue theorem, we need to see that $E$ is closed and bounded.
Since $K$ is compact, it is bounded, say $K \subset D_R(0)$. Then we have $\overline{D}_r(z) \subset D_{R+r}(0)$ for all $z\in K$, whence $E\subset D_{R+r}(0)$, so $E$ is bounded.
We have $w \in \overline{D}_r(z) \iff \lvert w-z\rvert \leqslant r \iff z \in \overline{D}_r(w)$, so
$$\mathbb{C}\setminus E = \{ w : K \cap \overline{D}_r(w) = \varnothing\}.$$
If $K\cap \overline{D}_r(w) = \varnothing$, then $s := \min \{ \lvert z-w\rvert : z \in K\} > r$. By the triangle inequality, we thus have $K\cap \overline{D}_r(u) = \varnothing$ for all $u \in D_{s-r}(w)$, i.e. $D_{s-r}(w)\subset \mathbb{C}\setminus E$. So $\mathbb{C}\setminus E$ is open, and the proof that $E$ is compact is complete.
Along the lines you started on, you generally can't write $E$ as a finite union of compact disks, but you can cover it by a finite family of compact disks of radius $s > r$. You start by covering $K$ by a finite family of (open) disks of radius $s-r$, and then consider the finite family of disks with radius $s$ and the same centres $x_k$. By the triangle inequality, that family covers $E$: If $z \in K$, there is a $k$ such that $\lvert z- x_k\rvert < s-r$, and hence $\overline{D}_r(z) \subset D_s(x_k)$. That shows that $E$ is relatively compact in $\Omega$, but to see that it is closed, you still need an argument like above.

A: Construct the set $E$ as in your attempt and consider arbitrary sequence $\{e_1,e_2,\ldots\}$ of points from $E$. Then, $e_i=z_i+\rho_ie^{\alpha_i}$ with $z_i\in K$, $\rho_i\in[0,r]$ and $\alpha_i\in[0,2\pi]$. By compactness, there is a subsequence $i_t$ such that $z_{i_t}\rightarrow z\in K$, $\rho_{i_t}\rightarrow \rho\in [0,r]$ and $\alpha_{i_t}\rightarrow \alpha\in [0,2\pi]$. It remains to note that $e=z+\rho e^{\alpha}\in E$ is a limit point of $\{e_1,e_2,\ldots\}$.

A: I think we can adapt the Lebesgue Number Lemma here:
$\Omega$ is open so for each $x\in K$ there is an open ball $B(x,r_{x})$ containing $x$ and contained in $\Omega$.
Since $K$ is compact, we can find a finite subcover of $K$, say $\left \{ B(x_{i},r_{i}) \right \}^{n}_{i=1}$.
Define $h:K\to \mathbb R$ by $h(x)=\frac{1}{n}\sum_{i=1}^{n}d(x,(K \setminus B(x_{i},r_{i})))$. Then $h>0$ and $h$ is continuous so it has a minimum value $\delta >0$.
Now let $E=\bigcup_{z\in K}\overline B(z,\delta )$ and consider any $\overline B(z_{0},\delta )\subseteq E$.
Then
$\delta \leq h(z_{0})\leq d(z_{0},(K \setminus B(x_{j},r_{j})))$,
where $d(z_{0},(K \setminus B(x_{j},r_{j})))$ is the largest of the numbers $\left \{ d(z_{0},(K \setminus B(x_{i},r_{i}))) \right \}^{n}_{i=1}$
Thus,
$\overline B(z_{0},\delta )\subseteq B(x_{i},r_{i})\subset \Omega$
so that $E$ has the required property.


text:
Q: Unable to extract selected value from dropdown to JSTL I am not sure why this isn't working. Is it because they are in two seperate JSP files?
First jsp:
 <form:select path="ShopParameters.foodType" id="food-type">
     <form:options items="${foodTypes}"/>
 </form:select>

Second jsp:
            <c:if test="${param.food-type == 2}">
                <form:options items="${veganOptions}"/>
            </c:if>

The if statement in my second JSP is never evaluating to true. I have also tried erasing param and just checking ${food-type == 2} but that didn't work.
I followed this guide: http://www.java2s.com/Tutorial/Java/0380__JSTL/GetvaluefromFormTextFieldAndOutputthevaluebyusingJSTL.htm.
UPDATE:
I tried simplifying/narrowing things down by placing everything in one JSP and trying a bunch of different things but i'm still not able to get anything to display. I'm only able to get things to display if I pull from the model attribute but I do not want to do that.
<input type="hidden" id="groceryType" name="groceryType" value="2">

        <c:if test="${param.groceryType == 2}">
        <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${param.groceryType == '2'}">
          <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${param.groceryType eq '2'}">
           <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${param.groceryType eq 2}">
            <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${groceryType == 2}">
          <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${groceryType== '2'}">
          <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${groceryType eq '2'}">
            <form:options items="${veganOptions}"/>
        </c:if>
        <c:if test="${groceryType eq 2}">
           <form:options items="${veganOptions}"/>
        </c:if>


text:
Q: Editable text to string How can I convert editable text into string in Android ? Any solution?

A: This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string
EditText dob=(EditText)findviewbyid(R.id.edit_id);
String  str=dob.getText().toString();

A: Based on this code (which you provided in response to Alex's answer):
Editable newTxt=(Editable)userName1.getText();
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:
String newString = userName1.getText().toString();

A: If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString().


text:
Q: Some questions about Vector in STL I have some questions about vector in STL to clarify.....

*

*Where are the objects in vector allocated? heap?

*does vector have boundary check? If the index out of the boundary, what error will happen?

*Why array is faster than vector?

*Is there any case in which vector is not applicable but array is a must?

A: *

*In a contiguous memory block on the heap. A vector<int> allocates memory the same way new int[x] would.

*Only if you use the at method. It throws an std::out_of_range exception if the boundary check fails. The operator[] doesn't perform bounds checking.

*Because an array gives direct access to memory, while accessing a vector element most likely involves a method call. The difference can be ridiculously small though, especially if your compiler decides to inline the calls.

*In general, you'll use a vector if you want your container to have a dynamic size, and a simple array if a known fixed size is enough. Be sure to check out the other containers, like deque and list, to be sure you pick the most appropriate one. Otherwise, if you need to deal with non-C++ APIs, you'll obviously need to have access to a regular array. (edit) @BillyONeal says you should use &vector[0] to get the address of the underlying array, but use it with care since it can change if the vector's capacity changes.

A:
Where are the objects in vector
  allocated? heap?

It depends on the STL implementation, but in all likelihood on the heap, yes.

does vector have boundary check? If the index out of the boundary,
what error will happen?

Yes, a vector grows dynamically, you can check its size using the capacity() member function. If it should run out of space, it generally allocates more space using the reserve() member function.

Why array is faster than vector?

Arrays can be faster because they are plain data that does not need to be accessed through a wrapper object such as vector. You can think of a vector as neatly packaged array for your convenience.

Is there any case in which vector is
  not applicable but array is a must?

I think there can be times where an array is preferable over a vector. For example, when dealing with legacy C code or when speed is of utmost importance. But generally you can solve any array problem by containing the data in an STL vector.

A: Ad 4.: When dealing with legacy interfaces (e.g. POSIX) arrays may be a must.

A: *

*On the heap (assuming you use the standard allocator, which is the default)

*It is not boundary checked when using operator[], but it is if you use the member function at (e.g. my_vec.at(0)). If you use at and the index is out or bounds, it throws an std::out_of_range exception.

*Arrays aren't generally faster. It depends whether or not the vector's operator[] calls are inlined or not. Most modern compilers should index it though, as it is just a single array index.

*In general, normal arrays can be replaced by vectors. You shouldn't really use a std::vector on the public interface of a library, and manu library APIs require raw C-style arrays.

A: *

*By default contents are allocated dynamically. (But I suppose you can provide an allocator that gets the memory from some place else.)

*The at method does bounds checks and throws an out_of_range. Other methods may or may not check bounds, depending on implementation and settings.

*I would assume a vector to be slower than an array when it does something different from an array. For example, dynamic allocation is costly, so vector has a cost that arrays don't have. Dynamically resizing a vector is costly, whereas an array can't be resized at all. I wouldn't expect to see any difference when accessing the elements (except for possible run-time checks done by the implementation which you should be able to turn off if desired).

*I don't know of such a scenario. You can always get a pointer to the underlying array of a vector with &vec[0]. However, a vector can be an overkill if you don't need any of the features it provides - mostly the ability to (re)size it dynamically. In such cases an array could do just fine, but note that there are classes that make an array a first-class object too (std::tr1::array or boost::array) which make the array copyable and not decay into a pointer.


text:
Q: Attach labels to items in TFS from the PowerBuilder IDE? We do this using the Advanced button on the checkin dialog now (with Merant, nee PVCS) but the Advanced button is disabled when I set TFS as my SCC provider.  Is there a switch we can flip on either side to enable this?

*

*Or do we need to write some custom extension?

*Or can I get the TFS changeset number to associate with the change in PB?

*Or am I coming at doing selective builds entirely the wrong way?

A: We can achieve what we want by creating a Note field in TFS and making it required on check in.  The SCC interface will make the TFS check-in dialog appear & force the developer to enter a value in the field.  We can then use the Note to find the associated changeset & do extracts based on the changeset.    Thanks to all who looked at this.


text:
Q: How to get specific parameter from ObservableCollection<> ? Or maybe make my INotifyPropertyChanged not as weird working I've build a semi-working app on C# and Xamarin.Forms, grocery list of sorts.

My issue is (me) when user deletes any item on his display (clicks on ImageButton (Trash Icon)), ImageButton is binded with function, which through TodoItems.Remove, removes that specific clicked "item" if u will but I would love to somehow get int Price of that ObservableCollection<TodoItem before it's removed and substract that specific price from my Total: price. Currently my subtraction from Total price works in the dumbest way. Let's say I click on ImageButton delete Broccoli (which cost 6.5). But Total price will be substracted by 3, not 6.5. That's because I implemented  INotifyPropertyChanged which updates Total price label and since my price of each item is binded to Entry, Total price is being substracted by number which is currently in the entry (Entry under bananas). Help me fix this issue, is there a way to implement id system for each ObservableCollection which consists of three elements: string - name, bool - checkbox, double - price of item.
Here's how my xaml looks like
    <ContentPage.BindingContext>
    <local:TodoListViewModel/>
</ContentPage.BindingContext>

<StackLayout Margin="10,50,10,10">
    <Button
        x:Name="start"
        Text="Start"
            Clicked="Start_Clicked"/>

    <Entry
        x:Name="recon"
        Text="{Binding NewTodoInputValue}"

        ReturnCommand="{Binding AddTodoCommand}">

    </Entry>
    <Entry x:Name="cashrecon" Text="{Binding Price}" ReturnCommand="{Binding AddTodoCommand}">

    </Entry>
    <Label x:Name="amount" >

    </Label>

    <ListView x:Name="TodoList" ItemsSource="{Binding TodoItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <FlexLayout JustifyContent="SpaceBetween" AlignContent="Center" Padding="10, 0">

                        <ContentView>
                            <FlexLayout AlignItems="Center">
                                <input:CheckBox
                                    IsChecked="False"
                                />

                                <Label Text="{Binding ToDoText}" FontSize="Large" Padding="10, 0"/>

                                <StackLayout>

                                    <Stepper Minimum="1"
                                             Scale="0.5"
                                             Maximum="10"
                                             Increment="1"
                                             HorizontalOptions="Center"
                                             VerticalOptions="Center"
                                             ValueChanged="Stepper_ValueChanged"
                                            />
                                    <Label x:Name="cena" Text="{Binding Price}" Margin="20,-40,0,10">

                                    </Label>

                                </StackLayout>

                            </FlexLayout>
                        </ContentView>

                        <ImageButton
                            Source="delete.png"
                            Command="{Binding Path=BindingContext.RemoveTodoCommand, Source={x:Reference TodoList}}"
                            CommandParameter="{Binding .}"
                            BackgroundColor="Transparent"
                            />

                    </FlexLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Label
          x:Name="Total"
           Text="{Binding DisplayName}"
            TextColor="Black"
             Padding="250,0,0,0">
    </Label>

</StackLayout>

Here's TodoItem class
namespace XFSpeechDemo

public class TodoItem
{
    public string ToDoText { get; set; }
    public bool Complete { get; set; }
    public double Price { get; set; }
    public TodoItem(string ToDoText, bool Complete, double Price)
    {
        this.ToDoText = ToDoText;
        this.Complete = Complete;
        this.Price = Price;
    }
}

And here's ViewModel, which Is the core issue of mine
namespace XFSpeechDemo

public class TodoListViewModel : INotifyPropertyChanged
{

    public ObservableCollection<TodoItem> TodoItems { get; set; }
    public TodoListViewModel()
    {
        TodoItems = new ObservableCollection<TodoItem>();
        TodoItems.Add(new TodoItem("todo 1", false, 0));
        TodoItems.Add(new TodoItem("todo 2", false, 0));
        TodoItems.Add(new TodoItem("todo 3", false, 0));
    }

    public ICommand AddTodoCommand => new Command(AddTodoItem);
    public string NewTodoInputValue { get; set; }
    public double Amount { get; set; }
    public double Price { get; set; }

    double name=0;
    public double TotalPrice
    {
        get => name;
        set
        {
            if (name == value)
            {
                return;
            }
            name = value;
            OnPropertyChanged(nameof(Price));
            OnPropertyChanged(nameof(DisplayName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    void AddTodoItem()
    {

        TodoItems.Add(new TodoItem(NewTodoInputValue, false, Price));
        TotalPrice += Price;

    }

    public ICommand RemoveTodoCommand => new Command(RemoveTodoItem);
    void RemoveTodoItem(object o)
    {
        TodoItem todoItemBeingRemoved = o as TodoItem;

        TodoItems.Remove(todoItemBeingRemoved);
        TotalPrice -= Price;

    }

    public string DisplayName => $"Total: {TotalPrice} Blr";
}

I'm not well spoken in all the terms. I can read documentation, but it's all confusing about ObservableCollection so if I'll be glad to a reply with technical solution, not a reply w technical terms n smart phrases which I simply won't understand.
BTW addition to Total: price works totally fine. It's just subtraction that I'm struggling with. Don't see obvious solution on how to create id system which will track each item added n can be called when user clicks any Trash icon ImageButton, correctly identify the deleted price and of course substract from Total Price of all items.

A: instead of doing this
void RemoveTodoItem(object o)
{
    TodoItem todoItemBeingRemoved = o as TodoItem;

    TodoItems.Remove(todoItemBeingRemoved);
    TotalPrice -= Price;
}

do this
void RemoveTodoItem(object o)
{
    TodoItem todoItemBeingRemoved = o as TodoItem;

    TodoItems.Remove(todoItemBeingRemoved);
    TotalPrice -= todoItemBeingRemoved.Price;
}

A: Perhaps changing the command to be one that allows and expects a parameter would help:
public ICommand RemoveTodoCommand => new Command(RemoveTodoItem);

would be switched to
public Command<TodoItem> RemoveTodoCommand => new Command<TodoItem>(RemoveTodoItem);

And your RemoveTodoItem would have to have its signature changed to:
void RemoveTodoItem(TodoItem item)

Which you can then use to subtract from your total:
void RemoveTodoItem(TodoItem item)
    {
        TodoItems.Remove(item);
        TotalPrice -= item.Price;

    }

You could also cast your object coming into your current RemoveTodoCommand to a TodoItem and subtract from your price that way (the way you have started), but you need to ensure you are subtracting the current item's price -- something like TotalPrice -= todoItemBeingRemoved.Price;


text:
Q: Poisson and exponential distributions If number of occurrences per time unit of some event is a random variable $X\sim \mathrm{Poisson}(\lambda)$, then the time between occurrences is a random variable $Y$ which has exponential distribution.
What isn't stated clearly anywhere is that is the parameter of the exponential distribution the same $\lambda$?

A: Yes, more precisely, if the number of arrivals in  an interval $t$ is Poisson $Po(\lambda)$, then the time between two consecutive arrivals is Exponential with mean $1/\lambda$.
Proof:
$$F_T(t)=P(T\leq t)=1-P(T>t)$$
Where $P(T>t)$ means: "calculate the probability that, in a size $t$ interval there are no arrivals".
In other words
$$P(T>t)=e^{-\lambda t}$$
that is
$$1-P(T>t)=1-e^{-\lambda t}$$
which is exactly the CDF of an exponential $\text{Exp}(\lambda)$


text:
Q: what software can take full advantage of hyperthreading? I'm wondering what software must have to take full advantage of hyperthreading? Let's say I have intel cpu with 4physical cores. With hyperthreading the cpu appears to have 8 cores to the OS that is aware of HT technology.So that means the OS can address two independent threads to a single core. So it means the cpu can run 8threads of control 100% parallel divided 2 threads for each core? But however can a single core have more than 1 program counter?

So if the above sentence is true, that means to fully utilize a 4core cpu with HTT the software at least must have 8 programmed threads of control?

A: A core can indeed run only one thread at a time. But while running that thread, it may run into idle time when it waits for something, eg. loading code or data from RAM (RAM is much slower than CPU) or wait for a computation of a specific circuit (FPU). Triggering scheduler is not an option because that needs a context swich which is (compared to RAM) very slow. With HT, instead of waiting, it switches to the second prepared thread.
How a core can have multiple program counters? Well, it just have two sets of all registers.


text:
Q: Remote execution stops when local computer boots When I run a process on a remote Linux machine, the process stops if the connection is terminated for some cause. This behavior is reasonable, because otherwise irrelevant processes would keep running forever.
However, is there a way to prevent this from happening? Namely, I want to open a remote shell, run a process and direct its output to a log file, and log out - but keep the process running.
Thanks,
Udi

A: You can either use a screen session or push the process to background disconnecting it from the shell.
also check,

shopt -u huponexit

A: Well first option can be to spawn you program as another process with the & operator like
$ myprogram > file.log &

Or you can have a look at the screen command where you can store and retrieve your terminal sessions.


text:
Q: Confirmation: The Lipschitz constant of gradient of $f(z):= \frac{1}{2}\|y - z\|_2^2$ is 1. Right? Sorry for the silly question. I just wanted to confirm whether the

Lipschitz constant of gradient of $f(z):= \frac{1}{2}\|y - z\|_2^2$ over $\mathbb{R}^n$ is 1, isn't it?

The definition of Lipschitz continuous gradient is
\begin{align}
\| \nabla f(z_1) - \nabla f(z_2)\|_2 \leq L \|z_1 - z_2\|_2 \quad \forall z_1, z_2 \in \mathbb{R}^n.
\end{align}
The gradient of $f(z)$ is $\nabla f(z) = -(y-z)$. So, plugging this in the above definition,
\begin{align}
& \| \underbrace{\nabla f(z_1)}_{-y+z_1} - \underbrace{\nabla f(z_2)}_{-y+z_2}\|_2 \leq L \|z_1 - z_2\|_2 \\
\Longleftrightarrow & \| z_1 - z_2 \| \leq L \|z_1 - z_2 \| \quad \Rightarrow \quad L \geq 1.
\end{align}

ADD: Of course $L$ may depend on the considered norm. I have assumed L2 norm though.

A: Certainly $\nabla f$ is non-expansive, by the argument provided. The argument doesn't quite rule out the possibility of some $L < 1$ also satisfying the condition (though it comes very close to concluding this), so the Lipschitz constant can only be concluded to be less than or equal to $1$.
To show the Lipschitz constant is indeed $1$, consider $z_1 = (1, 0) + y$ and $z_2 = y$. Then, for any eligible $L$,
$$\|\nabla f(z_1) - \nabla(z_2)\| \le L\|z_1 - z_2\| \implies \|(1, 0) \| \le L\|(1, 0)\| \implies L \ge 1.$$
Thus the Lipschitz constant is $1$.


text:
Q: What does parentheses combined with underscore syntax mean in latest C# version? I saw sample code as below:
namespace CSharpNewFeature {

   record Product(string Name, decimal Price, bool IsFood);

   record Order(Product Product, int Quantity) {
      public decimal NetPrice => Product.Price * Quantity;
   }

   record Address(string Country);
   record UsAddress(string State) : Address("us");

   public static class VatStrategy {
      static decimal Vat(Address address, Order order)
         => address switch {
            UsAddress(var state) => Vat(RateByState(state), order),
            ("de") _ => DeVat(order),  // <--------?
            (var country) _ => Vat(RateByCountry(country), order), // <--------?
         };

      static decimal Vat_Prop(Address address, Order order)
         => address switch {
            { Country: "de" } => DeVat(order),
            { Country: var c } => Vat(RateByCountry(c), order),
         };

      static decimal RateByCountry(string country)
         => country switch {
            "it" => 0.22m,
            "jp" => 0.08m,
            _ => throw new ArgumentException($"Missing rate for {country}")
         };

      static decimal Vat(decimal rate, Order order)
         => order.NetPrice * rate;

      static decimal RateByState(string state)
         => state switch {
            "ca" => 0.1m,
            "ma" => 0.0625m,
            "ny" => 0.085m,
            _ => throw new ArgumentException($"Missing rate for {state}")
         };

      static decimal DeVat(Order order)
         => order.NetPrice * (order.Product.IsFood ? 0.08m : 0.2m);
   }
}

I don't understand how to interpret these two statments below:
("de") _ => DeVat(order),
(var country) _ => Vat(RateByCountry(country), order),

Especially ("de") _, I know underscore mean "discard", but what are we discarding here? and what does ("de") do here? What is the feature name of (...) _ in latest C# specification?

A: There are a couple new(er) C# features being used here. The first is record deconstructing (sometimes also called "destructuring" in other languages) although it looks like the sample code is abridged because records require two positional fields in order to automatically generate a deconstructor.
record Widget(string Foo, string Bar);

var myWidget = new Widget("Hello", "World");

var (greeting, subject) = myAddress;

/* Prints "World". */
Console.WriteLine(subject);

Note that the type of the variables on the left side of the expression can be declared explicitly:
(string greeting, string _) = myAddress;

/* If the types match: */
string (greeting, _) = myWidget;

Or they can be inferred:
(var greeting, var _) = myWidget;

/* Or: */
var (greeting, _) = myWidget;

Or a mix of both:
(string greeting, var _) = myWidget;

The second feature being used is the relational patterns feature which is a new application of the traditional switch expression. The expression for the first pattern to match the input is executed and the rest are ignored. Here's a contrived example that returns a string based on the value of an enum. The discard is used like the default case; anything that reaches it will match.
enum Widget { Thing, Doodad, WhatsItCalled };

string WidgetIdentifier(Widget input) =>
    input switch {
        Widget.Thing => "You have a Thing! Lucky you!",
        Widget.Doodad => "You have a Doodad. That's not so bad.",
        _ => "You might have a Widget, but it's not worth much.";
    };

/* Prints "You have a Doodad! That's not so bad.". */
Console.WriteLine(WidgetIdentifier(Widget.Doodad));

/* Prints "You might have a Widget, but it's not worth much.". */
Console.WriteLine(WidgetIdentifier((Widget)12));

In your example, then:
static decimal Vat(Address address, Order order)
    => address switch {
        UsAddress(var state) => Vat(RateByState(state), order),
        ("de") _ => DeVat(order),  // <--------?
        (var country) _ => Vat(RateByCountry(country), order), // <--------?
    };

The switch is considering the address field which we know can be deconstructed. The patterns you asked about are:

*

*("de") which will match when the Country field of address is equal to "de". The discard (_) is completely unnecessary since we don't use the value of address in the expression for this pattern. You can leave it out (e.g. ("de") => DeVat(order)) and the statement would work the same. See for yourself on .NET Fiddle. Think of this case like "Deconstruct address and match it to the hypothetical deconstruction ("de")".

*(var country) _ which is both a pattern and a deconstruction to a variable. The discard means we're ignoring the value of address (and it can be omitted as in the first case), the (var country) deconstructs address so that country is equal to the value of the Country field on address. This will match any Address value. Think of this case like "Try to deconstruct address into (var country). Even if it matches, you can ignore the result. (But since you've delcared a variable country in scope, it can still be used even though the match result was discarded)". Again, this is an odd way to write this since we know if address is not null, we can deconstruct it. Leaving out the discard would make that more clear in my mind.

Conversely, it might be more clear if we used explicit names for the results of a match:
static decimal Vat(Address address, Order order)
    => address switch {
        UsAddress(var state) => Vat(RateByState(state), order),
        ("de") germanAddress => DeVat(order),  // <--------?
        (var country) someAddress => Vat(RateByCountry(someAddress.Country), order), // <--------?
    };

See how ("de") was used to match the case when address was in Germany, but we never used the germanAddress variable (which was identical to address)?
See how (var country) was used to match the case when address could be deconstructed? Here it's more obvious why you wouldn't always use a discard. We were able to access someAddress.Country (even though country contained the same value). This usage is unique in that there are two ways to access the value in address.Country - by deconstructing and using the result, or by matching and using the alias someAddress.Country.


text:
Q: hibernate. many to many between three tables Hello all
Today I faced some trouble...
I have 3 tables with many to many relationship between each. See link below
diagram
Below short definition of Entities:
Branchs
@Entity
@Table(name = "systembranches")
public class Systembranches {
    private long id;
    ...
    private Set<Systemusers> systemuserses;
    private Set<Userroles> userroleses;
    ...
    @ManyToMany
    @JoinTable(
            name = "branchroles",
            joinColumns = @JoinColumn(
                    name = "BranchId",
                    referencedColumnName = "Id",
                    nullable = false),
            inverseJoinColumns = @JoinColumn(
                    name = "UserId",
                    referencedColumnName = "Id",
                    nullable = false))
    public Set<Systemusers> getSystemuserses() {
        return systemuserses;
    }

    public void setSystemuserses(Set<Systemusers> users) {
        this.systemuserses = users;
    }

    @ManyToMany (mappedBy = "systembranches")
    public Set<Userroles> getUserroleses() {
        return userroleses;
    }

    public void setUserroleses(Set<Userroles> userroleses) {
        this.userroleses = userroleses;
    }
}

Users
@Entity
public class Systemusers {
    private long id;
    ...
    private Set<Userroles> userroles;
    private Set<Systembranches> systembrancheses;
    ...
    @ManyToMany
    @JoinTable(
            name = "branchroles",
            joinColumns = @JoinColumn(
                    name = "UserId",
                    referencedColumnName = "Id",
                    nullable = false),
            inverseJoinColumns = @JoinColumn(
                    name = "RoleId",
                    referencedColumnName = "Id",
                    nullable = false))
    public Set<Userroles> getUserroles() {
        return userroles;
    }

    public void setUserroles(Set<Userroles> roles) {
        this.userroles = roles;
    }

    @ManyToMany (mappedBy = "systemuserses")
    public Set<Systembranches> getSystembranches() {
        return systembrancheses;
    }

    public void setSystembranches(Set<Systembranches> systembrancheses) {
        this.systembrancheses = systembrancheses;
    }

}

Roles
@Entity
public class Userroles {
    private long id;
    ...
    private Set<Systemusers> systemusers;
    private Set<Systembranches> systembrancheses;

    ...

    @ManyToMany (mappedBy = "userroles")
    public Set<Systemusers> getSystemusers() {
        return systemusers;
    }

    public void setSystemusers(Set<Systemusers> systemusers) {
        this.systemusers = systemusers;
    }

    @ManyToMany
    @JoinTable(
            name = "branchroles",
            joinColumns = @JoinColumn(
                    name = "RoleId",
                    referencedColumnName = "Id",
                    nullable = false),
            inverseJoinColumns = @JoinColumn(
                    name = "BranchId",
                    referencedColumnName = "Id",
                    nullable = false))
    public Set<Systembranches> getSystembranches() {
        return systembrancheses;
    }

    public void setSystembranches(Set<Systembranches> systembrancheses) {
        this.systembrancheses = systembrancheses;
    }

}

As you can see all tables joined through fourth table (branchroles) that do not have entity in my application.
This table contains the following data:
id UserID BranchId RoleId
1    2        3        2
2    3        3        3
3    1        1        4
5    4        2        4
8    5        2        4
9    6        2        2

I need to get list of some entities (for example Roles) on depends on two Set<> property inside this entity (Set<Systemusers> and Set<Systembranchs>)
on SQL it should look like this:
SELECT * FROM Userroles r
JOIN branchroles connector ON r.id = connector.RoleId
JOIN systembranches b ON b.id = connector.BranchId
JOIN systemusers u ON u.id = connector.UserId
WHERE u.id = 3 and b.id = 2

In my Java code I wrote
getSessionFactory().getCurrentSession()
                   .createCriteria(Userroles.class)
                   .createCriteria("systemusers")
                   .add(Restrictions.eq("id", userId))
                   .createCriteria("systembranches")
                   .add(Restrictions.eq("id", branchId))
                   .list();

and other similar variants like
.createCriteria(Userroles.class, "r")
                   .createCriteria("r.systemusers", "u", JoinType.INNER_JOIN)

but each time Hibernate generate code like this
Hibernate SQL
As you can see in this SQL one extra JOIN and as result invalid dependency in next JOIN expression
How can I fix it? I want to write code using Criteria API and without one-to-many relationsips and without branchroles entity, if it possible. Could you please help?
Thanks

A: You are missing something in Your database structure.
If you are looking for Many To Many Relationship it can be Possible between Two table.
One Table will have mapping detail that is your owning table.
If you want to go for three table Many To Many than you need to Consider Your JoinTable as entity table in application.
Than Map it to third Table with Many to Many Relationship.
hope this will help you


text:
Q: Is there any API that can be used to update the Jboss configuration file (standalone.xml) I need to update the standalone.xml configuration file but I need to do it before I start-up the server. This is for jboss7.

A: What are you trying to accomplish? Editing the standalone.xml is rather simple with any text editor.
If you're looking for something automated you can write CLI scripts to execute after the server has started, then just restart (reload) it. There are some scripts you could use as an example too.

A: It would help your answers to describe why you need to change to configuration before it starts up. Being an open source project, any actual use case for the offline editing of a server configuration file via an API will be of interest to the development team.
Having said that, I can't think of having had that requirement myself. One of the advantages of JBoss Application Server 7 is that the Management Clients write persistent changes to the main standalone.xml, domain.xml and host.xml configuration files while the server is running. These same files as easily edited offline via any flavour of text editor.
As you likely know the recommended management workflow is via the Management Console or the Management CLI. These are the Management Clients documented in the JBoss Application Server 7 community documentation.
JBoss Application Server 7 - Management Clients
These Management Clients share a common and lower level utilisation of the Management API, which is also documented in the community documentation.
JBoss Application Server 7 - Management API
To make these low level changes via a client utilising the existing API, the server must be running, as described in the documentation.

Operation requests allow for low level interaction with the management
  model. They are different from the high level commands (i.e.
  create-jms-queue) in that they allow you to read and modify the server
  configuration as if you were editing the XML configuration files
  directly.

Put simply, you don't need an API to make edits to a plain text file. You can accomplish this far easier by utilising filesystem toolchains or scripting instead.

A: You can take benefits from this simple Java based API to make changes to standalone.xml programmatically.
Jboss Controller Operation Executer