text:
Q: Thermodynamics of supercooled water Now that it's been freezing outside for the last few days, I experimented a bit with supercooling. I've left a bottle of clean water outside for a few hours, and behold, when I shook the bottle, the liquid began to freeze rapidly, as expected.
However, not all of the water froze, only about half of it. This got me thinking.
I reasoned that happens because freezing releases heat, and that heat raises the temperature of the ice and remaning water to 0$^\circ$C, at which point the freezing stops.
To try to quantify this, set

*

*$H_f = 334000 \frac{J}{kg}$, the "freezing heat" (enthalpy of fusion) of ice,

*$c_i = 2110 \frac{J}{kg\cdot K}$, specific heat of ice,

*$c_w = 4181 \frac{J}{kg\cdot K}$, specific heat of water,

*$M$, initial mass of supercooled water,

*$T_0$, initial temperature of supercooled water,

*$m$, mass of ice at a given moment,

*$T$, temperature at a given moment.

We suppose that the energy released by the freezing of a $\textrm dm$ mass of ice is used up by raising the temperature of both the already frozen ice ($m$) and the remaining water ($M-m$):
$$ \textrm dm \cdot H_f = c_i m \cdot\textrm dT + (M-m)c_w \cdot\textrm dT$$
By rearranging we get a linear differential equation for $m(T)$:
$$\frac{\textrm dm}{\textrm dT}+\frac{c_w-c_i}{H_f}m = \frac{c_w}{H_f}M$$
The solution of this equation, using the initial condition that at $T=T_0$, $m=0$:
$$ m = M \frac{c_w}{c_w-c_i}\left[ 1-e^{-\frac{c_w-c_i}{H_f}(T-T_0)} \right]$$
This looks neat, however, plugging in the actual values of the constants, $T = 0^\circ$C and $T_0 = -6^\circ$C, I get that little more than 7% of the water should freeze - as opposed to more than half, as I've observed.
What's worse, the formula can be used to calculate the starting temperature required to freeze all the supercooled water:
$$T_{all} = \frac{H_f \log\frac{c_w}{c_i}}{c_i-c_w}=-110.26^\circ \textrm C$$ which seems absurd.
Where is the error in the calculation above?
I've made a number of assumptions which may or may not hold:

*

*the constants are really constant. I think this is a good approximation for $c_w$, a not that good but still acceptable approximation for $c_i$, and I suppose it holds to $H_f$ to some extent as well.

*there is no heat transfer with the environment, i.e. the bottle is a closed system. The process seemed fast enough (a few seconds at most) for this to be a good approximation.

*the system is in a thermal equilibrium at all times and the heat released by the freezing of the ice is distributed evenly in the emerging ice-water mixture. Now this is where I have doubts. Precisely because of the process happening so fast, this might not be true at all. However, acknowledging the presence of temperature variations makes the problem order of magnitudes harder: one has to solve a system of partial differential equations that take heat transfer, the shape of the bottle and \$deity knows what else into account.

A: I'm answering my own question.
Apparently this is one of those rare cases when the physicist must doubt what he observed -- or what he thought he observed -- and believe the numbers his theory yielded instead.
From further experiments I've noticed that the ice tends to form thin plates inside the supercooled water once the crystallization process starts -- this form of ice is apparently called dendritic ice. When the starting temperature of the water was about $-10^\circ$C, the resulting ice-water mixture still contained a lot of water by the time the process finished, and most of it was trapped between those thin ice plates. The latter fact would make it hard to measure the mass percentage of water exactly.
I've found some scholarly articles studying this process -- mostly in the context of formation of ice plugs in pipes. In [1] they measured the temperature at a number of points inside a capsule full of supercooled water during ice formation. From the time-dependent temperature profiles in the article it is obvious that my model above (that energy released by the freezing ice heats up all of the water and ice) is completely wrong. The process happens so fast (at a rate of a few cm/s, depending, among other factors, on the temperature), that the heat transfer between the already frozen (thus heated to $0^\circ$C) and still supercooled regions is practically negligible.
However, based on the observation that ice and water appears well mixed in the already frozen region, we can put forth a new model: the released latent heat of fusion is used up locally and quickly in the boundary layer of the expanding frozen region. As a particular region at the boundary freezes, it heats up rapidly to $0^\circ$C (or close to it), and heats up the water surrounding it. Since the ice plates thus formed are relatively close to each other, the resulting region containing ice-water mixture will mostly be free of temperature inequalities, and those inequalities that do exist will be damped quickly. Therefore the thermal profile of a volume of supercooled liquid undergoing freeze-out will consist of two flat regions, with a relatively sharp boundary between.
It would be quite interesting to look at the process with a thermal infrared camera. Such an observation could confirm or reject the model above. To my knowledge, no one published such an observation -- if such a publication exists, I'd be very interested in seeing it. A video made by such a camera would be especially enlightening.
With some simplifying assumptions (spherical container full of supercooled liquid with uniform temperature, and a single nucleation source at the center), the simple model above could be made quantitative, but I haven't done that yet.
1 Juan Jose Milon Guzman, Sergio Leal Braga: Dendritic Ice Growth in Supercooled Water Inside
Cylindrical Capsule, 2004

A: There is a simpler way to do the calculation, though using it also gives me 7% of the water freezing. The heat needed to warm the water from T degrees below zero is simply:
$$E = MTC_w$$
where $M$ is the mass of the water, $T$ is the degrees below zero and $C_w$ is the specific heat of water (assumed constant over this range). The heat released when a mass $m$ of the water freezes is:
$$E = mL_{f}$$
where $m$ is the mass that freezes and $L_{f}$ is the latent heat of fusion. Assuming the system ends up at zero degrees you can just set the two equal, and you get:
$$\frac{m}{M} = T \frac{C_w}{L_f}$$
But, just as you found, plugging the numbers in gives 7% of the water frozen.
I suspect that the 50% ice you saw was actually 7% ice with a lot of unfrozen water trapped within the matrix of ice crystals. If you're feeling in an experimental mood you can put a known mass of warm water into a thermos flask and measure it's temperature, then drop in your bottle and measure the temperature change. Actually, I wish I'd though of doing that - I wonder if my nephews would be interested in try the experiment ...

A: In your opening statement you said  "…….heat raises the temperature of the ice and remaining water to 0oC at which point the freezing stopped."
I don't believe the freezing stopped unless you placed the bottle in a warm environment.
Supercool water begin the freezing process only after latent heat is released and the temperature of the water is raised to 0oC by that heat (1). The amount of ice produced at moment that latent heat is first released in roughly proportional to the depth of supercooling and the thermal mass of the container that the water is in. Once latent heat is released freezing will continue until all the water in the container is frozen; if the container remain in a sub-zero environment.
(1) When does hot water freeze faster then cold water? A search for the Mpemba effect, James D. Brownridge, A, J. Phys. 79, 78 (2011)

A: Like you say, there seems to be something odd happening here. I have seen videos of water from a domestic fridge freezer being poured from a bottle and instantly forming a mound of ice. It is very hard to believe this mound, even though looking rather slushy, only contains a few percent of ice.
Is it possible that the supercooled water contains some of the ordered structure that occurs in ice and which is responsible for the latent heat of freezing. This would be seen as an apparent increase in the specific heat of water as it cools below 0 deg C as the water takes on some of the structure of ice, and a reduction in the latent heat when freezing eventually occurs, because the water already has some of the ordered structure of ice.


text:
Q: Navigate from HOC in next.js using Router in NextJs I am creating an HOC for the purpose of authentication protection, I have a layout component which I want to wrap inside of the HOC, the HOC is expected to redirector navigate the user to login when he/she tries to access the pages under the said layout, however, I am unable to navigate or redirect using the built in Router object from Next.js.
Below is the HOC function
import Router from "next/router";

const withAuth = (Component) => {
  const AuthenticatedComponent = (props) => {
    const isAuthenticated = false;
    if (isAuthenticated) {
      return <Component {...props} />;
    } else {
      Router.push("/");
      return;
    }
  };

  return AuthenticatedComponent;
};

export default withAuth;

And here is the wrapped layout
 const PrivateLayout = ({ children }) => {

  return (
    <>
      <LayoutContainer>
        <MainSection>
          <main>{children}</main>
        </MainSection>
      </LayoutContainer>
    </>
  );
};

export default withAuth(PrivateLayout)();

I have also tried making the withAuth a component in order to make use of the useRouter hook, but it still doesn't work. Please how can I achieve the redirection in this case.

A: Try to use the useRouter() hook instead of the Router object directly
import {useRouter()} from 'next/router'

const router = useRouter()

const withAuth = (Component) => {
  const AuthenticatedComponent = (props) => {
    const isAuthenticated = false;
    if (isAuthenticated) {
      return <Component {...props} />;
    } else {
      router.push("/");
      return;
    }
  };

  return AuthenticatedComponent;
};

export default withAuth;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Universal imageloader OutOfMemory Error I know this link alreday post this question -Universal-Image-Loader: OutOfMemory Error
But Lot Of Images arising problem OutOfMemoryError  I m using below
protected ImageLoader imageLoader = ImageLoader.getInstance();

DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.aboutlogoicn)
        .showImageForEmptyUri(R.drawable.aboutlogoicn)
        .showImageOnFail(R.drawable.aboutlogoicn)
        .cacheInMemory(true)
        .cacheOnDisc(true)
        .considerExifParams(true)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .build();

And ImageConfiguration
 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
    .memoryCache(new WeakMemoryCache())
    .denyCacheImageMultipleSizesInMemory()
    .discCache(new UnlimitedDiscCache(cacheDir))
        .enableLogging()
    .build();

This Type of error arising
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:546)

Wcom.nostra13.universalimageloader.core.decode.BaseImageDecoder.decodeStream(BaseImageDecoder.java:170)

at com.nostra13.universalimageloader.core.decode.BaseImageDecoder.decode(BaseImageDecoder.java:73)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.decodeImage(LoadAndDisplayImageTask.java:307)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:253)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:128)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

W/System.err(2291):     at java.lang.Thread.run(Thread.java:838)

I  m using below 2 configuration after init displayimage called.In My Android Device Cache memory size 19Mb if i m loading another images then showing onLoadingFailed reason is out of memory error.I m using this link for reference -https://github.com/nostra13/Android-Universal-Image-Loader
 if any solution or another way plz help


text:
Q: Facebook API - Get Life Events (graph-api or FQL) After reading extensively FB's documentation for graph-api and FQL I still can't find a way of obtaining my friends' life events (e.g. graduation date, anniversary, new home, etc).
The only event explicitly available in their documentation are birthdays (which is quite obvious).
I'm almost certain that it is possible to do the above because the IPhone App "Karma" (http://itunes.apple.com/us/app/karma/id457143798?mt=8) provides automatically that information after logging with FB (rulling out options such as crawling my friends wall, which would also be very unlikely due to FB's permissions)
Any ideas? Possible FQL selectors that are not being documented?
Thanks!
EDIT: Note that Karma's Android app does not provide life events.

A: The question was answered here: Grabbing Facebook life events
These posts have a 'type', with a code. For instance, Relationship status change would be code 62, location changes would be code 282.
Look at the link

A: Most of the changes to a user's personal info (education, work, hometown, relationship status) just generate a "normal" status update message – AFAIK there's no distinction made between those and other manual status updates.
So I'd say an app wanting to display that kind of info would have to go through the user's status messages and filter out the ones it thinks to be relevant itself by looking at the story text.

A: SELECT name, education_history, work_history, relationship_status from user where uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

You can use this for education and work history or user, but for other your have to pass through their feed using
id/feed

and check story edge for filtration.


text:
Q: Is there a way to change the original reference to an object in a function call I was working with an array in JavaScript and was wondering why changes I made to an array were correctly saving to localStorage, but weren't being reflected in the array past the function call. The code was the following:
function removeFromList(array, arrayName, key) {
  array = array.filter(function(element) { return element.key !== key; });
  localStorage.setItem(arrayName, JSON.stringify(array));
}

I did some googling and, through some old posts, discovered that the array was being passed by value to the function, that is, the array variable, which pointed to an array object, was being passed by value, and changing that copy did not affect the original variable that was pointing to my array object.
I came up with the following code as a workaround:
function removeFromList(array, arrayName, key) {
  arrayTemp = array.filter(function(element) { return element.key !== key; });
  for(var i = 0; i < array.length; i++) {
    if (!arrayTemp.some(item => item.key === array[i].key)) {
      array.splice(i, 1);
    }
  }
  localStorage.setItem(arrayName, JSON.stringify(array));
}

This solved my problem, and the new contents of the array was displayed in both localStorage and the array object that was pointed to by the original variable. However, I've been wondering if there is some new way introduced into JavaScript recently or an older method I did not find that would do a better job of achieving the desired result.

A:
I did some googling and, through some old posts, discovered that the array was being passed by value to the function, that is, the array variable, which pointed to an array object, was being passed by value, and changing that copy did not affect the original variable that was pointing to my array object.

Exactly right.

Is there a way to change the original reference to an object in a function call

No, JavaScript is still a purely pass-by-value language. While I suppose it's possible for that to change at some point, it hasn't as of this writing (and it seems really unlikely to me it ever will). If you do example(x) when x contains 42 (or an array reference), there still isn't any way for example to reach out and change the value of x (to 43, or to refer to a different array). If x refers to a mutable object (like an array), example can modify that object, but it can't make x refer to a whole new object.
Your workaround works by modifying the existing array. FWIW, in general it would be preferred to return the new array instead, so the caller has the option of either keeping the original or using the new one. E.g.:
function removeFromList(array, arrayName, key) {
    array = array.filter(function(element) { return element.key !== key; });
    localStorage.setItem(arrayName, JSON.stringify(array));
    return array;
}

And then when using it:
variableContainingArray = removeFromList(variableContainingArray, "nameInLocalStorage", 42);

But if you want to update in place, you don't need a temporary array:
function removeFromList(array, arrayName, key) {
    // Looping backward we don't have to worry about the indexes when we remove an entry
    for (let i = array.length - 1; i >= 0; --i) {
        if (array[i].key === key) {
            array.splice(i, 1);
        }
    }
    localStorage.setItem(arrayName, JSON.stringify(array));
}

A: Instead of using a for-loop to remove the values from the argument array you can also empty it out using splice and add the filtered values:
function removeFromList(array, arrayName, key) {
  var filtered = array.filter(function(element) { return element.key !== key; });
  array.splice(0, array.length, ...filtered);
  localStorage.setItem(arrayName, JSON.stringify(array));
}

I suggest changing var to const and function(element) { return element.key !== key; } to element => element.key !== key if those features are available within your runtime environment.


text:
Q: JDK warning in Jenkins 2.121.3 LTS version I have upgraded my jenkins from 2.89.4 to 2.121.3 version
I am seeing a very long list of warnings in logs. Not sure how to resolve it.
WARNING: Could not find dependency jdk-tool of gerrit-code-review
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of git-bisect
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of git-bisect
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of git-notes
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of ruby-runtime
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of git-notes
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of ruby-runtime
Sep 07, 2018 8:22:03 AM hudson.model.UpdateSite$Plugin getNeededDependencies
WARNING: Could not find dependency jdk-tool of git-prebuildmerge-trait


text:
Q: no such table: Users I added a database to my game and when I check in Unity Editor everything works fine, but when I run the game on my phone it gives an error no such table: Users although the database has this table
My code
    private void ConnectData()
    {
#if UNITY_EDITOR
        _path = Path.Combine(Application.streamingAssetsPath, "russianWords.bytes"); //Path to datab
#elif PLATFORM_ANDROID
        _path = Application.persistentDataPath + "russianWords.bytes";
        if (!File.Exists(_path))
        {
                Debug.Log("4");
            string timlesPath = "jar:file://" + Application.dataPath + "!/assets" + "russianWords.bytes";
            Debug.Log(timlesPath);
            WWW load = new WWW(timlesPath);
            while (!load.isDone) { }
            File.WriteAllBytes(_path, load.bytes);
        }

#endif

        _dbConnection = new SqliteConnection("URI=file:" + _path);
        _dbConnection.Open();
        if (_dbConnection.State == ConnectionState.Open)
        {
            m_sqlCmd = new SqliteCommand();
            m_sqlCmd.Connection = _dbConnection;
        }
    }

private void CheckEndGame()
{
    if(ResultWords.Count - 1 >= GameManager.Instance.TargetWordsAmount)
    {
        string words = "";
        foreach(var p in ResultWords)
        {
            if(p != "КОЛА")
                words += p + ", ";
        }

        ScrambleInterface.Interface.OpenResultPanel(words);
    }
}

A: To me it sounds like your WWW (which is long obsolete btw) simply fails since you look in the wrong place for your file.
You don't have any check for success or failure so I would simply claim: The load fails and therefore load.bytes is an empty byte[]. -> Nothing exists in that database at all.
Also you are e.g. using
_path = Application.persistentDataPath + "russianWords.bytes";

which is a path where your app doesn't even have access -> you might already get an exception for the File.Exists.

As said WWW is obsolete. You also shouldn't use blocking calls for this kind of stuff. I wouldn't even use a WebRequests here at all but rather simply direct FileIO like e.g.
    private void Connect()
    {
        Task.Run(async () => await ConnectAsync());
    }

    private async Task ConnectAsync()
    {
#if UNITY_EDITOR
        _path = Path.Combine(Application.streamingAssetsPath, "russianWords.bytes");
#elif PLATFORM_ANDROID
        _path = Path.Combine(Application.persistentDataPath, "russianWords.bytes");
        if (!File.Exists(_path))
        {
            Debug.Log("4");
            var sourcePath = Path.Combine(Application.streamingAssetsPath, "russianWords.bytes");
            Debug.Log(sourcePath);

            await CopyFileAsync(sourcePath, _path);
        }
#endif

        _dbConnection = new SqliteConnection("URI=file:" + _path);
        _dbConnection.Open();
        if (_dbConnection.State == ConnectionState.Open)
        {
            m_sqlCmd = new SqliteCommand();
            m_sqlCmd.Connection = _dbConnection;
        }
    }

    private async Task CopyFileAsync(string sourcePath, string destinationPath)
    {
        using (var source = File.Open(sourcePath))
        {
            using(var destination = File.Create(destinationPath))
            {
                await source.CopyToAsync(destination);
            }
        }
    }


text:
Q: Will the "closed" unit ball $\left\| x \right\| \le 1$ in $\Bbb R^n$ be a compact set for any norm?
Will the "closed" unit ball $\left\| x \right\| \le 1$ in $\Bbb R^n$ always be a compact set for any norm?

I am asking this question because the induced matrix norm is originally defined as a supremum,

Given a vector norm ${\upsilon}:\Bbb R^n\to \Bbb R$, the induced matrix norm $\mu:\Bbb R^{m\times n} \to \Bbb R$ is defined as $\mu({\bf{A}})=\sup\{{\bf{Ax}}:\upsilon({\bf{x}})\le 1\}$.

However, my lecture material later claims the closed ball "$\upsilon({\bf{x}})\le 1$" is compact so the supremum is actually a maximum, so

I don't know where this lector material comes from and I have googled but cannot find the Corollary 2.153. Hope someone can help with this. Thank you!

A: Two answers have already pointed out the theorem that all norms on $\mathbb R^n$ induce the same topology. So they agree as to which sets are open, which are closed, which are compact, etc. But I don't think that completely answers the question, because different norms have different closed unit balls.  (To avoid ambiguity in the notation $\Vert x\Vert$, I'll use $E$ for the standard Euclidean norm and $N$ for some arbitrary other norm.) We need to show that the unit $N$-ball $B=\{x:N(x)\leq1\}$ is compact, in the topology induced by $N$ --- or by $E$ or by any other norm, since they're all the same topology.
If (and it's a big "if") you already know that closed bounded sets are compact, for the arbitrary norm $N$, then this is easy.  $B$ is obviously bounded with respect to $N$.  It's closed because the norm function $N$ is continuous, thanks to the triangle inequality which implies $|N(x)-N(y)|\leq N(x-y)$.  So $B$ is compact.
But what if you know "closed bounded sets are compact" only for the standard Euclidean norm $E$? Then I want to prove that $B$ is closed and bounded with respect to $E$. The "closed" part of this is easy, since all norms agree as to which sets are closed, and I pointed out in the previous paragraph that $B$ is closed with respect to $N$.  So it remains to check that $B$ is bounded with respect to $E$.
I'll show this by contradiction. So suppose $B$ is not bounded with respect to $E$, i.e., there is, for each positive integer $n$, some $x_n\in B$ with $E(x_n)\geq n$.  Consider the sequence of vectors $(x_n/n)$.  Each of these vectors has $E$-norm $\geq1$, so the sequence doesn't converge to $0$ with respect to $E$. But, since all the $x_n$ are in $B$, we have $N(x_n/n)\leq1/n$, so the sequence does converge to $0$ with respect to $N$.  This contradicts the fact that $E$ and $N$ induce the same topology.
Confession: In the last paragraph, I proved a claim about boundedness using the fact that all norms induce the same topology.  As far as I'm aware, any proof that all norms induce the same topology will include information from which one can much more easily derive the claim about boundedness.  That information is likely to be of the form "there exists a constant $M$ such that, for all $x$, we have $E(x)\leq M\cdot N(x)$."  My excuse for giving the argument in the form I used is that the two previous answers and the earlier part of my answer all involved the fact that norms on $\mathbb R^n$ induce the same topology, so it seemed efficient to keep on using the same fact.
EDIT: To save people the bother of checking the timing of answers, the two previous answers I mentioned above are those of Theo and Yaddle.  Eric Wofsey's answer arrived while I was typing mine, and it includes the additional information that I said was lacking in the previous answers.

A: This follows from the fact that all norms on $\mathbb{R}^n$ are equivalent.  In particular, let $\|\cdot\|$ be your norm and let $\|\cdot\|_2$ be the Euclidean norm.  Since the norms are equivalent, they generate the same topology, so the closed unit $\|\cdot\|$-ball is also closed in the Euclidean topology.  Moreover, the norms being equivalent implies there is a constant $K$ such that $\|x\|_2\leq K\|x\|$ for all $x$.  This means that the closed unit $\|\cdot\|$-ball is contained in the closed Euclidean ball of radius $K$.  Thus the closed unit $\|\cdot\|$-ball is closed and bounded with respect to the Euclidean topology, and hence compact.  (It is compact with respect to either norm, since the two topologies are the same.)

A: The closed unit ball is compact in $\mathbb R^n$ respecting every norm. That is due to the fact that all norms on $\mathbb R^n$ are equivalent (and hence generate the same topology).
In general you can show that on every finite dimensional Banach space all norms are equivalent and hence the unit ball is compact respecting every norm.
You can even show that a Banach space is from finite dimension if and only if the unit sphere is compact. That is sometimes pretty handy in functional analysis. I hope that it helps you :)

A: Yes,  any two norms are equivalent on a finite dimensional Banach space, so they generate the same topology.
Perhaps for more detail, it is fairly easy to show that the unit ball under the $l_1$ norm, $B(l_1^n)$, is compact. If a sequence is bounded in the $l_1$-norm then it bounded coordinate-wise, and now apply Bolzano-Weierstarss (to the first coordinates, then to the second, and so on)  to select a sequence that converges point-wise. In $l_1$ is then immediate that pointwise convergence of the sequence implies norm convergence.
Since any two norms are equivalent,  $B(l_1^n)$ is a compact set in the topology determined by other norm $||\cdot||$ and the unit ball $B_{||\cdot||}$ is a closed subset of a multiple of $B(l_1^n)$, thus also compact.


text:
Q: Import, edit and Export saved SVG files I am having a requirement where I have to generate a single svg file from various svg file like shapes into the canvas in android platform like making a image. And above that after saving that svg file I can also re-import that svg file and can undo/redo the changes done previously as well as making adding new stuff and saving the new svg file.
I am not much aware regarding importing and reusing the svg file after once it is saved and redo/undo or edit the previous changes step by step according to the layers in svg file and additionally making new changes into it.
I had R&D in figuring out the way but could not find any helpful solution. It would be great help if anyone can suggest me convenient ways to do that so.
Thank you.


text:
Q: dotimes taking very long for large inputs (SBCL 2.2.0)
Playing around with the time function, I chanced upon an unexplainable happening with dotimes: after a certain limit, it takes forever to loop.
For example:

*

*For 100000: (it barely registers)

(time (dotimes (i 100000)
    (1+ 1)))

Evaluation took:
  0.000 seconds of real time
  0.000000 seconds of total run time (0.000000 user, 0.000000 system)
  100.00% CPU
  139,293 processor cycles
  0 bytes consed

*

*For 10000000:

(time (dotimes (i 10000000)
    (1+ 1)))
Evaluation took:
  0.010 seconds of real time
  0.000000 seconds of total run time (0.000000 user, 0.000000 system)
  0.00% CPU
  10,130,013 processor cycles
  0 bytes consed

*

*For 100000000 (note that it does not go 10x the previous value, rather ~5x)

(time (dotimes (i 100000000)
    (1+ 1)))
Evaluation took:
  0.050 seconds of real time
  0.031250 seconds of total run time (0.031250 user, 0.000000 system)
  62.00% CPU
  84,139,662 processor cycles
  0 bytes consed

*

*For 1000000000:

(time (dotimes (i 1000000000)
    (1+ 1)))
Evaluation took:
  0.404 seconds of real time
  0.328125 seconds of total run time (0.328125 user, 0.000000 system)
  81.19% CPU
  942,942,189 processor cycles
  0 bytes consed

*

*For 10000000000: explodes

(time (dotimes (i 10000000000)
    (1+ 1)))
Evaluation took:
  153.227 seconds of real time
  129.781250 seconds of total run time (128.781250 user, 1.000000 system)
  [ Run times consist of 11.651 seconds GC time, and 118.131 seconds non-GC time. ]
  84.70% CPU
  1 form interpreted
  370,698,869,379 processor cycles
  109,232,098,992 bytes consed

  before it was aborted by a non-local transfer of control.

Binary searching around the numbers, I found that the crossing over point is 4294967295, after which the loop never ends. Why does this happen so suddenly?

A: The one-word-but-slightly-wrong answer is 'bignums'.  You are using a 32-bit SBCL I assume and 2^32 is 4294967296.  For integers larger than that the implementation has to do arithmetic itself rather than using the machine to do it.  Worse, integers this large are not machine integers and so, generally, need to be heap-allocated which in turn means the GC now has work to do.
The more-correct answer is that, in fact, 2^32-1 will almost certainly be larger than the most positive fixnum (you can check what this is by looking at most-positive-fixnum) in a 32-bit SBCL, but SBCL has support for using naked machine integers in some cases, and this is probably one.


text:
Q: Invent new language, syntax check? i been thinking of a new programming language. Before trying to implement it i would like to check the syntax of code to see if there is much ambiguity. (i find it funny that its possibly to do var++++ to a class)

A: Write down the syntax in the correct format and use Antlr or any other parser generater to generate a parser. Those usually warn you about ambiguities.

A: Remember, grammars that are ambiguous for one style of parser many not be ambiguous for a different one.
If you want the language to work for you, test with the parser generator you plan to use.  If you want it to be easier for others to implement, test with a few different parser generators and study their errors/warnings until you understand exactly what ambiguity they are seeing.


text:
Q: Max size of function stack in C (gcc) I want to know what is the maximum number of (recursive)function calls allowed in gcc C. I have a program which can take stack depth of 400000 function calls each with size of around 200 bytes (so around 80 MB). How can I increase the maximum depth?

A: The stack limit is not imposed by the compiler, but by the operating system. On Unix, you can try using ulimit(1) to increase it.

A: I would recommend rewriting the routine into an iterative algorithm. Though nontrivial it should be straightforward to convert the algorithm, and will free you from having to deal with such resource limitations (which, I would guess, vary wildly by architecture, platform, computer details, etc.)
Also, please note: all recursive algorithms can be written iteratively.


text:
Q: Required: javax.xml.bind.JAXBElement; found java.lang.String I have a problem when setting the values in JAVA web services. I have done the web service client to be setting the values but I am getting the error messages  Required: javax.xml.bind.JAXBElement; found java.lang.String .
I have  developed web service client stubs and below is sample scripts from the stubs
 Service service = Service.create(url, qname);
    // Extract the endpoint interface, the service "port".
      ObjectFactory  daget = service.getPort(ObjectFactory.class);
      ComBdata  NewComdata = (ComBdata) daget.createProd();
         NewComdata.setNumberID(rd.getString(1));

From client stubs generated
 public void setNumberID (JAXBElement<String> value) {
    this. numberID = value;
    }

How can I solve this error? I am new to JABX

A: This method creates a JAXBElement with a certain value:
<T> JAXBElement<T> wrap( String ns, String tag, T o ){
    QName qtag = new QName( ns, tag );
    Class<?> clazz = o.getClass();
    @SuppressWarnings( "unchecked" )
    JAXBElement<T> jbe = new JAXBElement( qtag, clazz, o );
    return jbe;
}

Your call will be
JAXBElement<String> jbw = wrap( ?, ?, rd.getString(1) );

but I can't tell you namespace or element tag.


text:
Q: Issue on removing YouTube logo on embedded YouTube video I'm embedding a video on my website but I don't want it to have the YouTube logo and the controls. I searched on Google (date was June 2013) and it said that I just need to put "modestbranding=1&controls=0" on the src. The controls doesn't show up, but the YT logo is still there.
Here's my code:
<iframe width="471" height="280" src="https://www.youtube.com/embed/YOUTUBE_ID?modestbranding=1&controls=0" frameborder="0" allowfullscreen></iframe>

I was wondering if it's still possible to remove the logo. Before, I'm using the <object> with <param name="PARAMETER" value="VALUE"> but I found out that YouTube <object> embeds were deprecated as of January 27, 2015. It told me to migrate my applications to use <iframe> embeds, which can intelligently use whichever embedded player – HTML (<video>) or Flash (<object>).
Hope someone can help :) Thank you!


text:
Q: Как объединенные колонки в таблице разбить и поставить туда одинаковые значения? Есть таблица в которой для некоторых полей используется colspan и rowspan. Но мне нужно, чтобы PHP код убирал это объединение и допустим вместо colspan=2 делал 2 ячейки и заполнял их идентичными данными, которые были в этом поле с атрибутом colspan=2.

A: Это не вопрос из области PHP, а скорее по DOM. Как вам советует @splash58, почитайте про табличные теги, а PHP это средство вывода, а не верстки.


text:
Q: Trackpad works fine but there is no haptic feedback in Macbook air retina 2018 The trackpad stopped giving haptic feedback suddenly however force touch and other gestures are working fine. Hence, it didn't seem a hardware issue. Also,I did SMC reset and NVRAM/PRAM reset. No improvement.

A: The "haptic engine" is basically an electromagnet that causes a vibration in the trackpad and is "outside" how the trackpad capacitive touch sensors work. Something in that system has failed.
So even though your track pad works for input, you need to take it in for service because the trackpad needs to be replaced. Technically, the entire top case, which is comprised of the case, keyboard, trackpad, and battery will have to  be replaced. If your Mac is not under warranty, I would just live without the haptic feedback until you have to replace the battery due to age - it's an expensive fix


text:
Q: Why SparseCategoricalCrossentropy is not working with this machine learning model? I have a .csv database file which looks like this:
              Day   Hour  N1  N2  N3  N4  N5  ...  N14  N15  N16  N17  N18  N19  N20
0      1996-03-18  15:00   4   9  10  16  21  ...   48   62   66   68   73   76   78
1      1996-03-19  15:00   6  12  15  19  28  ...   63   64   67   69   71   75   77
2      1996-03-21  15:00   2   4   6   7  15  ...   52   54   69   72   73   75   77
3      1996-03-22  15:00   3   8  15  17  19  ...   49   60   61   64   67   68   75
4      1996-03-25  15:00   2  10  11  14  18  ...   55   60   61   66   67   75   79
...           ...    ...  ..  ..  ..  ..  ..  ...  ...  ...  ...  ...  ...  ...  ...
13596  2022-01-04  22:50  17  18  22  26  27  ...   64   65   71   72   73   76   80
13597  2022-01-05  15:00   1   5   8  14  15  ...   47   54   59   67   70   72   76
13598  2022-01-05  22:50   6   7  14  15  16  ...   54   55   59   61   70   71   80
13599  2022-01-06  15:00   9  10  11  17  28  ...   51   55   65   67   72   76   78
13600  2022-01-06  22:50   1   2   6   9  11  ...   51   52   54   67   68   73   75

I have found this article:
https://machinelearningmastery.com/how-to-develop-convolutional-neural-network-models-for-time-series-forecasting/
But I am trying to develop a modified version of that 1D CNN model by using softmax function on the last layer and SparseCategoricalCrossentropy() as loss function and also by adding new functions to that code making it different.
This is my code so far and the model I am trying to build and use:
# multivariate output 1d cnn example
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # or any {'0', '1', '2'}
import warnings

warnings.filterwarnings('ignore')
import pandas as pd
# multivariate output 1d cnn example
from numpy import array
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import *
from tensorflow.keras.losses import *
from tensorflow.keras.layers import *
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.callbacks import ModelCheckpoint

# Define the Required Callback Function
class printlearningrate(tf.keras.callbacks.Callback):
    def on_epoch_end (self, epoch, logs={}):
        optimizer = self.model.optimizer
        lr = K.eval(optimizer.lr)
        Epoch_count = epoch + 1
        print('\n', "Epoch:", Epoch_count, ', Learning Rate: {:.7f}'.format(lr))

printlr = printlearningrate()

# split a multivariate sequence into samples
def split_sequences (sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the dataset
        if end_ix > len(sequences) - 1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix, :]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

df = pd.read_csv('DrawsDB.csv')

print(df)
# df['Time'] = df[['Day', 'Hour']].agg(' '.join, axis=1)
df.insert(0, 'Time', df[['Day', 'Hour']].agg(' '.join, axis=1))
df.drop(columns=['Day', 'Hour'], inplace=True)
df.set_index('Time', inplace=True)
print(df)

numpy_array = df.to_numpy()

print(type(numpy_array))
print(numpy_array)

# choose a number of time steps
n_steps = 10
# convert into input/output
X, y = split_sequences(numpy_array, n_steps)
print(X.shape, y.shape)

# the dataset knows the number of features, e.g. 2
n_features = X.shape[2]
# Reduce learning rate when nothing happens to lower more the loss:
reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.9888888888888889,
                              patience=10, min_lr=0.0000001, verbose=1)

epochs = 10
# saving best model every epoch with ModelCheckpoint:
checkpoint_filepath = 'C:\\Path\\To\\Saved\\CheckPoint\\model\\'
model_checkpoint_callback = ModelCheckpoint(
    filepath=checkpoint_filepath,
    monitor='loss',
    save_best_only=True,
    save_weights_only=True,
    verbose=1)

# define model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=2, activation=LeakyReLU(), input_shape=(n_steps, n_features)))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(50, activation=LeakyReLU()))
model.add(Dense(n_features))
model.compile(optimizer=Nadam(lr=0.09), loss=SparseCategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])

# fit model
model.fit(X, y, epochs=10, verbose=2, callbacks=[printlr, reduce_lr, model_checkpoint_callback])

split_sequences function like its name says it is splitting the database by taking just N rows from it as input and trying to predict the all N+1 row from the database as the output.
However, I think there is a problem because I am getting this error every time I am trying to run the python script:
tensorflow.python.framework.errors_impl.InvalidArgumentError:  logits and labels must have the same first dimension, got logits shape [32,20] and labels shape [640]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits
 (defined at C:\Users\UserName\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend.py:5114)
]] [Op:__inference_train_function_1228]

Any idea on how to fix this problem, please?
Thank you in advance!

A: Assuming the labels are integers, they have the wrong shape for SparseCategoricalCrossentropy. Check the docs.
Try converting your y to one-hot encoded labels:
y = tf.keras.utils.to_categorical(y, num_classes=20)

and change your loss function to CategoricalCrossentropy:
model.compile(optimizer=Nadam(lr=0.09), loss=tf.keras.losses.CategoricalCrossentropy(),
              metrics=['accuracy', mean_squared_error, mean_absolute_error, mean_absolute_percentage_error])

and it should work.


text:
Q: Store all the keys of a JSON object in a variable I get from the server strings like the following:
{"Point Ref":[15629989,564646414,65494949],
"Effective Date":["2008-03-03","2010-12-14","2004-10-01"],
"Identifier":["EM","EM","SC"],"Status":["FI","SI","XC"]}"

which I convert to JSON with:
var jsonResponse = jQuery.parseJSON(xmlHttp.responseText.trim());

Until here everything is fine: I can loop through jsonResponse and do my stuff. However I can't find an easy quick way to have immediately all the key in one array.
Basically, is there anything else other than this:
var keys = new Array();
var n = 0
for (var i in jsonResponse){
    keys[n] = i
    n ++
}

Thanks.

A: You can use Object.keys:
var keys = Object.keys(jsonResponse);

A: An alternative solution using array.map()
//minified polyfill for old browsers:
if (!Array.prototype.map) { Array.prototype.map = function (e, t) { var n, r, i; if (this == null) { throw new TypeError(" this is null or not defined") } var s = Object(this); var o = s.length >>> 0; if (typeof e !== "function") { throw new TypeError(e + " is not a function") } if (t) { n = t } r = new Array(o); i = 0; while (i < o) { var u, a; if (i in s) { u = s[i]; a = e.call(n, u, i, s); r[i] = a } i++ } return r } }

var keys = jsonResponse.map(function(v, k) { return k; });


text:
Q: Can't auto-complete the React component tag using tab in vscode? Here is the code:

In the returned body of function Parent, when I type h1 and press tab, the h1 turns into

. But this doesn't work when I type Child and press tab. The Child doesn't turn into a pair of tags. It seems the auto-complete has failed in this condition. How could I solve this problem? Installing an extension or changing some settings?
Btw, I now have installed the Reacjs code snippet extension and edited the setting like this:
"emmet.includeLanguages": {
    "javascript":"javascriptreact"
},

A: You should create an external JavaScript file and then import it to your HTML file like this :

It's better if your file extension be .jsx, because VS Code treats that as a React app.
But this is not the suggested way to write react code.
I recommend to use create-react-app to create a React app:
npx create-react-app my-app

Make sure to install node before.


text:
Q: how to code to get facebook friend list in ios7 Hi am using following code
-(IBAction)FacebookFriendBtnClk:(id)sender
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
__block ACAccount *facebookAccount = nil;

ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

// Specify App ID and permissions
NSDictionary *options = @{
                          ACFacebookAppIdKey: @"743178525726332",
                          ACFacebookPermissionsKey: @[@"publish_stream", @"publish_actions",@"read_friendlists"],
                          ACFacebookAudienceKey: ACFacebookAudienceFriends
                          };

[accountStore requestAccessToAccountsWithType:facebookAccountType
                                      options:options completion:^(BOOL granted, NSError *error)
 {
     if (granted)
     {
         NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];

         facebookAccount = [accounts lastObject];
     }
     else {

         NSLog(@"error.localizedDescription======= %@", error.localizedDescription);
     }

 }];

NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];

//NSString *acessToken = [NSString stringWithFormat:@"%@",facebookAccount.credential.oauthToken];
//NSDictionary *parameters = @{@"access_token": acessToken};

NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:@"picture,id,name,link,gender,last_name,first_name,username",@"fields", nil];

NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/friends"];
SLRequest *feedRequest = [SLRequest
                          requestForServiceType:SLServiceTypeFacebook
                          requestMethod:SLRequestMethodGET
                          URL:feedURL
                          parameters:param];
feedRequest.account = facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
                                         NSHTTPURLResponse *urlResponse, NSError *error)
 {
     if(!error)
     {
         id json =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

         NSLog(@"Dictionary contains data: %@", json );
         if([json objectForKey:@"error"]!=nil)
         {
             //[self attemptRenewCredentials];
         }
         dispatch_async(dispatch_get_main_queue(),^{
             //nameLabel.text = [json objectForKey:@"username"];
         });
     }
     else{
         //handle error gracefully
         NSLog(@"error from get%@",error);
         //attempt to revalidate credentials
     }
 }];

}
Am getting following error in log
  2014-04-04 16:49:04.098 ImageProcessingDemo[4791:3c0b] error.localizedDescription======= (null)
  2014-04-04 16:49:34.964 ImageProcessingDemo[4791:3f07] Dictionary contains data: {
error =     {
    code = 2500;
    message = "An active access token must be used to query information about the current user.";
    type = OAuthException;
    };
}

A: Please try below code :-
-(void)getFrndList
{
    @try
    {
        [app showIndicator:@"Loading..."];
        if (![FBSession activeSession].isOpen) {
            [FBSession renewSystemCredentials:^(ACAccountCredentialRenewResult result,
                                                NSError *error)
             {
                 if(error)
                 {
                     [app stopIndicator];
                 }
                 NSArray *permissions = [NSArray arrayWithObjects:@"email", @"read_friendlists", @"user_photos", @"user_events", nil];
                 [FBSession openActiveSessionWithReadPermissions:permissions
                                                    allowLoginUI:YES
                                               completionHandler:
                  ^(FBSession *session,
                    FBSessionState state, NSError *error) {
                      if(error)
                      {
                          [app stopIndicator];
                      }
                      [self btnFriends:nil];
                  }];
             }];
        }
        else
        {
            [self btnFriends:nil];
        }
    }
    @catch (NSException *e) {

    }
}

-(IBAction)btnFriends:(id)sender
{

    FBRequest* friendsRequest = [FBRequest requestForMyFriends];
    [friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                                                          NSDictionary* result,
                                                          NSError *error) {
    NSArray* friends = [result objectForKey:@"data"];
    [arrFacebookFriends removeAllObjects];
    NSLog(@"Found: %i friends", friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:[NSString stringWithFormat:@"%@ %@",friend.first_name,friend.last_name] forKey:dictkeyName];
    [dict setValue:friend.id forKey:dictkeyId];
    [dict setValue:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large",friend.id] forKey:dictkeyImage];
    [arrFacebookFriends addObject:dict];
    NSLog(@"I have a friend named %@ with id %@", friend.name, friend.id);

    }

     [app stopIndicator];
     }];

}


text:
Q: Changing sqlite to PostgreSQL in ruby on rails I am using win 7 with docker and in docker I am using ruby on rails, I did an application that works very well with sqlite3 but when I try to upload to Heroku, Heroku gave me an error that it is not supported sqlite3 so I had to change my app database to PostgreSQL and I did the following changes:
in my Gemfile I commented gem sqlite3:
# Use sqlite3 as the database for Active Record
#gem 'sqlite3'
#posgresql
gem 'pg'

second i did a "bundle install" and then a docker-compuse build
then in my database.yml:
BEFORE:
default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

after the changes:
development:
  adapter: postgresql
  database: my_database_development
  pool: 5
  timeout: 5000

test:
  adapter: postgresql
  database: my_database_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: my_database_production
  pool: 5
  timeout: 5000

so when i tried to create a new datebase with "rake db:create" docker gave me the next error:
 $ docker-compose run web rails db:create
Starting grupo43_postgres_1 ... done
could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Couldn't create database for {"adapter"=>"postgresql", "database"=>"my_database_
development", "pool"=>5, "timeout"=>5000}
rails aborted!
PG::ConnectionBad: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `initialize'
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `new'
/usr/local/bundle/gems/pg-1.0.0/lib/pg.rb:56:in `connect'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
postgresql_adapter.rb:697:in `connect'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
postgresql_adapter.rb:221:in `initialize'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
postgresql_adapter.rb:38:in `new'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
postgresql_adapter.rb:38:in `postgresql_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:759:in `new_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:803:in `checkout_new_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:782:in `try_to_checkout_new_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:743:in `acquire_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:500:in `checkout'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:374:in `connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_adapters/
abstract/connection_pool.rb:931:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_handling.
rb:116:in `retrieve_connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/connection_handling.
rb:88:in `connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/postgresql_dat
abase_tasks.rb:10:in `connection'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/postgresql_dat
abase_tasks.rb:19:in `create'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:117:in `create'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:137:in `block in create_current'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:305:in `block in each_current_configuration'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:302:in `each'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:302:in `each_current_configuration'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/tasks/database_tasks
.rb:136:in `create_current'
/usr/local/bundle/gems/activerecord-5.1.6/lib/active_record/railties/databases.r
ake:27:in `block (2 levels) in <top (required)>'
/usr/local/bundle/gems/railties-5.1.6/lib/rails/commands/rake/rake_command.rb:21
:in `block in perform'
/usr/local/bundle/gems/railties-5.1.6/lib/rails/commands/rake/rake_command.rb:18
:in `perform'
/usr/local/bundle/gems/railties-5.1.6/lib/rails/command.rb:46:in `invoke'
/usr/local/bundle/gems/railties-5.1.6/lib/rails/commands.rb:16:in `<top (require
d)>'
/example/bin/rails:9:in `require'
/example/bin/rails:9:in `<top (required)>'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `load'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/client/rails.rb:28:in `call'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/client/command.rb:7:in `call'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/client.rb:30:in `run'
/usr/local/bundle/gems/spring-2.0.2/bin/spring:49:in `<top (required)>'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `load'
/usr/local/bundle/gems/spring-2.0.2/lib/spring/binstub.rb:31:in `<top (required)
>'
/example/bin/spring:15:in `require'
/example/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:create
(See full trace by running task with --trace)

i found different solution but for linux and mac, all i could inform here is that maybe the problem is because i have to delete some file that i didn t know where i can find with windows or with docker :(, all the information i found is here: PG::ConnectionBad - could not connect to server: Connection refused
this is my docker-compose.yml file:
version: '3'
services:
  postgres:
    image: postgres:10.3
    ports:
      - "3000"
  web:
    build: .
    env_file:
      - .env
    command: bash -c "(bundle check || bundle install) && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/example
    ports:
      - "3000:3000"
    depends_on:
      - postgres

A: Make sure you have installed PostgreSQL in your machine and add a helpful tool called pgAdmin, then update the database.yml file like below
default: &default
  adapter: postgresql
  encoding: unicode
  username: postgres
  password: xxxxx #<-- which you have defiend while installing postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: project_development

test:
  <<: *default
  database: project_test

production:
  <<: *default
  database: project_production
  username: username
  password: <%= ENV['PROJECT_DATABASE_PASSWORD'] %>

and gem pg use in your Gemfile like gem 'pg', '~> 0.20.0' with this version then run bundle install
rake db:create
rake db:migrate

for Heroku
heroku run rake db:migrate

and you can use rails command instead of rake if your rails version is rails > 5.0.0

A: The simplest way for me was to

*

*Create a new app like this rails new testapp --database=postgresql

*Open config/database.yml

*Copy everything in that file into my existing app

*Change the name in about 4 places in that file

*Everything worked!

An advantage of this solution is you can use it for any rails version (just make sure the new app you create is the same rails version as the one whose database you're switching).


text:
Q: Track how much network data my Android app uses In Android Studio 1.4 they've introuced a Network Monitor. This is great, but it only shows real time data.
Is there any way to see how much data is being used overall, or am I limited to watching only real time performance?


text:
Q: how to configure proxy server (squid) to certain link I need to configure a proxy server:

*

*which will allow my clients to connect to my proxy server then

*they will be able to see a login page.

When I asked some IT gurus they told me "configure the forwarding url in proxy".
How do I achieve this? What kind of proxy should I use?

A: Have you tried any hotspot services? Like Chilli Spot, etc.
Also you may be interested in special distros for routers which include such features including hotspot out-of-box: pfSense, m0n0wall, mikrotik, etc.


text:
Q: Calculating the path of a ball with spin moving across a table A ping pong ball is rolling over a smooth (but not frictionless) table. During its travel, a clockwise spin is placed on the ball. The ball's path is changed to move to the right (in perspective from it's initial path). If the friction of the table is a variable $f$ that can be altered, how does one calculate the altered path of the ball after spin is applied?

A: A single parameter is not going to be sufficient to capture the effect you seek. Think of a spinning disk, which will have an extended contact area in the shape of a circle. The motion of any point of the disk can be decomposed into a velocity $v_\parallel$ in the direction of the bulk motion, and an orthogonal velocity $v_\perp$. If friction were independent of speed, then $v_\parallel$ and $v_\perp$ will be reduced at the same rate everywhere, leading to a net slowing of both the bulk motion and the spin but not resulting in any redirection of the bulk motion.
The reason spinning objects' paths are redirected is that they experience asymmetric friction/drag forces as different parts move at different relative speeds in the fixed environment. In other words, $\dot{v}_\perp$ does not average out to $0$ over the contact area.

In order to lay the framework, suppose the disk has a bulk linear velocity $v_\mathrm{lin}$, an angular frequency $\omega$, and a direction of travel $\theta$ measured in the usual sense with respect to an $xy$-grid on the (presumably inertial) surface. Label points on the disk with a distance $r$ from the center and an angle $\phi$ measured with respect to the same $xy$-grid.
With these definitions it is easy to see (especially if you make a sketch) that
\begin{align}
v_\parallel & = v_\mathrm{lin} - r\omega \sin(\phi-\theta) \\
v_\perp & = r\omega \cos(\phi-\theta).
\end{align}
These components have directions
\begin{align}
\hat{v}_\parallel & = \cos(\theta) \hat{x} + \sin(\theta) \hat{y} \\
\hat{v}_\perp & = -\sin(\theta) \hat{x} + \cos(\theta) \hat{y},
\end{align}
and so the overall velocity is
$$\vec{v} = v_\parallel \hat{v}_\parallel + v_\perp \hat{v}_\perp. $$
Let
$$ v = \sqrt{v_\parallel^2 + v_\perp^2} $$
be the speed and define $\hat{v} = \vec{v} / \lvert \vec{v} \rvert = \vec{v}/v$.
The object is a rigid body, and so we can integrate forces over the whole contact area to find the net results. (Without rigidity, each point would have its own dynamics coupled to those of its neighbors, making for a much more complicated problem.) Let $f(v)$ be the magnitude of the friction force per unit area as a function of relative speed. The direction will simply be $-\hat{v}$, since friction can only work exactly opposite the direction of motion at a point. Then the total force on the disk $D$ is
$$ \vec{F} = - \int\limits_D f(v) \hat{v} \ \mathrm{d}A. $$
At the same time, there will be a torque per unit area given by $-f(v) \vec{r} \times \hat{v}$, where $\vec{r}$ is the vector with magnitude $r$ pointing in the direction $\phi$. The net torque on the disk will be
$$ \vec{\tau} = -\int\limits_D f(v) \vec{r} \times \hat{v} \ \mathrm{d}A. $$
Finally, we can connect the forces with the change in the variables of interest. The linear velocity
$$ \vec{v}_\mathrm{lin} = v_\mathrm{lin} \left(\cos(\theta) \hat{x} + \sin(\theta) \hat{y}\right) $$
will evolve according to
$$ \dot{\vec{v}}_\mathrm{lin} = \frac{1}{m} \vec{F}, $$
where $m$ is the mass of the disk. The disk will also spin down according to
$$ \dot{\omega} = \frac{1}{I} \tau, $$
where $I$ is the moment of inertia and $\tau = \lvert \vec{\tau} \rvert$.

As you can see, this can be complicated in general. Even some rather simple forms for $f(v)$ lead to intractable equations if you want analytic solutions. My recommendation is to simply numerically evolve the system under the guidance of the equations given.
The fact that the original question was for a ball rather than a disk changes little. The ball must have a non-vanishing contact area if it is to curve at all. The only trick is to remember to use the proper formulas for $m$ and $I$, and possibly to introduce $r$-dependence into $f$ to account for unequal weight per unit area over the contact surface.


text:
Q: Application of Intermediate Value Theorem for five-point formula (numerical differentiation) I have a specific, for-learning-sake-only question on how the author of this link:
http://www.math.ucla.edu/~yanovsky/Teaching/Math151A/hw5/Hw5_solutions.pdf
gets past the details of the Intermediate Value Theorem on the following paragraph. If someone could fill in the details for me, it would be greatly appreciated because I'm having a hard time understanding.
$$\begin{align}
\left(\frac{3}{12h}f^{(5)}(\xi_1)+\frac{18}{12h}f^{(5)}(\xi_2)-32\frac{6}{12h}f^{(5)}(\xi_3)+243\frac{1}{12h}f^{(5)}(\xi_4)\right)\frac{h^5}{120}&= \\
\left(\frac{3}{12}f^{(5)}(\xi_1)+\frac{18}{12}f^{(5)}(\xi_2)-32\frac{6}{12}f^{(5)}(\xi_3)+243\frac{1}{12}f^{(5)}(\xi_4)\right)\frac{h^4}{120}&= \\
6f^{(5)}(\xi)\frac{h^4}{120}&= \\
\frac{h^4}{20}f^{(5)}(\xi)
\end{align}$$
"Note that the IVT was used above..."
Shouldn't it be
"Suppose $f^{(5)}$ is continuous on $[x_0-h,x_0+3h]$ with
$x_0-h < \xi_1<x_0<\xi_2<x_0+h<\xi_3<x_0+2h<\xi_4<x_0+3h.$ Since $\frac{1}{4}[f^{(5)}(\xi_1)+f^{(5)}(\xi_2)+f^{(5)}(\xi_3)+f^{(5)}(\xi_4)]$ is between $f^{(5)}(\xi_1)$ and $f^{(5)}(\xi_4)$, the Intermediate Value Theorem implies that a number $\xi$ exists between $\xi_1$ and $\xi_4$, and hence in $(x_0-h,x_0+3h)$, with $f^{(5)}(\xi)=\frac{1}{4}[f^{(5)}(\xi_1)+f^{(5)}(\xi_2)+f^{(5)}(\xi_3)+f^{(5)}(\xi_4)]$"?


text:
Q: Allow users to view specific records based on custom security requirements I need some advice on how best to implement a security mechanism in a ASP.net core application. The application users are authenticated using AD authentication. Is there a best practice for this type of implementation?
I have a list of project records. Users should only be able to retrieve a list of projects that they have permission to access. I have three user types that have different levels of access as detailed below.

*

*Approvers – assigned to individual projects.

*State approvers – Can view state-wide projects.

*Global approvers – Can access all projects.

Does anyone have any suggestions on what model and logic to implement to achieve what is required?

A: Well, I secure pages with information "limited" to logged on users. So if they have membership in a particale role, then only those users can jump/see such pages.
However, in your case, and often?
Well, it not so much the web page the user can use, or be restricted from.
However, when a web page can be restriced based on IIS security and not your code, then that option should be used.
However, often in code, for example, we have indivdul users from a given company, and ONLY some can and are allowed to see all projects. (so some only can see their own projects, but from that company, some have rights to see + use all projects.
So, we often have code say like this:
    Dim cmdSQL As New SqlCommand("dbo.GetProjects", GetCon)
    cmdSQL.CommandType = CommandType.StoredProcedure

    cmdSQL.Parameters.Add("@LogonID", SqlDbType.Int).Value = Membership.GetUser.ProviderUserKey
    cmdSQL.Parameters.Add("Email", SqlDbType.NVarChar).Value = Membership.GetUser.Email
    cmdSQL.Parameters.Add("@PortalMaster", SqlDbType.Bit).Value = IIf(Roles.IsUserInRole("PortalMaster"), 1, 0)

so, if the user is a PortalMaster, then they can get and see all projects belonging to that company. (each company that logs into teh site can have 1 or 20 employees that belong to the given company).
So, in above, the query going to pull projects by EmployeeID (their logon), and thus they can only ever see their own projects.
If you are a member of the PortalMaster group, then we pull projects based on ComapnyID.
So, while you might not be using the older secuirty provider like above? Your queries that pull projects simple have to restrict rows returned based on above.
Once those projects are returned (in a nice grid - searching options included), then they can select (click on) a project. that next page does not really care anymore, since you can't get to the project details page until you selected a project.
So, obvious you must have for a given Project who created it. And thus your ability to display their current projects will be restriced based on their logon ID or whtever you using now.
But, for state level users? Then your critera is by their logon id and their state they belong to based on that logon.
And then there is the "admin" role or group - they can search and pull on all projects.
So, while we do restrict web pages by "role" security (based on IIS), that just means that all users can, or cannot hit some web pages based on their role memember ship (and such security does not require code on my part - the IIS secuirty assinged to those web pages can do all that dirty work for you.
However, if you are a legal logon, then you can only ever work on projects that belong to your company. But then it is a question if that user also has the role of "PortalMaster", and if they do, then we pull all projects for display to select from for that given user.
And of course we never use say URL "query parameters", and such internal database company ID, or ContactID (user id) are never exposed, nor possible allow display of information or data that don't belong to the given user.
So, you need to build some sql or some store procedures, and having a few "parameters" for those stored procedures that returns rows of data based on their role membership is quite much how you would approach this. So in above, if the user is a portal master, then the stored procedure simple queries the data based on company they belong to as opposed to their contact id.
Now, this of course asseumes the database schema is setup, and for example, we hvae a company table, a employee table (that has their logon information), and then of course each project created has both a created by, and the company the project belongs to. So, that simple information is enough to provide the 2 levels of security.
We actually don't have a "super user" that can look at and see all projects in the system, but it actually not all that bad of a idea, since for testing, or checking a project that has some problem is a "pain" right now, since we in theory have to create a logon for that company, or get a password.
So, all logons we create belong to a given company. And thus when a user creates a new project, it can only be created under that one company, and of course a project also requires the user that created the project.
So, you simple have to restrict records returned in the page in which they can select a project to work on. IIS security, or in fact SQL server security as a general rule can't do this type of security for you - you the developer have to.


text:
Q: Polynomial Calculator using Linked List I'm working on a polynomial calculator project and I'm working on the first part. Polynomials will be represented in a specific format where two polynomials are a sequence of integers representing the coefficients and exponents. Here's an example.
4 3 -2 2 6 1
6 3 5 2 3 1

Polynomial 1 = 4x^3 - 2x^2 + 6x and Polynomial 2 = 6x^3 + 5x^2 + 3x
I'm supposed to use Linked List to implement this.
Here's my class Node code:
class Node {
    int coef;
    int power;
    Node next;
    public Node(int coef, int power) {
        this.coef = coef;
        this.power = power;
    }
}

How do I efficiently separate the coefficients and the exponents and add to the Linked List?
Here's my code for pushing a new Polynomial node:
void addPoly(int coef, int pow) {
    Node newNode = new Node(coef, pow);
    if (head == null) {
        head = newNode;
        head.next = null;
    } else {
        Node curr = head;
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = newNode;
    }
}

Thanks!

A: You can split your input and then convert each resulting string to an integer. If the power is always in decreasing order you loop backwards to reduce code complexity.
String s = "4 3 -2 2 6 1";
int[] values = Arrays.stream(s.split(" "))
    .mapToInt(Integer::valueOf)
    .toArray();
assert values.length % 2 == 0;
for (int i = values.length - 1; i > 0; i = i - 2) {
    int coeff = values[i - 1];
    int power = values[i];
    addPoly(coeff, power);
}

addPoly can be reduced to
void addPoly(int coeff, int power) {
    Node node = new Node(coeff, power);
    node.next = head;
    head = node;
}

At the first iteration head is null so the first node becomes the end of the list. Each next step is the predecessor. So the head is it's next. Last but not least the new node becomes the next head.

A: Java-9 solution, using regex Pattern with two capture groups and a MatchResults stream:
String input = "4 3 -2 2 6 1";
Pattern p = Pattern.compile("\\s*(-?\\d+)\\s+(-?\\d+)");
// add all the polynomials to myList
p.matcher(input).results().forEach(m -> myList.addPoly(m.group(1), m.group(2));


text:
Q: Combining output of two java servlets I'm making a hostel management system with backend in java. I made a header class that shows the menu and I want it to be included on every servlet of my project. I have tried using request dispatcher. like this:
RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);

When I put it on some servlet, the output of that servlet is removed(only that output which is placed after this include line) and only header servlet is displayed. I have overloaded both doGet() and doPost() methods in header servlet.
The Following picture shows that my header is working fine
An Example servlet is here in which I'm including header servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class add extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
    PrintWriter out = res.getWriter();

    res.setContentType("text/html");
    out.println("<title>Add student</title>");
    RequestDispatcher rd1 = req.getRequestDispatcher("/header");
    rd1.include(req, res);           //I want to show the data after this line as well
    out.println("<form method='post' action='addtoDatabase'>");
    out.println("Roll Number : <input type='text' name='roll' placeholder='student Roll Number'>
");
    out.println("Name : <input type='text' name='studentName' autofocus placeholder='student name'>
");
    out.println("room number : <input type='text' name='roomNumber' placeholder='Room Number'>
");
    out.println("Address : <input type='text' name='address' placeholder='Address'>
");
    out.println("Phone : <input type='text' name='phone' placeholder='03001234567'>
");
    out.println("<input type='submit' value='Add Student'> ");

    out.println("</form>");
    out.close();
}
}

In the above code, the HTML form is not been displayed on the browser. Only the header is displayed as I have shown in the following screenshot.
Screenshot of remove page
How can I combine the output of both header and any other servlets on the browser?

A: there are Session Scope, also have Application Scope. I am wondering what are you achieving is share some data between different sessions. That is you need Application Scope. That is ServletContext , Please refer to Using application scope variables in java


text:
Q: remote_api in google app engine is the best way to store data? i don't know what  the remote_api will do
thanks

A: You can read about remote_api here: http://code.google.com/appengine/articles/remote_api.html
At a high level, it allows you to write code which interacts with your appengine application code and datastore without having to go through the request/response model.


text:
Q: Bootstrap Tooltip changes from top to bottom when it reaches the top of the screen I'm working with tooltip in the top position, the problem is that when I scroll and the tooltip is reaching the top of the window it changes its bottom position, which I do not want it to do, but keep it in position at all times higher.
If you start the code that I put in this question you will see that the tooltip is automatically displayed, and when you scroll down all the tooltip changes from top to bottom position which I do not want you to do, I want to keep it at all times top.
Thanks for the help.

$(window).ready(function() {
  $('[data-toggle="tooltip"]').tooltip({ placement: 'top', boundary: 'window'                 });
  $("#element").tooltip('show');
});
body{
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.btn-secondary{
  height: 50px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<button id="element" type="button" class="btn btn-secondary" data-toggle="tooltip"  title="Tooltip on top">
  Tooltip on top
</button>

<script
     src="https://code.jquery.com/jquery-3.3.1.min.js"
     integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
     crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>

A: You are missing data-placement="top"
try this
<button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top" title="Tooltip on top">
 Tooltip on top
</button>


text:
Q: Convert string to Date with zone in Ruby I am having a trouble with converting string to date object,
this is my string
dt='Fri Mar 29 2013 14:30:00 GMT 0530 (IST)' ;

i want to convert it to
2013-03-29 09:00:00

How can i do that ?
Thanks

A: Like this:
Time.parse(string).strftime('%Y-%m-%d %h:%m:%s')

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html
has plenty of info for how to format the output etc.

A: Quite easy in ruby:
require 'time'
Time.parse('Fri Mar 29 2013 14:30:00 GMT 0530 (IST)').strftime('%Y-%m-%d %H:%m:%S')

A: The point is that have to subtract the 5.5 hours from time. To do so have to convert it to a time object, then must subtract the time. Then have to to convert it again. A simple point. But i missed it.
time = Time.parse(time_string)
my_time = (time - 5.5*60*60).strftime("%Y-%m-%d %H:%M:%S")


text:
Q: Using MongoDB from client with Javascript I am trying to use MongoDB with just javascript from client, but MongoDB's documentation on how to achieve this is very confusing.
On this webpage there is nothing to download, I was expecting to see something like mongo.js.
Here I did find mongo.js, and using this I am trying to make it work but with no luck.
The Javascript console in Google Chrome is saying:

Uncaught TypeError: Object [object Object] has no method 'init'

In this snippet from mongo.js:
if ( typeof Mongo == "undefined" ){
  Mongo = function( host ){
    this.init( host );
  }
}

Does anyone have any tips on using MongoDB with pure Javascript?

A: Update: MongoDB has a service introduced this year , MongoDB Stitch. This allows developers to connect to MongoDB Atlas (cloud) and expose data as well as queries to be consumed directly at the ui ( through js) . Currently, its in beta but documentation and samples are on their site for reference.

A: There are lots of limitations in using REST web services provided by MongoDB. It is having very limited functionality and we can not provide query criteria or sort options while querying the data.
I suggest to write your own server side script or servlet to provide REST interface to fetch the data from MongoDB.

A: The documentation you linked to is about accessing MongoDB with server-sided Javascript using the node.js framework.
MongoDB does offer a REST webservice allowing rudimentary queries through XmlHttpRequests. To enable it, you have to start mongod with the --rest parameter. You can then query it like this:
http://127.0.0.1:28017/yourDatabase/yourCollection/?filter_name=Bob

You can query this URL with an AJAX XmlHttpRequest like any webservice. It will access a database on localhost and return JSON equivalent to a query like this:
yourDatabase.yourCollection.find({name:"Bob"});

This interface, however, is very rudimentary. It only offers simple find queries. But there are 3rd party middleware layers which expose more advanced functionality. This feature and a list of 3rd party solutions is documented here:
http://docs.mongodb.org/ecosystem/tools/http-interfaces/


text:
Q: startActivityForResult(Intent, int) what is the purpose of the integer argument I am following a tutorial that uses "startActivityForResult" function. I know why this function is used and if we want to use the returned data, we use onActivityResult() function. The thing that I wana know is, why do we pass an Integer to startActivityForResult() function? And where is it used?
Thanks for your kind help!

A: When the Activity that you're starting finished, that second argument is passed to the method onActivityResult() of the calling Activity. This is to distinguish different results from one another.
You may have a case where an Activity needs to call several others for results, and by specifying a unique int for each of them, you can determine the correct thing to do when you get a result.
Edit: Here's an example.
Suppose you have a screen (Activity A) where you choose a picture from your gallery, and you choose a friend to send it to. You'll start an activity to pick a picture from the gallery on a button click, and maybe you also have a "friend picker" activity which you can also start from Activity A.
You want both of those activities to return the data the user selected. onActivityResult() will get called on Activity A when the user finishes with the two activities described above. By specifying the requestCode for startActivityForResult() for the gallery activity, and your "friend picker", you know what to do in onActivityResult().
Also, note that you don't need a complicated scheme for requestCode. You could just pass in the values 1 and 2 for the gallery and friend picker, respectively.

A: It is to differentiate between different results.  You might use different intents to start each Activity and typically you have constants like this:
ACTIVITY_RESULT_INTENT_1 = 1
ACTIVITY_RESULT_INTENT_2 = 2

So if you passed one of these into startActivityForResult(), then it will also return these request codes to allow you to use whatever logic you want.

A: From the reference

If >= 0, this code will be returned in onActivityResult() when the activity exits.

So, its for your own benefit. Just set a code - if you want, use an ENUM to set some proper return values. :)

A: As per documentation

requestCode   If >= 0, this code will be returned in onActivityResult() when the activity exits.


text:
Q: VBA Search Range for text then run macro I'm trying to write a VBA macro (which I'll attach to a command button) which searches K7 through K13 to find "Sheet1", "Sheet2", "Sheet3", or "Sheet4" Only one answer is possible based on pre-existing If/Then statements.
When it finds "Sheet1" I want it to run macro "GoToSheet1"
When it finds "Sheet2" I want it to run macro "GoToSheet2"
When it finds "Sheet3" I want it to run macro "GoToSheet3"
When it finds "Sheet4" I want it to run macro "GoToSheet4"
Basically i have four possible conditions which could exist based on how someone answers two yes/no questions. That is what the initial if/then statements cover. However, I cannot get the VBA macro to search across the cell range K7 through K13 for any one of the four text phrases.

A: Surely you can loop thru the range K7:K13 for checking each cell values. However using Range.Find method would be a better way to do this.
Private Sub CommandButton1_Click()
    Dim lookingRange As Range
    Set lookingRange = Range("K7:K13")
    If Not lookingRange.Find(What:="Sheet1", LookIn:=xlValues) Is Nothing Then GoToSheet1: Exit Sub
    If Not lookingRange.Find(What:="Sheet2", LookIn:=xlValues) Is Nothing Then GoToSheet2: Exit Sub
    If Not lookingRange.Find(What:="Sheet3", LookIn:=xlValues) Is Nothing Then GoToSheet3: Exit Sub
    If Not lookingRange.Find(What:="Sheet4", LookIn:=xlValues) Is Nothing Then GoToSheet4: Exit Sub
    MsgBox "not found"
End Sub


text:
Q: SQL security to database I am using Visual Basic.net and have a question regarding a SQL connection to an online database.
If I connect to a SQL database via code, how secure is this connection? If I have the password and address of the server in code, can a user work out the login and tamper with the database?

A: "If I have the password and address of the server in code, can a user work out the login and tamper with the database?"
Yes - using freely available tools on the internet a user could decompile your code and find the password and username.
If you need to store a password, store it as an encrypted  string and then decrypt it just before connecting to the database.

A: I wrote a program a while back that connected to a SQL database which I distributed, before I knew how easily .Net can be decompiled. It is extremely easy to get pretty much your full source code which would allow anyone to view the connection information. Even if you encrypt the connection strings, if the encryption/decryption is written as a sub in your program, you are providing them the tools to decrypt it anyways (which will just take up more of their time and cause them to be more malicious).
The way I got around this was to completely lock down the permissions of the user so that they can only see/select/update the areas I wanted them too. I restricted all actions they did not need and only allowed my application to use stored procedures. Even with that in place, users could still cause some problems with those.
There are tools out there called obfuscators that will scramble the source code to make it harder to read. Note that I said harder, and not impossible.


text:
Q: Covert a file from mp4 to a file that HTML video tag can display I have a mp4 file and I want to display it in HTML. The problem is that it won't, not only in HTML but also in my player. In VLC I can watch the video but there is no sound. Maybe the file is corrupted?
This is the output when I run ffmpeg -i my_file.mp4:
[h264 @ 000001b4afc61880] decode_slice_header error
[h264 @ 000001b4afc61880] no frame!
[h264 @ 000001b4afc61880] non-existing PPS 0 referenced
    Last message repeated 1 times
[h264 @ 000001b4afc61880] decode_slice_header error
[h264 @ 000001b4afc61880] no frame!
Input #0, mpeg, from '150_2.mp4':
  Duration: 00:50:51.75, start: 13182.386222, bitrate: 983 kb/s
    Stream #0:0[0x1e0]: Video: h264 (High), yuv420p(progressive), 1280x720, 25 fps, 25 tbr, 90k tbn, 50 tbc
    Stream #0:1[0x1c0]: Audio: pcm_alaw, 8000 Hz, mono, s16, 64 kb/s
At least one output file must be specified.

Can I convert this with ffmpeg to a good quality of video and audio?


text:
Q: Why is my for-loop not accessing the arrays inside this object? I am trying to draw orange ellipses but the for-loop at the bottom of my code isn't drawing anything. I know the code below is the correct way to access arrays inside objects because I used it in another task and it worked. I previously had beginShape(); and endShape(); before and after my for-loop but that didn't work either.
Everything looks correct and I'm not sure what I'm doing wrong. I would appreciate everyone's help. Thanks

Case 601 - Cross Reference - stage 2

Fry is still on the loose. We think she's resorted to stealing to get by.
Hopefully we can track her down by cross-referencing sightings and recent thefts in the area.

In the setup function, use a for loop to traverse the sightings, marking all of the locations on the map
where she was last seen. Do this by drawing small, DarkOrange stroke ellipses at each location.

In addition, we've assembled a list of recent thefts in the area. Using another for loop to traverse the
recent crime records, you should mark those locations on the map. Do this by drawing small, Magenta stroke rectangles centered over each location.

Use X11 colours. You can find a reference table at https://en.wikipedia.org/wiki/Web_colors.

For this mission you will need ONLY the following:

- for loop
- stroke
- ellipse()

- stroke
- rect() NB. Draw each rectangle with the point at its center.

*/

var countyMap;

//Sightings of Casey Fry.

var absconder_record = {
    Loc_X: [639, 681, 712, 756, 715, 701, 753, 815, 795, 788, 781, 768, 750, 732, 714, 695, 693, 654, 624, 594, 555],
    Loc_Y: [288, 286, 293, 310, 368, 425, 436, 468, 506, 497, 486, 489, 500, 506, 514, 531, 552, 523, 500, 484, 474],
};

//Recent crime records.

var robbery_record = [
  { PointX : 403, PointY : 401},
  { PointX : 402, PointY : 360},
  { PointX : 427, PointY : 403},
  { PointX : 646, PointY : 284},
  { PointX : 639, PointY : 264},
  { PointX : 830, PointY : 434},
  { PointX : 809, PointY : 443},
  { PointX : 844, PointY : 496},
  { PointX : 802, PointY : 350},
  { PointX : 683, PointY : 413},
  { PointX : 552, PointY : 464},
  { PointX : 629, PointY : 498},
  { PointX : 712, PointY : 562},
  { PointX : 783, PointY : 603},
  { PointX : 415, PointY : 225},
  { PointX : 561, PointY : 282},
  { PointX : 562, PointY : 392},
  { PointX : 751, PointY : 283},
  { PointX : 680, PointY : 359},
  { PointX : 626, PointY : 436},
  { PointX : 701, PointY : 455},
  { PointX : 838, PointY : 565},
  { PointX : 322, PointY : 508},
  { PointX : 468, PointY : 556},
  { PointX : 625, PointY : 737}
];

function preload()
{
    countyMap = loadImage("map.png")
}

function setup()
{
  createCanvas(countyMap.width, countyMap.height);

    image(countyMap, 0,0);

    //add your code below here
    stroke(255, 140, 0);

    for(i = 0; i <absconder_record.Loc_X[i].length; i++ ){
        ellipse(absconder_record.Loc_X[i], absconder_record.Loc_Y[i], 5)
    }

}

Here is the image its supposed to draw on:

A: Looking at i <absconder_record.Loc_X[i].length,

*

*absconder_record.Loc_X is an array

*absconder_record.Loc_X[i] is a number

*absconder_record.Loc_X[i].length is the length property of a number (cooerced to a Number object) which is undefined

*A comparison check for a number being less than undefined returns false
So the loop condition always fails and the loop body never executes.

A: Looking at this line:
 for(i = 0; i <absconder_record.Loc_X[i].length; i++ ){

I think what you meant to do was:
i <absconder_record.Loc_X.length

i <absconder_record.Loc_X[i].length

*

*i is 0

*absconder_record.Loc_X[0] is 639

*639 doesn't have a length property.

Follow up on the question in the comment:

how do you loop through the array robbery_record?

A for loop takes 3 expressions:

*

*an initializer, usually used to initialize a counter, as in i = 0;. (This runs only once, not on each iteration.)

*a condition to test. if the condition is true, the body of the loop runs. the most common use is to see if the counter has exceeded some threshold, as in i > 10. if i is less than 10, run the body of the loop.

*an expression that runs after each iteration of the loop. most commonly used to increment the counter: i++.

Taken together it looks like this:
for (let i = 0; i < 10; i++) {
  // body
}

*

*i starts with a value of 0.

*The condition is evaluated: Is i less than 10?

*If so, the body of the loop runs.

*after the body runs, the last expression (i++) is executed. Now i is 1.

*Repeat 2-4 until the condition isn't true any more (when i is no longer less than 10).

To use a for loop to iterate over an array, the common approach is to do exactly as above, but replace 10 with the length of the array. So in your case with robbery_record:
for (let i = 0; i < robbery_record.length; i++) {
  // do stuff
}

Usually when someone's doing this it's because they want to execute the body once for each item in the array. Conveniently, because i gets incremented each time through the loop, you can get the current item inside the body of the loop via robbery_record[i]:
for (let i = 0; i < robbery_record.length; i++) {
  const record = robbery_record[i];
  // do stuff with the current record
}

Each of your robbery_record entries is an object with PointX and PointY properties, so you can use those in the body of the loop:
for (let i = 0; i < robbery_record.length; i++) {
  // record is an object, like: { PointX: 123, PointY: 456 }
  const record = robbery_record[i];

  // do stuff with the object's properties
  console.log(record.PointX) // 123
  console.log(record.PointY) // 456

  const x = record.PointX; // now x === 123
  const y = record.PointX; // now y === 456

  // etc.
}

Hope this helps.


text:
Q: Proving $x+y =\sup\left\{ r+s: r,s \in \mathbb{Q}, r\leq x, s\leq y\right\}$ I am trying to show that the following holds:
$$x+y =\sup\left\{ r+s: r,s \in \mathbb{Q}, r\leq x, s\leq y\right\}.$$
I have been able to show that
$$x=\sup\{q\in \mathbb{Q}: r\leq x\}$$
and similarly that
$$y=\sup\{q\in \mathbb{Q}: r\leq y\}.$$
Thus, I am essentially trying to show that
$$\sup\left\{ r+s: r,s \in \mathbb{Q}, r\leq x, s\leq y\right\}=\sup\{q\in \mathbb{Q}: r\leq x\}+\sup\{s\in \mathbb{Q}: s\leq y\}.$$
One direct is trivial, namely that $$\sup\left\{ r+s: r,s \in \mathbb{Q}, r\leq x, s\leq y\right\}\leq\sup\{q\in \mathbb{Q}: r\leq x\}+\sup\{s\in \mathbb{Q}: s\leq y\}=x+y.$$
The other direction is tricker, though. I was trying to approach this by contradiction: Let $A=\{ r+s: r,s \in \mathbb{Q}, r\leq x, s\leq y\}$ and suppose that $\sup A < x+y$. I was trying to use the fact that $\mathbb{Q}$ is dense in $\mathbb{R}$, but I'm still not seeing how to get the proof to work out. Suggestions?? Thank you!!


text:
Q: performing more than one Where in query return null!!! why? how to fix this? i have wrote a method that filters output with provided query and return it. when one Where excuted; it return correct output but when more than one Where excuted; output is null and Exception occured with message "Enumeration yielded no results". why? how i can fix it?
public IQueryable<SearchResult> PerformSearch(string query, int skip = 0, int take = 5)
    {
        if (!string.IsNullOrEmpty(query))
        {
            var queryList = query.Split('+').ToList();
            var results = GENERATERESULTS();
            string key;
            foreach (string _q in queryList)
            {
                if (_q.StartsWith("(") && _q.EndsWith(")"))
                {
                    key = _q.Replace("(", "").Replace(")", "");
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase));
                }
                else if (_q.StartsWith("\"") && _q.EndsWith("\""))
                {
                    key = _q.Replace("\"", "").Replace("\"", "");
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture));
                }
                else if (_q.StartsWith("-(") && _q.EndsWith(")"))
                {
                    key = _q.Replace("-(", "").Replace(")", "");
                    results = results.Where(q=> !q.Title.Contains(key, StringComparison.CurrentCultureIgnoreCase));
                }
                else
                {
                    key = _q;
                    results = results.Where(q => q.Title.Contains(key, StringComparison.CurrentCulture));
                }
            }
            this._Count = results.Count();
            results = results.Skip(skip).Take(take);
            this._EndOn = DateTime.Now;
            this.ExecutionTime();
            return results;
        }
        else return null;
    }

thanks in advance ;)

A:         string key;
        foreach (string _q in queryList)
        {

Ah, the expression binds to the key variable.  You need a new key variable for each execution of the loop.
        foreach (string _q in queryList)
        {
           string key;


text:
Q: If statement not working? Player wins function Tic-Tac-Toe     var boxId = ['boxMid','boxLeft','boxRight','boxTopMid','boxTopRight','boxTopLeft','boxLow        Mid','boxLowLeft','boxLowRight'];

    var turn = 0;

    var pOne = "X";
    var pTwo = "O";
    var blankBox = "";

    var boxMid = document.getElementById('boxMid').innerhtml;
    var boxLeft = document.getElementById('boxLeft').innerhtml;
    var boxRight = document.getElementById('boxRight').innerhtml;
    var boxTopMid = document.getElementById('boxTopMid').innerhtml;
    var boxTopLeft = document.getElementById('boxTopLeft').innerhtml;
    var boxTopRight = document.getElementById('boxTopRight').innerhtml;
    var boxLowMid = document.getElementById('boxLowMid').innerhtml;
    var boxLowLeft = document.getElementById('boxLowLeft').innerhtml;
    var boxLowRight = document.getElementById('boxLowRight').innerhtml;

    var i = 0;

My player win function is not working and I've had several others look at it, so I figured I would get an outside perspective.
    function xWins() {
        if(boxId[0,1,2] == 'X'||
        boxTopLeft == "X" && boxTopMid == "X" && boxTopRight == "X"||
        boxLowMid == "X" && boxLowLeft == "X" && boxLowRight == "X"||
        boxMid == "X" && boxTopMid == "X" && boxLowMid == "X"||
        boxLeft == "X" && boxTopLeft == "X" && boxLowLeft == "X"||
        boxRight == "X" && boxTopRight == "X" && boxLowRight == "X"||
        boxMid == "X" && boxTopLeft == "X" && boxLowRight == "X"||
        boxMid == "X" && boxLowLeft == "X" && boxTopRight == "X" ) {
        alert ('Player One Wins!');
        turn = 1;
        }
    }
    function oWins(){
        if(boxId[0,1,2] == "O"||
        boxTopLeft == "O" && boxTopMid == "O" && boxTopRight == "O"||
        boxLowMid == "O" && boxLowLeft == "O" && boxLowRight == "O"||
        boxMid == "O" && boxTopMid == "O" && boxLowMid == "O"||
        boxLeft == "O" && boxTopLeft == "O" && boxLowLeft == "O"||
        boxRight == "O" && boxTopRight == "O" && boxLowRight == "O"||
        boxMid == "O" && boxTopLeft == "O" && boxLowRight == "O"||
        boxMid == "O" && boxLowLeft == "O" && boxTopRight == "O" ) {
        alert ('Player Two Wins!');
        turn = 0;
        }
    }

    function test(bx){
    if(document.getElementById(boxId[bx]).innerHTML == ""){
            if (turn<1) {
                document.getElementById(boxId[bx]).innerHTML = pOne;
                document.onclick (turn++);
                oWins();
                xWins();
            }

            if (turn == 1) {
                document.getElementById(boxId[bx]).innerHTML = pTwo;
                document.onclick (turn--);
                oWins();
                xWins();
            }
        }
    }

    function reset() {
        for(i=0;i<boxId.length;i++)
        document.getElementsByClassName('boxy')[i].innerHTML = blankBox;
    }

As far as I know, everything else works except for my scoreboard, but I'll figure that out when I get there. Please keep in mind that I am a high school student that has less than 2 months of real experience coding, so I probably did some things that could've been a lot easier, and more DRY.

A: Cause of Bug: You are telling it that oWins() by calling the oWins function, where it runs through your cascasde of OR conditionals to which one of them is matching. So you have 2 problems. 1, that oWins() is always testing true via your OR statements, and 2, that xWins() is being called after the oWins() function that is evaluating to true each time. Stringing together OR conditionals like that is problematic and often difficult to debug.
  if (turn == 1) {
            document.getElementById(boxId[bx]).innerHTML = pTwo;
            document.onclick (turn--);
            oWins();
            xWins();
        }