text:
Q: Derivation of a equation in closed, phases coexisting system
I'm trying to show that for a closed system consisting of two phases coexisting in equilibrium at a temperature $T$ and under a pressure $P$. $$\left(\frac{\partial P}{\partial V}\right)_S=-\frac{T}{C_v}\left(\frac{dP}{dT}\right)^2$$ Here $\frac{dP}{dT}$ is the slope of the phase equilibrium curve.

I tried to perform some calculation at both sides of the equation. For the left side, using the relation $$Tds=c_v\left(\frac{\partial T}{\partial P}\right)_v dP+c_P\left(\frac{\partial T}{\partial v}\right)_P dv$$
I get $$\left(\frac{\partial P}{\partial V}\right)_S=-\frac{C_P}{C_V}\left(\frac{\partial T}{\partial V}\right)_P\left(\frac{\partial P}{\partial T}\right)_V$$
For the right side, I use Clausius-Clapeyron equation $$\frac{dP}{dT}=\frac{l}{T\Delta v}$$
where $l$ is the latent heat. But I have difficulty to relate two sides. Maybe I should head for another direction?

A: This question is problem 10.7 in Adkins, "Equilibrium Thermodynamics." I was going to ask a question about this problem, since my solution, detailed below, is not quite the same as Adkins', but then I noticed the exact same question had been asked already.
For a system of one component in two phases, the equilibrium condition is that the chemical potentials are equal $\mu^{I}(P,T)=\mu^{II}(P,T)$. In principle, this equation could be solved to get $P=P(T)$. This is the co-existence curve of the two phases. So, $P(T)$ is supposed to be known and so is the slope $dP/dT$. So, in whatever way we change the system, $P,T$ are locked in step as $P=P(T)$. The volume V of the system and the mole fractions of the component in each phase will change depending on the details of the change.
Since $\left(\frac{\partial P}{\partial V}\right)_{S}$ appears in the problem, it seems worthwhile to consider a reversible adiabatic change in which the entropy of the complete system is constant. Furthermore, the problem contains the heat capacity at constant volume, so $S=S(V,T)$ seems appropriate.
\begin{equation}
0=dS=\left(\frac{\partial S}{\partial V}\right)_{T}dV+\left(\frac{\partial S}{\partial T}\right)_{V}dT
\end{equation}
Dividing by $dT$ and bringing in the heat capacity at constant volume
$C_{V}=T\left(\frac{\partial S}{\partial T}\right)_{V}$ gives,
\begin{equation}
0=\left(\frac{\partial S}{\partial V}\right)_{T}\frac{dV}{dT}+\frac{C_{V}}{T}
\end{equation}
Now use Maxwell's relation $\left(\frac{\partial S}{\partial V}\right)_{T}
=\left(\frac{\partial P}{\partial T}\right)_{V}$. This gives,
\begin{equation}
0=\left(\frac{\partial P}{\partial T}\right)_{V}\frac{dV}{dT}+\frac{C_{V}}{T}
\end{equation}
It remains to get a formula for the volume change $dV/dT$ in terms of the slope $dP/dT$ of the co-existence curve. Since we need to bring in $dP/dT$ and $S$ is constant, it seems sensible to use $V=V(S,P)$.
\begin{equation}
\frac{dV}{dT}=\left(\frac{\partial V}{\partial S}\right)_{P}\frac{dS}{dT}+\left(\frac{\partial V}{\partial P}\right)_{S}\frac{dP}{dT}
=\left(\frac{\partial V}{\partial P}\right)_{S}\frac{dP}{dT}
\end{equation}
The last equality is because the change is adiabatic. Substituting in the penultimate equation,
\begin{equation}
0=\left(\frac{\partial P}{\partial T}\right)_{V}\left(\frac{\partial V}{\partial P}\right)_{S}\frac{dP}{dT}+\frac{C_{V}}{T}
\end{equation}
A re-arrangement of this result gives something close to the desired answer,
\begin{equation}
\left(\frac{\partial P}{\partial V}\right)_{S}=-\frac{T}{C_{V}}\left(\frac{\partial P}{\partial T}\right)_{V}\frac{dP}{dT}
\end{equation}
This would be the desired answer to Adkins' question if $\left(\frac{\partial P}{\partial T}\right)_{V}=\frac{dP}{dT}$. However,
\begin{equation}
\frac{dP}{dT}=\left(\frac{\partial P}{\partial T}\right)_{V}+\left(\frac{\partial P}{\partial V}\right)_{T}\frac{dV}{dT}
=\left(\frac{\partial P}{\partial T}\right)_{V}+\left(\frac{\partial P}{\partial V}\right)_{T}\left(\frac{\partial V}{\partial P}\right)_{S}\frac{dP}{dT}
\end{equation}
The last equality used the earlier result for $dV/dT$. Now, the usual gymnastics with partials can be used to obtain the well known result (see equation (8.7) of Adkins, for example),
\begin{equation}
\left(\frac{\partial P}{\partial V}\right)_{S}=\frac{C_{P}}{C_{V}}\left(\frac{\partial P}{\partial V}\right)_{T}=\gamma\left(\frac{\partial P}{\partial V}\right)_{T}
\end{equation}
The coefficient of $dP/dT$ on the RHS of the penultimate equation is $1/\gamma$. We can now re-arrange things to get the relation between $dP/dT$ and  $\left(\frac{\partial P}{\partial T}\right)_{V}$ for an adiabatic process.
\begin{equation}
\left(\frac{\partial P}{\partial T}\right)_{V}=\frac{\gamma-1}{\gamma}\frac{dP}{dT}
\end{equation}
Substituting, in my partial result,
\begin{equation}
\left(\frac{\partial P}{\partial V}\right)_{S}=-\frac{T}{C_{V}}\left(\frac{\gamma-1}{\gamma}\right)\left(\frac{dP}{dT}\right)^{2}
\end{equation}
So, this result differs from that of Adkins by the factor containing the ratios of heat capacities. I would appreciate it if someone more adept at thermodynamics than myself would figure out if this factor is erroneous or not.


text:
Q: Call base member in lambda function from inherited class constructor? I have a base class
type MyBase() =
    let param = myfun()
    member this.Param = param

type MyInherited() =
    inherit MyBase()
    do
         base.Param.DoSomething() // cannot access base in let or do binding.

I would like to call DoSomething exact once during the inherited object instantiation. But here I am not allowed. What shall I do then?
Do I have to create a method
     member this.DoSomething() = base.Param.DoSomething()

and call it in the constructor?
type MyInherited() as self =
    inherit MyBase()
    do
         self.DoSomething()

It feels a bit weird, and duplicated
Update
My initial simplified example is not appropriate. Check the followings:
type MyBase() =
    let param = "test"
    member this.Param = param

type MyInherited() =
    inherit MyBase()
    do
       (fun () -> base.Param) () |> ignore  // Doesn't work,
   // A protected member is called or 'base' is being used.
   // This is only allowed in the direct implementation of members
   // since they could escape their object scope.

type MyInherited() as self =
    inherit MyBase()
    do
       (fun () -> self.Param) () |> ignore  // Works

Now actually it is a lot better, all I need to do is to use self instead of base...(I don't have to redefine Param since it is already inherited.)
The reason why F# has such restriction is explained here:
why is base only possible in private members?
But I am still not clear why base cannot be used in a closure, although it is accessible in a simple let binding.

A: your initial code was perfectly valid.  You don't have to define a method first that calls through to a base.
This works:
do
  this.DoSomething()
member this.DoSomething() = base.DoSomething()

but this avoids duplication like you mentioned:
do
  base.DoSomething()

This is what was tripping you up -- constructors can not have a return value.  If the last statement in a sequence has a return, F# assumes that the function has a return of whatever that value/type is.  However, this can not act contrary to a method signature if explicitly defined.  So F# asks you to be explicit about your intention in such a case.  If your intention is to throw away the return of base.DoSomething(), use the pipe-to-ignore operator combination of |> ignore like this:
do
  base.DoSomething() |> ignore

Let's put this another way, if a functions' purpose is to return a value with no side effects, and if this value is consequently not used, then we can safely conclude that the function doesn't need to be called in the constructor.  So the compiler / interactive environment warns you about that.  That's what F# is encouraging here.
To be fair, that's not immediately obvious, unless you take the following into account: do compiles all such statements into the primary constructor.  If you check out the F# OO-style for constructor overloading it might be clearer where the unit * signature was coming from.
Normally, having implicitly defined return value makes writing function a more fluid experience... as Rich Hickey puts it, it is just down to familiarity now.

*

*another name for unit in other languages is void

Update
Possibly a compiler constraint is being applied in an overeager fashion, or probably behind-the-scenes the do is defined as a closure before getting unwound and applied to the constructor by the compiler.  The closure would be able to see the this, but a method / constructor gets a this and a base.  That's not very intuitive is it?  It seems like you've found a rough edge that needs some sanding.  Please consider making a feature request.  F# is now completely open source, so it is worthwhile documenting cases like this.
I did a short exercise on this.  While this can be used in a constructor, that will not be adequate when there's an override.  I think the following might be a decent way forward (see the new() block at the end).
[<AbstractClass>]
type MyBase()  =
    let letValue = "let value"
    abstract Method : unit -> string
    default this.Method() = "test"
    member this.Method2() = "Param2"

type MyInherited(param : string) as this =
    inherit MyBase()

    // let localLetValue() = this.letValue      // fails.  let values are private members

    do
      //(fun () -> base.Param) () |> ignore     // Error: The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls.
      (fun () -> this.Method) () |> ignore       // succeeds -- takes local
      (fun () -> this.base_Method) () |> ignore  // succeeds -- takes base
      (fun () -> this.Method2) () |> ignore      // succeeds -- takes base

    override this.Method() = "ABCdefHIJ"
    member this.base_Method() = base.Method()

    new() as this =
      let a = base.Method()                     // succeeds
      let b = this.Method()                     // succeeds
      MyInherited("some value")

A: This works:
type MyInherited2() =
    inherit MyBase()

    let p = base.Param

    do
        (fun () -> p) () |> ignore

The problem in your MyInherited example was due to the fact that base.Param was being captured in a closure. This works in a let binding, because for all intents and purposes a let binding in object constructor is a direct implementation of a member.
But you're right about inheritance feeling weird. It's a big can of worms in F# and best to keep it dead simple if you can't avoid it altogether.

A: Cannot reproduce. For example this is working for me:
type MyBase() =
    let param = "test"
    let param' = fun _ -> printfn "test'"
    member this.Param = param
    member this.Param' = param'

type MyInherited() =
    inherit MyBase()
    do
       printfn "%s" (base.Param.ToString())
       base.Param'()

let inh = new MyInherited()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Publish Sheet add-on always shows dialog "Go to the G Suite Marketplace SDK..." I have configured the "Google Workspace Marketplace SDK" configuration panel. My app is internal to my organization domain, hopefully won't need any OAuth review nor the app preview.
When I click the Publish-->Deploy as add-on

it always shows a dialog box

Go to the G Suite Marketplace SDK. If you are publishing a new add-on follow this guide. To update an existing add-on follow these steps.

I have connected my Apps Script with GCP standard project, configured the scopes everywhere.
Who can tell me what to do next steps? I want to to publish an internal (private use only) add-on.

Btw, the "G Suite Marketplace API" doesn't have a place to configure apps publication, I did it from the "Google Workspace Marketplace SDK". They are super confusing names...

A: After you finished your "App Configuration" screen for Google Workspace Marketplace SDK (which is opened by default when you click "open SDK" link from Apps Script editor) you also need to make sure your listing is created - this may need to be done just once on initial add-on publishing.
Click on "Store Listing", make sure you filled all required sections, and submit the form.
After successful form submit you will be able to see your listing status:


text:
Q: Trying to get an SVGZ file to display locally I'm doing local development of some web pages, before posting them online.
SVGs inside <img> tags show up just fine, in both Firefox and Chrome. SVGZs do not. However they do show up okay when I actually post my files to the web and they're viewed non-locally. How do I configure my system so that SVGZs show up on a local page? (Linux Mint, if it matters. The SVGZs in question were created with Inkscape, and I've inspected them to make sure that they're valid.)
I've already tried adding this local mime.types file:
image/svg+xml svg svgz

and this local .htaccess file:
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

As near as I can tell, these had no effect.
Thank you.

A: As .svgz files are just gziped .svg files, you can uncompress them for testing.
gzip -cd file.svgz > file.svg
All modern Webservers should be configured to use some sort of Transfer encoding. So there usualy is no need to upload .svgz ... if you still need .svgz anyways, to recompress them:
gzip file.svg
This will result in a file.svg.gz, rename it to file.svgz and you are good to go...


text:
Q: What is $\mathbf Z[x,y]/(y+1)$ isomorphic to?
What is $\mathbf Z[x,y]/(y+1)$ is isomorphic to?

I  was  wondering about this question and I think the answer must be $\mathbf{Z}[x]$. How can I show that this is isomorphic to $\mathbf{Z}[x]$? Any hints?

A: There's a homomorphism $\mathbf{Z}[x,y] \to \mathbf{Z}[x]$ mapping $f(x,y)$ to $f(x,-1)$. What are its kernel and image?


text:
Q: Chain rule for maximal correlation Let a pair of random variables $(X,Y)$ be defined over finite alphabet $\mathcal{X}\times \mathcal{Y}$ with joint distribution $P_{XY}$. The maximal correlation $\rho(X;Y)$ between $X$ and $Y$ is defined as
$$\rho(X;Y):=\max_{f,g}\mathbb{E}[f(X)g(Y)],$$ where the maximization is taken over real-valued functions $f$ and $g$ such that $\mathbb{E}[f(X)]=\mathbb{E}[g(Y)]=0$ and $\mathbb{E}[f^2(X)]=\mathbb{E}[g^2(Y)]=1$. A single-function characterization of maximal correlation correlation was given by by Renyi as follows:
$$\rho^2(X;Y)=\max_{f}\mathbb{E}[(\mathbb{E}[f(X)|Y])^2],$$ where $f$ satisfies the above conditions as well. One can easily see that for any arbitrary random variables $X$ and $Y$, $0\leq\rho(X;Y)\leq 1$ where 0 is achieved iff $X$ and $Y$ are independent and 1 is achieved iff there exists a pair of functions $f$ and $g$ such that $f(X)=g(Y)$ almost surely.
Suppose $X, Y$ and $Z$ satisfy the Markov condition $X\to Y\to Z$ (that is, $P_{XYZ}(x, y, z)=P_X(x)P_{Y|X}(y|x)P_{Z|Y}(z|y)$). Then it can be easily shown that (see for example page 4 of this)
$$\rho((X,Y); Z)=\rho(Y;Z).$$
I am interested to find a closed form expression for
$$\rho((X,Y);Z)-\rho(X;Z),$$ in general case for any $X, Y$ and $Z$. From above, this has to reduce to $\rho(Y;Z)-\rho(X;Z)$ when $X\to Y\to Z$.
I am in particular interested to prove a chain-rule-like statement for maximal correlation (like chain rule for mutual information and entropy in information theory).
Any ideas and thoughts on how to (dis)prove this? Or any reference talking about a similar problem?


text:
Q: How to insert values into sqlite3 using autohotkey My problem is I am unable to insert values into sqlite3 using autohot key.
My code is:
MyName := name
myTel := telphonenumber

$sSQL := "insert into myTable Values ('" %MyName% "', " %myTel% ");"

and I also tried with ,
$sSQL := "insert into myTable Values ( ' " . MyName . " ', " . myTel . ");"

But neither of these works.
Any suggestion is appreciated..

A: I've not used AHK with SQLite before, but is it just the query you're having issues with? Try this (note the lack of the colon before the equals sign):
$sSQL = "insert into myTable Values ('%MyName%', '%myTel%');"

Your second attempt produces a query that is technically valid, but it would put a space either side of the name in the database ('John' would be ' John '). Also I'm guessing you don't really want to be using a numeric field in your database for a telephone number? If a number begins with 0 or is to large you could have issues. The version above will insert it as a string.

A: MyName := name
myTel := telphonenumber

$sSQL := "insert into myTable Values ('" MyName "', '" myTel "');"
I prefer to put the phone number also into apostrophe.
if you do not have a phone number then there is no error:
insert into myTable Values ('John', '' );
and as Gary said right: "If a number begins with 0 or  ... issues."
the select of the telephone number 0177... will give you later 177...
better you also use a string for the phone number and not an number format.
create table myTable
(
    name TEXT
    phone TEXT
) ;


text:
Q: Bernoulli Differential Equation solving Hello I have the equation $$x'=-tx+e^{-t^2/4}{x^{1/2}}$$ I made the Bernoulli-Substitution $$u=x^{1/2}$$ and got the equation $$u'=-1/2tu+1/2e^{t^{2}/4}$$
Now I dont know how to solve this equation. Thanks Ciwan

A: Write your equation in the form
$$\frac{x'(t)}{2\sqrt{x(t)}}+\frac{1}{2}t\sqrt{x(t)}$$
substituting $$v(t)=\sqrt{x(t)}$$ and computing an integrating factor $$\mu(t)=e^{\int\frac{t}{2}dt}=e^{t^2/4}$$ so we get
$$\frac{d}{dt}\left(e^{t^2/4}v(t)\right)=\frac{1}{2}$$


text:
Q: An analytic function such that $|f^2(z)-1|=|f(z)-1|\,|f(z)+1|<1.$ Let $f$ be an analytic function such that $$|f^2(z)-1|=|f(z)-1|\,|f(z)+1|<1.$$ on a non empty connected set $U$. Then
(A) $f$ is constant.
(B) $Im (f)>0$ on $U$.
(C) $Re(f)\not = 0$ on $U$.
(D) $Re(f)$ is of fixed sign on $U$.
I tried through taking $f(z)=u(x,y)+iv(x,y)$ and putting on the relation, but I could not conclude anything from there.

A: Only the third one and the fourth one are correct in general, so I'll start with them.
$$\begin{align}
\Re(f(z))=0 & \implies |1-i\Im(f)|\cdot|1+i\Im(f)|<1 \\
 & \implies (1+\Im(f(x))^2)<1 \\
 & \implies \Im(f(x))^2 < 0
\end{align}$$
This can't be since $\Im(z)$ is a real number. So $(3)$ is true.
Since $f$ is analytic, it is also continuous. Therefore its real part is continuous. If it wasn't of fixed sign on $U$. You could find a continuous path between two points $z_1,z_2 \in U$ such that $\Re(f(z_1))<0$ and $\Re(f(z_2))>0$. You could deduce that $\exists z$ on that path such that $\Re(f(z))=0$, which can't be, as we've proven earlier. So $(4)$ is also true.
Let $f(z) := \displaystyle\frac{z}{2}+1$ on $U=U=D(0,1)\cap D(-4,4)$, which is connected (convex, even.)
$$\begin{align}
|f(z)^2-1| & =|\frac{z^2}{4}+z| \\
 & = \frac{1}{4}|z|\cdot|z+4|<\frac{1}{4}\cdot1\cdot4=1
\end{align}$$
So $f$ satisfies our condition. But $f$ is neither constant, nor is its imaginary part positive (or even of fixed sign) on all of $U$.


text:
Q: Asking Excel To pick the value from the first row Lets say you have two rows in excel
     S1 S2 S3 S4 S5 S6
ROW1 1   2  3  4  5  6
ROW2 7   8  9  10 11 12

I wish to have excel go through the numbers in the second row and give the name from the first row as the output.
Like for example if I ask for 1, then excel should give S1.
I have been trying to use HLOOKUP("value"; array; 2; FALSE), but it doesn't seem to work. It works if I turn the rows around so that the names are second row while the numbers are first. But that is not an option since I have multiple rows and I have to apply that formula to each row.
Is there a way around to fix this issue?

A: With data like:

In G2 enter 1 and in H2 enter:
=INDEX(1:1,,MATCH(G2,A2:F2,0))


text:
Q: Unique popup window using window.open in an iframe I have an iFrame with a window open(url,uniqueID,windowparams).
The iFrame is located on a single page app and hosted in another server.
Everytime I refresh or change the page then return to the IFrame page, then try to initiate the same window.open. Instead of refreshing the already opened window, it creates an instance of the same window. Upon checking the window.name of each popup, it returns the same uniqueID as its window name. If the url is set blank it behaves as expected. But when a url is set, it creates a new instance of the window.

*

*Do iFrame window.open behave like that when destroyed?

*I tried running the iFrame source locally and the window open behaves properly even after refreshing.

*I tried in IE, Firefox, and Chrome, and it returned the same behaviour.

UPDATE:
Mike successfully fixed the behavior for Webkit browsers by added sandbox properties for the iFrame source. Now the window.open method works as intended and not creating new instances of the same window of the same window.name.
However, Mike still has no luck with Firefox. If someone could give a work around for this, it would be much appreciated.
The Webkit browser behaviour for an iFrame with sanboxed properties in the video below.

See that the parent, even when refreshed still can detect that there is an already opened popup of the same name.
  https://youtu.be/z5_xXRjY8Ow

The Firefox behaviour for an iFrame with sanboxed properties in the video below.

When the parent window is refreshed, the browser could not detect the already opened popup and creates another instance of the pop up with the same window.name.
  https://youtu.be/uHaDveW1Sd0

Is there a workaround to make Firefox behave like Webkit browsers?
UPDATE:
Mike found out that using a blank url in window.open behave properly in firefox.
But still how to fix this haha.
UPDATE:
Here's Johnny! er Mike means another test case.
Try using webkit browsers and firefox.
After opening a popup, refresh the page then open another popup
webkit browsers will only have one instance of thy window, however firefox will create a new one.
console.log(window.name) on the opened popup window and you shall get 'Mike' as the window name
https://bug1295839.bmoattachments.org/attachment.cgi?id=8782242

A: There are several problems that I see in your code:

*

*You are calling a function that are nested inside another function to close the window, that never gets triggered because parent function is not callable at this time.
function openWin(){
     /* code */
}
function closeWin(){
     /* code */
}

*To insure browser compatibility to close the Window, I strongly suggest to set and call an injectable function inside generated popup from parent window
Example to inject a function:
myWindow.document.write(
        "
This is 'myWindow'
"
        +"

A: seems like t'is a chrome bug

https://bugzilla.mozilla.org/show_bug.cgi?id=1295839
https://bugs.chromium.org/p/chromium/issues/detail?id=640620


text:
Q: Delphi Update record´s Insert if necessary from Adotable 2 into AdoTable 1 Filter AdoQuery_1 Record
SQL.Add('SELECT * from    Med');
                  SQL.Add('Where Cliente Like ''%'+Edit1.text );
and

update AdoQuery_1 from AdoQuery_2  (master)
 Update record´s of Table1 from Table2 (chield)
    Update record´s of Table3 from Table4 (chield)

is there a faster way to update the selected record and do the same for the child table records?

A: *

*Best - more simple and more fast - will be to do that in SQL. Depending on your DBMS, you can create a stored procedure, doing all these 3 steps.

*I am not sure, but in AdoQuery_1 you are using LIKE to select a single client or few clients ? If few, then (1) approach will really speedup updates.


text:
Q: OpenCL : internal deadlock in multi-thread environment since driver update (Nvidia) I work on an OpenCL 3.0 application on Windows using the Khronos SDK, that consist in processing a lot of data stored on the drive using the GPU.
To do so, I use several CPU threads that read from the drive, process, send to the GPU and get the result back to write it on the drive. For more than a year, I used this code without any issue, but after recently updating my nvidia GPU driver (from version 460 something to the latest, 517.xx), the program suddenly does not work anymore. I tried a few older drivers in the 5XX range but none changed this behavior.
After looking a bit into what caused this, I discovered that OpenCL calls lock (even ones that should be non-blocking) and never return.
If all calls are done on a single thread, everything's fine, but any subsequent thread will never return from its first call.
As a simple example, just creating a few threads that create each one an OpenCL queue, the first one to execute will work fine, but all others will never return from the clCreateCommandQueue call.
I tested it on two PC, with a GTX1650 and an RTX3070ti, and after a week of trying to figure out a solution and searching online for a similar issue, I found absolutely nothing.
Thanks for reading me, if anyone either has an idea of what could be the issue or can attest that I'm not the only one confronted with it?
Thanks in advance!
TLDR : OpenCL with any recent Nvidia driver cause my clCreateCommandQueue (and other cl calls) to never return if called from more than one CPU thread.

A: I have a code example here.
It is not that minimal because I only get the behavior described by eba04348 if an ocl error occurs in the cl context before.
I filed a bug already to nvidia about this.
#include <iostream>

#define CL_HPP_MINIMUM_OPENCL_VERSION 110
#define CL_HPP_TARGET_OPENCL_VERSION 110

// https://github.com/KhronosGroup/OpenCL-CLHPP
#include "opencl.hpp"

#include <vector>
#include <thread>

struct DeviceData
{
    cl::Context mContextCL;
    cl::Program mProgramCL;
    cl::Kernel mKernelCL;
    cl::CommandQueue mQueueCL;
    std::vector<cl::Buffer> mBufferListCL;
    int static constexpr n = 10000;
};

/*! Please do not use in production code!
 *
 * @param context produce error in this context
 * @param device related to context
 * @return this has to return false
 */
bool produceError(cl::Context& context, cl::Device& device){
    cl_int error = CL_SUCCESS;

    std::vector<float> data (512 * 1024 * 1024 / sizeof(float), 17.0f);
    auto const dataSizeInBytes = data.size() * sizeof(float);

    using Buffers = std::vector<cl::Buffer>;
    Buffers clBufferDstList;
    Buffers clBufferSrcList;

    cl::CommandQueue queue (context, device, 0, &error);
    if (CL_SUCCESS != error)
        return false;

    // Initialize main source buffer, will be cloned many times "inside the device"
    cl::Buffer clMainBufferSrc (context, 0, dataSizeInBytes, nullptr, &error);
    if (CL_SUCCESS != error)
        return false;
    error = queue.enqueueWriteBuffer (clMainBufferSrc, CL_TRUE, 0, dataSizeInBytes, data.data(), nullptr, nullptr);
    if (CL_SUCCESS != error)
        return false;

    // Loop until things break down
    while (true) {
        cl::Buffer clNewBufferSrc(context, 0, dataSizeInBytes, nullptr, &error);
        if (CL_SUCCESS != error)
            return false;
        cl::Buffer clNewBufferDst(context, 0, dataSizeInBytes, nullptr, &error);
        if (CL_SUCCESS != error)
            return false;
        clBufferSrcList.push_back(clNewBufferSrc);
        clBufferDstList.push_back(clNewBufferDst);

        // Copy data to new src and dst buffer - on the device / initialize buffers
        error = queue.enqueueCopyBuffer(clMainBufferSrc, clNewBufferSrc, 0, 0, dataSizeInBytes);
        if (CL_MEM_OBJECT_ALLOCATION_FAILURE == error)
            break;
        if (CL_SUCCESS != error)
            return false;
        error = queue.enqueueCopyBuffer(clMainBufferSrc, clNewBufferDst, 0, 0, dataSizeInBytes);
        if (CL_MEM_OBJECT_ALLOCATION_FAILURE == error)
            break;
        if (CL_SUCCESS != error)
            return false;
        error = queue.finish();
        if (CL_SUCCESS != error)
            return false;
    }

    return true;
}

int main() {
    // get all platforms (drivers), e.g. NVIDIA
    std::vector<cl::Platform> all_platforms;
    cl::Platform::get(&all_platforms);

    if (all_platforms.size()==0) {
        std::cout<<" No platforms found. Check OpenCL installation!\n";
        exit(1);
    }
    cl::Platform default_platform=all_platforms[0];
    std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";

    // get default device (CPUs, GPUs) of the default platform
    std::vector<cl::Device> all_devices;
    default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
    if(all_devices.size()==0){
        std::cout<<" No devices found. Check OpenCL installation!\n";
        exit(1);
    }

    // use device[1] because that's a GPU; device[0] is the CPU
    // or [0] if CPU has no ocl drivers
    cl::Device default_device=all_devices[0];
    std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";

    DeviceData data;
    data.mContextCL = {default_device};

    auto f1 = [default_device, &data]() {
        // create a queue (a queue of commands that the GPU will execute)
        data.mQueueCL = {data.mContextCL, default_device};

        // create the program that we want to execute on the device
        cl::Program::Sources sources;

        // calculates for each element; C = A + B
        std::string kernel_code =
                "   void kernel simple_add(global const int* A, global const int* B, global int* C, "
                "                          global const int* N) {"
                "       int ID, Nthreads, n, ratio, start, stop;"
                ""
                "       ID = get_global_id(0);"
                "       Nthreads = get_global_size(0);"
                "       n = N[0];"
                ""
                "       ratio = (n / Nthreads);"  // number of elements for each thread
                "       start = ratio * ID;"
                "       stop  = ratio * (ID + 1);"
                ""
                "       for (int i=start; i<stop; i++)"
                "           C[i] = A[i] + B[i];"
                "   }";
        sources.push_back({kernel_code.c_str(), kernel_code.length()});

        data.mProgramCL = {data.mContextCL, sources};
        if (data.mProgramCL.build({default_device}) != CL_SUCCESS) {
            std::cout << "Error building: " << data.mProgramCL.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device) << std::endl;
            exit(1);
        }

        data.mKernelCL = {data.mProgramCL, "simple_add"};

        // create buffers on device (allocate space on GPU): A, B, C, N(1)
        data.mBufferListCL = {
                {data.mContextCL, CL_MEM_READ_WRITE, sizeof(int) * data.n},
                {data.mContextCL, CL_MEM_READ_WRITE, sizeof(int) * data.n},
                {data.mContextCL, CL_MEM_READ_WRITE, sizeof(int) * data.n},
                {data.mContextCL, CL_MEM_READ_ONLY,  sizeof(int)}
        };
    };

    auto f2 = [default_device, &data]() {
        // create things on here (CPU)
        int A[data.n], B[data.n];
        for (int i = 0; i < data.n; i++) {
            A[i] = i;
            B[i] = data.n - i - 1;
        }

        // apparently OpenCL only likes arrays ...
        // N holds the number of elements in the vectors we want to add
        int const N[1] = {data.n};

        auto& buffer_A = data.mBufferListCL[0];
        auto& buffer_B = data.mBufferListCL[1];
        auto& buffer_C = data.mBufferListCL[2];
        auto& buffer_N = data.mBufferListCL[3];

        // push write commands to queue
        data.mQueueCL.enqueueWriteBuffer(buffer_A, CL_TRUE, 0, sizeof(int) * data.n, A);
        data.mQueueCL.enqueueWriteBuffer(buffer_B, CL_TRUE, 0, sizeof(int) * data.n, B);
        data.mQueueCL.enqueueWriteBuffer(buffer_N, CL_TRUE, 0, sizeof(int), N);

        // RUN ZE KERNEL
        data.mKernelCL.setArg(0, buffer_A);
        data.mKernelCL.setArg(1, buffer_B);
        data.mKernelCL.setArg(2, buffer_C);
        data.mKernelCL.setArg(3, buffer_N);
        data.mQueueCL.enqueueNDRangeKernel(data.mKernelCL, cl::NullRange, cl::NDRange(10), cl::NullRange);
        data.mQueueCL.finish();
    };

    auto f3 = [&data]() {
        auto &buffer_C = data.mBufferListCL[2];
        int C[data.n];
        // read result from GPU to here
        data.mQueueCL.enqueueReadBuffer(buffer_C, CL_TRUE, 0, sizeof(int) * data.n, C);

        std::cout << "result: {";
        for (int i = 0; i < data.n; i++) {
            std::cout << C[i] << " ";
        }
        std::cout << "}" << std::endl;
    };

    // First run to show that all is fine if we stay on the main thread

    produceError(data.mContextCL, default_device);

    f1();
    f2();
    f3();

    // Second run where we get stuck in t2, at the first data.mQueueCL.enqueueWriteBuffer() call.
    // It works if we uncomment the call to produceError() below.
    // It also works if we recreate the cl::Context again after the produceError() call.

    data = {};
    data.mContextCL = {default_device};

    produceError(data.mContextCL, default_device);

    auto t1 = std::thread(f1);
    auto t1_id = t1.get_id();
    t1.join();
    auto t2 = std::thread(f2);
    auto t2_id = t2.get_id();
    t2.join();
    auto t3 = std::thread(f3);
    auto t3_id = t3.get_id();
    t3.join();

    std::cout << t1_id << std::endl;
    std::cout << t2_id << std::endl;
    std::cout << t3_id << std::endl;
    return 0;
}


text:
Q: Disprove or prove using delta-epsilon definition of limit that $\lim_{(x,y) \to (0,0)}{\frac{x^3-y^3}{x^2-y^2}} = 0$ I want to prove if the following limit exists, using epsilon-delta definition, or prove it doesn't exist:$$\lim_{(x,y) \to (0,0)}{\frac{x^3-y^3}{x^2-y^2}} = 0$$
My attempt:
First I proved some directional limits, like for $y=mx$ , and $y=ax^n$, and for all of them I got 0. So I conjectured that this limit exists and it's 0. Then I have to prove:
$$\forall \delta \gt 0 : \exists \epsilon \gt 0 : \|(x,y)\| \lt \epsilon \rightarrow \left| \frac{x^3-y^3}{x^2-y^2}\right| \lt \delta$$
First I noted that $\frac{x^3-y^3}{x^2-y^2} = \frac{(x^2+xy+y^2)(x-y)}{(x+y)(x-y)} = \frac{x^2+xy+y^2}{x+y}$.
Then I did $\left|\frac{x^2+xy+y^2}{x+y}\right| \leq \left|\frac{x(x+y)}{x+y}\right|+\frac{y^2}{\vert x+y\vert} = \vert x \vert + \frac{y^2}{\vert x+y\vert}$
Using $\|(x,y)\| = \vert x\vert + \vert y\vert$ and assuming  $\|(x,y)\| \lt \epsilon$
$\vert x\vert + \vert y\vert  = \vert x \vert + \frac{ y^2}{\vert y \vert} \geq \vert x \vert+\frac{y^2}{\vert y\vert+\vert x\vert}$
but I can't continue from that since $\vert x + y \vert \leq \vert x \vert + \vert y \vert$
.
I don't know what else to try.

A: So, you've reduced it to $\frac{x^2+xy+y^2}{x+y}$. That denominator is zero at more than just the origin $(0,0)$. What happens on (or close to) the line $y=-x$?

A: Hint: Try something close to the forbidden lines $x^2=y^2,$ like $y=x^3-x.$

A: Use polar coordinates $x=r\cos\theta$, $y=r\sin\theta$.  Because of the domain we have $\cos\theta\ne\pm\sin\theta$.  Substituting into your formula gives
$$\frac{x^3-y^3}{x^2-y^2}=r\,\frac{\cos^3\theta-\sin^3\theta}{\cos^2\theta-\sin^2\theta}\ .$$
Now it is not hard to prove that
$$\frac{\cos^3\theta-\sin^3\theta}{\cos^2\theta-\sin^2\theta}\to\infty\quad
  \hbox{as}\quad \theta\to\Bigl(\frac{3\pi}{4}\Bigr)^{\textstyle-}\ .$$
So consider the path given by
$$r=\frac{\cos^2\theta-\sin^2\theta}{\cos^3\theta-\sin^3\theta}\ ,\qquad
  \theta\to\Bigl(\frac{3\pi}{4}\Bigr)^{\textstyle-}\ .$$
This will approach the origin, but for every point on this path you have
$$\frac{x^3-y^3}{x^2-y^2}=1\ .$$
So the limit does not exist.

A: OK, here is a completely different answer using $(x,y)$ coordinates only and no parameters.
Basically, try a power curve $y=x^n$.
BUT this gives you a path approaching the origin near the $x$ or $y$ axis, which is not a problem.  So we need to modify it to place it near the "problem" line $y=-x$.
Consider the curve
$$y=-x+x^2\ .$$
This will lie within the domain of your function as long as $x\ne0,2$.  So we can take $x\to0$, which implies $y\to0$, so the curve approaches the origin.  Along this curve we have
$$\frac{x^3-y^3}{x^2-y^2}=\frac{2x^3-3x^4+3x^5-x^6}{2x^3-x^4}
  =\frac{2-3x+3x^2-x^3}{2-x}$$
which tends to $1$ as $x\to0$.  Hence the limit does not exist.


text:
Q: looping back to beginning of statement using while loop (java) I've been given the task of making a factorial calculator that takes input from 9 to 16 using a while loop. The conditions are that if the user puts in an input that is not 9 to 16 or an int, it should loop back in the beginning and ask for input again.
My code looks like this:
Scanner myScanner;
int x = 1;
int factorial=1;
int input;
myScanner = new Scanner(System.in);
System.out.println("put in an int and i will show you its factorial");
while (true) {
        input = myScanner.nextInt();
        if (input<9 || input >16) {
                System.out.println("please enter a valid int");
        }
        else{
                break;
        }
}
for (int i=input; i >0; i--) {
        factorial *= i;
}

The problem is that this isn't really using a while loop to go back to the beginning of the code. I'm really just inputting a redundant statement to make it a while loop.
So I guess my question is, how can I make a while loop that goes back to the beginning of the loop if the wrong input is typed in?

A: Try doing it this way:
Scanner myScanner;
int x = 1;
int factorial=1;
int input = 0;
myScanner = new Scanner(System.in);
System.out.println("Put in an integer value between 9 and 16 and I will show you its factorial. Type -1 to exit.");

while (input != -1) {
    //Try block for handling invalid string inputs
    try {
        input = myScanner.nextInt();
    } catch (Exception e){
        input = 0;
    }

    if (input<9 || input >16) {
        System.out.println("please enter a valid int");
    }
    else {
        for (int i=input; i >0; i--) {
            factorial *= i;
            //input = -1; //Optionally end here if that's how things are intended to function
        }
        System.out.println(factorial);
    }
}

Initialize the input with a value (0). And inform the user if they type in a certain value (i.e. -1) the loop ends. Move your for loop in the else block and set the while condition as input != 1.
Alternatively, if you want the program to end if the user supplies a valid value, then in the else block, set the input value to -1 manually, or just break out of the loop using the break keyword.

A: an alternative is to use a boolean value such as
boolean validInput = false;

and loop until you have valid input. that way you won't try to calculate a value when users enter -1 in the other answer


text:
Q: SWF file only plays an abbreviated version when not accessed through an internet connection on Safari- How can this version be saved for offline use? I have a young niece who has gotten hooked on online flash games but has no internet connection at home. I've been trying to save them on a hard drive for her to access offline, and so far have been successful using a mozilla plugin and an offline flash player. However, one particular game only plays in its full version on safari. I've tried everything to download the file from safari-plugins, archiving the entire page, even going through the source code- and while it saves like every other file from this particular site, once the internet connection is cut it goes back to the same shortened, partially-functional version seen when accessed through firefox. Is there any explanation for why the file itself would play differently- maybe another file that needs to be saved with it? And, more importantly, is there any way I can preserve the full version of the game even when offline? It's not a matter of life or death, obviously, but it's got me pretty seriously stumped.
Here's the link to the page:
http://www.dolldivine.com/rebel-girl-dress-up.php

A: stick with firefox and download the addon "userAgentSwitcher" for its maturity and stability.
Use the menus to emulate Safari
Revisit the site and verify it can access the content in the manner you like.
Then get the addon YoutubeDownload, open its menus and enable the "save SWF files for FlashGames" or similar option since there wil be only one like it.
revisit the site and have her finsih the game as she likes or until she turns old enough to discover  boys.
Open YT downloader and you'll find a list of files ready to download, select your location and do so accordingly.
Flash content, espeically interactive flash content like games is often segmented into multiple files to reduce the amount of time you spend caching content for play, most flash legacy flash content except for streaming YT videos but swf game files like you're leeching (leech is a generic term like "junk bond" and not a characterization) is often segmented at milestones like book chapters and explains why your prior attempts to access offline didn't succeed.


text:
Q: JavaScript Based Image Input & Keyboard Output this is my first post!
I am working on a project with AI for a game. I am trying to recreate Tetris with Javascript, HTML, and CSS to train an AI to play. After making the game, I would then need to incorporate the AI into it. After it is trained, I want to test the AI against other, real-time players to see how good it is. This is similar to what Code Bullet did, I have attached that video. My question is, is there any way to have my AI play on a website against other players? I think this would be possible if I could somehow get input from the site it is playing on, sending it to the AI, and receiving output in the form of simulated presses from the AI. I know this is possible with Python, but I am unfamiliar with that language. If you could help me, that would be much appreciated.
Thank you!
Code Bullet's video
P.S. Since this is my first post, please let me know if I am doing something wrong/missing something in my post. Thank you again!


text:
Q: С помощью функции надо найти все простые числа от 1 до 100. Те создать еще одну функцию, которая будет передавать значения. В чем ошибка, function isPrime(num) {
  for (let i = 2; i < num; i++) {
    if (num % i == 0) {
      return false;
    }
  } return true;
}

 function digits(){
 for (let i = 1 ; i <= 100; i++) {
   if(isPrime(true)) {
   return i;
  }
}
}console.log(digits());

A: В функции isPrime(num) аргумент num используется как число, а Вы в эту функцию передаёте в качестве аргумента значение true(Boolean). А вообще такие вопросы не стоит задавать, лучше самому отлаживать код. Подробнее: Отладка кода
Кстати, думаю лучше всего для этого использовать рекурсивную функцию.  Подробнее: Рекурсия в js


text:
Q: Running into errors trying to read Text File Okay so I'm building a program for work to track volume each day and also split the volume up to how much each different location receives. There are 8 lines in the building. The Text file consists of the day's date, the total volume for the building and the volume for each location (PEN).
Im running into two problems right now both are segregated to my readDay function. where result = fscanf(pi->Date, 40, fp);
issues are
1. Incompatible integer to pointer conversion passing 'int' to parameter of type 'const char*'
2. Incompatible pointer types passing 'char[40]' to parameter of type 'FILE*'(aka 'struct_sFILE*')
Can anyone explain to me what these issues mean. Or if you need any more info in order to help me feel free to ask.
#include <stdio.h>
#include <stdlib.h>

struct  Day  {
char Date[40];
int Total;
int Pen1;
int Pen2;
int Pen3;
int Pen4;
int Pen5;
int Pen6;
int Pen7;
int Pen8;

};

const char fileName [] = "UPS.txt";

void StartRecord(void);
void printDay(struct Day* pi);
void writeDay(FILE *fp, struct Day *pi);
int readDay(FILE *fp, struct Day *pi);
void readFile(void);
void addDay(void);

int main(int argc, const char * argv[]) {

StartRecord();

int choice;
printf("Enter 1 to read this file or enter 2 to add to it.");
scanf("%d", &choice);
switch (choice) {
    case 1: readFile();
        break;
    default: printf("Not a valid choice\n");
        break;
}
getchar();
getchar();

}

void StartRecord(void)    {

int count;
int i;
struct Day aDay;
FILE *fp;

fp = fopen(fileName, "w");
if (fp != NULL) {
    printf("Enter volume for how many days? ");
    scanf("%d", &count);
    for (i = 0; i < count; ++i) {
        printf("What is today's date? ");
        gets(aDay.Date);
        printf("What was the total volume for the building for the day?");
        scanf("%d", &aDay.Total);
        printf("What was the volume for Pen 1? ");
        scanf("%d", &aDay.Pen1);
        printf("What was the volume for Pen 2? ");
        scanf("%d", &aDay.Pen2);
        printf("What was the volume for Pen 3? ");
        scanf("%d", &aDay.Pen3);
        printf("What was the volume for Pen 4? ");
        scanf("%d", &aDay.Pen4);
        printf("What was the volume for Pen 5? ");
        scanf("%d", &aDay.Pen5);
        printf("What was the volume for Pen 6? ");
        scanf("%d", &aDay.Pen6);
        printf("What was the volume for Pen 7? ");
        scanf("%d", &aDay.Pen7);
        printf("What was the volume for Pen 8? ");
        scanf("%d", &aDay.Pen8);
        getchar();
        writeDay(fp, &aDay);
    }
    fclose(fp);
}else {
    printf("\nError opening file.\n");
}

}

void readFile(void) {
FILE *fp;
struct Day aDay;

fp = fopen(fileName, "r");
if (fp != NULL) {
    while (readDay(fp, &aDay)) {
        printDay(&aDay);
    }
    fclose(fp);
} else  {
    printf("\nError opening File!\n");
}
}

void writeDay(FILE *fp, struct Day *pi) {
fprintf(fp, "%s\n", pi->Date);
fprintf(fp, "%d\n", pi->Total);
fprintf(fp, "%d\n", pi->Pen1);
fprintf(fp, "%d\n", pi->Pen2);
fprintf(fp, "%d\n", pi->Pen3);
fprintf(fp, "%d\n", pi->Pen4);
fprintf(fp, "%d\n", pi->Pen5);
fprintf(fp, "%d\n", pi->Pen6);
fprintf(fp, "%d\n", pi->Pen7);
fprintf(fp, "%d\n", pi->Pen8);
}

int readDay(FILE *fp, struct Day *pi)  {
int result;

fgetc(fp);    // read the endline
result = fscanf(pi->Date, 40, fp);
if (result == EOF) {
    return 0;
}
fscanf(fp, "%d", &pi->Total);
fscanf(fp, "%d", &pi->Pen1);
return 1;

}

void PrintDay(struct Day *pi)  {
printf("Records for the day of: %s\n", pi->Date);
printf("Total Volume: %d", pi->Total);
printf("Volume for Pen 1: %d", pi->Pen1);
printf("Volume for Pen 2: %d", pi->Pen2);
printf("Volume for Pen 3: %d", pi->Pen3);
printf("Volume for Pen 4: %d", pi->Pen4);
printf("Volume for Pen 5: %d", pi->Pen5);
printf("Volume for Pen 6: %d", pi->Pen6);
printf("Volume for Pen 7: %d", pi->Pen7);
printf("Volume for Pen 8: %d", pi->Pen8);
printf("\n\n");

}

A: In one sense, your arguments are the wrong way round. This:
fscanf(pi->Date, 40, fp);

should be:
fscanf(fp, pi->Date, 40);

just like you already have it a few lines further down.
In another sense, what you're trying to do is very strange - you can't read anything into a literal integer. You probably want something more like:
fscanf(fp, "%s", pi->Date);

or possibly:
fscanf(fp, "%39s", pi->Date);

or similar.


text:
Q: 'System.OutOfMemoryException' in system.drawing.image i store my website image in form of byte array , but when i try to save them as jpeg file ,some of this file throw exception.here is my code for get image:
IList<PropertyInfo> properties = typeof(ApplicationUser).GetProperties()
                               .Where(x => x.PropertyType == typeof(Byte[])).ToList();

var imaBytes = property.GetValue(user, null) as Byte[];
if (imaBytes == null || imaBytes.Length == 0) continue;

Image userImage = ImageHelper.byteArrayToImage(imaBytes);
userImage.Save(pathname + $@"\{DirName}\" + property.Name + ".jpg", ImageFormat.Jpeg);

and this is my ImageHelper.byteArrayToImage :
public static Image byteArrayToImage(byte[] byteArrayIn)
{
    try
    {
        using (MemoryStream ms = new MemoryStream(byteArrayIn))
        using (var image = Image.FromStream(ms,false,true))
        {
            byteArrayIn = new byte[0];
            return new Bitmap(image);
        }
    }
    catch (Exception e)
    {
       Logger.log(e);
    }
}

edit:
i wrap MemoryStream and Image code with using statment and  change my code and add ImageToDisk method :
public static void ImageToDisk(byte[] byteArrayIn, string pathToSave)
    {
        try
        {
            using (MemoryStream ms = new MemoryStream(byteArrayIn))
            {
                using (var image = Image.FromStream(ms, false, true))
                {
                    image.Save(pathToSave, ImageFormat.Jpeg);
                    image.Dispose();

                }

            }
        }
        catch (Exception e)
        {
            Logger.log(e);
            throw;
        }

    }

and main code is this:
 foreach (var property in properties)
                    {
                        try
                        {
                            var imaBytes = property.GetValue(user, null) as Byte[];
                            if (imaBytes == null || imaBytes.Length == 0)
                            {
                                continue;
                            }

                            ImageHelper.ImageToDisk(imaBytes, pathname + $@"\{DirName}\" + property.Name + ".jpg");

                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                        }
                    }

but now am getting system.runtime.interopservices.externalexception
EDIT 2:
i am completely dizzy!!! its seems some user upload images from IE and IE change MIME type to image/PJPEG

error occurred is some file with this MIME type but also some other image/PJPEG files save correctly without any exception

how can i resolve this error??

A:
some of this file throw exception

I'm almost sure the problem is with disposing your images. Make sure all resources are released:
using (Image userImage = ImageHelper.byteArrayToImage(imaBytes))
{
  //do whatever you need
  userImage.Save(pathname + $@"\{DirName}\" + property.Name + ".jpg", ImageFormat.Jpeg);
}

Bitmaps consume a lot of memory. Under the hood Image uses GdipLoadImageFromStream method. To release resources, it should be paired with GdipDisposeImage. That's what happens inside Image.Dispose() method.


text:
Q: Animating cubical perspective in flutter I'm trying to implement the cubical swipe as outlined by Marcin Szalek in his Flutter talk for the  different pages in my app. I was able to implement it for the left side, as he had shown. But if I want to implement it for the right hand side of the main page, or if I want to add a Gesture detector for another action, how can I stack these GDs on top of one another, if at all possible? Or should I restrict the GDs to certain sections of the screen? Thanks in advance.
      GestureDetector(
          onHorizontalDragStart: _onDragStart,
          onHorizontalDragUpdate: _onDragUpdate,
          onHorizontalDragEnd: _onDragEnd,
          behavior: HitTestBehavior.translucent,
          onTap: toggle,
          child: AnimatedBuilder(
            animation: animationController,
            builder: (context, _) {
              return Material(
                color: Colors.black,
                child: Stack(
                  children: <Widget>[
                    Transform.translate(
                      offset: Offset(maxSlide * (animationController.value - 1), 0),
                      child: Transform(
                        transform: Matrix4.identity()
                          ..setEntry(3, 2, 0.001)
                          ..rotateY(math.pi / 2 * (1 - animationController.value)),
                        alignment: Alignment.centerRight,
                        child: SettingsDrawer(),
                      ),
                    ),
                    Transform.translate(
                      offset: Offset(maxSlide * animationController.value, 0),
                      child: Transform(
                        transform: Matrix4.identity()
                          ..setEntry(3, 2, 0.001)
                          ..rotateY(-math.pi * animationController.value / 2),
                        alignment: Alignment.centerLeft,
                        child: widget.child,
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
    ]);
  }
  void _onDragStart(DragStartDetails details) {
    bool isDragOpenFromLeft = animationController.isDismissed;
    bool isDragCloseFromRight = animationController.isCompleted;
    _canBeDragged = isDragOpenFromLeft || isDragCloseFromRight;
  }

  void _onDragUpdate(DragUpdateDetails details) {
    if (_canBeDragged) {
      double delta = details.primaryDelta / maxSlide;
      animationController.value += delta;
    }
  }

  void _onDragEnd(DragEndDetails details) {
    //I have no idea what it means, copied from Drawer
    double _kMinFlingVelocity = 365.0;

    if (animationController.isDismissed || animationController.isCompleted) {
      return;
    }
    if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
      double visualVelocity = details.velocity.pixelsPerSecond.dx /
          MediaQuery.of(context).size.width;

      animationController.fling(velocity: visualVelocity);
    } else if (animationController.value < 0.5) {
      animationController.reverse();
    } else {
      animationController.forward();
    }
  }


text:
Q: jVectorMap, store center coords before redraw the map I'm currently using jVectorMap to keep track of an app users activities.
Every time an user position is updated, the server fire an event and the client redraw the map.
I would like to keep track of last scale and coordinates values so that I can redraw the map in the same position and zoom instead of the default one.
I've already tried to use onViewportChange to store the scale value and pass it to the new map with focusOn and it works but i can't get any lat lng or x y values with that.
How can i get map's center coordinates or x y values? Any ideas?


text:
Q: AngularJS 1.x.x. List all active controllers into browser's console Is there a way to list all active controller names into console? Need this for external E2E testing, to check if controller has loaded without waiting for DOM to fully render.

A: As mention in the comment you can log a message inside your controller to monitor when it is used.
angular.module("myApp").controller('MyController', function(){
    Console.log("MyController loaded !")
})


text:
Q: Well-defined and Equivalence relations I am wondering why the following is well-defined...
The definition of well-defined is given as;
$g:(X/\sim) \to Z$ is well-defined if a mapping $f:X \to Z$ can be found where $f$ has the property $x \sim y \implies f(x)=f(y)$
So, I am asked if the following is well-defined;
$E(x) \to e^{2i \pi x}$
I thought No. Because, actually, the mapping didn't really make sense to me. Say $x_1,x_2 \in E(x)$ then, $x_1-x_2=z \in \mathbb{Z}$. Now, $E(x_1)=e^{2i \pi (z+x_2)}=e^{2i \pi z}e^{2i \pi x_2}$ and $E(x_2)=e^{2i \pi x_2}$. Thus $E(x_1) \neq E(x_2)$ unless $x_1 = x_2$ so at least, $x_1 \sim x_2$ does not imply $E(x_1) = E(x_2)$. Which is strange, since both $x_1,x_2$ are related and so in the same equivalence class, but the mapping from the said class does not go to the same element in the image.
And how am I supposed to find "mapping $f:X \to Z$ where $f$ has the property $x \sim y \implies f(x)=f(y)$"?
I can't randomly try out every possible mapping a person can think of from $X$ to $Z$ of course, but I mean the definition just says "mapping" which is very very broad.
Say, even if I construct a mapping $f:X \to e^{2i \pi x}$ such that $f(x_1) = e^{2i \pi x_1}$,  for $f(x_1)=f(x_2)$ to happen, I definitely need $x_1=x_2$ for reals...
But the answer apparently says that they are well-defined, and, by definition, I have no idea why.
Am I misunderstanding the definition of well-defined? I really don't see why this mapping is so at all...

A: 'Well-defined' is a rather foggy concept, and you'll find it used in lots of different ways throughout mathematics.  Typically, one makes a definition, and then one sometimes has to check various things hat show that the definition makes sense.  For example, it's not unheard of to use well-defined in the following sense:

We define a function $f\colon \mathbb N \to \mathbb N$ by setting $f(k)$ to be the smallest natural number $s$ such that every positive integer can be expressed as the sum of at most $s$ $k$-th powers.
Indeed, by the Hilbert-Waring Theorem, such an $s$ exists for every $k$.  So this map is well-defined.

As another example, we might define a function $f\colon X\to Y$ by $f(x)=$ such and such, and then prove that the function $f$ is 'well-defined' by showing that our value of $f(x)$ actually is contained in $Y$.

Now, you are using 'well-defined' in a rather specific way.  Indeed, this is the most common usage of the term 'well-defined'.  Namely, given a set $X$ and an equivalence relation $\sim$ on $X$, we sometimes define a map $f\colon X/\sim\to Y$ by setting

$f([x])=$ some expression depending on $x$

In other words, there is a function $g\colon X\to Y$ and we have set $f([x])=g(x)$.
Of course, this definition doesn't make sense if there exist $x\sim y$ with $g(x)\ne g(y)$.  hen $f([x])=g(x)\ne g(y)=f([y])=f([x])$, which is absurd.  So, in order to check that this map is 'well-defined', we need to check that $g(x)=g(y)$ whenever $x\sim y$.
Algebraists prefer to express this as a universal property.  Given a set $X$ and an equivalence relation $\sim$ on $X$, there is a natural map $p\colon X\to X/\sim$, given by $p(x)=[x]$.  $p$ satisfies the property that $p(x)p(y)$ whenever $x\sim y$, and it is said to be universal among all maps with this property: that is, whenever $g\colon X\to Y$ is a map such that $g(x)=g(y)$ whenever $x\sim $, then there is a unique map $f\colon X/\sim\to Y$ such that $g=f\circ p$.

A: Normally well-defined means that if you have choices to make during the evaluation of some function or quantity, it doesn't matter what choices you make you'll end up with the same result.  When dealing with equivalence classes this means you have to get the same function value for whatever representative you choose from the equivalence class.
For what you're doing, I believe this should be interpreted as: If $x\sim y\implies f(x)=f(y)$, you have to show that the implication holds for all pairs of elements in the equivalence class.  That way, the function can be interpreted as acting on the entire class, rather than just members of the class.
Your example $E(x)$ works, because if $x\sim y$, then
$x-y\in\mathbb{Z}$.  So, $x=y+n$.  Then
$$E(x)=e^{2\pi ix}=e^{2\pi i(y+n)}=e^{2\pi iy}e^{2\pi in} = e^{2\pi iy}=E(y)$$
This works because $e^{2\pi in}=1$ for any integer $n$.
So we just showed that $x\sim y\implies E(x)=E(y)$.  Because $x$ and $y$ were arbitrary members of the equivalence class, this is well-defined.


text:
Q: How to transfer video stream from python to electron? Suppose I have a code written in python where in a loop I get frames from streaming video! How can I transfer these frames in real time to a graphical interface that is written on an electron.js?

A: See available implementations.

A: You could create a Flask server and pass all the frames directly to html page. Then from your electron code call the server to show the flow.
webstreaming.py (your Flask server):
# initialize video capture object to read video from external webcam
video_capture = cv2.VideoCapture(1)
# if there is no external camera then take the built-in camera
if not video_capture.read()[0]:
    video_capture = cv2.VideoCapture(0)

# initialize a flask object
app = Flask(__name__)

@app.route("/")
def index():
    # return the rendered template
    return render_template("index.html")

def analyze():
    # grab global references to the video stream, output frame, and
    # lock variables
    global video_capture, outputFrame, lock, status

    while(video_capture.isOpened()):
        # read video frame by frame
        ret, frame = video_capture.read()

        frame = cv2.flip(frame, 1)

        # acquire the lock, set the output frame, and release the
        # lock
        with lock:
            outputFrame = frame.copy()

def generate():
    # grab global references to the output frame and lock variables
    global outputFrame, lock
    # loop over frames from the output stream
    while True:
        # wait until the lock is acquired
        with lock:
            # check if the output frame is available, otherwise skip
            # the iteration of the loop
            if outputFrame is None:
                continue
            # encode the frame in JPEG format
            (flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
            # ensure the frame was successfully encoded
            if not flag:
                continue
        # yield the output frame in the byte format
        yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
            bytearray(encodedImage) + b'\r\n')

#This route accepts request against the url http://domain_name/change_label
#You could add the argument, method=["POST"],
So the route only accepts post request against that url.
@app.route("/get_label")
def change_label():
    global status, lock

    with lock:
        return status

@app.route("/video_feed")
def video_feed():
    # return the response generated along with the specific media
    # type (mime type)
    return Response(generate(),
        mimetype="multipart/x-mixed-replace; boundary=frame")

if __name__ == "__main__":
    # start a thread that will perform motion detection
    t = threading.Thread(target=analyze)
    t.daemon = True
    t.start()
    # start the flask app
    app.run(host="0.0.0.0", port=8000, debug=True, threaded=True, use_reloader=False)

# release the video stream pointer
video_capture.release()

Then in your index.html (inside templates.html)

    <title>Video Streaming Demonstration</title>

Video Streaming Demonstration

And in your main.js
const {app, BrowserWindow} = require('electron')

function createWindow () {
    window = new BrowserWindow({width: 800, height: 600})
    window.loadFile('index.html')
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
})

Important: you should add  in the index.html that redirects you to templates/index.html (don't confuse these are 2 different files).
You also to need to start the server beforehand, using concurrently package for exemple and electron-forge.


text:
Q: Exception in Apache StringUtils hello guys i am try to use the StringUtils.remove Method but the below exception is raising i have include the jar file and StringUtils.lowercase and String.countsMatches is working only remove is not what may be the problem
<%@page import="org.apache.commons.lang.StringUtils"%>

this is how i imported and the exception is as follows
java.lang.NoSuchMethodError:
org.apache.commons.lang.StringUtils.remove(Ljava/lang/String;Ljava/lang/String;)
Ljava/lang/String;

A: The remove(String,String) method was added to version 2.1 of commons-lang. It is not present in 2.0 and earlier.
Depending on which Servlet Container or Application Server you use (and which version of it), the server class path may contain an outdated version of commons-lang, which is used instead of your copy of commons-lang in the applications /lib folder. If that's your problem, you can configure your application to prefer the application class path, instead of the server class path.

A: Because as far as I can see in javadoc StringUtils has method remove that accepts 2 string arguments and does not have one that accepts 3 arguments:
public static String remove(String str,
                            String remove)

see http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html
Since there are different versions of StringUtils double check that your are working with the same version in development and deployment environment.


text:
Q: AppleScript, set the position of the frontmost window, even if not AppleScriptable I am trying to write a script to center the frontmost window of the active app, when I select this AppleScript from the Script menu in the menu bar. It should work with any app, including non-scriptable apps.
When I run this from Script Editor, it works fine. whether I select the current app or another app from the "tell" application menu in Script Editor, it still sees that the Script Editor is the frontmost app, and moves that window accordingly. (I have also debugged by manually assigning the name of another app to currentApplication, including a non-scriptable app, and that also works fine.)
The trouble seems to be when the script is run from the Script menu item. I have debugged by displaying a notification with the text of currentApplication, and every time it displays the name of the frontmost application, as expected. However, it does not move the position of the window. What gives?
-- Get name of the current application and its front window
tell application "System Events"
    set activeApps to name of application processes whose frontmost is true
    set currentApplication to item 1 of activeApps
    -- DEBUG -- currentApplication seems to be the correct application
    -- display notification currentApplication
    -- activate currentApplication
    -- Get the front window and its measurements
    set frontWindow to the first window of application process currentApplication
    set windowSize to size of frontWindow
    set windowPosition to position of frontWindow
end tell

-- Get the bounds of the screen
tell application "Finder"
    set screenBounds to bounds of window of desktop
end tell

--calculate the center of the current window
set windowSizeX to item 1 of windowSize
set windowSizeY to item 2 of windowSize
set windowCenterX to windowSizeX / 2
set windowCenterY to windowSizeY / 2

-- calculate the center of the screen
set screenCenterX to (item 3 of screenBounds) / 2
set screenCenterY to (item 4 of screenBounds) / 2

--calculate the new window position
set newWindowPositionX to screenCenterX - windowCenterX
set newWindowPositionY to screenCenterY - windowCenterY

-- set the new window position
tell application "System Events"
    set position of frontWindow to {newWindowPositionX, newWindowPositionY}
end tell

A: The answer was to allow SystemUIServer.app to control the computer, in the Security > Privacy > Accessibility preferences. I had so many Finder windows open, I can only assume that the warning dialogue was popping up behind them. Once the permission is granted, it works fine.


text:
Q: Is there different types of .svg? I am currently learning css and I have encountered some question about the SVG img. I have discovered that some SVG will take up the whole width of webpage if their width or height are not set, while some don't and have a defined size. What does this property called? Is it related to the design of SVG image? example
Also, if I put a SVG which takes up the whole width of webpage into a flex box, the SVG will decrease in size. Why does this happen? Considing that a normal image and a SVG with defined size will not decrease the size in the same situation.example(fixed with class = "flex" instead of id).
I am also wondering how does the computer determine what size should the SVG decreased to? I have tried a few SVG(which take whole width) and almost each of them will decreased to a value near 150px x 150px in the flex box.

A: outer <svg> elements are replaced elements in CSS/HTML parlance and follow the rules for replaced element sizing
In particular if replaced elements have no defined size the browser falls back to a size of 300px x 150px, which is likely what you're seeing.
Normal i.e. raster images always have a defined size and are not replaced elements.
See also the SVG specification for how CSS affects SVG sizing


text:
Q: includegraphics aspects ratio problem? I'm using texmaker. I create my diagrams with excel via a pdf print. When I include this pdf to my document I scale this pdf to the textwidth. The result looks like that the aspect ratio wasn't respected. There is suddenly an ugly gap between the units on the y-axis.
That's the code including my pdf
\begin{diagram}
\centering
 \includegraphics[width=1\textwidth]
{xxx.pdf}
\captionof{diagram}{\label{dia:dia name}
\end{diagram}

Adding keepaspectratio=true to includegraphics doesn't help. It looks like latex doesn't respect the aspects ratio.
That's the diagram sniping with the wrong y axis. Why is there suddenly a blank space.....It doesn't appear in the original pdf generated from excel.

please help.
greetings

Its again me the thread starter.....at the blank space should be a µ.
Why can latex not display it anymore? I used in excel Latin Modern 12. With another font like arial latex can display the µ.


text:
Q: WPF: How to bind to interface that inherits from another interface? I have an interfaces:
public interface IDocument : IEntity
{
    string FileName { get; set; }
    ...
}

public interface IEntity : IComparable
{
    int Id { get; set; }
    ...
}

I'd like to bind as following:
<ItemsControl Grid.Row="0" ItemsSource="{Binding SelectedEventPhotoList}"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            Name="SelectedListView">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1" Columns="3"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=(documents:IDocument.FileName)}"/>
                <TextBlock Text="{Binding Path=(documents:IDocument.Id)}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The SelectedEventPhotoList is placed to view model as following:
public List<IDocument> SelectedEventPhotoList
{
    get { return _selectedEventPhotoList; }
    set
    {
        if (Equals(value, _selectedEventPhotoList))
            return;

        _selectedEventPhotoList = value;
        RaisePropertyChanged(() => SelectedEventPhotoList);
    }
}

The first binding to FileName works fine, but the second one doesn't.
How to make it work?

A: If IEntity.Id is an explicitly implemented property you should replace IDocument with IEntity in your binding path:
<TextBlock Text="{Binding Path=(documents:IEntity.Id)}"/>

If not you should be able to bind to it using the common binding syntax:
<TextBlock Text="{Binding Path=Id}"/>


text:
Q: .NET Core 2.0 soap client call fails with "WinHttpException: The operation timed out" I have a simple soap client developed in .Net core 2.0 to consume calculator methods from the following web service:
http://www.dneonline.com/calculator.asmx?WSDL
The service is imported into Visual Studio 2017 as a connected service and the code that calls the service methods looks as below:
        var binding =  new BasicHttpBinding(BasicHttpSecurityMode.None);
        var ep = new EndpointAddress("http://www.dneonline.com/calculator.asmx?WSDL");

        Calculator.CalculatorSoapClient client =
            new Calculator.CalculatorSoapClient(binding, ep);

        client.AddAsync(1, 3).Wait();
        Console.WriteLine("Finished successfully");
        Console.ReadLine();

Now the thing is that this code fails after 20 seconds when calling the AddAsync methodwith an exception of "WinHttpException: The operation timed out". Other relevant observations:

*

*The exact same code (incluing the generated connected service) works well in VS 2015 with .NET Framework.

*Our dev machines are behind the company firewall and by that the wirshark trace looks different between the two executions. The successfull run on .NET Framework can establish the connection while the other one cannot connect to the proxy.

*I have seen other articles talking about increasing the timeout value on long running or heavy calls but this one is neither heavy nor a long running method.

Has anyone faced any similar issue or knows why .NET core behaves differently?
Update 1
We tested the solution on a cloud based computer and it worked fine. So, it looks to be the company firewall blocking the outgoing communication.
On the other hand on the same local computer, we tested a simple .Net Core application that downloads an image from a website and that worked well too.
This is all while VS 2015 with .NET Framework has no problem running the same code, calling a web service and fetching the results.
So, the new question can be why .NET Core behaves differently on the network communication? Is there any new rule, policy, permission, restriction, capability, etc that needs to be turned on/off to enable coomunication with the internet?

A: There was a bug in .net Core 2.0 with proxy configuration, as you could see here: https://github.com/dotnet/wcf/issues/1592.
The solution for my project (VS 2017/.net Core 2.0) was to upgrade it to .net Core 2.1, and update System.ServiceModel.Http and other dependencies to latest stable (4.5.3 in my case). Then the IE/Edge proxy settings are used.
This question is possibly a duplicate of: Connecting to a SOAP service with .Net Core 2.0 behind a proxy


text:
Q: Adding a widget to the main window from another thread Qt I have just started crawling in Qt. Installed qt4 on my Ubuntu machine and tried some basic examples. Now I am trying a develop a multithreaded application. Firstly I am confused whether to use pthreads or Qthreads. Can someone tell me which one is better to use.?
Further in my application, I will send some values from one thread to another thread. The 2nd thread will print those in a box. My query is, whether a thread other than main thread, can add a widget  to the main window?

A: *

*Use QThread. It uses pthreads internally, but you don't rely on pthreads and can (potentially) run your program on other platforms and OSes just as well.

*You cannot create QWidget instances from worker threads. There is only one GUI thread in Qt: the thread which runs main(). Only this thread may create anything which communicates with the window manager (widgets and pixmaps).

So between threads, you communicate data only. The GUI thread manages the graphical user interface by itself, and just accepts data from worker threads. Have a look at the Qt documentation for how to implement multi-threaded applications.

A: You could use QApplication which has a static method topLevelWidgets() in which you can "find" one of your main widgets.
Like this:
#include <QApplication>

foreach(QWidget *widget, QApplication::topLevelWidgets())
{
    if(widget->accessibleName() == "YourMainWidgetName")
    {
        myMainTopWidget = widget;
    }
}

When you send value from one thread to another, then use signals and slots. They are thread-safe and easy to use.


text:
Q: Stored procedure to find the number of records from input table name In a stored procedure, I pass a table name as the input variable.  I want to return the number of rows of this table with that stored procedure.
I tried something like this but it did not work:
clear screen;
set serveroutput on;
declare  tbl_nm varchar2(50);
create or replace procedure table_cnt(table_name in varchar2(50), cnt out integer) as
begin
tbl_nm:=table_name;
select count(*) into cnt from tbl_nm;
end;

working in oracle 11g.

A: Here is a function from AskTOM, you can refer to it
create or replace
function get_rows( p_tname in varchar2 ) return number
as
l_columnValue number default NULL;
begin
execute immediate
'select count(*)
from ' || p_tname INTO l_columnValue;

return l_columnValue;
end;
/

select user, table_name,
get_rows( user||'.'||table_name) cnt
from user_tables
/


text:
Q: Javascript, running functions or getting global variables of obfuscated code I just bought this javascript obfuscation script: http://codecanyon.net/item/php-javascript-obfuscator/411175?ref=WiseLoop
Now I want to run a function in the script that is obfuscated. Ofcourse that doesn't work any more because the function names are changed. How is this achieved?
Thanks.


text:
Q: Is it possible to connect MongoDB to React directly? I have a small react component that lists data from a gist api
async componentDidMount() {
    const url = "(the gist URL)";
    const response = await fetch(url);
    const api_data = await response.json();
    this.setState({data: api_data})
    console.log(api_data)
  }

I would like to know how I can pull the same data from a mongodb without having to use express.


text:
Q: Export Opengl ES video XCode has the ability to capture Opengl ES frames from the iPad, and that's great! I would like to extend this functionality  and capture an entire Opengl ES movie of my application. Is there a way for that?
if it's not possible using XCode, how can i do it without much effort and big changes on my code? thank you very much!

A: I use a very simple technique, which requires just a few lines of code.
You can capture each OGL frame into UIImage using this code:
- (UIImage*)captureScreen {

    NSInteger dataLength = framebufferWidth * framebufferHeight * 4;

    // Allocate array.
    GLuint *buffer = (GLuint *) malloc(dataLength);
    GLuint *resultsBuffer = (GLuint *)malloc(dataLength);
    // Read data
    glReadPixels(0, 0, framebufferWidth, framebufferHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // Flip vertical
    for(int y = 0; y < framebufferHeight; y++) {
        for(int x = 0; x < framebufferWidth; x++) {
            resultsBuffer[x + y * framebufferWidth] = buffer[x + (framebufferHeight - 1 - y) * framebufferWidth];
        }
    }

    free(buffer);

    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, resultsBuffer, dataLength, releaseScreenshotData);

    // prep the ingredients
    const int bitsPerComponent = 8;
    const int bitsPerPixel = 4 * bitsPerComponent;
    const int bytesPerRow = 4 * framebufferWidth;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

    // make the cgimage
    CGImageRef imageRef = CGImageCreate(framebufferWidth, framebufferHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);
    CGColorSpaceRelease(colorSpaceRef);
    CGDataProviderRelease(provider);

    // then make the UIImage from that
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return image;
}

Then you will capture each frame in your main loop:
- (void)onTimer {

    // Compute and render new frame
    [self update];

    // Recording
    if (recordingMode == RecordingModeMovie) {

        recordingFrameNum++;

        // Save frame
        UIImage *image = [self captureScreen];
        NSString *fileName = [NSString stringWithFormat:@"%d.jpg", (int)recordingFrameNum];
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[basePath stringByAppendingPathComponent:fileName] atomically:NO];
    }
}

At the end you will have tons of JPEG files which can be easily converted into a movie by
Time Lapse Assembler
If you want to have nice 30FPS movie, hard fix your calc steps to 1 / 30.0 sec per frame.


text:
Q: VBA Removing ListBox Duplicates I'm trying to add a list of names from another worksheet that has duplicates. On the listbox, I want to have unique names, instead of duplicates. The following code is not sorting them for duplicates, it errors out. Any help is appreciated.
Dim intCount As Integer
Dim rngData As Range
Dim strID As String
Dim rngCell As Range
dim ctrlListNames as MSForms.ListBox
Set rngData = Application.ThisWorkbook.Worksheets("Names").Range("A").CurrentRegion

'declare header of strID and sort it
strID = "Salesperson"
rngData.Sort key1:=strID, Header:=xlYes
'Loop to add the salesperson name and to make sure no duplicates are added
For Each rngCell In rngData.Columns(2).Cells
    If rngCell.Value <> strID Then
        ctrlListNames.AddItem rngCell.Value
        strID = rngCell.Value
    End If
Next rngCell

A: Way 1
Use this to remove the duplicates
Sub Sample()
    RemovelstDuplicates ctrlListNames
End Sub

Public Sub RemovelstDuplicates(lst As msforms.ListBox)
    Dim i As Long, j As Long
    With lst
        For i = 0 To .ListCount - 1
            For j = .ListCount - 1 To (i + 1) Step -1
                If .List(j) = .List(i) Then
                    .RemoveItem j
                End If
            Next
        Next
    End With
End Sub

Way 2
Create a unique collection and then add it to the listbox
Dim Col As New Collection, itm As Variant

For Each rngCell In rngData.Columns(2).Cells
    On Error Resume Next
    Col.Add rngCell.Value, CStr(rngCell.Value)
    On Error GoTo 0
Next rngCell

For Each itm In Col
    ctrlListNames.AddItem itm
Next itm

A: Private Sub Workbook_Open()
Dim ctrlListNames As MSForms.ListBox
Dim i As Long
Dim j As Long

ctrlListNames.List = Application.ThisWorkbook.Worksheets("Names").Range("Salesperson").Value

With ctrlListNames
For i = 0 To .ListCount - 1
    For j = .ListCount To (i + 1) Step -1
        If .List(j) = .List(i) Then
            .RemoveItem j
        End If
    Next
Next
End With

End Sub

And it says invalid property array index.

A: It says invalid property array index because the list gets shortened after the removal of entries. if we use FOR, the end value is static, therefore, we need to use DO while loop. Use the following code to remove duplicates.
Count = ListBox1.ListCount - 1

i = 0
j = 0

Do While i <= Count
j = i + 1
Do While j <= Count
If ListBox1.List(i) = ListBox1.List(j) Then
ListBox1.RemoveItem (j)
Count = ListBox1.ListCount - 1  'Need to update list count after each removal.
End If
j = j + 1
Loop
i = i + 1
Loop


text:
Q: ExpandableListView group views change when selected in Android I am trying to create an ExpandableListView which I have done before and I know that it recycles views, but I am trying to get the views to be final and not change. When I select the group view to expand the view, the group view sometimes changes to another group view's text.
Please can someone have a look at my code and see what I am doing wrong.
public class ClientListAdapter extends BaseExpandableListAdapter
{
private Context context;
private List<Client> listOfClients;

public ClientListAdapter(Context context, List<Client> listOfClients)
{
    this.context = context;
    this.listOfClients = listOfClients;
}

private static class ViewHolder
{
    TextView name;
    TextView ID;
    TextView email;
    TextView phoneNumber;
    Button writeToNFC;
}

@Override
public int getGroupCount()
{
    return listOfClients.size();
}

@Override
public int getChildrenCount(int groupPosition)
{
    return 1; // There will only ever be 1 child in the group.
}

@Override
public Object getGroup(int groupPosition)
{
    return groupPosition;
}

@Override
public Object getChild(int groupPosition, int childPosition)
{
    return null;
}

@Override
public long getGroupId(int groupPosition)
{
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition)
{
    return groupPosition;
}

@Override
public boolean hasStableIds()
{
    return true; // Stops child views from resetting.
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
    final ViewHolder viewHolder;

    if(convertView == null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.unexpanded, parent, false);

        viewHolder = new ViewHolder();
        viewHolder.name = (TextView) convertView.findViewById(R.id.ClientName);

        viewHolder.name.setText(listOfClients.get(groupPosition).getName());

        System.out.println("Group name: " + listOfClients.get(groupPosition).getName());

        convertView.setTag(viewHolder);
    }
    else
    {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
    final ViewHolder viewHolder;

    if(convertView == null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.client_details, parent, false);

        viewHolder = new ViewHolder();

        convertView.setTag(viewHolder);
    }
    else
    {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.ID = (TextView) convertView.findViewById(R.id.ClientID);
    viewHolder.email = (TextView) convertView.findViewById(R.id.ClientEmail);
    viewHolder.phoneNumber = (TextView) convertView.findViewById(R.id.ClientTel);
    viewHolder.writeToNFC = (Button) convertView.findViewById(R.id.WriteToNFC);

    viewHolder.ID.setText(listOfClients.get(groupPosition).getClientID());
    viewHolder.email.setText(listOfClients.get(groupPosition).getEmail());
    viewHolder.phoneNumber.setText(listOfClients.get(groupPosition).getPhoneNumber());

    viewHolder.writeToNFC.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            MainActivity mainActivity = (MainActivity) context;

            String ndefMessage = viewHolder.ID.getText().toString();

            mainActivity.setNdefMessage(ndefMessage);

            Toast.makeText(context, "Client details selected.", Toast.LENGTH_SHORT).show();

            System.out.println("NDEF message: " + ndefMessage);
        }
    });

    System.out.println("Group position: " + groupPosition);
    System.out.println("Child position: " + childPosition);

    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
    return false;
}

}

A: I actually just managed to fix the error. What I had to do was put the viewHolder.name functions outside of the if statement like this:
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
    final ViewHolder viewHolder;

    if(convertView == null)
    {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.unexpanded, parent, false);

        viewHolder = new ViewHolder();

        System.out.println("Group name: " + listOfClients.get(groupPosition).getName());

        convertView.setTag(viewHolder);
    }
    else
    {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.name = (TextView) convertView.findViewById(R.id.ClientName);

    viewHolder.name.setText(listOfClients.get(groupPosition).getName());

    return convertView;
}

A: Use below Override methods from BaseExpandableListAdapter
public int getChildType(int groupPosition, int childPosition) {
//define a condition here to differentiate between your child views.
}

public int getChildTypeCount() {
    return 2; <-- this is the number of views for your child
}

Hope this will help.


text:
Q: How do I set the uncomment shortcut? For previous versions of Visual Studio --- Tools => Options => Keyboard => Edit.UncommentSelection => Ctr+Shift+/.  This removes the // in front of comments.
For Visual Studio 2019, Ctr+Shift+/ places /**/ around that line.
Note that setting Edit.CommentSelection to Ctrl+/ works fine for all versions of VS (places // in front of comments).

A: You may use the default Keyboard shortcut (Ctrl+K, Ctrl+U) for uncommenting snippets of code, or assign a new shortcut to replace the default option with keys of your choice, as shown below:

Reference: Customize a keyboard shortcut


text:
Q: D3 proper text() in tremap i'm new to d3. My problem is unreadable text.
I suppose it's cuz i added text not to rect but to svg. How do i recode or fix this thing?
https://codepen.io/DeanWinchester88/pen/xxrjLrM
       svg
      .selectAll("text")
       .data(root.leaves())
       .enter()
          .append("text")
          .attr("x", (d)  =>  d.x0 +10)
          .attr("y",  (d) =>  d.y0  + 20)
          .text(  (d) => d.data.name)
          .attr("font-size", "12px")
          .attr("fill","white")
          .attr("overflow", "hidden")
          .attr("max-width",  (d) =>  d.x1 -  d.x0)
  tspan = text.text(null)
                        .append("tspan")
                        .attr("x", x)
                        .attr("y", y)
                        .attr("dy", dy + "em")

A: Here's your revised code based on my comment above:
https://codepen.io/mattsrinc/pen/MWozBWQ
 svg
  .selectAll("text")
  .data(root.leaves())
  .enter()
    .append("text")
    .attr('transform', d => 'translate(' + d.x0 + ',' + d.y0 + ')')
    .selectAll('tspan')
    .data(d => d.data.name.split(/(?=[A-Z][^A-Z])/g))
    .enter()
      .append('tspan')
      .attr('font-size', '0.8em')
      .attr('fill', 'white')
      .attr('x', function(d) { console.log(d); return '0.5em' })
      .attr('y', (d, i) => 12 * (i + 1))
      .text(d => d);

I've left the console.log command so that you can see how the (game) name is split into parts. And that Pac-Man is right but it's the only one game for the console category (2600) so it translates to thin black rectangle on top left (something you should consider how to solve it visually).
Then also SVG CSS attribute "overflow: hidden" won't work for your data cells with TSPAN. You would have to handle that with calculating this cell width and width of the current word(s) in a line (of TSPAN tag to add). It would be better to follow and expand your other referenced codepen to work with cells that would ease this task.
Other than that I've just changed the color palette used and you can see color ranges here:
https://github.com/d3/d3-scale-chromatic


text:
Q: Library behaviour while migrating from VB6 to VB.NET I have a VB6 application which i need to convert to VB.NET 3.5. The application uses a lot of Business objects libraries and some external libraries.
I would like to know if these libraries would behave the same way when i move from VB to VB.net?Are there chances that things would break?Please advice..

A: The answer is it depends.  There should be no issue and I know Microsoft has made a great effort to make sure this type of migration path works, but being third party you never know if something may go wrong.  The only advice I can give is test often and test everything.  If it is possible make a program to just test the functionality of the libraries.  HTH.
Wade


text:
Q: Prove that $\frac{a}{a+b}+\frac{b}{b+c}+\frac{c}{c+a}\ge\frac{3}{2}$ For $a\geq b\geq c >0$. Prove that $$\dfrac{a}{a+b}+\dfrac{b}{b+c}+\dfrac{c}{c+a}\ge\dfrac{3}{2}$$
$a=100;b=1;c=1/100$ it's wrong ???

$\dfrac{a}{a+b}+\dfrac{b}{b+c}+\dfrac{c}{c+a}\ge\dfrac{3}{2}$
$<=>\sum\frac{a}{a+b}-\frac{1}{2}+\frac{b}{b+c}-\frac{1}{2}+\frac{c}{c+a}-\frac{1}{2}\geq 0$
$<=>\sum \frac{a-b}{2(a+b)}\geq 0$$<=>\sum\frac{z-y}{2x}\geq 0$
$<=>xy^2+yz^2+xz^2-x^2y-y^2z-z^2x\geq 0$
$<=>(y-x)(z-y)(z-x)\geq 0$
And we have $y-x\le 0; z-x\le 0; z-y\geq 0$
we are done !?

A: For $a\geq b\geq c>0$ we obtain:
$$\sum_{cyc}\frac{a}{a+b}-\frac{3}{2}=\sum_{cyc}\left(\frac{a}{a+b}-\frac{1}{2}\right)=\sum_{cyc}\frac{a-b}{2(a+b)}=$$
$$=\sum_{cyc}\frac{(a-b)(c^2+ab+ac+bc)}{2\prod\limits_{cyc}(a+b)}=\sum_{cyc}\frac{c^2a-c^2b}{2\prod\limits_{cyc}(a+b)}=$$
$$=\sum_{cyc}\frac{a^2b-a^2c}{2\prod\limits_{cyc}(a+b)}=\frac{(a-b)(a-c)(b-c)}{2\prod\limits_{cyc}(a+b)}\geq0$$


text:
Q: Dockerfile: RUN command with special parameters I want to run bash commands with special parameters like $_ inside the Dockerfile.
I tried the following example but it seems to be not working. If I execute the same command in the bash directly, it works like a charm. Does anyone have an idea what I'm doing wrong?
$ RUN mkdir /foo && cd $_ && pwd

A: It depends on shell in base container. ubuntu is using dash for example, changing default shell to bash is helping to get result which you expect:
FROM ubuntu
RUN rm /bin/sh && ln -s /bin/bash /bin/sh
RUN mkdir /foo && cd $_ && pwd

result:
docker build --rm .
Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon
Step 0 : FROM ubuntu
 ---> d0955f21bf24
Step 1 : RUN rm /bin/sh && ln -s /bin/bash /bin/sh
 ---> Using cache
 ---> c90ef9fd9710
Step 2 : RUN mkdir /foo && cd $_ && pwd
 ---> Running in 8e1d943a6b60
/foo
 ---> 1871918ee02c
Removing intermediate container 8e1d943a6b60
Successfully built 1871918ee02c


text:
Q: Regex: Grab second string between two single quotes Can I get a little help matching a string in the below text?

The default username and password is 'user' and 'ZWiliWH8E2mV'.

I'm trying to get the string between the second set of single quotes: ZWiliWH8E2mV.  This string is randomly generated, and I can only rely on the formatting, and not the ZWiliWH8E2mV.  After some googling, I can match it with grep:
cat file_name | grep -oP "(?<=').*?(?=')"

but it's the 3rd match, and I'm not sure how to get to it from there.  I'm open to using other tools if they're better for what I'm trying to do, but I'm not very versed in them.

A: As you stated in the question states that you are trying to get the string between the second set of single quotes, you could match the first 3 single quotes and start the match after it until the occurrence of the fourth single quote.
The negated character class [^']+ matches any char except a single quote.
^(?:[^']+'){3}\K[^']+(?=')

Explanation

*

*^ Start of string

*?:[^']+'){3}' Match 3 times any char except ' then match '

*\K Clear the match buffer (Forget what is matches until this point)

*[^']+ Match 1+ times any char except ' (What you want to match)

*(?=') Positive lookahead, assert what is directly to the right is a '
Regex demo | Bash demo
The updated code might look like
cat file_name | grep -oP "^(?:[^']+'){3}\K[^']+(?=')"

A:
I'm trying to get the string between the second set of single quotes

Using awk, you can avoid regex:
s="The default username and password is 'user' and 'ZWiliWH8E2mV'."

awk -F "'" '{print $4}' <<< "$s"

ZWiliWH8E2mV

Here we are using ' as field delimiter and 4th field in awk will give us 2nd value wrapped inside single quotes.

A: You may grab the value between the last two single quotation marks using grep:
grep -oP ".*'\\K[^']+(?=')" file_name

See the online demo
The -o option outputs only matched substrings and P makes grep use PCRE regex engine.
PCRE regex details

*

*.* - any 0 or more chars other than line break chars, as many as possible

*' - a ' char

*\K - match reset operator that discards all text matched so far in the overall match memory buffer

*[^']+ - one or more chars other than a ' char

*(?=') - a positive lookahead that makes sure there is a ' char immidiately to the right of the current location.

A: If you have multiple single quoted fields:
$ s="'first' and 'second' and 'third' and 'fourth' and the rest"

You can use the following Perl one liner to get the nth field:
echo "$s" |
perl -lne 'while (/[\x27]([^\x27]*)[\x27]/g) {print $1 if ++$i==3}'

# third

So for your example, the password is the second quoted field:
echo "The default username and password is 'user' and 'ZWiliWH8E2mV'." |
perl -lne 'while (/[\x27]([^\x27]*)[\x27]/g) {print $1 if ++$i==2}'

Prints:
ZWiliWH8E2mV

You can also use gawk with FPAT set to the same regex to print the nth field:
s="'first' and 'second' and 'third' and 'fourth' and the rest"

echo "$s" |
gawk -v n=2 'BEGIN{FPAT="[\x27][^\x27]*[\x27]"}
            { gsub(/[\x27]/,"",$n); print $n}'

# second

Or you can use a pipeline of two GNU sed commands with n being the line you print in the second sed:
echo "$s" |
gsed -E 's/[^\x27]*\x27([^\x27]*)\x27[^\x27]*/\1\n/g' | gsed -nE '4p'
# fourth

Note:
[\x27] is the hex character representation for '. Hex character representations are supported by most regex implementations but not all. POSIX sed for example is dodgy.


text:
Q: Storing text files inside root directory I am currently in the /bin directory. I am trying to create a text file of the content of the
/bin directory and direct it to be stored in another file within the /root directory. I have entered the command ls -l >/directoryname/filename
yet I don't have permissions to run it. I have tried entering sudo before the commmand
however this doesn't work either. Does anyone know how I can gain permissions
to store this file? It would be very much appreciated, Thanks.

A: When running sudo ls > /root/out.txt only the ls part of the command is being run with elevated privileges. Because of this the redirection part of your command does not have the permissions needed to access the location you want.
Instead you can use tee prefixed with sudo like so:
ls | sudo tee /root/out.txt

A: An easy solution in order to run a number of commands with sudo is the following:
sudo bash -c 'command1;command2'

For your situation this would work great:
sudo bash -c 'ls -l >/directoryname/filename'

This of course is only when you are using bash.

A: If you enter sudo chmod 777 /filename and then run that, you will have permissions to run the commands you previously tried to run. chmod 777 essentially gives any user read, write and execute permissions in this directory. You can change the permissions later though so users can only read or write for example.


text:
Q: Lowest cardinality of a subset of $N$ being able to be divided in $2017$ ways Find the lowest cardinality of $А\subseteq\Bbb{N}$ such that there are 2017 different partitions  $B_i\subseteq A$  and $A\backslash B_i$ for which $\operatorname{lcm}(B_i) =\gcd(A\backslash B_i)$
How is it possible that we are looking for a GCD of a factor set?
And what are we really looking for? That the number of sets in the power set of A is 2017?
Here is my attempt [link]

A: For a valid partition we need in particular that every $x\in B_i$ divides every $y\in A\setminus B_i$.
Hence for different indices $i,j$ we one of $B_i\setminus B_j$, $B_j\setminus B_i$ must be emtpy, i.e., we have $B_i\subseteq B_j$ or $B_j\subseteq B_i$. So the $B_i$ are linearly ordered by inclusion:
$$\emptyset\subsetneq B_1\subsetneq B_2\subsetneq B_3\subsetneq \ldots \subsetneq B_{2017}\subsetneq A$$
Suppose for some $k$, $1\le k\le 2017$, we have $|B_{k+1}\setminus B_{k-1}|=2$ (with $B_0=\emptyset$ and $B_{2018}=A$ understood), so $B_{k}=B_{k-1}\cup \{m\}$, $B_{k+1}=B_{k}\cup\{n\}$ for some distinct numbers $m,n$. Then $\operatorname{lcm}(B_{k})=m$ and $\gcd(A\setminus B_{k})=n$, i.e., we should have $n=m$. We conclude $|B_{k+1}|\ge |B_{k-1}|+3$ for $1\le k\le 2017$. By induction, $|A|=|B_{2018}|\ge |B_0|+1009\cdot 3\ge 2027$.
But can this lower bound be achieved? Yes! For $n\in\Bbb N$ let
$$S_n=\{\,2^a3^b: |a-b|\le 1, a+b<n\,\}. $$
Verify that $\operatorname{lcm}(S_{2n})=\operatorname{lcm}(S_{2n+1})=6^n$ and that for $m>2n$ or $m>2n+1$, respectively,
$\gcd(S_m\setminus S_{2n})=\gcd(S_m\setminus S_{2n+1})=6^n$ as well.
Also $|S_{2n}|=3n$.
This allows us to pick $B_k=S_k$ for $1\le k\le 2017$ and $A=S_{2018}$ with $|A|=3027$.