text:
Q: Limit of Bernoulli R.V.s is a singular distribution Working through an exercise in Probability (the question can be found in Lamperti).
Let $X_1,\dots$ be independent Bernoulli random variables with $\mathbb{P}(X_i=1) = p$ and $\mathbb{P}(X_i=0)=1-p$. Let $$Z = \sum_{k=1}^\infty X_k 2^{-k}$$ and $F_p(x) = \mathbb{P}(Z \le x)$.
Show that if $p = 1/2$ then $F_{1/2}(x) = x$, $0<x<1$. That is, $Z \sim U(0,1)$ and if $p\in(0,1)\setminus\{1/2\}$, then $F_p$ is continuous, strictly increasing and singular. That is, $F'_p(x) = 0$ almost-everywhere with respect to the Lebesgue measure.
We did the first part as an assignment question, where you approach it from a partial sum up to $n$ Bernoullis and take the characteristic function of that and then let $n\to\infty$. I'm not sure how to approach the singular part, because it was given as an exercise before we covered characteristic functions. Lampert hints that the distribution is singular if and only if the corresponding measure puts probability 1 on a set of Lebesgue measure 0.
Any hints or help would be appreciated! Thanks

A: This might be complicated to describe rigorously, using elementary notions, but the underlying concept is simple: almost all real numbers between $0$ and $1$, when written in binary, have equally many zeros and ones.  Because $Z$ assigns zero probability to such numbers--it favors an imbalance of zeros and ones when $p\ne 1-p$--it must have a singular distribution.
The statement in bold needs a clear definition.  I am going to sneak up on the definition by developing a series of simpler definitions and notations.  But before we proceed, let's look at some of these distributions.

The colored curves plot the CDFs.  They are all self-similar in the sense suggested by the underlying rectangles: The curve in the lower left rectangle is obtained by taking the entire curve and multiplying all x-values by $1/2$ and multiplying all y=values by $1-p$.  That is, the curve is shrunk towards the origin $(0,0)$ by factors of $1/2$ and $1-p$.   Likewise, the curve in the upper right rectangle is obtained by shrinking the entire curve towards the coordinate $(1,1)$ by factors of $1$ and $p$.  (This description completely determines each curve!)
Here are the major steps in the analysis.

*

*Let $a_1, a_2, \ldots, a_n$ be any sequence of zeros and ones.  It represents a binary number in the interval $[0,1)$ by "putting a binary point in front of it."  As a matter of notation, and to define precisely what this means, let $$[a_1\,a_2\,\cdots\,a_n] = a_1 2^{-1} + a_2 2^{-2} + \cdots + a_n 2^{-n}.$$

*Since we will be studying the proportions of ones within binary representations, let's invent a notation for that.  Define  $$\rho([a_1\,a_2\,\cdots\,a_n]) = \frac{\#\{i \in \{1,2,\ldots, n\}\mid a_i=1\}}{n}$$ to be that proportion.

*We cannot analyze all the infinitely many binary digits of any real number $x$ all at once: we have to look at finitely many of them and take limits.  To this end, extend the function $\rho$ to entire intervals of real numbers determined by their initial sequences.  That is, if $$[a_1\,a_2\,\cdots\,a_n] \le x \lt [a_1\,a_2\,\cdots\,a_n] + 2^{-n},$$ then define $$\rho_n(x) = \rho([a_1\,a_2\,\cdots\,a_n]).$$  The functions $\rho_n$ are defined on the entire interval $[0,1)$.
If you like, you could also define the $\rho_n(x)$ numerically in terms of the binary expansion of the integer part of $2^n x$ (which is how the next figure was produced), but I thought the preceding description might give a clearer idea of the underlying concept.

*The key idea is to collect all numbers that look, based on the initial (finite!) part of their binary representation, like they have a given proportion of ones.  We should allow for that proportion to be in a narrow range, say between $\alpha$ and $\beta$ where $0 \le \alpha \le \beta \le 1$.  To this end, define the (Borel measurable) set $R$ by $$R(n,\alpha,\beta) = \{x\in [0,1)\mid \alpha \le \rho_n(x) \le \beta\}.$$  That is, the proportion of ones within the first $n$ binary digits of $x$ lies between $\alpha$ and $\beta$.
In the preceding figure, you may visualize $R(n,\alpha,\beta)$ by referring to the graph of $\rho_n$, drawing the interval $[\alpha,\beta]$ on the vertical axis, identifying all parts of the graph whose heights are within that interval, and looking down at the horizontal ($x$) axis to see which numbers correspond to those heights: that (highly disconnected) set is $R(n,\alpha,\beta)$.

*At this point we may leave the world of binary representations and focus on the digits themselves.  When those first $n$ binary digits are generated by $X_1, X_2, \ldots, X_n$, each having a chance $p$ of being $1$, then the proportion of ones has a Binomial$(n,p)$ distribution.  Thus, unless $X_{n+1}=X_{n+2}=\cdots = 1$, $$\rho_n(Z) = \rho[X_1\,X_2\,\cdots\,X_n] \sim \frac{1}{n}\text{Binomial}(n,p).$$  We may exclude all values of $Z$ that end in all ones because (as is easy to see and show) their chance of occurring is zero.

*Consequently, writing $F_{n,p}$ for the Binomial$(n,p)$ distribution function, $$\mathbb{P}(Z \in R(n,\alpha,\beta)) = F_{n,p}(n\beta) - F_{n,p}(n\alpha).$$

*Now suppose $p\ne 1/2$.  Pick $\alpha,\beta$ such that $p\in[\alpha,\beta]$ but $1/2\notin[\alpha,\beta]$.  It is easy to prove (in many ways, ranging from the Weak Law of Large Numbers to Chebyshev's Inequality) that as $n$ grows large, the value of $F_{n,p}(n\beta)-F_{n,p}(n\alpha)$ approaches $1$: that is, the Binomial distribution becomes concentrated around its expected value $p$.  This means as $n$ grows large, all the probability of $Z$ becomes concentrated within the (very complicated union of intervals) $R(n,\alpha,\beta)$.

*However, the result for the case $p=1/2$ (for which the distribution of $Z$ is Lebesgue measure) shows that the Lebesgue measure of $R(n,\alpha,\beta)$ approaches zero.  Together with (7) we conclude that for $p\ne 1/2$, the distribution of $Z$ is singular (with respect to Lebesgue measure).

*In fact, the same argument shows that the various distributions of $Z$ for any two different $p$ are all mutually singular: as $n$ grows large, the probability of one concentrates within a region that has vanishingly small probability for the other.

Example R code to plot one of these distribution functions follows.  Function f generates the sequence of integers $n\rho_n(0), n\rho_n(2^{-n}), n\rho_n((2)2^{-n}), \ldots, n\rho_n((2^n-1)2^{-n}).$  These count the number of $X_i$ for $i=1,2,\ldots, n$ that are equal to $1$. It then computes the associated probability and accumulates it to approximate the CDF of $Z$ across an equally-spaced set of $2^n$ points in the interval $[0,1]$.  This process emulates the self-similarity transformation described at the beginning of this answer.
#
# The distribution function, approximated to an accuracy of 2^(-n) in Z.
#
f <- function(n, p=1/2) {
  y <- rep(0, 2^n)
  if (n > 0)
    for (i in 1:n) {
      j <- 1:(2^(i-1)); y[j + 2^(i-1)] <- y[j] + 1
    }
  cumsum(p^y * (1-p)^(n-y))
}
#
# Example: plot a distribution for given `p`.
#
n <- 11
p <- 1/6
z <- c(0:(2^n) / 2^n)
Probability <- c(0, f(n, p))
plot(z, Probability, type="S")


text:
Q: How can I get a reference to my deployed verticle after deploying it with Vertx? I have a service called TestService which extends AbstractVerticle:
public class TestService extends AbstractVerticle {
  @Override
  public void start() throws Exception {
    //Do things
  }
}

I then deploy that verticle with vertx like this:
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(TestService.class.getName());

How can I get a reference to my deployed TestService after vertx instantiates it?

A: You should use an alternative method for deployment:
vertx.deployVerticle(TestService.class.getName(), deployment -> {
  if (deployment.succeeded()) {
    // here is your ID
    String deploymentId = deployment.result();
  } else {
    // deployment failed...
  }
});

If you're just interested in listing all deployed verticles then you can just request the list of ids:
vertx.deploymentIDs()

A: I know this question is old however it may be useful to someone to see an example of how to do this.
You will often see examples for deployment like this  from vertx-examples
this follows as asynchronous micro service framework, however its really easy to get the reference as the method 'deployVerticle' (see line 29 in the link) will take an instance as shown in the simple example below, and u can get a reference in the call back as shown.
example in Kotlin easily translate to java
MyVert: io.vertx.core.AbstractVerticle() {
    override fun start() {
    // init
     }
    fun someFunction() {
    }
}

fun main() {
 val vertx = Vertx.vertx()
 val myVert = MyVert()

 vertx.deployVerticle(myVert) {
    if(it.succeeded()  ) {
        myVert.someFunction()
    }
    else { println(it.cause().localizedMessage)}   }
}

A: you can get all deployed verticles in current vertx instance by this way
Set<String> strings = vertx.deploymentIDs();
strings
    .stream()
    .map(id -> ((VertxImpl)vertx.getDelegate()).getDeployment(id))
    .forEach(deployment -> System.out.println(deployment.verticleIdentifier() + " " + deployment.isChild() ));

A: Looks like the vertx API does not allow you to retrieve the Verticle objects once they are deployed. Maybe because verticles can be distributed over multiple JVM.
I needed to do it for unit tests though and I came up with this.
This is unreliable since you rely on VertxImpl (it can break at any vertx version upgrade). But I prefer this over changing production code to be able to test it.
private static <T extends Verticle> List<T> retrieveVerticles(Vertx vertx, Class<T> verticleClass) {
    VertxImpl vertxImpl = (VertxImpl) vertx;
    return  vertxImpl.deploymentIDs().stream().
            map(vertxImpl::getDeployment).
            map(Deployment::getVerticles).
            flatMap(Set::stream).
            filter(verticleClass::isInstance).
            map(verticleClass::cast).
            collect(Collectors.toList());
}

Usage example:
vertx.deployVerticle(new MainVerticle());
// some MyCustomVerticle instances are deployed from the MainVerticle.start
// you can't reach the MyCustomVerticle objects from there
// so the trick is to rely on VertxImpl
List<MyCustomVerticle> deployedVerticles = retrieveVerticles(vertx, MyCustomVerticle.class);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my WordPress lost password redirect to 404 aswell I been working on a Wordpress PHP code which redirect the wp-admin to another URL string for example. it would change wp-admin to wp-login.php?mysecretstring=login. This works fine however which it comes to another URL like wordpress reset password & incorrect passwords it redirects to a 404 (wp-login.php?action=lostpassword). Is it possible to exclude the lost password url or change it?
function protection_login_page() {
        global $redux_demo;
        $QS = $redux_demo['zx-wpadmin-protect-key'];
        $httpconnection = $redux_demo['zx-wpadmin-protect-http'];
       /* $QS = '?mysecretstring=foobar';*/
        $theRequest = $httpconnection . $_SERVER['SERVER_NAME'] . '/' . 'wp-login.php' . '?'. $_SERVER['QUERY_STRING'];
        $theRequestlost = $httpconnection . $_SERVER['SERVER_NAME'] . '/' . 'wp-login.php?action=lostpassword' . '?'. $_SERVER['QUERY_STRING'];

        if ( site_url('/wp-login.php').$QS == $theRequest )  {
            echo '
Redirect Working
';
        } elseif ( site_url('/wp-login.php?action=lostpassword').$QS == $theRequestlost ) {

        }else {
            header('Location:/404.php');
        }
    }
    add_action('login_head', 'protection_login_page');


text: Q: Getting the filesize in spark I want to get the size of a file in Spark without pouring it into an RDD. How Can I do that? I don't  want to pour it into a RDD since it can cause an overload to my application and my files are large.


text:
Q: How to get the first revision without having a delete button?

        Delete
        Cancel
        Save

The first revision or revision A should not have a delete button. Every other revision needs to have one, so that's revision B, C, etc. Does anyone have any ideas on how i can do this?
The above part is the footer for the summary revision dialog. It includes the action buttons of save, cancel, and delete. Delete button is the main focus here.
The below part is the JavaScript controller code that tells what the button to do. When the revision is opened it will display the original revisions details along with which revision this is. the close function is simple, just simply closing the dialog without saving the entered and changed information. The save function is also pretty simple, saves the entered data and will show the changes when the save button is clicked on. The Delete function will delete the current revision and move back the the revision before it, so for example, deleting revision C will display revision B. But what I am trying to do is hide the delete button on Revision A(the first revision) so it will not delete the initial revision and keep the delete button display for any other revision.
Thank you developers for your help.
angular.module('Comet').controller('RevisionEditController', function ($scope, $rootScope, $objectExtensions, $odataModel, $validation, $toast, ProposalsService, ErrorsService) {
const DIALOG_SEL = '#revisionEditDialog';
$scope.originalRevision = null;
$scope.revision = null;

/**
 * Opens the dialog.
 * @param {number} proposal - The proposal that the revision is for.
 * @param {object} [revision] - The existing revision to edit. Null when creating a new revision.
 */
$scope.open = function (proposal, revision) {
    $scope.originalRevision = new $odataModel.ProposalDetail(revision);
    $scope.revision = new $odataModel.ProposalDetail(revision);
    $scope.revision.rev = revision ? revision.rev : getNextRevision(proposal.proposalDetails);
    $scope.revision.proposal = {
        id: proposal.id
    };

    $(DIALOG_SEL).modal('open');
};

/**
 * Closes the dialog.
 */
$scope.close = function () {
    $(DIALOG_SEL).modal('close');
};

/**
 * Saves the revision.
 */
$scope.save = function () {
    if ($validation.validate($scope.revisionEditForm)) {
        $rootScope.dataReady = false;

        if ($scope.revision.id) {
            ProposalsService.editProposalDetail($scope.revision.proposal.id, $scope.revision.id, $scope.originalRevision, $scope.revision)
                .then(onSaveSuccess, onSaveFailure);
        } else {
            ProposalsService.addProposalDetail($scope.revision.proposal.id, $scope.revision)
                .then(onSaveSuccess, onSaveFailure);
        }
    }
};

/**
 * Deletes the revision.
 */
$scope.delete = function () {
    ProposalsService.deleteProposalDetail($scope.revision.proposal.id, $scope.revision.id)
        .then(onDeleteSuccess, onDeleteFailure);
};

/**
 * Calls the revision updated callback and closes the dialog.
 * @param {object} updatedRevision - The updated revision.
 */
function onSaveSuccess(updatedRevision) {
    $scope.$ctrl.onRevisionUpdated({ revision: updatedRevision });
    $scope.close();
    $rootScope.dataReady = true;
}

/**
 * Displays an error message and logs the exception.
 * @param {object} ex - The exception to log.
 */
function onSaveFailure(ex) {
    $toast.error('There was an error saving the revision. Please try again.');
    ErrorsService.log(ex);
    $rootScope.dataReady = true;
}

/**
 * Calls the revision deleted callback and closes the dialog.
 * @param {number} id - The ID of the revision that was deleted.
 */
function onDeleteSuccess(id) {
    $scope.$ctrl.onRevisionDeleted({ id: id });
    $scope.close();
    $rootScope.dataReady = true;
}

/**
 * Displays an error message and logs the exception.
 * @param {object} ex - The exception to log.
 */
function onDeleteFailure(ex) {
    $toast.error('There was an error deleting the revision. Please try again.');
    ErrorsService.log(ex);
    $rootScope.dataReady = true;
}

/**
 * Gets the next revision number.
 * @param {object[]} revisions - The previous revisions.
 * @returns {string} The next revision number.
 */
function getNextRevision(revisions) {
    var nextRevision = '';
    var latestRevision = revisions
        .sort(function (a, b) {
            var order = 0;

            if (a.id > b.id)
                order = -1;
            else if (a.id = 0 && increment; idx--) {
            var currLetter = latestRevision.rev[idx].charCodeAt(0);

            if (currLetter == 90) {
                nextRevision = nextRevision + 'A';
            } else {
                increment = false;
                nextRevision = String.fromCharCode(currLetter + 1) + nextRevision;
            }
        }

        if (nextRevision.length < latestRevision.rev.length) {
            nextRevision = latestRevision.substring(0, nextRevision.length - 1) + nextRevision;
        }
    }

    return nextRevision;
}

A: I assume that there is a loop where you iterate the revisions, use the loop's index to check with ngIf if the button should be shown.


text:
Q: ShrinkToFit does not expand frozen columns if grid has width to expand I'm creating a pivot table using jqgrid with group headers. I do some calculation on input data to figure out if combined column width would exceed the fixed width of grid. If it does not exceed then i would change shrinkToFit : truefor grid to occupy full width. If I do it, then dragging column width creates alignment issues between header and body.
Problem gets worse if frozen column are enabled. The fixed header div wont expand like the column underneath it if shrinkToFit is enabled.
Here is a demo to understand the problem :  http://codepen.io/anon/pen/NbxWrQ
Any leads will be helpful.
Thanks in advance.


text:
Q: Why are some duplicate questions not closed despite my flags being marked helpful? I have flagged many questions on Stack Overflow as duplicate and the flags are dismissed as helpful by a moderator, but the questions are not closed. One example is a question regarding Android development in C#, which is definitely a duplicate of another question here, here, and here.

A: I often mark a flag as "useful" because I can understand why the flagger flagged it, but ultimately I disagree with the flag.
For example, if I see a question linking to a dupe, and it's pretty close but not close enough, I still mark it as helpful because they had a pretty valid point, and I don't want to discourage them from further flagging - even though I'm not going to action the flag.


text:
Q: Why use UART to communicate between Arduino and ESP Wi-Fi module? I have been learning about the different communication protocols used between Arduino and other components/sensors, namely, SPI, UART and I2C. I want to add Wi-Fi to my Arduino UNO project using ESP8266 (for now, and maybe later upgrade to an ESP32 as it's more powerful).
But i am wondering why in all the schematics that i have seen in my online research, the Arduino is always connected to the ESP8266 module via UART? Why not use SPI or I2C? Why is UART (apparently) considered superior for ESP communication with the Arduino over the two other communication protocols?
Thanks in advance for the help.

A: UART offers two way communication with just 2 wires.
I2C is one way communication for 2 wires. It can be made two way by implementing a custom notify mechanism where slave sends a signal whenever it has some data to send using a GPIO connection. This requires another pin and hence 3 wires for two way communication as compared to two in UART. Another alternative is polling as pointed out in comments below. Personally I prefer interrupt driven flow over polling. However if you are OK with polling, 2 wires can indeed do the job.
SPI requires a minimum of 4 wires. (Maybe 3 wires in case of single slave as Elliot commented)
Given the limited number of pins available on esp modules, I guess community might have chosen to use UART as the primary data transfer mechanism. Plus UART is simpler to implement than other counterparts. (This line could be opinion based so please pardon me if you tend to disagree)
It's possible to use esp modules as a stand alone MCU for general projects. You can use port expanders in case more GPIOs are needed. I used a similar architecture in one of my projects. I used esp-arduino for developing the firmware inside arduino IDE itself.


text:
Q: Why is this statement false? Can someone provide or direct me to a proof? Question:
True or False: If $a = b$, then $||ai + bj|| =sqrt(2a)$
Answer:
False:$||ai + bj|| = sqrt(a^2 + b^2) = sqrt(2)||a||$

A: Suppose as stated that $a = b$. Try setting $a < 0$ as said by Jonathan in the comments. You should find that both sides of the equation don't hold. Secondly, it is possible to prove the alternative answer.
\begin{align*}
    \|ai + bj\| &= \sqrt{a^2 + b^2}\\
                &= \sqrt{a^2 + a^2}\\
                &= \sqrt{2a^2}\\
                &= \sqrt{2}\sqrt{a^2}\\
                &= \sqrt{2}\|a\|
\end{align*}


text:
Q: How to clear NextJs GetStaticPaths cache / "unpublish" a dynamic route? I think this is quite a vanilla question but I can't find anything on Google.
I'm learning NextJs (using TypeScript) and I've got a site successfully working with dynamic routes, SSR, and incremental regeneration all setup and deployed to Vercel. Here's an example of the GetStaticProps and GetStaticPaths code in my dynamic route handler:
export const getStaticPaths: GetStaticPaths = async () => {
    const routes = new CmsHelper().GetRoutes();

    const paths = (await routes).items.map((item, index, items) => {
        return item.fields.urlPath;
    })

    return {
        paths: paths,
        fallback: 'blocking',
    };
}

export const getStaticProps: GetStaticProps = async (context) => {
    const urlParts = context.params?.url as string[] || [];
    const urlPath = `/${urlParts.join('/')}`;
    const article = await new CmsHelper().GetArticle(urlPath);
    return {
        props: {
            article
        },
        revalidate: 10,
    }
}

If I request a new path that was published in the cms after build time, it successfully regenerates on the server and returns the page.
So far so good.
However, if I unpublish a route in my CMS... it is still returned by the app, unless I rebuild and redeploy (or otherwise cause the process to restart, in dev).
So my question is: how do I dynamically cause NextJs to remove a dynamic route from its GetStaticPaths cache?
I understand that GetStaticProps is going to be called at most once every 10 seconds because of the revalidate configuration. But as far as I know, GetStaticPaths will only be called if a request comes in from a route that is not currently cached(?)
In other words, for an integration with a headless CMS, how can I support unpublishing or renaming pages with NextJs without triggering a rebuild/deploy?
Thanks in advance!

A: Maybe try this approach described here.
Also providing the code here for reference purposes.
// pages/blog/[slug].js

import {useRouter} from 'next/router'
import DefaultErrorPage from 'next/error'

export async function getStaticProps({ params }) {
  // fetch data from CMS through params
  const post = await getBlogItem(params.slug)
  return {
    props: {
      post
    }
  }
}

export async function getStaticPaths() {
  return {
    fallback: true,
    paths: []
  }
}

export default function MyPage({post}) {
  const router = useRouter()

  if(router.isFallback) {
     return
Loading...

  }

  // This includes setting the noindex header because static files always return a status 200 but the rendered not found page page should obviously not be indexed
  if(!post) {
    return <>

        <meta name="robots" content="noindex">

      <DefaultErrorPage statusCode={404} />
    </>
  }

  return
{post.title}

}

So, instead of deleting/clearing the cache, maybe try to handle successfully that the content you are fetching is "unpublished" and if so, you can display a 404 Not found page or something of your choice.
Something like this:
export async function getStaticProps(context) {

    const {params: {id}} = context

    let data;
    try {
        data = await httpClient...
    } catch (err) {
        if (not err is caused due to content being unpublished){
            // re throw it
            throw err;
        }
        // Else handle it gracefully
        data = null;
    }

    return {
        props: {
            data,
        },
        revalidate: 1
    };
}

and then on your View:
export default function Data(props) {
    const {data} = props;

    const router = useRouter()

    // If the page is not yet generated, this will be displayed
    // initially until getStaticProps() finishes running
    if (router.isFallback) {
        return
Loading...

    }

    if (!data) {
        return (
            <>

                    <meta name="robots" content="noindex"/>

                <DefaultErrorPage statusCode={404}/>
            </>
        )
    }

    return <DataView {...data} />;

}

A: I was facing a similar but different problem: Deploying my project generated URL from the data, but I couldn't add any new URLs when the data in the DB changed.
The key to my problem was that I was setting fallback to false in my getStaticPaths method. When I set it to true the production deploy started behaving like my local development build.
I see that you're passing a string value for your fallback property. You might try using a boolean value as described here: https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required

A: With Next.js 12.2 released in summer 2022 you can use On-Demand Incremental Static Regeneration to update generated pages on demand, i.e. when you publish changes in your headless CMS and use its webhook features.
// pages/api/revalidate.js

export default async function handler(req, res) {
  // Check for secret to confirm this is a valid request
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' })
  }

  try {
    // this should be the actual path not a rewritten path
    // e.g. for "/blog/[slug]" this should be "/blog/post-1"
    await res.revalidate('/path-to-revalidate')
    return res.json({ revalidated: true })
  } catch (err) {
    // If there was an error, Next.js will continue
    // to show the last successfully generated page
    return res.status(500).send('Error revalidating')
  }
}

https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#using-on-demand-revalidation


text:
Q: PHP "include" fails (redux) Sorry for another "php include" chapter but searching on that gives some 90,000 entries and I feel like I've read 1/2 of 'em.
I'm resurrecting a web page I wrote some 9 years ago on Win 2000 Pro.  Since then I've easily ported it to Ubuntu 10.0, Windows 7 and published it online through 2 different hosting sites.  Now I'm on Ubuntu 14.04 and I cannot get the php "include" command to work.  The code is as follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Main Menu movietime.php</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<?php error_reporting(E_ALL);?>

<form method="post">
<input type="hidden" name="hiddenn" value="hide & ">
<hidden name="hidden" value="well hid">
</form>

<?php
include dirname(__FILE__).'menu.php';
?>

Movie Database

Main Menu

<?php
echo '
'.$status.'
';
?>

The problem here is that the include for 'menu.php' never happens so the links to the rest of the application don't appear.  The code for menu.php is:

Home Page
Create Movie Table
Delete Movie Table
List
Add Movie
Delete Movie

The follow-on php statement to display the $status always works.  I'd like to show you the resultant page but I don't have enough points to do so ( I think ... first time on here ).
Things I have tried are:

*

*ctrl-u on Firefox shows the source.  The source displayed by ctrl-u
is no different than the original code.

*I set up a php_errors.log file in /var/log and pointed to it within
php.ini.  Nothing ever goes into it.  Permissions are 755.  I even
misspelled "include" and still no errors.

*Substituted php.ini_development for php.ini and still no go.
(error_reporting and display_errors were enabled in both).

*I tail -f the Apache access.log in one xterm window and tail -f
the error.log in another. The only time I see output in error.log is when
I shutdown/startup Apache.  The only time I see output in access.log
is when I reload the page.  It shows a GET for movietime.php and a
GET for wood.gif and that's it.

*Tried substituting a full directory reference for "dirname(FILE)" in the include statement ... nogo.
Don't know what else to do at this point.  I'm running Apache 2.4.7 and PHP 5.5.9
I look forward to any and all suggestions / insights.
--thanks
  --Gary

A: Make sure that your urls have an absolute path, like:
/path/file.php
not
path/file.php


text:
Q: The definition and direction of an energy function, related to the direction of a trajectory, for the ode $\ddot x + 2\epsilon \dot x + x = 0$. This is from Glendinning's book Stability, Instability and Chaos, Example 1.2.
For the ode $\ddot x + 2\epsilon \dot x + x = 0,$ let $y = \dot x$, let $E(x,y)$ be a conserved function (like energy) $\frac12(x^2+y^2)$, then $\frac{dE}{dt} \leq 0. \quad(R1)$
It is argued that from this we expect 'all trajectories tend to minima of $E$ .. (0,0).'
$\\$
Why is the argument valid?
It seems that $E(x,y)$ does not decrease along the curve described by $E(x,y) = C$, but along any trajectory $(x(t),y(t))$ described by the above ode (proof: (R1) shows that the changes of $E$ and $t$ are opposite, and so along the positive direction of the curve $t$ increases suggesting $E$ must decrease?), without exception. And so the direction of $E$'s decreasing could be used to indicate the rough direction of the trajectories.
Therefore, it seems reasonable to argue that the trajectories would end up somewhere $E$ is small.
But why necessarily (0,0) where $E$ is minimum. Would not it be possible that a trajectory stop midway?
$\\$
Besides, the reason that $E$ is called the energy is that it describes the movement of points along the trajectory? Must it also be a conserved function? Can $E$ be any other such function? How to define 'conserved' for an energy function?
BTW, is this (a function decreasing along parametrized curves+conserved) actually the more accurate definition of energy than those in the common conception? And how is it related to the energy in differential geometry and Hamiltonian mechanics, where the geodesic is indicated by the minimum of energy function? Are the two energies consistent?

A: $E$ is defined this way in association to the energy of a mechanical system, acceleration or force equal to the gradient of the potential energy and a friction term. Or one could see the equation as a perturbation of the conservative case $ϵ=0$.
For a Lyapunov functional you could more generally also use
$$
E=\frac12\dot x^2+px\dot x+\frac{q}2x^2
$$
leading to
\begin{align}
\dot E&=(\dot x+px)\ddot x+p\dot x^2+qx\dot x
\\
&=-(\dot x+px)(2ϵ\dot x+x)+p\dot x^2+qx\dot x
\\
&=(p-2ϵ)\dot x^2+(q-2ϵp-1)x\dot x-px^2.
\end{align}
So that for instance $p=ϵ$ and $q=1+2ϵ^2$ gives
$$
E=\frac12(\dot x+ϵx)^2+\frac12x^2,~~\dot E=-ϵ(\dot x^2+x^2),
$$
which gives a more strict descent condition.


text:
Q: Nontrivial lower-bound for $\inf_{x \in \Delta_n} \|Gx\|$ Let $G$ be and $m \times n$ matrix of full-rank $n \le m$ in particular, and let $\Delta_n := \{x \in \mathbb R^n \mid x_1,\ldots,x_n \ge 0,\;\sum_{i=1}^n x_i = 1\}$ be the $(n-1)$-dimensional unit simplex. Define $s(G)$ by
$$
s(G) := \inf_{x \in \Delta_n} \|Gx\|.
$$

Question. Is there a nontrivial lower-bound for $s(G)$ in terms of simpler quantities (say, it terms of a function of the singular-values of $G$, etc.) ?

For a trivial bound, note that
$$
s(G) \ge \inf_{x \in \Delta_n} s_{\min}(G)\|\cdot\|x\| = s_{\min}(G) \cdot \inf_{x \in \Delta_n} \|x\| = s_{\min}G)/\sqrt{n},
$$
where $s_{\min}(G) := \inf_{\|x\|=1} \|Gx\|$ is the least singular-value of $G$.

A: You can get a lower bound by omitting the nonnegativity constraint. The problem becomes:
$$\min_{x \in \Delta_n} \{ x^T G^TG x : e^Tx = 1 \}.$$
Note that this is a convex optimization problem that satisfies the Slater condition, so the KKT conditions are necessary and sufficient. The Lagrangian is $L(x,y) = x^T G^TG x + y(e^Tx - 1)$, and setting its derivatives to $0$ results in the following KKT system:
$$\begin{pmatrix}2G^TG & e \\ e^T & 0\end{pmatrix} \begin{pmatrix}x \\ y \end{pmatrix} = \begin{pmatrix} 0 \\ 1 \end{pmatrix}.$$
Solving for $x$ and computing $||Gx||$ gives a lower bound.
Instead of solving via the Lagrangian, you can also eliminate the last element of $x$ by writing it as $x_n = 1-e^T\tilde{x}$, which gives an unconstrained quadratic objective function.

A: This is a follow-up on LinAlg's answer (accepted!).

Claim. The bound in the accepted answer is always better than my trivial bound $s(G) \ge s_\min(G)/\sqrt{n}$

Proof. As carefully observed in the accepted answer, we can drop the nonnegativity constraint and get a lower-bound, namely $s(G)^2 \ge \min \{x^TG^TGx \mid e^Tx = 1\}$. Now, let $R \succ 0$ a square-root of $G^TG$. Thus $R$ is a positive-definite matrix such that $G^TG = R^2$. Consider the change of variable $z = Rx$. We then get
$$
\begin{split}
s(G)  &\ge \min \{\sqrt{x^TG^TGx} \mid e^Tx = 1\} = \min\{\|z\| \mid (R^{-1}e)^Tz = 1\}\\
&= \text{dist}(0,\{z \in \mathbb R^n \mid (R^{-1}e)^Tz = 1\}) = \frac{1}{\|R^{-1}e\|} = \frac{1}{\sqrt{e^T(G^TG)^{-1}e}},
\end{split}
$$
That is, $s(G) \ge \dfrac{1}{\sqrt{e^T(G^TG)^{-1}e}}$. To see that this is a better lower-bound, note that
$$
\frac{1}{\sqrt{e^T(G^TG)^{-1}e}} \ge \frac{1}{\sqrt{\lambda_{\max}((G^TG)^{-1})}\|e\|} = \frac{\sqrt{\lambda_\min(G^TG)}}{\|e\|} = \frac{s_\min(G)}{\sqrt{n}}.
$$


text:
Q: Cannot get .NET winforms app to open to help topic in a CHM file I have a vb.net Winforms application.  I also have a compiled help file (chm) file that I created using RoboHelp 6.0.
I want to open to a specific help topic and so to do that I am using the following code.
System.Windows.Forms.Help.ShowHelp(Me, "MyHelpFile.chm",HelpNavigator.KeywordIndex, "MyTopic")
Of course I am using variable instead of string literals ... work with me here   ; / )
In this case the Help file opens to the Index in the left pane and the topic is selected in the Index pane but the right (Content) pane is showing the Main/First page of the help file...not my topic.
I have tried every combination from the HelpNavigator enum and none of them work.  Only a few of them should work since most of them are not designed to open to a specfic topic...but for the ones that should work here is the result.
HelpNavigator.Topic  -  When I use this option I get the left pane opens to the TOC with everything collapsed and nothing selected.  The right pane gives a standard IE error:
"This program cannot display the webpage

   Most likely causes:
You are not connected to the Internet.
The website is encountering problems.
There might be a typing error in the address.

   What you can try:
     Check your Internet connection. Try visiting another website to make sure you are connected.

     Retype the address.

     Go back to the previous page.

     More information "

HelpNavigator.TopicID - I cannot try because as far as I can tell my topics do not have Topic IDs.
Here are my questions -
Any ideas what is wrong?  How can I troubleshoot help file issues?  (For example, validate that the topic exists in the help file?  I am sure it is in the source but it doesn't seem to find it in the compiled version.  If you double click the topic in the index or TOC it opens just fine.)
My ideal solution would be to open the TOC in the Left pane with the topic selected (but I will settle for Index int the left pane) and the Right pane shows the Topic content.
Seth

A: The following link has the explanation--
http://www.cmcandrew.com/robocolumn/the-perils-of-context-sensitive-help/
You have to add a map id and alias it to a topic.
Seth

A: The problem is one of permissions.
If a help file was downloaded from the Web or comes from a Zip file that was downloaded from the Web, the file will be blocked which manifests with the behavior you describe: The content pane displays an error.
To fix this go into Explorer right click the CHM file, and then click on the Unblock option on the bottom right of the dialog.
To fix this problem correctly, you need to ensure you install the CHM file as part of an installation process which tells Windows that the file is safe to use. Avoid direct installation from a zip file of internet downloaded content into a folder.
More detailed info here:
http://weblog.west-wind.com/posts/2012/Jan/11/Problems-with-opening-CHM-Help-files-from-Network-or-Internet


text:
Q: How to mimic click event of anchor tag in Vaadin flow? I am able to use Upload Component to upload file from page to my file system like below.
          return (MultiFileReceiver) (String fileName, String mimeType) -> {
          try {
              File file = new File(uploadFileDirectory,fileName);
              return fileOutputHandlerService.fileOutput(file);
          } catch (Exception e) {
              throw new RuntimeException(e);
          }
      };

But when it comes to download that file with given path I can't accomplish that.
Only explanation to do that is using Anchor element. but I want to use ContextMenu component to trigger a download .
I have a contextmenu Component derived from a Grid
 fileListContext = grid.addContextMenu();
 fileListContext.addItem("Download",uiListener.fileDownloadRequestListener());

I implemented that context menu listener like below. I want to click that context menu pop up and prompt browser to open save location for user to start download.
        private  ComponentEventListener <GridContextMenu.GridContextMenuItemClickEvent<FileEntity>>  fileDownloadRequestListener(){
      //created stream user and anchor element. how to trigger download attribute of anchor?
      return selectedFile-> {
          StreamResource resource = new StreamResource(selectedFile.getItem().get().getFileName(),
                  ()->fileInputHandlerService.fileInput(selectedFile.getItem().get()));
          anchor = new Anchor(resource,"a");
          anchor.getElement().setAttribute("download",true);
          anchor.setVisible(true);
          add(anchor);
      };
    }

A: Just adjust your fileDownloadRequestListener to this and it should work:
    private ComponentEventListener<GridContextMenu.GridContextMenuItemClickEvent<FileEntity>> fileDownloadRequestListener() {
        return selectedFile -> {
            StreamResource resource = new StreamResource(selectedFile.getItem().get().getFileName(),
                    () -> fileInputHandlerService.fileInput(selectedFile.getItem().get()));
            anchor = new Anchor(resource, "a");
            Element element = anchor.getElement();
            element.setAttribute("download", true);
            // Hide the anchor from the user
            element.getStyle().set("display", "none");
            add(anchor);
            // Trigger click and remove when ready
          element.executeJs("return new Promise(resolve =>{this.click(); setTimeout(() => resolve(true), 150)})", element).then(jsonValue -> remove(anchor));
    }

A: Anchor download = new Anchor();
download.add(downloadButton);
download.getElement().setAttribute("download", "Hscodelistdownload.xlsx");
downloadButton.addClickListener(e -> {

                 StreamResource resource = new StreamResource("Hscodelistdownload"+System.currentTimeMillis()+".xlsx", Exporter.exportAsExcel(grid));
                   download.setHref(resource);
                   Element element = download.getElement();
                   element.setAttribute("download", true);
                   element.getStyle().set("display", "none");
                   element.executeJs("return new Promise(resolve =>{this.click(); setTimeout(() => resolve(true), 150)})", element).then(jsonValue -> remove(download));
                   StreamRegistration regn = VaadinSession.getCurrent().getResourceRegistry().registerResource(resource);
                   UI.getCurrent().getPage().open(regn.getResourceUri().toString());

            });
add(downloadButton);


text:
Q: How to go to certain part of android database I am tying to do something if row 1 in the database is created and if its not created something else is done. its in a septate file called data.java
i want something like
if( data.ROW_ID !- 1 {
//do something
}
else{
//do this
}

A: Possibly something like this?
Cursor mCursor = mDatabase.query("tablename", null, "ROW_ID = 1", null, null, null, null);
if(mCursor.getCount() == 0){
   //do whatever
} else {
   //do different thing
}


text:
Q: Can JQuery Form Wizard submit 'pages' that haven't been shown? I'm using the JQuery Form Wizard plugin without a final AJAX submit, just a regular POST. Using AJAX isn't feasible due to the complexity of the final form processing code.
The problem is that on an error I need to redisplay the form, and jump the user to the correct page with formwizard('show', 'spanid' ). The problem is that then the wizard counts all the other steps as not viewed and doesn't re-submit their input values when the user re-submits.
I have considered copying all the other inputs into the page being displayed as hidden fields but really this isn't feasible, there are too many complex variables involved.
Does anyone know if it's possible to instruct the plugin to submit all inputs regardless of whether they're on a skipped page?
Thanks.

A: I am not sure about your question but so far what I found is you want to submit the for regardless of validation.
In form wizard you can use "formOptions" property to define your own submition.
even if its not ajax you can simply use some script to redirect.
Hope it helps :-)
Reards,
 Amjad


text:
Q: How to create fallback if value is not found in JSON when saving to state React This is my get request which grabs a few different JSON end points:
// Grabs the posts from the json url
private getPosts() {
   axios
      .get( this.getCompanyUrl() )
      .then(response =>
        response.data.map(post => ({
          id: `${ post.Id || post.jobId }`,
          name: `${ post.Name || post.advertisements[0].title.localization[0].value }`,
          name2: `${ post.Name || post.title.localization.pop().value }`,
          //location: `${ post.Location || post.department.title.localization[0].value || 'Fall back location' }`,
        }))
      )
      .then(posts => {
        this.setState({
          posts,
          isLoading: false
        });
      })
       // Error catching
      .catch(errors => this.setState({ errors, isLoading: false }));
}

If a location is not found in the JSON, I want to add a fallback location, however it does not seem to be working:
Line 214 >> location: `${ post.Location || post.department.title.localization[0].value || 'Fall back location' }

I receive this error, even when there should be a fall back working:

    TypeError: Cannot read property 'title' of undefined
    at JsonFeed.tsx:214
    at Array.map ()
    at JsonFeed.tsx:210

Any ideas where I am going wrong?

A: If your app supports optional chaining then you could do it like this:
post.Location || post.department?.title?.localization?[0]?.value || 'Fall back location'

Otherwise, you could use the old-school style:
post.Location ||
(
  post.department &&
  post.department.title &&
  post.department.title.localization &&
  post.department.title.localization[0] &&
  post.department.title.localization[0].value
) ||
'Fall back location'


text:
Q: Tree roots doctrine I want to get roots of tree in database, it works correctly but problem is here that it query database 500 times for 500 nodes, is there a way to improve this?
$query = $this->createQueryBuilder('n')
            ->where('n.parent IS NULL')
            ->getQuery();`

entity structure:
Radio\ArchiveBundle\Entity\Category:
    type: entity
    table: null
    repositoryClass: Radio\ArchiveBundle\Repository\CategoryRepository
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        name:
            type: string
            length: 255
        isActive:
            type: boolean
            nullable: true

    oneToMany:
        tracks:
            targetEntity: Radio\ArchiveBundle\Entity\Track
            mappedBy: category
    manyToOne:
        parent:
            targetEntity: Radio\ArchiveBundle\Entity\Category
            inversedBy: childrens
            fetch: EAGER
    oneToMany:
        childrens:
            targetEntity: Radio\ArchiveBundle\Entity\Category
            mappedBy: parent
            cascade: [persist, remove]

Symfony2 profiler image:

A: Why 500 queries?
As you say, you've fetched 500 root nodes from the database. Somewhere in the request the property Category::$childrens is accessed. Probably in a view by calling a method on Category that uses that property (like $node->getChildren()).
Accessing that property means that Doctrine will need to load the Collection in order to fetch the children of that node. This results in a query for each root node. Hence you have 500 additional queries.
If you need to access the children, it's wise to fetch them immediately when querying for the root nodes:
SELECT rt, chld FROM Category rt LEFT JOIN rt.childrens chld WHERE rt.parent IS NULL

This way the direct children of the root nodes are hydrated along with the root nodes themselves. You'll have reduced the number of queries from 501 to just 1.
PS: The plural form of "child" is "children" (not "childrens").
Nested Set model
IMHO the structure of the Category tree could be improved by switching to the Nested Set model. While it is slightly less performant when inserting new nodes to the tree, updating and selecting trees becomes significantly cheaper.
For example: Fetching an entire tree with the parent/children model you use now will need roughly 1 query for each level of depth (or 1 JOIN for each level, but this only works when the maximum depth is known). With the Nested Set model you can fetch an entire tree with just a single query (regardless of the depth). This will improve performance drastically when the level of depth increases.
Have a look at the Tree behavior of the Doctrine Extensions library, with which you can easily implement the Nested Set model. There's also a Symfony 2 bundle to integrate that library.
Simply add it to Composer and follow the instructions.
composer.phar require stof/doctrine-extensions-bundle

A: Your parent entity is eagerly fetched and has a reference with itself.
manyToOne:
    parent:
        targetEntity: Radio\ArchiveBundle\Entity\Category
        inversedBy: childrens
        fetch: EAGER

Because it is a self reference on the fields parent and children.
When fetching a category, it fetches the children as well (as you would expect). But the parent entity for these joined entity is fetched as well (when they exist). Resulting in a extra queries. This goes on and on until all the parents have been traversed.


text:
Q: Distance between a point and the origin in Poincaré Disk How to calculate the distance between the origin and the point $p=(a,0)$, $a>0$, using the metric $g = \frac{4}{(1-x^2-y^2)^2}(dx^2+dy^2)$? I don't how to use correctly these $dx^2$'s

A: You'll have to integrate along the path. $\mathrm dx^2+\mathrm dy^2$ is simply the squared length of an infinitesimally short piece of your path. The geodesic from the origin to a point on the $x$ axis will follow that axis, so you can omit those $y$s and compute the distance as
$$ d
= \int_0^a \sqrt{\frac{4}{\left(1-x^2\right)^2}\mathrm dx^2}
= \int_0^a \frac{2}{1-x^2}\mathrm dx
$$
Actually computing that integral will likely take some work. Wolfram Alpha aparently isn't up to this task. But you don't have to do this work yourself: the Wikipedia article on the Poincaré disk model mentions your formula (for arbitrary dimensions and labeled "metric tensor"), but it also has a formula where you simply plug in the norms of some euclidean vectors:
$$ d(u,v)
= \operatorname{arcosh}\left(1+2\frac{\lVert u-v\rVert^2}{\left(1-\lVert u\rVert^2\right)\left(1-\lVert v\rVert^2\right)}\right) \\
d\left(\begin{pmatrix}0\\0\end{pmatrix},\begin{pmatrix}a\\0\end{pmatrix}\right)
= \operatorname{arcosh}\left(1+2\frac{a^2}{1-a^2}\right) \\
$$
You can compute the derivative of this to check that it agrees with the integrand in the above formula. At least for positive $a$ it does, otherwise you'd need absolute values in that formula.
You can also plug that formula into Wolfram Alpha to find nicer notations. Among those listed for $a>0$ you'll find the following shorter alternative:
$$d = \log\left(\frac{1+a}{1-a}\right) $$


text:
Q: LilyPond: Is it possible to revert to "atonal" key? In LilyPond, there is a distinction between specifying \key c \major and leaving the key blank. In the former case, transposing instruments will change the key signature accordingly, while in the latter case, no key signature will be added. Using \transpose c d, for instance, will add two sharps if \key c \major is listed, but not when no key is listed.
What happens when I go from an 'open key' section to a tonal section, and back to 'open key'? I've tried \revert \key, but this seems to be bad syntax. Is there a way to revert to a key-free area?
Minimal example, which should have a key signature of one flat in the second section but no sharps or flats elsewhere:
\transpose c d {
  % Open key
  c8 e f g e d des c

  \key c \minor
  c es g es f d c b

  % How to return to open key??
  c8 e f g e d des c
}

A: On the LilyPond mailing list, I was told that there really isn't a way for this to be done—although the following is a workaround as regards the problem with transposition:
\withMusicProperty #'untransposable ##t \key c \major

This code prevents C major from being transposed.

Another workaround, which I have used, is to use tags, so that transposing scores use different keys than C scores. Here is an overview of tags: http://lilypond.org/doc/v2.12/Documentation/user/lilypond/Different-editions-from-one-source


text:
Q: CRC error-correction library? Is there a CRC library that enables the user not only detect errors but also correct them? I'm looking for a C/C++ or Java library, ideally open-source.

A: I believe that CRCs can only detect errors, not correct them.  That's certainly true of the most common implementation.  You want some kind of error correction technique, not a CRC.  I'm not aware of any libraries for doing this, but they must be easy enough to find once you know what you're looking for.

A: You don't want CRC, but FEC (forward error correction).  You can find an open source implementation in libfec.

A: The best technical solution about Error Correction is called turbocode.
See http://en.wikipedia.org/wiki/Turbo_code for more information about that.
But I'm afraid you won't find much free implementations of it.
If you really want a free one, give a try at http://rscode.sourceforge.net/

A: In reference to the following: I believe that CRCs can only detect errors, not correct them.
The writer is misinformed.  CRCs CAN be used to correct single bit errors.
C/C++ Users Journal - June 2003 - page 6.
http://www.drdobbs.com/an-algorithm-for-error-correcting-cyclic/184401662?queryText=Bill%2BMcDaniel

A: I don't think CRC is used often for error correction, however if you want to check and repair sets of files you can always try par2, which is often used on usenet. You can find a lot of documentation and implementations on the internet, for example a win32 library.


text:
Q: how to find the tangent-lines of a circle, given eq. of the circle and point of the tangents outside the circle? So I have a circle: $x^2 + y^2 = 25$ and a point $P = (7,1)$ of the tangent-lines and I have to find the equations of these tangent-lines.
So I know that the radius is $5$ and that the center is $C = (0,0)$.
I also know that the equation of a tangent-line is $y=mx+h$.
I can substitute $x$ and $y$ of $P$ in the equation of the tangent-line, so I would have $x$ and $y$ but how do I find $h$ and $m$ then?

A: The lines that contains $P$ have equations:  $y-1=m(x-7)$ and we want the lines that have only a common point with the circle $x^2+y^2=25$.
The  common points are the solutions of the system
$$
\begin{cases}
x^2+y^2=25\\
y-1=m(x-7)
\end{cases}
$$
Substituting $y$ ( or $x$) from the second to the first equation you find a second degree equation in $x$ (or $y$) and this equation has only one solution (only  one common point) iff its discriminant is null.
Note that the discriminant $\Delta(m)$ is a second degree polynomial in $m$ so The equation $\Delta(m)=0$ can have $2$ distinct solutions ( if the point $P$ is external to  the circle and we have two tangent lines), one solution ( if the circle contains $P$ so that we have only one tangent line) or no real solutions if the point $P$ is inside the circle.
Anyway, solving $\Delta(m)=0$ you find the slope of the tangents lines,  if they exist.

A: HINT: write $$y=mx+n$$ for the searched Tangent line, then we have the equation $$y=m(x-7)+1$$ plug this in the equation of the given circle then you will get
$$x^2+(m(x-7)+1)^2=25$$ solve this equation for $x$ and set the discriminant equal to Zero
you will get
$$-24m^2+14m+24=0$$ to compute $m$


text:
Q: Run command on cisco switch I made the below script to login to a switch and execute a command. as soon as i execute the script it logins to switch and exits without running the command.
#!/usr/bin/expect -f

set timeout 3000

spawn bash -c "ssh ananair@10.60.255.100"

expect "*assword:"

send "pass@123\n"

expect "*#"

send "show interfaces status"

A: I suspect the problem is the missing \n in your final send. If you simply send "string", then expect never hits Enter at the end of the command, And since there's no final expect, it figures its work is done, and exits, probably even before it has a chance to echo the command it sent but never executed.
Consider the following:
#!/usr/bin/expect -f

set timeout 3000

spawn ssh switchhostname          # no need to run this inside a shell

expect "ssword:"

send "1ns3cur3\n"                 # it would be better to use key based auth...

expect "#"

send "term len 0\n"               # tell the switch to avoid "More" prompts

expect "#"

send "show interfaces status\n"   # note the final "\n"

expect "#"                        # don't quit until the "show" command finishes

You might also consider getting access to this information via SNMP.

A: try \r instead of \n
I have my expect script that I use to login to my cisco switches for me. and then I use interact from the expect script that leaves me at the cisco prompt.
I would need to rework it to not show passwords but I can definitely help you out.
I didn't need timeouts in mine.
#!/usr/bin/expect
proc enable {} {
 expect "assword:" {
  send "<enable password>\r"
  expect "#" {
  }
 }
}

proc login {} {
 send "<login password>\r"
 expect {
  "failed" {
   send "<username>\r"
   enable
  }
  ">" {
   send "en\r"
   enable
  }
  "#" {
 }}
}
set user_computer_attached [lindex $argv 0]
set user_computer [split $user_computer_attached "@"]
spawn ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \
-oGlobalKnownHostsFile=/dev/null -o UserKnownHostsFile=/dev/null \
-oStrictHostKeyChecking=no $user_computer_attached
expect_after eof {
  wait
  spawn telnet [lindex $user_computer 1]
  expect "name:"
  send [lindex $user_computer 0]
  send "\r"
  expect "assword:" {
   login
  }
}
expect "assword:" {
 login
}
interact


text:
Q: BufferedIterator implementation Does someone know of an open source BufferedIterator, where the next N elements are eagerly fetched on a background thread?
Here is an implementation from a TechRepublic article, but I assume it has not been thoroughly tested.
Iterators.buffer(Iterator toBuffer, int bufferSize) would be a nice addition to Guava, has that been considered?

A: The linked implementation appears to have been written for Java 4 and can be simplified a little using guava and java.util.concurrent:
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

import com.google.common.base.Throwables;
import com.google.common.collect.AbstractIterator;
import com.google.common.util.concurrent.Executors;

public abstract class Iterators2 {
    public static <E> Iterator<E> buffer(final Iterator<E>      source,
                                         int                    capacity) {
        return buffer(source, capacity, defaultExecutor);
    }

    public static <E> Iterator<E> buffer(final Iterator<E>      source,
                                         int                    capacity,
                                         final ExecutorService  exec) {
        if (capacity <= 0) return source;
        final BlockingQueue<E> queue = new ArrayBlockingQueue<E>(capacity);

        // Temporary storage for an element we fetched but could not fit in the queue
        final AtomicReference<E> overflow = new AtomicReference<E>();
        final Runnable inserter = new Runnable() {
            @SuppressWarnings("unchecked")
            public void run() {
                E next = (E) END_MARKER;
                if (source.hasNext()) {
                    next = source.next();
                    // ArrayBlockingQueue does not allow nulls
                    if (next == null) next = (E) NULL_MARKER;
                }
                if (queue.offer(next)) {
                    // Keep buffering elements as long as we can
                    if (next != END_MARKER) exec.submit(this);
                } else {
                    // Save the element.  This also signals to the
                    // iterator that the inserter thread is blocked.
                    overflow.lazySet(next);
                }
            }
        };
        // Fetch the first element.
        // The inserter will resubmit itself as necessary to fetch more elements.
        exec.submit(inserter);
        Iterator<E> iterator = new AbstractIterator<E>() {
            protected E computeNext() {
                try {
                    E next = queue.take();
                    E overflowElem = overflow.getAndSet(null);
                    if (overflowElem != null) {
                        // There is now a space in the queue
                        queue.put(overflowElem);
                        // Awaken the inserter thread
                        exec.submit(inserter);
                    }
                    if (next == END_MARKER) {
                        return endOfData();
                    } else if (next == NULL_MARKER) {
                        return null;
                    } else {
                        return next;
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    return endOfData();
                }
            }
        };

        return iterator;
    }

    protected Iterators2() {
        throw Throwables.propagate(new InstantiationException(Iterators2.class + " is a static class and cannot be instantiated"));
    }

    private static ExecutorService defaultExecutor =
        java.util.concurrent.Executors.newCachedThreadPool(Executors.daemonThreadFactory());

    private static final Object END_MARKER = new Object();

    private static final Object NULL_MARKER = new Object();
}

Note: the above implementation makes no attempt to handle exceptions in the source iterator (if one is thrown, the inserter task will terminate abruptly, leaving the calling thread deadlocked.)


text:
Q: How to put default text in input fields while keeping JS form validation functionality Some jQuery plugin checks whether my form fields (text input and select) have been filled out before I can submit the form. Now I want to add default values in the fields such as "please enter your name". But if I do that, the JS plugin will validate these fields whereas in fact the user didn't enter anything in them.
I want JS NOT to validate fields containing a default value. Is it possible?

A: Use Placeholder in your fields
EX:
<input type="text" name="username" placeholder="please enter your name">


text:
Q: SOOT like program analysis tool for Javascript I have looked at this question already but a graphical representation is not exactly what I want.
Is there a SOOT like tool for Javascript that gives you an intermediate representation you can play with? Or else, is there a Javascript -> Java-bytecode -> Javascript converter? (so that I can use SOOT with Java-bytecode to do my transformations and get it back as Javascript)

A: I don't think such a tool exists. WALA can analyze JS to some extent but it cannot generate JS code again. Many people I know who analyze JS do this by modifying a JIT compiler.


text:
Q: Emacs Jedi python tool unable to load "error searching for program: permission denied, python"? I get the following error when I try to open a python file in emacs:

can't guess python indent offset, using defaults: 4
deferred error: (error searching for program: permission denied,
  python)

My assumption is that the python environment variable needs to be copied to the Emacs PATH variable, because I had to do the same thing for Mac OS X by using bradleywright's path.el script but now I need to do the same thing for Windows 7. How can I do this?
init.el
(load "~/.emacs.d/path.el")

(require 'package)
(add-to-list 'package-archives
             '("marmalade" . "http://marmalade-repo.org/packages/") t)
(package-initialize)

(require 'jedi)
(setq jedi:server-command
  (list "C:/Python33/python.exe" jedi:server-script))

(add-hook 'python-mode-hook 'jedi:setup)
(setq jedi:complete-on-dot t)

(global-auto-complete-mode t)

(require 'ido)
(ido-mode t)

(add-to-list 'load-path "~/.emacs.d/elpa/magit-1.2.0/magit.el")
(require 'magit)

(require 'linum)
(global-linum-mode 1)

A: Open Python and get the full path to Python using sys.executable:
>>> import sys
>>> sys.executable

And then set jedi:server-command like this:
(setq jedi:server-command
      (list "THE-PATH-YOU-GOT" jedi:server-script))

see also: http://tkf.github.io/emacs-jedi/latest/#jedi:server-command
Note that you need to install Python modules (i.e., epc and jedi) and they should be importable for this Python.  So make sure that this works in your Python:
>>> import epc, jedi

A: Look for a "deferred.el". Exist two functions inside which raise that error. Running them under edebug should reveal the cause.

A: Restarting* my computer fixed this error:

deferred error: (error searching for program: permission denied,
  python)

*This was my first restart since installing Python.
Everything seems to be working fine now, I still get the can't guess python indent offset, using defaults: 4 error but jedi tab-completion is working fine.
Thanks for everyone's suggestions, it certainly helped!


text:
Q: Variable not being changed With the following code I am trying to move a small dot across the screen every time the document is hovered over.
The problem is that the "x.style.left" property which is initialized but not defined is updated the first time(I checked it with console.log) but after that it does not update any-more and remains at that value even though I changed it further in the code.
here is the code:
var x = document.getElementById("bot");
document.onmouseover = function(){move()};

function myfunc(){

}

function move(){
       x.style.position="relative";
       x.style.left;
       console.log(x.style.left);
       x.style.left=String(10 + 10) + "px";
       console.log(x.style.left);
}

fiddle: https://jsfiddle.net/puxg59td/

A: You need to get the value and add to it each time.
function move(){
       x.style.position="relative";
       var value = parseInt(x.style.left);
       if (!value) {
           value = 0;
       }
       console.log(x.style.left);
       x.style.left=String(value + 10 + 10) + "px";
       console.log(x.style.left);
}

Fiddle: https://jsfiddle.net/puxg59td/1/

A: Updated (Here is the jsfiddle update: https://jsfiddle.net/puxg59td/10/):

var x = document.getElementById("bot");
document.onmouseover = function(){move()};

function move(){
    x.style.position="relative";
    var curLeft = parseInt(x.style.left) || 0;
    x.style.left= (curLeft + 10) + "px";
}
#body{
    border:2px solid black;
    height:100px;
}

#bot{
    height:1px;
    width:1px;
    background-color:black;
    border:2px solid black;
}

A: You have to increment position. Your problem is that you always give x same 20px left style;
try this:
function move(x){
   x.style.position="relative";
   var l = x.getBoundingClientRect().left;
   console.log(l);
   x.style.left =l + 20 + "px";
   console.log(x.style.left);
}


text:
Q: Django + feincms. How to show self-formed list in admin interface? Django with FeinCMS can show anything from tables and it looks like nice. But what if I have to show some data which is not present in a certain table?
Here is my code:
##  models.py  ##
##  This is my main class.
class Application(models.Model):
    name = models.CharField(max_length=100)
    category = TreeForeignKey('Category', blank=False, null=False, verbose_name="name")
    ....

    class Meta:
        ordering = ('category__tree_id', 'category__lft', 'name')

##  This is my category class.
class Category(MPTTModel):
    name = models.CharField(max_length=50, unique = True)
    parent = TreeForeignKey('self', blank=True, null=True, related_name='children')

    class MPTTMeta:
        include_self = False
        order_insertion_by = ['name',]
        ordering = ['tree_id', 'lft']

##  This function returns list that I need to show in admin interface. As you can see I have to show name of every object which belongs to category.

    def get_trailer(self):
        application = Application()
        apps_list =  [application.__unicode__() for application in Application.objects.filter(category=self.id)]
        logging.error("This is apps_list from get_trailer!")
        logging.error(apps_list)
        return apps_list

##   Registering Category model as MPTT.
mptt.register(Category, order_insertion_by=['name'])

Here we got code of admin interface:
##  admin.py  ##
##  This is class for show Application.
class ApplicationAdmin(admin.ModelAdmin):
    list_display = ('name', 'category')
    list_filter = ('category',)
    ordering = ('category__lft',)

##  This is class for show Category.
class CategoryAdmin(tree_editor.TreeEditor):
    list_display = ('name', 'id',)
    list_filter = ('parent',)
    ordering = ('category__lft',)

Ok. Here we get all categories in tree-like format. When we click in any category we see just its name and parent. Look at this screenshot:

So, how to show this list through django and feincms? I don't want to create new keys in tables to do it.


text:
Q: Intersection and derivatives If two functions $f$ and $g$ are such that:

*

*$f(0) = g(0)$

*$\forall x > 0,\ f^\prime(x) > g^\prime(x)$

is it true that $f\neq g$ for any $x>0$?
I believe so, but I don't know how to prove it. This seems simple though, there might be something I don't see quite yet.

A: Let $h(x)=f(x)-g(x)$. Then $h(0)=0$ and $h'(x)>0$ for all $x>0$. If $h(a)=0$ for some $a>0$, we get a contradiction by applying the mean value theorem on the interval $[0,a]$.


text:
Q: Udf with multiple argument failes when called in dataframel I am working in Scala and spark sql where I want to call UDF which takes multiple arguments. I am not able to figure out what is wrong with my call
the udf is
private def parseJsonUdf: UserDefinedFunction = udf(parseJson _)
def parseJson (json: org.json.JSONObject, arg1: String, arg2: String = ""): String = {
  ***
}

I am calling it this way, here fields is Seq[String] and data column contains json string
for(field <- fields){
 df.withColumn(field, parseJsonUdf(col("data"), lit(field)))
}

Probably I dont know how to pass the string as JSONOBJECT inside udf or something else. I get the below runtime error
java.lang.ClassCastException: ********$$parseJsonUdf$1 cannot be cast to scala.Function2

    at org.apache.spark.sql.catalyst.expressions.ScalaUDF.<init>(ScalaUDF.scala:107)
    at org.apache.spark.sql.expressions.UserDefinedFunction.apply(UserDefinedFunction.scala:71)

How can I make it work?

A: try below (naive approach)-
private def parseJsonUdf: UserDefinedFunction = udf(parseJson _)
def parseJson (jsonString: String, arg1: String, arg2: String = ""): String = {
val jsonObj:org.json.JSONObject = // parse  jsonString -> JSONObject
***
}

then call-
for(field <- fields){
 df.withColumn(field, parseJsonUdf(col("data"), lit(field), lit("")))
}


text:
Q: How to mock an @INPUT value in tests for angular component In my angular app, I am writing a testcase for a component which has @Input value.
How can I mock the @Input value.
The main component's testSave() method uses subComponent's InputObject's id.
When I run the testcase it says undefined is an object at 'this.subComponent.InputObject.id;'
export class SubComponent implements OnInit {
  @Input() inputObj: InputObject;
}

export class MainComponent implements OnInit {
  @Input() subComponent: SubComponent;

  testsave() {
  this.subComponent.InputObject.id;
  }
}

export class InputObject {
  contructor(id:string, name: string)
}

TestCase:
 it('should save', fakeAsync(()  => {
//     const event: MockEvent = new MockEvent();
//     fixture = TestBed.createComponent(MainComponent);
//     component = fixture.componentInstance;
 });

A: Since subComponent and inputObj are public you can simply override it, if you test MainComponent you can have something like:
component.subComponent = {inputObj: {id: 'someId', name :'someName'}};


text:
Q: lmer - linear mixed model- formula optimisation assistance for experimental analysis I have conducted an experiment using some insects. The insects are placed in different concentrations of chemical and their movement measured over 24h by a machine.
Here was the lmer() formula divised:
M1_Xa24D=lmer(value~concentration+machine+history+population+1|population/genotype/replicate)+(1|batch)+(1|machine/Well),data=Xa24D,REML=FALSE,  control = lmerControl(optimizer ="Nelder_Mead"))
Is this formaula the missing something, given the definitions below?
concentration: concentration of chemical placed in.
History: whether they had been pre-exposed to the chemical prior to the experiment.
Population: which population an insect belongs to.
Genotype: a name is assigned to insects which are clones of each other
machine - which machine insects were placed in  (placed in one of two available measuring machines)
Well: insects were placed in a well (one well per insect), 12 wells per tray. 1 tray was placed into each machine.
Batches: same experiment was run on different days. different repeats of the experiment were called batches.
Any help would be massively appreciated.


text:
Q: Add extra new line in the output using CSS, Javascript I am creating a blog website. I am taking the input using a textarea and storing it in MongoDB. For displaying the data I use: white-space: pre-wrap;.
With pre-wrap if I give the input as:
hello
world

The output is:
hello
world

I want the output as:
hello

world

Code:
Taking the input:
<form action="/post/compose" method="post">

      Title
      <input type="text" class="form-control" name="postTitle" >
      Body
      <textarea class="form-control" name="postBody" rows="10" col="10"></textarea>

    <button class="btn btn-success" type="submit">Publish</button>
</form>

Storing the input in database:
 const post=new Post({
      Title:req.body.postTitle,
      Content:req.body.postBody,

      });
      post.save();

Displaying the input

<%= post.Title %>

<%- post.Content %>

css:
#Postcontent{
  white-space: pre-wrap;
}

Now as I added white-space property if there is \n in the input ,in the output single whitespace is included.But I want two white spaces.
Is it possible to do this without regex in Javascript? Please help. Thanks in advance.

A: Ok so it sounds like what you want is to display line breaks entered in the original text?
In that case, probably you don't want a <textarea>. You might like to use this approach by replacing your textarea with an element (say, a div) with contenteditable=true, and then using a JavaScript function to capture the contents of the div (you won't be able to get it with a standard form submission).


text:
Q: Open multiple files in vim with mixed splits I need to open 3 files with vim using linux terminal, but they shoud be open with mixed splits.
"/src/main.cpp" being the main window "input" and output are vertically split. Please refer to the image attacheed. i tried
vim src/main.cpp -O result -o output

but it opens all windows either in all vertical or all horizontal. vim help says
-O[N]           Open N windows, split vertically.  Otherwise it's like -o.
                If both the -o and the -O option are given, the last one on
                the command line determines how the windows will be split.

A: If you want the splits to be of different orientations, each of a specific
size, I think the best way is to write a function that you can just call that
has the desired split arrangement. I have one for a 4-way split:
" make a 4-way split and resize the windows how I like
function! WorkSplit()
    let l:currentWindow=winnr()
    execute "normal! :vsplit\<cr> :buffer 2\<cr>"
    execute "normal! :split\<cr> :resize -20\<cr> :b scratch2\<cr>"
    execute l:currentWindow . "wincmd w"
    execute "normal! :split\<cr> :resize -20\<cr> :b scratch1\<cr>"
endfunction

" split vim into 4 windows, load first and second files on buffers 1 and 2.
" make the bottom windows short and load scratch*.m
nnoremap <silent><Leader>4 :call WorkSplit()<cr>

You'll notice that this function is not very general - it looks for two files
named scratch1 and scratch2 - which I often have in my projects - and tries to
put them in the two lower splits. So if I have open 4 files in vim called A, B,
scratch1 and scratch2, doing Leader+4 will do this:
-----------------
|       |       |
|   A   |  B    |
|       |       |
|       |       |
-----------------
| scr1  | scr2  |
-----------------

If I don't have the scratch1 and scratch2 files, the function will complain,
but still create the splits (the lower splits will simply contain the 3rd and
4th files.


text:
Q: Applying a GPO to local users except local administrators on Workgroup computers I have a set of configurations which I need to replicate from my domain joined computers to non-domain (Workgroup) joined computers. I created a GPO, enabled Loopback processing and imported them via LGPO.exe (Microsoft Security Compliance Toolkit).
One of the configurations include software restriction policies. I want to restrict normal users accessing the certain file extensions, where as administrators should have full access. On the domain level, it works fine when I apply security filtering for Domain Admins. But on the Workgroup level, it doesn't. The policy gets applied for all the users, including Local Administrators.
I want to make sure that only local users are affected by the user configuration policies.
If I apply a WMI filter to exclude Built-in Local Administrators group, will it work?
Please advice. Thanks in advance.

A: Is there any specific reason why you are not using "Enforcement" under "Software Restriction Policies"?
Computer Configuration \ Policies \ Windows Settings \ Security \ Software Restriction Policies \ Enforcement


text:
Q: how to create java zip archives with a max file size limit I need to write an algorithm in java (for an android app) to read a folder containing more folders and each of those containing images and audio files so the structure is this: mainDir/categorySubfolder/myFile1.jpg
My problem is that I need to limit the size of the archive to 16mb and at runtime, create as many archives as needed to contain all my files from my main mainDir folder.
I tried several examples from the net and I read the java documentation but I can't manage to understand and put it all together the way I need it. Has someone done this before or has a link or an example for me?
I resolved the reading of the files with a recursive method but I can't write the logic for the zip creation.
I'm open for suggestions or better a working example.

A: zip4j is a great library that can create multi-part zip files.
net.lingala.zip4j.core.ZipFile zipFile = new ZipFile("out.zip");
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.createZipFileFromFolder("path/to/source/dir", parameters, true, maximum size);

You can find more examples on their web-site.

A: I am using below code/class to split and zip a large amount/size of files.
I have tested this class on below

*

*number of uncompressed files : 116

*total size (uncompressed) : 29.1 GB

*ZIP file size limit (each) : 3 GB [MAX_ZIP_SIZE]

*total size (compressed)   : 7.85 GB

*number of ZIP file (splited as MAX_ZIP_SIZE): 3

you have to change the value of MAX_ZIP_SIZE to 16(MB)10241024=16777216-22(zip header size)=16777194.
In my code, MAX_ZIP_SIZE set to 3 GB (ZIP has limitation of 4GB on various things).

final long MAX_ZIP_SIZE = 3221225472L; //3 GB

package com.company;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class QdeZip {

    public static String createZIP(String directoryPath, String zipFileName, String filesToZip) {
        try {
            final int BUFFER = 104857600; // 100MB
            final long MAX_ZIP_SIZE = 3221225472L; //3 GB
            long currentSize = 0;
            int zipSplitCount = 0;
            String files[] = filesToZip.split(",");
            if (!directoryPath.endsWith("/")) {
                directoryPath = directoryPath + "/";
            }
            byte fileRAW[] = new byte[BUFFER];
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toUpperCase()));
            ZipEntry zipEntry;
            FileInputStream entryFile;
            for (String aFile : files) {
                zipEntry = new ZipEntry(aFile);
                if (currentSize >= MAX_ZIP_SIZE) {
                    zipSplitCount++;
                    //zipOut.closeEntry();
                    zipOut.close();
                    zipOut = new ZipOutputStream(new FileOutputStream(directoryPath + zipFileName.toLowerCase().replace(".zip", "_" + zipSplitCount + ".zip").toUpperCase()));
                    currentSize = 0;
                }
                zipOut.putNextEntry(zipEntry);
                entryFile = new FileInputStream(directoryPath + aFile);

                int count;
                while ((count = entryFile.read(fileRAW, 0, BUFFER)) != -1) {
                    zipOut.write(fileRAW, 0, count);

                    //System.out.println("number of Bytes read = " + count);
                }
                entryFile.close();
                zipOut.closeEntry();
                currentSize += zipEntry.getCompressedSize();
            }

            zipOut.close();
            //System.out.println(directory + " -" + zipFileName + " -Number of Files = " + files.length);
        } catch (FileNotFoundException e) {
            return "FileNotFoundException = " + e.getMessage();
        } catch (IOException e) {
            return "IOException = " + e.getMessage();
        } catch (Exception e) {
            return "Exception = " + e.getMessage();
        }

        return "1";
    }
}

I have returned all Exception Messages as String to work with it. this
my own case related to project.

A: As far as I can see How to split a huge zip file into multiple volumes? just suggests keeping track of the archive size so far, and when it approaches some arbitrary value (which should be lower than your max), it'll decide to start a new file. So for a 16MB limit, you could set the value to 10MB and start a new zip whenever this is reached, but if you reach 9MB and your next file zips down to 8MB, you'll end up with a zip bigger than your limit.
The code given in that post didn't seem to work for me because 1) it got the size before the ZipEntry was created, so it was always 0 and 2) it didn't write out any zip :-) If I've got that wrong - let me know.
The following works for me. For simplicity, I've taken it out of the Wrapper and just have it all in main(String args[]). There are many, many ways this code could be improved :-)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ChunkedZipTwo {

    static final long MAX_LIMIT = 10 * 1000 * 1024; //10MB limit - hopefully this

    public static void main(String[] args) throws Exception {
        String[] files = {"file1", "file2", "file3"};
        int i = 0;
        boolean needNewFile = false;
        long overallSize = 0;
        ZipOutputStream out = getOutputStream(i);
        byte[] buffer = new byte[1024];

        for (String thisFileName : files) {
            if (overallSize > MAX_LIMIT) {
                out.close();
                i++;
                out = getOutputStream(i);
                overallSize = 0;
            }

            FileInputStream in = new FileInputStream(thisFileName);
            ZipEntry ze = new ZipEntry(thisFileName);
            out.putNextEntry(ze);
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.closeEntry();
            in.close();
            overallSize += ze.getCompressedSize();
        }
        out.close();
    }

    public static ZipOutputStream getOutputStream(int i) throws IOException {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream("bigfile" + i + ".zip"));
        out.setLevel(Deflater.DEFAULT_COMPRESSION);
        return out;
    }
}


text:
Q: Adding code to child theme function.php via my plugin I am developing a plugin that needs to overwrite the hook to the parent style.css.
I use the plugin to dequeue the style from the child theme but then I need to enqueue another file into it so that the child theme css works. Not sure if I am making sense.
Basically how would I go about adding this code into the child theme functions.php via my plugin:
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'child-style', plugins_url( '/plugin/css/3.0.31' ) . '/style.min.css' );
}

As it is a plugin it would need to do it automatically without access to the file.
Any ideas?
Thanks


text:
Q: Make ground signal last longer? I'm trying to figure out a way to make a ground signal last longer on my car. I'll explain what is happening and what needs to be done.
I'm hooking up an factory alarm on my car. It uses a negative trigger to trip the locks, I got everything working like it should, you hit lock button on the key fob, it locks and hit the unlock button and it unlocks. The only thing I'm trying to figure out is how to arm the theft system with the door closed..it only arms with the door open, then you have to shut the door.
Everything is tied in with the door switch...
The lock button has 12v constant but when you hit the lock button on the key fob it sends a negative trigger and drops the voltage to 0V for half a second which locks the car.
Door switch-When the door is open it is grounded..when the door is closed it gets 12V constant.
I tried tricking the car into thinking the door was open when I hit the lock button when the door is closed but the ground signal only last half a second and I need it to last about 3 seconds.
I ran a jumper wire from the lock wire to the door switch and placed a 1n4001 diode in the jumper wire to only let the ground signal pass to the door switch when I hit the lock button but it only last half a second. In order to arm the theft system I need the door switch to be grounded for atleast 2-3 seconds then get the 12V back.
To make this long story short, when I hit the lock button it sends a very short half second ground signal to the door switch but jumps back up to 12V..I need it to last about 3 seconds, then jump back up to 12V.
Remember the lock has 12V constant power when you hit the button it sends a negative trigger and drops voltage to 0V for a quick half second..just need it to last 2-3 seconds then return back to 12V.
What can I use to accomplish this? I was thinking a time delay relay but it needs to be triggered by a ground signal using the lock button.

A: You can use RC-circuit with logic elements: short "0" impulse should charge some capacitor then while this capacitor did not disharged to "zero" logic level, you should invert it's logical voltage.

simulate this circuit – Schematic created using CircuitLab
The greather R3 resistance is, the longer delay you'll get. V2 is logic-levelvoltage source.


text: Q: LINQ to SQL Quick conversion to compiled query We have hundreds of LINQ to SQL calls and are encountering performance problem due to compilation. Migrating to EF6 is not an option. Is there a quick way like setting that can be used to produce compiled query instead of rewriting static methods with CompiledQuery.Compile? I couldn't find such an option. Just wanted to check before rewriting all.


text:
Q: The xcopy command that was running before is not working now in power shell Be sure, thecommand below was working one year ago
set source=C:\Users\sinan.almac\OneDrive - Terrafile\EKOL
set destination=\uzyttn\Excel\EKOL
xcopy %source% %destination% /y
her is the error message :

Set-Variable : A positional parameter cannot be found that accepts argument 'Terrafile\EKOL'.
At line:1 char:1

*

*set source=C:\Users\sinan.almac\OneDrive -Terrafile\EKOL

*
  + CategoryInfo          : InvalidArgument: (:) [Set-Variable], ParameterBindingException
  + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetVariableCommand

Cold you help me?


text:
Q: Parse error help, PHP unexpected T_STRING (probably something simple) It's probably something simple I am not seeing because I've stared at it too long.
Any ideas?  It's throwing on line 119, I've indicated it below

Parse error: syntax error, unexpected T_STRING in /home6/cleanai4/public_html/act.php on line 119

I'm just trying to format a phone number.
        if(isset($submit)):
        $db = mysql_connect("localhost", "#######", "#######");
        mysql_select_db("###########", $db);
        $date = date("Y-m-d");
        $address = $street . ", " . $city . " " . $zip;
Line 19->   $phonetmp = '('substr($phone, 0, 3)')' . substr($phone, 3, 3) . '-' . substr($phone, 6);
        $phone = $tmp;
        $sql = "INSERT INTO ########
        VALUES(NULL,'$name', '$address', '$email',  '$phone', '$info', '$sign', '$date' )";
        mysql_query($sql);
        print("
We appreciate your support
\n");
        print("Now, spread the word
\n");
    endif;

A: You're missing the concatenation after the first part of $phonetmp, should be '(' . substr($phone, 0 , 3) . ')'...
Also note: unless you have a variable called $tmp outside of the code segment, you're setting $phone to an undeclared variable. And make sure you sanitize user inputs!

A: That's not a password I'm seeing in the mysql_connect call is it? ;)


text:
Q: How to use a document property for $maxDistance in a $nearSphere query? I have a collection which contains documents like this:
{
    "_id" : "cysMrqjootq6YS6WP",
    "profile" : {
        ……
        "deliveryDistance" : 20,
        "address" : {
            "loc" : {
                "type" : "Point",
                "coordinates" : [
                    —2.120361,
                    52.536273
                ]
            }       }
    }
}

And I have a GeoJSON point like:
var referencePoint= {
                "type" : "Point",
                "coordinates" : [
                    —2.120361,
                    52.536273
                ]
            }

I am using Meteor.js, Node.js and MongoDB. I would like to create a query where the maxDistance from this point is the deliveryDistance property from each document into my collection.
If the maxDistance was a fixed value, the query would be:
myCollection.find({
    "profile.address.loc":{
      "$nearSphere": {
        "$geometry": referencePoint,
        "$maxDistance": 20000 //for 20Kms
      }
    }
  })

But this is not the case. For each document, the maxDistance has to be the value of 'profile.deliveryDistance'. How do I use this value from the document as maxDistance in this query? Is it possible? If not, any other ideas?

A: You cannot reference existing properties of a document within a .find() query, and at least not within a $near or $nearSphere operation.
Instead the approach here is to use the aggregation framework and $geoNear. This allows you to calculate the distance from the queried point and then compare if that falls within the "deliveryDistance" in the document.
So for meteor, you are probably best off installing the meteorhacks aggregate package, and then doing something like this:
Meteor.publish("aggResults",function(referencePoint) {
   var self = this;

   var results = myCollection.aggregate([
       { "$geoNear": {
           "near": referencePoint,
           "distanceField": "distance",
           "spherical": true
       }},
       { "$redact": {
           "$cond": {
               "if": { "$lt": [ "$distance", "$profile.deliveryDistance" ] },
               "then": "$$KEEP",
               "else": "$$PRUNE"
           }
       }}
   ]);

   _.each(results,function(result) {
       self.added("client_collection_name",result._id, {
           "profile": result.profile,
           "distance": result.distance
       });
   });
   self.ready();
})

If your MongoDB sever was less than version 2.6 ( and would have to be at least 2.4 for geospatial queries ) then you would use $project and $match in place of $redact to filter out the documents that did not fall within the "deliveryDistance":
   var results = myCollection.aggregate([
       { "$geoNear": {
           "near": referencePoint,
           "distanceField": "distance",
           "spherical": true
       }},
       { "$project": {
           "profile": 1,
           "distance": 1,
           "within": { "$lt": [ "$distance", "$profile.distance" ] }
       }},
       { "$match": { "within": true } }
   ]);

But that is the basic case, where you give the server the tools to work out the distance comparison and then return any of those documents.
The wrapping of aggregate output really depends on which way it is important for you to use the data in your application. This is just one sample of putting the output into a client addressable collection.
Of course you can also dig into the driver internals to call .aggregate() as shown here, but it's likely not as flexible as using the mentioned meteor package.


text:
Q: Xamarin Post Json data Error (405 Method Not Allowed) Guys i have to make program with posting. Using Postman for it. I need get data from a link. That link doesnt allow Get method. Its my link : http://api.lokmanecza.com/api/GetControlPackageList/1/1
I took my datas with using postman. And convert that jsons to c#. I trying post it but its giving error.
Its my error:
"System.Net.Http.HttpRequestException: 'Response status code does not indicate success: 405 (Method Not Allowed).'"
Its my codes :
string url = $"http://api.lokmanecza.com/api/GetControlPackageList/1/1";
            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetStringAsync(url);
                LoginApiResponseModel rootObj = JsonConvert.DeserializeObject<LoginApiResponseModel>(response);
                var content = new StringContent(rootObj.ToString(), Encoding.UTF8, "application/json");
                var result =   client.PostAsync(url, content).Result;
                lbl.Text = rootObj.InvoiceID.ToString();

            }


text:
Q: SparkContext object not getting created I am using Jupyter notebook and trying to run PySpark commands. I ran the below import commands which ran fine.
import findspark
findspark.init()
from pyspark import SparkConf
from pyspark import SparkContext

conf=SparkConf()
conf.setMaster('local')
conf.setAppName('spark_basic')

Post this, when I am trying to initialize a variable with SparkContext as below, it keeps on running without any error/output:

sc=SparkContext(conf=conf) #command running without any error/output

Could you please provide any resolution on this issue.


text:
Q: How to extract values from array along with other columns in HIVE
Hi,
  I have a hive table with following columns
  partid string, store string and location array in table, values are save in this order

part123, store123, location
[{"position":1,"price":124.0,"card_pos":"External","clicked":0},
 {"position":2,"price":94.78,"card_pos":"Cbox","clicked":0},
 {"position":3,"price":94.77,"card_pos":"External","clicked":0}]
>

I can see values of arry in one line which is fine, I would also like to
see values from partid, store, location values in this way.
>
+---------+-----+----------+--------+-----------+----------+
partid |store   | position | price  | card_pos  | clicked  |
+---------+-----+----------+--------+-----------+----------+
part123|store123| 1        | 124.0    | External | 0       |
part123|store123| 2        | 94.78    | Cbox     | 0       |
part123|store123| 3        | 94.77    | External | 0       |
+---------+-----+----------+----------+----------+---------+

>
So far I can only see array values by using inline function in this way.
select inline(location) as (position, price, card_pos, clicked) from table;

>+---------+--------+-----------+----------+
| position | price  | card_pos  | clicked  |
+----------+--------+-----------+----------+
| 1        | 124.0    | External | 0       |
| 2        | 94.78    | Cbox     | 0       |
| 3        | 94.77    | External | 0       |
+----------+----------+----------+---------+

>

A: Use lateral view in conjunction with inline and select the other columns.
select partid,store,t.position,t.price,t.card_pos,t.clicked
from table
lateral view inline(location) t as position, price, card_pos, clicked

Edit: Per OP's request to handle cases when the array column is null, use lateral view outer option.
select partid,store,t.position,t.price,t.card_pos,t.clicked
from table
lateral view outer inline(location) t as position, price, card_pos, clicked


text:
Q: React Native - Centering flexWrap container's content I have an image container that wraps dynamic number of circular image components as shown below:
<View style={styles.imageContainer}>
  {imageList.map(item=> <Image .../>)}
</View>

container has the following style:
imageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-start',
    flexWrap: 'wrap',
    width: '100%',
    borderWidth: 1,
    paddingVertical: 20,
  },

As you can see, since justifyContent is flex-start, it leaves more space on the right than on the left side of the container. I tried doing justifyContent: 'center', but it leaves with the following:

now the left and right spaces are equal, but problem is that the images on the second row are centered, which is not what I want. I want them to align to left just like the first screen shot (but left/right space of the container being equal).
How would I solve the problem?
Thanks!


text:
Q: Where are all the cats in Arkham City? You have to use cats to switch between Catwoman and Batman in the main story, but I've seen only seen one group of cats, the ones right next to Catwoman's apartment. It's a hassle to fly back there whenever I want to switch. The game says that there are multiple groups of them, but I can't find more. Where are all of the other cats?

A: Here are the cat locations in Arkham City:

A close-up:

A: There's one on the shore near the Joker's side of town.  They should be visible on your minimap with a cat icon