text:
Q: Conservation of Energy vs Expansion of Space My question pertains to a possible inconsistency between the first law of thermodynamics and the general expansion of space itself.
First, the knowns:

*

*Space itself has, and continues to expand - the acceleration aspect is not relevant to the discussion

*Empty space in a vacuum has intrinsic energy - some refer to this as dark energy

*Energy cannot be created or destroyed as per the first law of thermodynamics

Concisely, what is the source of energy that is imbued into this "new" space?
A few speculations:

*

*The energy for this process is taken from something other source that already exists inside or outside the known universe.

*The energy for this process is created from nothing, thus violating the first law.

*If space itself is quantized, perhaps the planck length itself is expanding across the universe, giving the appearance that new space is created, but actually it is just the space "particles" themselves that are expanding.  At some critical point this expanding space would have observable consequences for our own scale of existence.

These ponderings can also be applied to the big bang theory - either energy was created at some point (from nothing) or existence of anything has been an infinite cycle into the past. Either way we are dealing with infinites. Create something from nothing and you will find infinites cropping into your calculations.

A: Conservation of energy relies on the symmetry of your system under time translation (see Noether Theorem).
In a system that is not time translation invariant, eg expanding universe, energy doesn't have to be conserved.

A: The claim that energy conservation does not hold in GR is debatable, as any choice of time-like vectorfield will yield such a law via Noether's second theorem (energy conservation in GR was in fact the reason why Noether developed her theorems in the first place). However, these laws are (in Noether's terminology) 'improper', ie given through linear combinations of differential identities given by the 'Lagrangian expressions' and their derivatives (cf Invariant Variational Problems by Emmy Nother).
From the more practical perspective of physics, the issue with these laws is that they contain a delocalized contribution that cannot be associated with an energy density. A classical analogon would be energy conservation in accelerated frames of reference, with the caveat that in contrast to classical mechanics, in GR we cannot just go to an inertial frame to make all 'fictious' forces go away globally.
Now, for your case specifically (for convenience, I'll consider the spatially flat Friedmann model), it turns out that if we choose cosmic time as our parameter field, we'll end up with the first Friedmann equation
$$
\left(\frac {\dot a}a\right)^2 = H^2 = \frac{8\pi}{3} \rho + \frac 13 \Lambda
$$
or more suggestively
$$
\rho + \frac 1{8\pi} \Lambda - \frac 3{8\pi} H^2 = 0
$$
with positive contributions by matter and dark energy balanced by a negative contribution that we identify with the gravitational field.
As an aside, we can also rewrite the second Friedmann equation
$$
\frac {\ddot a}a = \dot H + H^2 = -\frac{4\pi}3 (\rho + 3p) + \frac 13 \Lambda
$$
in a way that, depending on your point of view, is either eye-opening or misleading.
Compute $\dot H$ by differentiating the first equation and insert it into the second one, substitute $H^2$ as well and you'll arrive at
$$
\dot\rho + 3H(\rho + p) = 0
$$
Now, consider a finite volume $V=(R_0a)^3$. As $H = \dot V / 3V$ multiplying by $V$ yields
$$
\dot\rho V + \rho\dot V + p\dot V = 0
$$
or with $U = \rho V$
$$
\mathrm dU + p \mathrm dV = 0
$$
Note the lack of explicit contributions by either dark energy or gravity, though they implicitly contribute dynamically.

A: Dark energy is a form energy that appears to have a constant density in space even as the universe expands. The simplest model for this is a cosmological constant in the gravitational field equations. This model agrees with observations. What dark energy really is or whether this model is correct is beside the point here. My answer assumes this hypothesis. The question we need to answer is how can we reconcile energy conservation with that model?
As the universe expands the amount of dark energy in an expanding volume increases in proportion to the volume. Meanwhile the amount of energy contained in cold matter remains constant. It sounds like dark energy is therefore being created out of nothing in violation of the law of energy conservation.
In fact there is also a negative contribution of energy in the gravitational field due to the dynamic expansion of space itself. As the expansion of the universe accelerates due to dark energy the magnitude of this negative background gravitational energy increases. This matches all other forms of energy so that the total is constantly zero and energy is conserved.
The equation for energy in the standard cosmological models for an expanding universe including radiation and dark energy as well as ordinary matter can be derived from these formulations and is as follows:
$E = Mc^2 + \frac{\Gamma}{a} + \frac{\Lambda c^2}{\kappa}a^3 - \frac{3}{\kappa}\dot{a}^2a - Ka = 0$
$E$ is the total energy in an expanding region of volume $a(t)^3$. This always comes to zero in a perfectly homogeneous cosmology.
$a(t)$ is the universal expansion factor as a function of time normalised to 1 at the current epoch. It started as zero and increases with time as the universe gets bigger.
$\dot{a}$ is the derivative of $a$ with respect to time, in other words it is the rate of expansion of the universe.
$M$ is the total mass of matter in the region
$c$ is the speed of light
$\Gamma$ is the density of cosmic radiation normalised to the current epoch
$\Lambda$ is the cosmological constant also known as dark energy, thought to be positive.
$\kappa$ is the gravitational coupling constant. In terms of Newton's gravitational constant $G$ it is $\kappa = \frac{8\pi G}{c^2}$.
$K$ is a constant that is positive for spherical closed space, negative for hyperbolic space and zero for flat space.
This equation tells us that the positive energy in matter, radiation and dark energy is perfectly balanced by a negative quantity of energy in the gravitational field that depends on the rate of expansion of the universe. As the universe expands the length scale $a(t)$ increases. The amount of energy in ordinary matter $Mc^2$ is constant in an expanding volume. The radiation energy $\frac{\Gamma}{a}$ decreases due to cosmic redshift and the amount of dark energy  $\frac{\Lambda c^2}{\kappa}a^3$ increases as the volume expands. The rate of expansion must adjust so that the negative gravitational energy balances the sum of these energies. In particular the dark energy must eventually become the dominant positive term and the expansion of space accelerates to balance the energy equation.
Some people claim incorrectly that energy is not conserved in an expanding universe because space-time is not static. The law of Energy conservation is derived from Noether's theorem when the dynamical equations are unchanged with time. These people confuse the invariance of the equations with the invariance of the solution. Space-time changes but the equations obeyed by the expanding universe do not change. Space-time cannot be treated as a background, its dynamics must be included when deriving the enrgy equations via Noether's theorem. This leads to the equations given above which show that energy is indeed conserved.

A: In the question on dark energy I gave an elementary answer that is reduced to Newtonian mechanics. The Hubble frame has a remarkable property that one can look at local cosmology in a Newtonian fashion. The total energy is set to zero. This does give a result that is commensurate with the Friedmann-Lemaitre-Robertson-Walker theory of the expanding universe. It even covers the de Sitter spacetime accelerated expansion.
This conservation law is at best local and is a manifestation of our local frame. The spacetime metrics for cosmologies are type O solutions in the Petrov scheme and these have not Killing vectors. In general relativity a Killing vector $\xi_\mu$ must act as an isometry by projecting on a vector, say the momentum vector $P^\mu$ so that $\xi_\mu P^\mu~=~const$. This gives Noether theorem results for conservation laws. Cosmologies lack this property on a global level, which is one reason the little Newtonian model I present above must break down on some level.


text:
Q: How can I perform RenderTransform within ScrollViewer (WP7)? I've tried many ways to manage RenderTransform within ScrollViewer (Windows Phone 7 Silverlight), but it seems to me almost impossible now. What I got is Grid with with its sizes inside ScrollViewer and I want to change grid's content size from code by RenderTransform by it do nothing!
      <ScrollViewer x:Name="scrollViewer" Width="800" Height="480" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
        <Grid x:Name="grid" Width="1600" Height="960" HorizontalAlignment="Left" VerticalAlignment="Top">
            <Grid.RenderTransform>
                <CompositeTransform x:Name="scaleTransform" ScaleX="1" ScaleY="1"/>
            </Grid.RenderTransform>
            <Image x:Name="backgroundImage" Source="/Images/backgrounds/Happy rainbow.png" Stretch="Fill"/>
        </Grid>
    </ScrollViewer>

In code:
        private void button_Click(object sender, RoutedEventArgs e)
    {
            (grid.RenderTransform as CompositeTransform ).CenterX = 0;
            (grid.RenderTransform as CompositeTransform ).CenterY = 0;
            (grid.RenderTransform as CompositeTransform ).ScaleX = 0.5;
            (grid.RenderTransform as CompositeTransform ).ScaleY = 0.5;
            grid.UpdateLayout();
    }

Binding on Scale and Visual states do nothig too. I really would appreciate your help.

A: Better idea... put your Grid content into an ItemsControl, and perform a ScaleTransform on the ItemsControl.
<Grid>
    <ItemsControl x:Name="ContentScaler">
        <Image x:Name="backgroundImage" Source="/Images/backgrounds/Happy rainbow.png" Stretch="Fill"/>
    </ItemsControl>
</Grid>

And in the code-behind...
ContentScaler.RenderTransform = new ScaleTransform() { ScaleX = 0.5, ScaleY = 0.5, CenterX = 0, CenterY = 0 };

Depending on what else you may need to do, you may need to do something like set a WrapPanel as the ItemsPanelTemplate and/or resize the ItemsControl when you do your scaling.  It can get a little tricky, but hopefully this will get you pointed in the right direction.
The use of Grid in Silverlight tends to be a bit overused also, IMHO, unless one needs to break things into a table type layout.  A Canvas may be better suited for what you are doing.

A: I'm not sure if this is exactly what you need but if you insert an extra grid like this...
            <ScrollViewer Grid.Row="1" x:Name="scrollViewer"
                      Width="800"
                      Height="480"
                      HorizontalScrollBarVisibility="Visible"
                      VerticalScrollBarVisibility="Visible">
            <Grid x:Name="grid"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top">
                <Grid
                    Width="1600"
                    Height="960">
                    <Grid.RenderTransform>
                        <CompositeTransform x:Name="scaleTransform"
                                            ScaleX="1"
                                            ScaleY="1" />
                    </Grid.RenderTransform>
                    <Image x:Name="backgroundImage"
                           Source="ApplicationIcon.png"
                           Stretch="Fill" />
                    </Grid>
            </Grid>
        </ScrollViewer>

at least the contents will get scaled..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grep and CMD escaping I am trying to grep this pattern: ^#include\s+"[^"]+"
Unfortunately, when I try the following in a Windows batch file, the pipe (|) and the sort are treated as inputs to grep, probably because of the unbalanced quotes.
> grep -P '^#include\s+"[^"]+"' --include=*.h --include=*.cpp | sort

grep: |: No such file or directory
grep: sort: No such file or directory

I tried different combinations of escaping, both with backslash and with caret, but could not get it to work.
Edit:
By trial and error, I got this to work:  grep -P '^^#include\s+\"[^\"]+\^"' --include=*.h --include=*.cpp | sort
It is a weird mix of CMD escapes (^) and regex escapes (\), without an apparent rhyme or reason to which one needs to be used where.
I am leaving the question open in the hope that someone will offer a general explanation.

A: PowerShell has regex support. If you are on a supported Windows system, PowerShell was installed with it.
=== Do-Grepit.ps1
Get-ChildItem -Path '*.h','*.cpp' |
    ForEach-Object { Select-String -Pattern '^#include\s+"[^"]+"' -Path $_ }

At an interactive console, using aliases could make for less typing, but aliases should not be coded into script files.
gci -pa *.h,*.cpp|%{sls '^#include\s+"[^"]+"' $_}

If you are desperate to run this from a cmd batch-file, then you could:
powershell -NoLogo -NoProfile -File "Do-Grepit.ps1"


text:
Q: cx_Oracle.DatabaseError: ORA-01841: (full) year must be between -4713 and +9999, and not be 0 i have Cx_Oracle insert query like below,
cur.execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYYMMDD' ")

cur.execute("INSERT INTO table(col A,col B,col C,col D) values (:1,:2,:3,:4)",(lines['col A'],lines['col B'],lines['col C'],lines['col D']))

here my column B&C are Date datatype, when i have a values in both they get loaded successfully.
but when i have it has "NULL" or "" it is throwing me the below error.
> cx_Oracle.DatabaseError: ORA-01841: (full) year must be between -4713 and +9999, and not be 0

A: A null value must be passed as the value None in Python. You cannot use the string value "NULL". You can also frequently use the empty string, which Oracle treats as null as well, but I would use None if at all possible.
You can see this if you do the following in SQL*Plus.
alter session set nls_date_format = 'YYYYMMDD';
select to_date('') from dual;     /* works -- returns null */
select to_date('NULL') from dual; /* fails with the error you received */

All of the code in your example is not present. It would be helpful to show a complete set of code that demonstrates the problem, including the SQL for creating the table -- assuming that the hints given above are insufficient!


text:
Q: Круглый график с текстом снаружи
Хочу создать подобный график. Нашел библиотеку chart js, однако там нет возможности добавить текст снаружи. Текст должен двигаться вместе со шкалой.
Буду благодарен за любую информацию ( статью, видео, пример кода ) !!


text:
Q: When Click an Image QFrame Size Changes Everything is OK in the first picture .

There are qlabels that display images . When I click one of them, a size problem occured the top of the second picture .I don't understand  what is the problem ?

A: If you do not want your QLabel to resize try to set a fixed size.
For the height you can use: setFixedHeight(int n)
I also advise you to read Qt Layout Management if you haven't already.


text:
Q: How to change JSP version in Tomcat? I am upgrading my old Java webapp using JSP spec 2.0 to tomcat 7 that uses JSP specs 2.2 and the EL specs have changed much in recent versions of Tomcat 7. I have a lot of JSPs that uses old EL that are not compatible with newer versions of EL in JSP 2.2.
My question (Futile alert!), can I somehow change Tomcat 7 to use JSP 2.0 spec. You'd say why don't I use older Tomcat; I can't because I need to use Servlet 3.0 specs.

A: No you can't. If you somehow did, you wouldn't be able to use Servlet 3.0 because your JSP(s) are compiled into Servlets. Tomcat releases are tied to JSP and Servlet versions.
Per the Apache Tomcat 7 documentation,

Apache Tomcat version 7.0 implements the Servlet 3.0 and JavaServer Pages 2.2 specifications from the Java Community Process, and includes many additional features that make it a useful platform for developing and deploying web applications and web services.


text:
Q: spying on functions returned by a function sinon I'm a bit new to Sinon and having some trouble with the scenario where I need to spy on not only a function, but the functions returned by the function. Specifically, I'm trying to mock the Azure Storage SDK and ensure that once I've created a queue service, that the methods returned by the queue service are also called. Here's the example:
// test.js

// Setup a Sinon sandbox for each test
test.beforeEach(async t => {

    sandbox = Sinon.sandbox.create();
});

// Restore the sandbox after each test
test.afterEach(async t => {

    sandbox.restore();
});

test.only('creates a message in the queue for the payment summary email', async t => {

    // Create a spy on the mock
    const queueServiceSpy = sandbox.spy(AzureStorageMock, 'createQueueService');

    // Replace the library with the mock
    const EmailUtil = Proxyquire('../../lib/email', {
        'azure-storage': AzureStorageMock,
        '@noCallThru': true
    });

    await EmailUtil.sendBusinessPaymentSummary();

    // Expect that the `createQueueService` method was called
    t.true(queueServiceSpy.calledOnce); // true

    // Expect that the `createMessage` method returned by
    // `createQueueService` is called
    t.true(queueServiceSpy.createMessage.calledOnce); // undefined
});

Here's the mock:
const Sinon = require('sinon');

module.exports =  {

    createQueueService: () => {

        return {

            createQueueIfNotExists: (queueName) => {

                return Promise.resolve(Sinon.spy());
            },

            createMessage: (queueName, message) => {

                return Promise.resolve(Sinon.spy());
            }
        };
    }
};

I'm able to confirm that the queueServiceSpy is called once, but I'm having trouble determining if the methods returned by that method are called (createMessage).
Is there a better way to set this up or am I just missing something?
Thanks!

A: What you need to do is stub your service function to return a spy that you can then track calls to elsewhere. You can nest this arbitrarily deep (though I would strongly discourage that).
Something like:
const cb = sandbox.spy();
const queueServiceSpy = sandbox.stub(AzureStorageMock, 'createQueueService')
    .returns({createMessage() {return cb;}}});

const EmailUtil = Proxyquire('../../lib/email', {
    'azure-storage': AzureStorageMock,
    '@noCallThru': true
});

await EmailUtil.sendBusinessPaymentSummary();

// Expect that the `createQueueService` method was called
t.true(queueServiceSpy.calledOnce); // true

// Expect that the `createMessage` method returned by
// `createQueueService` is called
t.true(cb.calledOnce);


text:
Q: Jquery fancy box not working on div I have html source as

And I am trying to apply jquery fancybox and that is not working.
$(document).ready(function() {
    /* Apply fancybox to multiple items */
    $("#widget-container .a").fancybox({
        'transitionIn'  :   'elastic',
        'transitionOut' :   'elastic',
        'speedIn'       :   600,
        'speedOut'      :   200,
        'overlayShow'   :   false
    });
});

Any inputs to work this one

A: widget-container is the class of your container, not the id. Also, as far as I can see, there are no elements within there with the class name a, I think you mean to target the tagname a:
$(document).ready(function() {
    /* Apply fancybox to multiple items */
    $(".widget-container a").fancybox({
        'transitionIn'  :   'elastic',
        'transitionOut' :   'elastic',
        'speedIn'       :   600,
        'speedOut'      :   200,
        'overlayShow'   :   false
    });
});


text:
Q: PDE separation of variables questions
Solve using method of separation of variables:
$$\nabla^2u = 0, \ \ \ \ \  a<r<b, 0 \leq \theta < 2\pi \\ u(a,\theta) = 0 \\ u(b,\theta) = 2\sin^2(\theta)$$

So the way I started it was seeing it's in a rectangular domain and since it's polar coord. it is. So have the condition due to periodicity:
$$u(r,0) = u(r, 2\pi) , \frac{\partial u}{\partial \theta}(r,0) = \frac{\partial u}{\partial \theta}(r,2\pi)$$
We also use the laplacian in polar coord. :
$$\frac{\partial^2 u}{\partial r^2}+ \frac{1}{r} \frac{\partial^2 u}{\partial r} + \frac{1}{r^2}\frac{\partial^2 u}{\partial \theta^2} = 0 $$
Do we also have the new stuff of :
$u(a,0) = u(a,2\pi) = 0$ and then the same periodicity for $u(b,\theta)$ ?
I'm just confused because in the examples we've seen in lectures it was always with one condition given in the question which was straightforward, but this has two which has got me confused. If someone could help walk me through this it would be really appreciated.
Thank you!
$\textbf{Edit}$: Now that I think about it, I can see how this is more not a circle problem but an annulus problem. I will attempt it using this fact. If you have any hints/tips please do feel free to comment - it would be really helpful


text:
Q: Create a JSON Object based on input parameter in MuleSoft DataWeave 2.0 So I have a REST API which can have there input Params: START, STOP, RESTART. Start and Stop are distinct operations for the REST API but RESTART essentially means STOP and START. Hence I want to create a Dynamic JSON of either 1 node or 2 nodes based on the operation chosen For e.g. For START/STOP the JSON will be:
{ "appID": "1234",
   "operation": "START"}

OR
{ "appID": "1234",
   "operation": "STOP"}

While for RESTART it be be like:
{ "appID": "1234","operation": "STOP"},{ "appID": "1234","operation": "START"}

I can then loop through this array and call my API once or twice.However I am at a loss to understand how do I create this JSON dynamically in data weave based on the Operation param passed as an input to the REST API call.I have tried to create a variable with 2 node JSON nodes and then try too loop but that doesn't seem to be working.
I tried something like this:
var count = 0
var appID = "1234567890"
var op = "START"
---
(operation map ((item, index) -> {
    "appID": appID,
    "operation": if(op=='START' and index == 0) "START"
                 else if(op=='STOP' and index==0) "STOP"
                 else if(op=='RESTART' and index==0) "STOP"
                 else if(op=='RESTART' and index==1) "START"
                 else ''
})) [ 0 to operation.totalcount - count ]

where the value of Count is either 0 or 1 based on the operation

A: If I understand correctly if the input value operation is "RESTART" then the script should return an array of elements start and stop, if "START" just a start element and if "STOP" just a stop element. I assume the output is always an array.
For this script the variable op represents the input. I use the value of op to return the operation if it is not "RESTART". If it is I return "STOP" first and add a second element for "START".
%dw 2.0
output application/json
var appID = "1234567890"
var op = "RESTART"
---
[
    {
        "appID": appID,
        "operation": if(op !='RESTART') op
                    else "STOP"
    }
] ++ if (op =='RESTART') [{
        "appID": appID,
        "operation": "START"
    }] else []

Output:
[
  {
    "appID": "1234567890",
    "operation": "STOP"
  },
  {
    "appID": "1234567890",
    "operation": "START"
  }
]


text:
Q: Arduino SoftwareSerial Write bluetooth cutting off static text message write back I am fairly new to Arduino, so this is likely to be some very simple C/C++ issue that I don't know
I am working on a RGB LED Cube that I made from parts based off of GreatScott's video. It works fine. I decided to improve wahat can be done with it by adding Bluetooth. I am using an HM-11 from DSD tech.
I am able to write commands from my phone to the arduino over bluetooth with no problems, and I use that to swap modes.
The issue I am facing is when I try to write back to my phone over bluetooth. I am sending back help text over bluetooth, so that whoever connects to it and sends help can find a list of supported commands. Using SoftwareSerial, I have the following (snippet of problem area):
if(strcmp(command,"help")==0){

    Serial.print(F("============== RGBCube Bluetooth Help ==============\n"
                  "Commands:                                           \n"
                  "  mode:#                 select mode to operate in  \n"
                  "  help                   pull up help screen (this) \n"
                  " Mode 4 only:                                       \n"
                  "  reset                  resets cube to black       \n"
                  "  pt:x,y,z=r,g,b         sets led at (x,y,z) to rgb \n"
                  "  set:r,g,b;r,g,b...     sets entire cube to the    \n"
                  "                         specified colour           \n"
                  "                         64 colours long. Faster    \n"
                  "                         than 64 pt calls           \n"));

    BTSerial.print(F("============== RGBCube Bluetooth Help ==============\n"
                  "Commands:                                           \n"
                  "  mode:#                 select mode to operate in  \n"
                  "  help                   pull up help screen (this) \n"
                  " Mode 4 only:                                       \n"
                  "  reset                  resets cube to black       \n"
                  "  pt:x,y,z=r,g,b         sets led at (x,y,z) to rgb \n"
                  "  set:r,g,b;r,g,b...     sets entire cube to the    \n"
                  "                         specified colour           \n"
                  "                         64 colours long. Faster    \n"
                  "                         than 64 pt calls           \n"));
  }

When this is runs, the serial port receives:

============== RGBCube Bluetooth Help ==============
Commands:
mode:#                 select mode to operate in
help                   pull up help screen (this)
Mode 4 only:
reset                  resets cube to black
pt:x,y,z=r,g,b         sets led at (x,y,z) to rgb
set:r,g,b;r,g,b...     sets entire cube to the
specified colour
64 colours long. Faster
than 64 pt calls

but my phone receives at maximum:

============== RGBCube Bluetooth Help ==============
Commands:
mode:#                 select mode to operate in
help                   pull up help screen (this)
Mode 4 only:
reset                  resets cube to black
pt:x,y,z=r,g,b         sets led at (x,y,z) to rgb
set:r,g,b;r,g,b...     sets entire cube to the

As you can see, this is truncated. I have tried many things, including shoving the string into progmem, cutting it apart into smaller stringsm Char array for loops, forcing it to save in flash, etc. Cutting it into smaller strings worked, but I don't really want to do that, as the next thing I want to add to it is a similar length write from phone to arduino.
Sometimes fewer characters make it also, but this is the average, and the maximum, making me think there is some form of limit, but it is not a mulitple of 2 (about 80ish last I counted)
Any help would be greatly appreciated.

A: It looks like you are able to send about 252 bytes before it gets truncated. That figure seems to be about the maximum data size in a BLE packet.
There is some discussion around the maximum data size at: Maximum packet length for Bluetooth LE?
BLE "long read" and "log write" functionality include an offset along with the handle in the request so that the characteristic value can be read/written in successive chunks over multiple request/response pairs. I am not aware if the Arduino library and HM-11 hardware support that functionality or not.


text:
Q: YouTrack API Form Data Description I am trying to send the description in form data to create an issue but it seems it is only possible through parameters with a length restriction. Does anybody know a way around this or am I doing something wrong?
PUT /rest/issue?project=LSDebug&summary=Debug%2520Log HTTP/1.1
Connection: keep-alive
Content-Length: 266
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/index.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

Query String Parameters
    project:LSDebug
    summary:Debug%20Log
Form Data
    description=Submitted%20Form%20name%3A%20null%2C%20Id%3Anull%0D%0AInput%20name%3A%20null%2C%20Id%3Anull%2C%20NgModel%3Aresult.homeTeamScore.score%2C%20Value%3A%201%0D%0AInput%20name%3A%20null%2C%20Id%3Anull%2C%20NgModel%3Aresult.awayTeamScore.score%2C%20Value%3A%202

A: I think you need to embed the data in XML within the body of your PUT request as documented in the Import REST API docs.

A: Html forms only support GET or POST. So i would suggest you to post the form data using POST method instead of PUT. So that the form content will go into the body of the message and you will able to evade the URL restriction


text:
Q: Perl POE: Alarm/Delay queueing This is my first attempt at the Perl Object Environment (POE). I am attempting to create a program that will run as a service that obtains a list of devices via couchdb, spawns child processes to ping them in 60 second intervals, while restricting the maximum number of concurrent child processes to 3.
I am able to successfully re-queue child processes after a delay (1 min), however, I am not sure how to manage multiple alarms/delays that call the same event. I am attempting to store them in $_[HEAP]->{timers}->{$_} where $_ is a given host.
#!/usr/bin/perl

use warnings;
use strict;
use POE qw(Wheel::Run Filter::Reference);
use CouchDB::Client;
use Data::Dumper;

use constant MAX_CONCURRENT_TASKS => 3;

our $couch      = CouchDB::Client->new(uri => 'http://192.168.1.100:5984/')->newDB('devices');

POE::Session->create(
        inline_states => {
                _start      => sub {
                        push (@{$_[HEAP]->{devices}}, $couch->newDoc($_->id)->retrieve->id) for @{$couch->listDocs};
                        $_[KERNEL]->delay_set('refresh', 60);
                        $_[HEAP]->{timers}->{$_} = $_[KERNEL]->delay_set('spawn', 1, $_) for @{$_[HEAP]->{devices}};
                },
                refresh => sub {
                        undef @{$_[HEAP]->{devices}};
                        $_[KERNEL]->delay_set('refresh', 60);
                        push (@{$_[HEAP]->{devices}}, $couch->newDoc($_->id)->retrieve->id) for @{$couch->listDocs};
                        print "\nRefreshing device list.\n\n";
                },
                spawn   => sub {
                        if (keys(%{$_[HEAP]->{task}}) < MAX_CONCURRENT_TASKS) {
                                print "Starting $_[ARG0].\t # of tasks running: ". keys(%{$_[HEAP]->{task}}),$/;
                                my $host = $_[ARG0];
                                my $task = POE::Wheel::Run->new(
                                        Program      => sub { \&do_stuff($host) },
                                        StdoutFilter => POE::Filter::Reference->new(),
                                        StdoutEvent  => "task_result",
                                        StderrEvent  => "task_debug",
                                        CloseEvent   => "task_done"
                                );
                                $_[HEAP]->{task}->{$task->ID} = $task;
                                $_[KERNEL]->sig_child($task->PID, "sig_child", $_[ARG0])
                        } else {
                                $_[KERNEL]->delay_adjust($_[HEAP]->{timers}->{$_[ARG0]}, 5);
                        }
                        print Dumper 'spawn', sort $_[HEAP]->{timers};
                },
                task_result => sub {
                        print "Result for $_[ARG0]->{task}: $_[ARG0]->{status}\n";
                },
                task_done   => sub {
                        delete $_[HEAP]->{task}->{$_[ARG0]};
                },
                task_debug  => sub {
                        print "Debug: $_[ARG0]\n";
                },
                sig_child   => sub {
                        delete $_[HEAP]->{$_[ARG1]};
                        $_[HEAP]->{timers}->{$_[ARG3]} = $_[KERNEL]->delay_set('spawn', 60, $_[ARG3]) if $_[ARG3] ~~ $_[HEAP]->{devices};
                        $_[KERNEL]->alarm_remove($_[HEAP]->{timers}->{$_[ARG0]});
                }
        }
);
sub do_stuff {
        binmode(STDOUT);
        my $filter = POE::Filter::Reference->new();

        sleep(rand 5);

        my %result = (
                task   => shift,
                status => "complete.",
        );

        my $output = $filter->put([\%result]);
        print @$output;
}
POE::Kernel->run();
exit 0;

Any advice/strategies would be welcome.
Edit 1: I found out that $_[KERNEL]->delay wasn't setting timers on a per child basis. I am able to get this to work by using $_[KERNEL]->delay_set instead. What I am unable to piece together now, is how to restrict the program from running more than 3 processes at a given time.
I am creating the initial timers in _start. As spawn is being called $_[KERNEL]->delay_adjust should extend the delay by 5 seconds if the child process count is 3 or higher.
Apologies for the time it took to respond to questions, this lives on my work PC and this edit is on Monday, my first day back.


text:
Q: How do I prevent the browser (JavaScript and CSS) from disabling text selection on web pages without disabling all JavaScript? Some websites insist on ruining usability and accessibility by disabling the ability to select text on the page. Sites can do this via CSS or JavaScript (example page).
Is there some way that this can be disabled in Firefox so that the user can always select text no matter how the web page tries to disable it?
Disabling JavaScript globally is not a solution as it breaks many websites.

A: First, good question - I also notice this and it hugely annoys me.
The solution will depend on how the site disables text selection. As you write, this can be done using either CSS or JavaScript.
Disabled via CSS
The site most likely uses the CSS propert "user-select".
user-select: none; will disable text selection.
To fix this, you would have to change the CSS styling the site uses. This can be done by running this small JavaScript snippet:
document.styleSheets[0].insertRule("* { user-select:text !important }", 1);

This will insert a new CSS rule that overrides the "user-select" setting of the page.
To run this: Either paste it into the JavaScript console of your browser's developer tools (and press enter), or use a userscript manager .
Disabled via JavaScript
This is probably trickier, because there are multiple ways of doing this. Most involve registering an event handler for mouse or selection events, but there are multiple events and multiple ways of registering them, so it's hard to give a general rule.
The pragmatic solution probably would be to temporarily disable JavaScript.
However, most sites I have seen that disable selection do it via CSS nowadays.

A: To avoid typing the code into the console, you can use a bookmarklet. Create a bookmark with the the following code at the place of the URL:
javascript:(function(){javascript:document.styleSheets[0].insertRule("* { user-select:text !important }", 1);})();


text:
Q: Use DB Relation To Avoid Redundancy I have designed an ERD of movies and tv series which is confidential. I can give you an overview of database.
It has more then 20 tables (more tables will be added later) and it is normalized. I have tables like Movie, Actors, Tv Seriers, Director, Producer etc. So these tables will contain most important information and also these tables are connected (by foreign keys and middle tables like MovieActor, MovieDirector etc).
So the scenario is like
1) The standard "starting" database should have Actors, Directors, Producers, Music Composers, Genres, Resolution Types… pre populated and pre defined by the Admin.
2) For every user creating his personal movie collection, he will be starting of his database with all the pre defined data, but if he wants to, he may add further data to his personal database.  These changes will only be affecting his database and not the standard "starting" database (which was defined by Admin).
3) The Admin should have a separate view to add Actors, Directors, Producers… that will become part of the standard "starting" database.  Any further changes done to this database will be available to the users as updates.
Suggested Solution

Question
The suggested solution is seems like I have to create new databases all the time for each user which seems not possible. My question is how can I manipulate the suggested solution so that my solution will be effective and possible. I would prefer to handle the situation by using database relations, not by separate storage.

A: You wouldn't create multiple databases, you would simply add an ownerId field to all relevant tables - admin would have ownerId = 0, indicating the row is part of the 'starting database' and new admin entries are instantly available to users.
In any output for a user where you want to display the starting data and their own, you would add WHERE (ownerId = 0 or ownerId = userId) to the appropriate query or if they need to see just their own, just ownerId = userId.
Presumably, they would be able to create relationships between their own data or 'starting' data and this approach should still work.
Foreign keys will still work but deleting will delete user data - basically you should only ever add to the starting data, not take away or you will run into problems.


text:
Q: Using calibri, consolas and other microsoft cleartype fonts by default In my opinion the website would look much better with calibri as the first font in the CSS font-family attribute. What do you think?
This is a screenshot after some firebug hackery (remember to zoom in and see it at 100% zoom), this is the normal one. Note that I simply changed a couple of things without giving it much thought, probably a much better job could be done.
EDIT: Jeff's answer is a valid issue, but I think it can be fixed fairly easily with the jQuery font.isInstalled plugin, that allows you to check whether the user has or doesn't have a certain font through javascript.
Then you can add the following code that adds the calibri.css style if a user has the font:
$(document).ready(function () {
   if (font.isInstalled("Calibri"))
      ImportCss("calibri.css");
});

function ImportCss(name) {
    if (document.createStyleSheet) {
        document.createStyleSheet('/static/' + name);
    }
    else {
        var styles = '/static/' + name;
        var newSS = document.createElement('link');
        newSS.rel = 'stylesheet';
        newSS.type = 'text/css';
        newSS.href = styles;
        document.getElementsByTagName("head")[0].appendChild(newSS);
    }
}

Then, in calibri.css you can have - for example -:
body
{
    font-family: Calibri;
    font-size: 16px;
}

caption, h1, h2
{
    font-family: Candara, Calibri;
}

And have this in your main css file:
body
{
    font-family: Arial, Sans-Serif;
    font-size: 13px;
}

So if someone doesn't have calibri (or javascript enabled) they will see the website with the current font and the right size. If someone does have calibri, calibri.css will be imported and both the font and the size will be changed.
This is what I do on my website, and it works pretty well.

A: Although I love the "C" fonts, there are some fairly serious problems with them when used in websites intended for large audiences:

*

*They are significantly smaller per px than other fonts, enough so that it's a serious problem for substitutions

*Only Windows machines with Vista, Win7, or Office 2007 will have the "C" fonts installed
We actually started the SO beta with Calibri as the default font, and I had to pull it out.

A: I don't think this is really needed.  I guess it wouldn't really hurt, either.  If you don't have those fonts it would just fall back to the next one.  But to really explain why I don't think they should do this I have to tell a short story.
You see, I never cared about fonts at all until just over a year ago.  My philosophy was, "Arial, Helvetica: who cares?"  And then chrome came out at about the same time as StackOverflow.  At the time I normally used Firefox.  I wanted to give Chrome a good try, so I decided to use it as my primary means of browsing StackOverflow.  I didn't visit StackOverflow from firefox at all for a long time.
Then one day, it happened.  I already had a Firefox window handy and wanted to look up something on StackOverflow.  I was shocked at how bad the site looked in Firefox by comparison to Chrome.  Looking at them side by side it was obvious that the big difference between the two browsers for this site was the font rendering.
Now I knew what to look for.  As I started using Chrome more often I noticed the difference in a few other sites as well.  The odd thing was that sometimes Firefox came out better in my opinion.  It really depended not only on what I was familiar with but also which rendering style worked better for that design.
So you could say I learned an important lesson about fonts here (except that I still don't know how to choose the right fonts for my own work).  But the real reason I'm telling this story is that you might find the StackOverflow font choices already work pretty well if you just try a different browser.


text:
Q: Fluent validation Vary object validator according to the class it's used in I have a class which gets reused in multiple places. It has a default validator applied to it, which has the following attribute,  [Validator(typeof(ChildValidator))].
I wanted to be to override the validator that's been applied to Child class depending on the parent class that's using it. Below is a simplified version of my model. So instead of validate Child with ChildValidator, I want to apply rules in ChildValidator2.  Can this be done?
Note: the follow code will always fail the validation because it will always apply rule in ChildValidator
Models:
    [Validator(typeof(ParentValidator))]
    public class Parent
    {
        public bool IgnoreChild { get; set; }
        public DateTime Birthdate { get; set; }

        public Child Children { get; set; }
    }

    [Validator(typeof(ChildValidator))]
    public class Child
    {
        public string ChildProperty{ get; set; }
        public DateTime Birthdate { get; set; }
    }

Validators:
public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
         RuleFor(model => model.Name).NotEmpty();

         When(x=>x.IgnoreChild, () =>
         {
             RuleForEach(model => model.Child).SetValidator(new ChildValidator2());
         });
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(model => model.ChildProperty).NotEmpty();
        //Compare birthday to make sure date is < Parents birthday
    }
}

public class ChildValidator2 : AbstractValidator<Child>
{
    public ChildValidator2()
    {
        RuleFor(model => model.ChildProperty).Empty();
    }
}

A: If you debug FluentValidation source code, you will see that AttributedValidatorFactory works only for parameters of controller action (Parent), not it's child property classes (Child). If you didn't applied validator by SetValidator() method - no validation actions would be performed. So, your experiment results could be caused by another reason, not one you though.
Try to specify validators explicitly for both values of IgnoreChild flag:
public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
         RuleFor(model => model.Name).NotEmpty();

         When(x=> x.IgnoreChild, () =>
         {
             RuleForEach(model => model.Child).SetValidator(new ChildValidator2());
         });
         When(x=> !x.IgnoreChild, () =>
         {
             RuleForEach(model => model.Child).SetValidator(new ChildValidator());
         });
    }
}


text:
Q: Class D Amplifier with Inverting Logic If a class D amplifier had an additional logic input which was used to indicate that the amplifier's output should be inverted, could one use this signal to swap the logic of amplifier's switches so that the amplifier's output was inverted?
Where inverting results in a signal that has +x on the input to the amplifier with a signal that has -x on the output.
Is this a "thing" with existing terminology surrounding it?

A: In theory this is logically true. In practise no, because we need to know prop delay, dead-time (!) , impedance of commutation switches , load and reactance of everything.
This thing is called a "Half-Bridge" also used in Buck-Boost SMPS and have many specific parameters for each load and power range for specs.
Then for differential high power from a low voltage to a woofer, one can use a full-bridge with differential output. But for low DCR motors and surge battery chargers and other nonlinear surge current loads, use RdsOn=< 10% of Motor DCR or <= 1% of rated V/I for starting choice for loss vs cost. But too low and Q rises with ringing.
It is most important to understand the power loss budget with RdsOn, DCR of chokes, ESR of caps and low Q for light loaded LC filters that  can resonate on harmonics. Examine transfer functions on a simulator looking for spurious simulated resonances then verify with the best layout practices.


text:
Q: Setting up gradle and gradle plugin and dependencies in in android studio After installing arctic fox on linux, I tried to create a new project but was told there was no gradle and it wanted to download one.  Not having a great internet connection I downloaded gradle 6.9.2 and I pointed the gradle to the folder.
It's apparently not enough to just have gradle but it needs a plugin as well. Which gets specified in project structure - project.  None of the options in project structure work but manually setting version 3.5.3 in the build.gradle does.
The issue I have now is that I have no idea where the 3.5.3 comes from?  Is there a folder where all these plugins are installed where one can check what is available?
I'm having the same issue with other dependencies where just starting a new project requires that I re-download all the dependencies again despite the fact that I can open another project and it builds just fine.

A: The plugin version depend on gradle plugin. You can see version require docs from here: https://developer.android.google.cn/studio/releases/gradle-plugin
And plugin will be downloaded from google maven repository: https://maven.google.com/web/index.html#com.android.tools.build:gradle
You can also find them on your local maven cache directory.


text:
Q: MySQL query select students who do not have all 'A' grade I have two tables, gradereport and student
The gradereport table has the studentNo which is a foreign key from the table student and it also has the grades for each student,
I must query the gradereport table to find out which students do not have all grade 'A' in the courses they took.
If they have any grades that are not 'A' then they should not be included in the results.
How can I query the table gradereport to find students who do not have all 'A's in their courses.
gradereport table

student table

A: Students who do not have all A grade could be found as
select s.*,
gr.section,
gr.grade
from student s
join gradereport gr on gr.studentNo = s.studentnumber
group by s.studentnumber,gr.section
having sum(gr.grade='A') <> count(*) ;

Or if you dont care about the section then
select s.*
from student s
join gradereport gr on gr.studentNo = s.studentnumber
group by s.studentnumber
having sum(gr.grade='A') <> count(*)

A: you can do an exclusive check like so
SELECT distinct studentno FROM gradereport gr
WHERE gr.grade = "A"
AND NOT EXISTS
(   SELECT 1
    FROM gradereport
    WHERE grade <> "A"
    AND studentno = gr.studentno
)

DEMO
you could also do an exclusive join (my preference)
SELECT DISTINCT gr.studentno
FROM gradereport gr
LEFT JOIN gradereport gr1 ON gr1.studentno = gr.studentno AND gr1.grade <> "A"
WHERE gr1.studentno is null

BETTER DEMO

A: Try this:
SELECT student.name, student.number
FROM student, gradereport
WHERE student.number = gradereport.StudentNumber
AND gradereport.Grade != 'A'

A: Find all students which have at least one grade A:
SELECT DISTINCT `StudentNo` FROM `gradereport` WHERE `Grade` = 'A'

Finding the oposite results:
SELECT `StudentNo` FROM `gradereport` WHERE `StudentNo` NOT IN (SELECT DISTINCT `StudentNo` FROM `gradereport` WHERE `Grade` = 'A')

A: I'd do something like this:
SELECT
     DISTINCT StudentNo
 FROM
     gradereport GR
 WHERE
     NOT EXISTS (
         SELECT 1
         FROM gradereport GR2
         WHERE
              GR.StudentNo = GR2.StudentNo
              AND
              GR2.Grade != 'A'
      )


text:
Q: How to determine number of parabolas tangent to three given lines, or tangent to two given lines at specific points I recently came across a question which prompted me to think how we could determine the uniqueness of a parabola

How many parabolas would satisfy the following conditions:

*

*Tangent to $3$ given (evidently non-concurrent) lines

*Tangent to $2$ given (evidently non-parallel) lines at specific points on the lines; eg, tangent to $y=0$ at $(12, 0)$ and to $y+x=5$ at the point $(4, 1)$

I heard somewhere that a parabola requires $4$ degrees of freedom, I'd also appreciate an explanation in context to this statement.
In the latter case, how would we find the equation of the parabola, if a unique one does exist?

A: In the ${\Bbb P}^5$ of coefficients $(a:b:c:d:e:f)$ for the conic $ax^2+bxy+cy^2+dxz+eyz+fz^2=0,$ going through a point is linear condition; just specify the point say $(4:1:1)$ and the condition, by substituting the point, is $16a+4b+c+4d+e+f=0.$
The condition to be tangent to given lines $a_i x+b_i y+c_i z=0$ is each of degree two. The dual conic through say $0.2 x+0.7 y+1=0,$ is again by substituting the point $(0.2:0.7:1)$ in the dual plane of lines in the plane into the dual conic of lines tangent to the original conic: $25cf+9bf+(81af)/25-(25e^2)/4-(9de)/2+5be+(18ae)/5-(81d^2)/100-10cd-(9bd)/5=0.$
(The dual conic is given by the inverse matrix (or more generally the adjugate matrix) of the matrix of the original conic.)
Now a (linear, quadratic etc) condition generally cuts away one dimension. Think of one, two, three, four, and five linear equations in five unknowns. This is why we expect five conditions to determine a finite number of conics. In addition looking at the fact that five linear conditions give $1^5$ conics through five points we might expect the number to be given by Bezout more generally.
Being a parabola is a tangency with the line at infinity $z=0,$ so for parabolas one condition of degree $2$ is taken and four more are needed to get a finite number. And for parabolas through four points we get $2\cdot 1^4$ which is correct.
Now there is a complication that I leave for the end, so that we cannot trust the Bezout numbers, like $6^5$ conics tangent (for a conic to be tangent to a conic is a degree $6$ condition on the coefficients) to five conics in general position; the actual number, famously, is $3264$.
For 2. Using the geogebra app in the answer in the linked question in my comment to the question I get $x^2-12xy+36y^2-24x-52y+144=0.$
For 1. There is an infinity of parabolas tangent to three lines. But I elect to show a way to get the unique parabola tangent to four given lines in general position. For example, if we take the four lines to be $x X_i+y Y_i+1=0,$ where  $X_1=0.2,Y_1=0.7,X_2=2.5,Y_2=-0.9,X_3=2.8,Y_3=-5,X_4=5,Y_4=1.2,$ the dual conic $afY^2-\frac14 d^2Y^2-bfXY+\frac12 deXY-aeY+\frac12 bdY+cfX^2-\frac12 e^2X^2+\frac12 beX-cdX+ac-\frac14 b^2=0$ (dual to $ax^2+bxy+cy^2+dx+ey+f=0$) evaluated at $(X_i,Y_i)$ together with the condition to be a parabola $b^2-4ac=0$ give in M2
T=QQ[a,b,c,d,e,f,MonomialOrder=>Lex]
J=ideal(25*c*f+9*b*f+(81*a*f)/25-(25*e^2)/4-(9*d*e)/2+5*b*e+(18*a*e)/5-(81*d^2)/100-10*c*d-(9*b*d)/5, (4*c*f)/25-(14*b*f)/25+(49*a*f)/25-e^2/25+(7*d*e)/25+(2*b*e)/5-(14*a*e)/5-(49*d^2)/100-(4*c*d)/5+(7*b*d)/5, (784*c*f)/25+56*b*f+100*a*f-(196*e^2)/25-28*d*e+(28*b*e)/5+20*a*e-25*d^2-(56*c*d)/5-10*b*d, 100*c*f-24*b*f+(144*a*f)/25-25*e^2+12*d*e+10*b*e-(24*a*e)/5-(36*d^2)/25-20*c*d+(12*b*d)/5,b^2-4*a*c)
gens gb J
primaryDecomposition radical J
toString oo -- {ideal(4*c*f-e^2,2*b*f-d*e,b*e-2*c*d,4*a*f-d^2,2*a*e-b*d,4*a*c-b^2),
ideal(98051402514954215*e+85617834771997822*f,
      19610280502990843*d-49279136609744940*f,
      490257012574771075*c-1031289706001844147*f,
      19610280502990843*b-40544108165505524*f,
      58830841508972529*a-29886571227928900*f)}

If we let $f=1,$ clear denominators, and factor the coefficients, the unique solution parabola is $(2\cdot 5^2\cdot 17287733\cdot x+3\cdot 1013\cdot 578789\cdot y)^2+2^2\cdot 3^2\cdot 5^3\cdot 79\cdot 10396442322731\cdot x-2\cdot 3\cdot 5\cdot 7\cdot 113\cdot 54119996695321\cdot y+3\cdot 5^2\cdot 97\cdot 971\cdot 98731\cdot 2108819=0.$
Now, the problem is interesting in intersection theory, because the Veronese of double lines (ideal(4*c*f-e^2,2*b*f-d*e,b*e-2*c*d,4*a*f-d^2,2*a*e-b*d,4*a*c-b^2) above) appears. This is why the Bezout answer to how many conics are tangent to five lines (there are five degree two conditions; so $2^5$) is wrong, beacuse there's excess intersection and the equivalent of the double lines amounts to $31$ (Fulton Intersection Theory Example 9.1.8).

A: Not really an answer, but I would like to show a very simple geometric construction to find the parabola tangent to four given lines, thus also providing a proof of its uniqueness.
The construction relies on a beautiful property of parabolas:

The focus of a parabola lies on the circumcircle of the triangle
formed by any three tangents to the parabola (see Appendix for a
geometric proof).

Let then $a$, $b$, $c$, $c$ be four given lines (no two of them parallel). The focus $F$ of the parabola tangent to them must lie (by the above property) on the circumcircle of the triangle formed by lines $abc$, and at the same time it must lie on the circumcircle of the triangle formed by lines $abd$. Those two circles have in common the intersection point of lines $ab$, which cannot be the focus. Hence the focus of the parabola is uniquely determined as the other intersection of the circumcircles.
To complete the construction we can then use another well-known property:

The perpendicular projection of the focus of a parabola onto any
tangent, lies on the line passing through the vertex and perpendicular
to the axis of the parabola.

If $A$ and $B$ are the projections of the focus on lines $a$ and $b$, the line through the focus perpendicular to line $AB$ is then the axis, and the intersection of the lines is the vertex of the parabola.
APPENDIX.
Proof of the property given at the beginning.
Let three tangents to a parabola be given, with tangency points $A$, $B$, $C$ and intersecting at $P$, $Q$, $R$ (see figure below). Let $F$ be the focus of the parabola, and $D$, $E$ the intersections of the axis of the parabola with lines $PQ$ and $QR$.
It is well known that $FA=FD$, which entails
$\angle FAQ=\angle EDQ$.
In addition, we know that (see here for a proof):

the exterior angle between any two tangents is equal to the angle
which either segment of tangent subtends at the focus,

which in our case implies $\angle AFQ=\angle DQE$.
It follows that in triangles $AFQ$, $DEQ$ we also have
$\angle FQA=\angle DEQ$.
But with an analogous reasoning we can prove that
$\angle FRB=\angle FER=\angle DEQ$. It follows that
$\angle FRP=\angle FQP$, and points $FPQR$ are concyclic as it was to be proved.


text:
Q: System.IO.File.Delete throws Arithmetic operation resulted in an overflow I have this weird error. When I call System.IO.File.Delete(), it throws

JobCleaner.CleanFiles(): Unable to delete file: D:\WorkerData\4\Run128\Run_TEMPLATE_Rail_Scenario_Type35_INFHD2_NO_TAX_NOMEP\output_panels\FileIndex55.bin
Error: Arithmetic operation resulted in an overflow.

There is no stack trace.
Here is my code:
foreach (string strFile in System.IO.Directory.GetFiles(strFolder))
{
    try { System.IO.File.Delete(strFile); }
    catch (Exception ex)
    {
        //Exception here
        AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
        return false;
    }
}

Any idea? I tried everything, I check the security on the folder. I enabled "Everyone" with full controls, but still encounter this "Arithmetic operation resulted in an overflow" exception.
Can anyone help, please? I am using Windows 2012 R2 Datacenter to run my application.

A: I wouldn't expect it to throw an arithmetic exception, but I have observed some weird behavior when you modify an IEnumerable within the foreach that is walking it. Try moving the file listing out of the loop, like this:
string[] files = System.IO.Directory.GetFiles(strFolder);
foreach (string strFile in files)
{
  try { System.IO.File.Delete(strFile); }
  catch (Exception ex)
  {
    //Exception here
    AddToLog("JobCleaner.CleanFiles(): Error occurred when trying to delete file \"" + strFile + "\".\nError:\n" + ex.Message);
    return false;
  }
}


text:
Q: SQL Show items that don't exist in other categories I have a table of Tier, Category and Items.  For Tier = 2, each Category should have the same # of items. I want to display the items that are missing from each category.
Here is a sample table:
IF OBJECT_ID('tempdb..#Items') IS NOT NULL DROP TABLE #Items
CREATE TABLE #Items (
    Tier        int,
    Category    nvarchar(25),
    Item        nvarchar(25)
)

INSERT INTO #Items
SELECT '2', 'CategoryA',    'Item1'
UNION ALL
SELECT '2', 'CategoryA',    'Item2'
UNION ALL
SELECT '2', 'CategoryA',    'Item3'
UNION ALL
SELECT '2', 'CategoryB',    'Item1'
UNION ALL
SELECT '2', 'CategoryB',    'Item3'
UNION ALL
SELECT '2', 'CategoryC',    'Item1'
UNION ALL
SELECT '2', 'CategoryC',    'Item2'
UNION ALL
SELECT '2', 'CategoryC',    'Item3'
UNION ALL
SELECT '2', 'CategoryC',    'Item4'

SELECT
    Tier,
    Category,
    Item
FROM #Items
ORDER BY Tier, Category, Item

Tier    Category    Item
2   CategoryA   Item1
2   CategoryA   Item2
2   CategoryA   Item3
2   CategoryB   Item1
2   CategoryB   Item3
2   CategoryC   Item1
2   CategoryC   Item2
2   CategoryC   Item3
2   CategoryC   Item4

If I show a count of items in each category:
SELECT
    Tier,
    Category,
    COUNT(Item) as ItemCount
FROM #Items
GROUP BY Tier, Category

They should all have the same 4 items:
Tier    Category    ItemCount
2   CategoryA   3
2   CategoryB   2
2   CategoryC   4

I want to display a list of the items that are missing from each category.  This could works but is obviously clumsy and just to present the data how I would like to see it.
SELECT DISTINCT
    Tier,
    'CategoryA' as [Category],
    Item
FROM #Items i
WHERE Item NOT IN (SELECT Item from #Items WHERE Category = 'CategoryA')
UNION ALL
SELECT DISTINCT
    Tier,
    'CategoryB' as [Category],
    Item
FROM #Items i
WHERE Item NOT IN (SELECT Item from #Items WHERE Category = 'CategoryB')
UNION ALL
SELECT DISTINCT
    Tier,
    'CategoryC' as [Category],
    Item
FROM #Items i
WHERE Item NOT IN (SELECT Item from #Items WHERE Category = 'CategoryC')

And shows the results:
Tier    Category    Item
2   CategoryA   Item4
2   CategoryB   Item2
2   CategoryB   Item4

A: You can do that with a cartesian product of items, then pull out the ones that don't exist in the source table:
SELECT DISTINCT
    i1.Tier,
    i1.[Category],
    i2.Item
FROM Items i1, Items i2
WHERE i2.Item NOT IN (SELECT Item from Items WHERE Category = i1.Category)

Results:
TIER    CATEGORY    ITEM
----    --------    -----
2       CategoryA   Item4
2       CategoryB   Item2
2       CategoryB   Item4

You can test the query here.

A: I would do this with a cross join and then left joining it back to itself:
select
     _Categories.category
    ,_Items.item
from(
  select distinct
      category
  from Items
) _Categories
cross join (
  select distinct
      item
  from items
) _Items
left join Items _ActualItems
  on _ActualItems.category = _Categories.category
  and _ActualItems.item = _Items.item
where _ActualItems.item is null

Here is a SQL Fiddle Example of this.


text:
Q: Examination of a very long sentence and classification of its component I've got a really complicated sentence to me. If someone could figure out what it imply, please explain me. First of all these modifying clauses in the sentence below ("in which" , " by that" and "where") refers to which word(s) ? And in addition to that what is the predicate and subject of this sentence. Thank you in advance.
Here is the sentence:

The conflict between royalists and parliamentarians unleashed a torrent of radical thinking in which the traditional image of society as a rigid hierarchy was displaced by that of a structure of equal rights where individuals exercise autonomy in crucial areas of their lives.

A: The relative clause in which &c modifies torrent of radical thinking†: expressed as an independent clause this would be "the traditional image was displaced in this torrent of radical thinking".

† You might alternatively argue that it is only radical thinking which is modified; it doesn't make much difference.

The preposition phrase headed by by complements displaced, expressing the Agent of the passive verb: expressed in the active voice this would be "a structure of equal rights displaced the traditional image".
The relative clause introduced by where modifies a structure of equal rights: expressed as an independent clause this would be "in this structure individuals exercise autonomy".
As for the rest of your questions:

*

*The Subject is indeed The conflict between royalists and parliamentarians.

*English grammars which use the term 'Predicate' would say that everything from unleashed to the end of the sentence comprises the Predicate in this sentence; unleashed is the 'Verb' or 'Predicator'.

*Everything from a torrent to the end of the sentence is the Object. Its 'core' is the Noun Phrase a torrent of radical thinking, and what follows is a Relative Clause modifying the preceding Noun Phrase—which (as I said above) may be taken to be either the phrase headed by torrent or the phrase headed by thinking.

*In any case, there is no adverbial which modifies unleashed. In crucial areas of their lives may be taken as an adverbial modifying the clause headed by exercise. Traditional grammar might classify the Preposition Phrase headed by by as an adverbial modifying displaced; I would classify it as an agentive complement of displaced licensed by the passive construction.


text:
Q: Set the date and time manually - java i'm trying to allow a customer to set the date and time they would want to make a reservation. The code which i have already completed creates lots of text in the text file when saved and crashes when you try to load it again.
This is my code for adding a reservation:
 public static List<Reservation> addReservations(List<Reservation> reservations, List<Customer> customers) {
    int newReservationId = Reservation.getNumberOfReservations() + 1;
    String startString = readString("Enter Reservation date");
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date date = null;
    try {
        date = sdf.parse(startString);
    } catch (ParseException ex) {
        Logger.getLogger(ProjectIncrement5.class.getName()).log(Level.SEVERE, null, ex);
    }
    Calendar dateTime = Calendar.getInstance();
    dateTime.setTime(date);

    listCustomers(customers, reservations);
    int reservationCustomerId = readInt("Enter Customer Id", Customer.getNumberOfCustomers(), 1);
    Customer reservationCustomer = customers.get(reservationCustomerId - 1);
    Reservation res = new Reservation(newReservationId, dateTime, reservationCustomer);
    reservations.add(res);
    return reservations;
}

Reservation Class:
public class Reservation {

private int reservationId;
private Calendar dateTime;
private Customer customer;

private static int numberOfReservations = 0;

public Reservation() {
    this.reservationId = 0;
    this.dateTime = null;
     this.customer = null;

    numberOfReservations++;
}

public Reservation(int reservationId, Calendar dateTime, Customer customer) {
    this.reservationId = reservationId;
    this.dateTime = dateTime;
      this.customer = customer;

    numberOfReservations++;
}

public static int getNumberOfReservations() {
    return numberOfReservations;
}

public int getReservationId() {
    return reservationId;
}

public void setreservationId(int reservationId) {
    this.reservationId = reservationId;
}

public Calendar getDateTime() {
    return dateTime;
}

    public Customer getCustomer()
{
    return customer;
}

public void setCustomer(Customer customer)
{
    this.customer = customer;
}

public String setDateTime() {
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String dateString = formatter.format(this.dateTime.getTime());
    return dateString;
}

@Override
public String toString() {
    return "Reservation id: " + getReservationId() + ", "
            + "Date/Time " + setDateTime() +
    "customer: " + getCustomer();

}
}

This is what saves into the text file causing the error:

1:java.util.GregorianCalendar[time=851385600000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=1996,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=359,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]:4:<

I think the error occurs when getting the instance of the calendar but I'm am unsure of how to do it an easier way and fix this problem. Can anyone help?

A: The problem is you store the Calendar.toString() and not the real date into the text file.
Look at what you have posted:

firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=1996,MONTH=11,WEEK_OF_YEAR=52,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=359,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=4,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

That seems a correct date. I will say more, this seems a really complete date, with a lot of information doesn't??? ;)

I don't know how this date is supposed to be stored, but, for example, if you want to store date in format dd/MM/yyyy use this lines of code to check if it's a valid date (you already do this in your code).
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
date = sdf.parse(startString);

After checking this, if the startString is valid, you don't need to create any Calendar instance just write startString to the text file.

UPDATE:

So in my Reservation class, instead of having: private Calendar dateTime I will take that out and just have: private String startString?

NOPE. The idea is:

*

*In a Java class, store in a specific Object (Calendar is ok, but Date will be also)

*In text file, send a human readable date via String.

Sorry but I can't be more specific, I can't execute your code because a lot of parts are missing (Customer, readInt, listCustomers etc...).

A: I accept Jordi Castilla's Answer, and also want to tell other option to do the same.
here you are saving the Date & Time to file using Calendar.toString() method, instead you could use following code
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String stringToFile = df.format(date);//you can send this string to the file which you want to store the Date & Time

A: Avoid legacy date-time classes
The modern approach uses java.time classes. Avoid the troublesome, confusing, and poorly-designed old legacy date-time classes such as Calendar.
LocalDate
Collect the date portion. Catch any DateTimeParseException in case of bad input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
try {
    LocalDate ld = LocalDate.parse( input , f ) ;
} catch ( DateTimeParseException e ) {
    …
}

Seems like you are not explicitly tracking the time-of-day. So the LocalDate class suffices.
ISO 8601
When you serialize your data to a text file, you should be using standard ISO 8601 formats. These formats are designed to be practical & unambiguous, easy to parse by machine, easy to read by humans across cultures, and not assume proficiency in English.
The java.time classes use the standard formats by default when parsing and generating strings. Merely call toString to generate.
String output = ld.toString() ;  // Ex: 2017-01-23

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

*See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: c# WebBrowser DocumentText works once but not in a loop? I am interested in checking the content of a website, the content changes frequently and when I view the website on any browser, it refreshes itself every 30 seconds. I want to know when the content has changed.
I am using winforms and I want to just click a button to start a loop, every 30 seconds. I don't want to hit the website too frequently, in fact the web pages own refresh is more than enough for my needs.
My code works when I click a button (btnCheckWebsite), if I wait a minute and then click btnCheckWebsite again, my message box pops up because the web page has changed. This is great however I want to do this in a while loop. When I un-comment my while loop, the DocumentText never changes. I have debugged it and for some reason it's the same text every time, even when the web page has changed in the real world, it stays the same in my code.
So my question is why can't I use a loop and what can I do instead to run this repeatedly without any input from me?
As a bonus, I would like to remove the .Refresh() I added this because it won't work without it however as I understand it, this refreshes the whole page. When I use a browser I see the page updating even when I don't refresh the whole page.
Just for background info, I did start by having a WebBrowser control on my form, the page refreshes automatically. I used the same code and have the same problem, interestingly, the WebBrowser control on my windows form refreshes by itself no problem, until I click btnCheckWebsite and then it stops refreshing! Also I know about webrequest but I don't know how to use it for my purposes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Check_Website
{
    public partial class Form1 : Form
    {
        public WebBrowser _memoryWebBrowser = new WebBrowser();
        String _previousSource = "emptySource";

        public Form1()
        {
            InitializeComponent();

           _memoryWebBrowser.Navigate(new Uri("http://www.randomurl.com/"));

        }

        private void btnCheckWebsite_Click(object sender, EventArgs e)
        {
            //I want to un-comment this while loop and let my code run itself but it stops working
            //when I introduce my while loop.

            //while (1 < 2 )
            //{
                //Thread.Sleep(30000);

                checkWebsite();

            //}
        }

        private void checkWebsite()
        {
            //Why do I need this refresh? I would rather not have to hit the web page with a refresh.
            //When I view the webpage it refreshed with new data however when I use a WebBrowser
            //the refresh just doesn't happen unless I call Refresh.
            _memoryWebBrowser.Refresh();

            Thread.Sleep(500);

            while (((_memoryWebBrowser.ReadyState != WebBrowserReadyState.Complete) || (_memoryWebBrowser.DocumentText.Length < 3000)))
            {
                Thread.Sleep(1000);
            }

            String source = _memoryWebBrowser.DocumentText;

            if ((source != _previousSource) && (_previousSource != "emptySource"))
            {
                //Hey take a look at the interesting new stuff on this web page!!
                MessageBox.Show("Great news, there's new stuff on this web page www.randomurl.co.uk!!" );
            }

            _previousSource = source;

        }
    }
}

A: You'd need to do your processing upon DocumentCompleted event. This event is asynchronous, so if you want to do this in a loop, the execution thread must pump messages for this event to fire. In a WinFroms app, your UI thread is already pumping messages in Applicaiton.Run, and the only other endorsed way to enter nested message loop on the same thread is via a modal form (here's how it can be done, see in the comments).
Another (IMO, better) way of doing such Navigate/DocumentCompleted logic without a nested message loop is by using async/await, here's how. In the classic sense, this is not exactly a loop, but conceptually and syntactically it might be exactly what you're looking for.

A: You can catch the WebBrowser.Navigated Event to get notified when the page was reloaded. So you wouldn't need a loop for that. (I meant the ready loop)
Just navigate every 30 seconds to the page in a loop and in the Navigated Event you can check whether the site has changed or not.

A: You'd better hook up DocumentCompleted event to check its DocumentText property!

A: The WebBrowser Element is very buggy and has much overhead for your needs. Instead of that you should use WebRequest. Because you said you don't know how to use, here's an (working) example for you.
using System;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace Check_Website
{
    public partial class Form1 : Form
    {
        String _previousSource = string.Empty;
        System.Windows.Forms.Timer timer;

        private System.Windows.Forms.CheckBox cbCheckWebsite;
        private System.Windows.Forms.TextBox tbOutput;

        public Form1()
        {
            InitializeComponent();

            this.cbCheckWebsite = new System.Windows.Forms.CheckBox();
            this.tbOutput = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // cbCheckWebsite
            //
            this.cbCheckWebsite.AutoSize = true;
            this.cbCheckWebsite.Location = new System.Drawing.Point(12, 12);
            this.cbCheckWebsite.Name = "cbCheckWebsite";
            this.cbCheckWebsite.Size = new System.Drawing.Size(80, 17);
            this.cbCheckWebsite.TabIndex = 0;
            this.cbCheckWebsite.Text = "checkBox1";
            this.cbCheckWebsite.UseVisualStyleBackColor = true;
            //
            // tbOutput
            //
            this.tbOutput.Location = new System.Drawing.Point(12, 35);
            this.tbOutput.Multiline = true;
            this.tbOutput.Name = "tbOutput";
            this.tbOutput.Size = new System.Drawing.Size(260, 215);
            this.tbOutput.TabIndex = 1;
            //
            // Form1
            //
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.tbOutput);
            this.Controls.Add(this.cbCheckWebsite);
            this.Name = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

            timer = new System.Windows.Forms.Timer();
            timer.Interval = 30000;
            timer.Tick += timer_Tick;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (!cbCheckWebsite.Checked) return;

            WebRequest request = WebRequest.Create("http://localhost/check_website.html");
            request.Method = "GET";

            WebResponse response = request.GetResponse();

            string newContent;
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                newContent = sr.ReadToEnd();
            }

            tbOutput.Text += newContent + "\r\n";

            if (_previousSource == string.Empty)
            {
                tbOutput.Text += "Nah. It's empty";
            }
            else if (_previousSource == newContent)
            {
                tbOutput.Text += "Nah. Equals the old content";
            }
            else
            {
                tbOutput.Text += "Oh great. Something happened";
            }

            _previousSource = newContent;
        }
    }
}


text:
Q: Simulate a Windows Docker setup in a VM I'm developing a command line (in Golang) which interacts with Docker. It works fine on Linux & Mac, although I have a bug when I try to make it work with Windows 10, but I don't have a Windows 10 laptop available.
What are my solutions ? I've tried the nested virtualization, but Hyper-v (which is used by Docker Desktop) is not able to start in my Windows virtual machine (created with VirtualBox which obviously doesn't support thise use case).
The Cloud providers don't seem to support this use case either, I'm kind of stucked.


text:
Q: How to let this JavaScript/jQuery script use HTML? I'm trying to make my small website multilingual, and after testing many options, this script seems to be the best:
( https://jsfiddle.net/imihandstand/fh1rcy97/1/ . Source: https://stackoverflow.com/a/47612798/4024828 )

<select id="country_select" onchange="loadsLanguage(this.value);">
</select>

  /

But I have one huge issue with it: It does not care about HTML-tags I use in it - but I would need that. So text in  should be shown as bold, etc.
How could I change this script to make it use the HTML-tags? I tried for 2-3 hours and I'm unable to solve it...
Thank you very much!


text:
Q: How to parse XML data and store it in string value in swift I have an API call which returns response as XML type, the thing is I have to get value from the xml data and store it in String, can you suggest how to get or map the value from the xml response?
Here my sample response from server :
responseString = <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<email-address>xxx02v@gmail.com</email-address>
</person>

A: For the native XML parsing you can NSXMLParser and NSXMLParserDelegate. it has many methods which is useful in parsing the XML data
Useful methods using NSXMLParserDelegate
    - parserDidStartDocument:
    - parserDidEndDocument:
    - parser:didStartElement:namespaceURI:qualifiedName:attributes:
    - parser:didEndElement:namespaceURI:qualifiedName:
    - parser:foundCharacters:

Apple Doc: NSXMLParser
Apple Doc: NSXMLParserDelegate
Example
var parser = NSXMLParser()
var posts = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var date = NSMutableString()

func beginParsing()
    {
        posts = []
        parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
        parser.delegate = self
        parser.parse()
    }

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
    {
        element = elementName
        if (elementName as NSString).isEqualToString("item")
        {
            elements = NSMutableDictionary()
            elements = [:]
            title1 = NSMutableString()
            title1 = ""
            date = NSMutableString()
            date = ""
        }
    }

func parser(parser: NSXMLParser!, foundCharacters string: String!)
    {
        if element.isEqualToString("title") {
            title1.appendString(string)
        } else if element.isEqualToString("pubDate") {
            date.appendString(string)
        }
    }

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!)
    {
        if (elementName as NSString).isEqualToString("item") {
            if !title1.isEqual(nil) {
                elements.setObject(title1, forKey: "title")
            }
            if !date.isEqual(nil) {
                elements.setObject(date, forKey: "date")
            }

            posts.addObject(elements)
        }
    }

Full demo example:
NSXML Parser Swift 1
NSXML Parser Swift 2


text:
Q: i am unable to install NPM packages in my react native project Simultaneously I am seeing npm update check failed message on the screen. Are these both related? please help me to go in detail.
Click here for image

A: Can you try deleting your Node modules folder and then try? also, you can try reinstalling the npm (How to Reinstall Broken npm)


text:
Q: How do I Perform an API Call for each Item in a List I'm trying to get Price data for each company in a list of tuples [(company_name, symbol)]. In this instance I am using the TD Ameritrade API.
Also, I am having the same problem with Reddit. The only difference is I am trying to retrieve all the comments for each post 'id'. But, with the Reddit code I am pulling the ID from a pandas df instead of a list.
This is where I am at now:

*

*This is for the TD Ameritrade API
    async def run_app(symbols):
        # empty list to append dataframes to
        all_dfs = []
        for sym,name in symbols:

            # gets the price history data
            rdata = asyncio.get_price_data(symbol=sym, period='10', periodType='day', frequency='minute', frequencyType='1')

            # prepares data for panda df
            can = unpack_ph_data(rdata, 'candles', 'symbol')

            # function for creating a panda df
            df = create_ph_df(can) # function for creating a panda df

            # append to all_dfs
            all_dfs.append(df)

            return rdata

My thinking was that using the for statement it would run each step for each item in the symbol list. First I tried without the asyncio then I saw an example similar to this but not with an API, so I figured I would try it.

*For Reddit:
I am trying something similar using the praw package. But for this I am pulling data from each row in a pandas df and ran into the same problem.
I have a function that gets a specified subreddit and returns all the data in a pandas df:
def get_subreddit_data(subreddit="all", limit=25):
    """
    :param subreddit: Which subreddit to get top posts.
    :param limit: number of desired posts (This will be for setting the limit
    after.hot(limit=num_of_posts)and eventually determined from user input.
    Default 25

    :returns: top posts in subreddit or default (top posts on reddit).
    data is returned in pandas df with the following columns:
    >>> title, score, id, subreddit, url, comments, selftext, created <<<
    """
    # empty list to insert data to:
    posts = []

    # variable for data
    top_posts = reddit.subreddit(subreddit).hot(limit=limit) # limit and subreddit params

    # FOR loop to append data to posts
    for post in top_posts:
        posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created])

    # Create df
    df = pd.DataFrame(posts, columns=["title","score", "id", "subreddit", "url", "comments","selftext", "created"])

    return df

df = get_reddit_subreddit(subreddit, limit) works fine and returns a pandas df
This is where I run into issues:
IDs = []
for ID in [df["id"]]:
    IDs.append(ID) # Add IDs to ID list

def return_comments_for(ID_list):
    # empty list to append comments to
    _comments = []
    """
    :param ID_list: list of post IDs
    :returns: list of comments for each post ID
    in ID_list
    """
    # for loop to extract each ID one by one
    for ID in ID_list:
        # Create submission instance
        submission = reddit.submission(id=ID)
        submission.comments.replace_more(limit=None)
        for comment in submission.comments.list():
            _comments.append(comment.body)

comments = return_comments_for(IDs)

That didn't work so I tried without creating a function and using a queue:
# Empty list for all IDs
queue = []
IDs = [df["id"]] # get IDs from DF
for i in IDs:
    queue.append(i) # Add IDs to queue

# list to append comments to
_comments = []
while queue:
    # pop item index 0 and assign to ID
    ID = queue.pop(0)
    # create submission instance for ID
    submission = reddit.submission(id=ID)
    submission.comments.replace_more(limit=None)

    # for each comment in submission instance
    for comment in submission.comments.list():
        _comments.append(comment.body) # append to main comment list

This isn't the only way I tried to use a queue stack either. I have tried multiple different ways I just can't remember them all. But either way, none of them worked so I am missing something.
This is the entire error message I get every time. No matter how I try it.
ValueError                                Traceback (most recent call last)
<ipython-input-9-2cddf98f54ba> in <module>
     20
     21
---> 22 comments = return_comments_for(IDs)
     23 print(comments)

<ipython-input-9-2cddf98f54ba> in return_comments_for(ID_list)
     14     for ID in ID_list:
     15         # Create submission instance
---> 16         submission = reddit.submission(id=ID)
     17         submission.comments.replace_more(limit=None)
     18         for comment in submission.comments.list():

C:\ProgramData\Anaconda3\lib\site-packages\praw\reddit.py in submission(self, id, url)
    847
    848         """
--> 849         return models.Submission(self, id=id, url=url)

C:\ProgramData\Anaconda3\lib\site-packages\praw\models\reddit\submission.py in __init__(self, reddit, id, url, _data)
    532
    533         """
--> 534         if (id, url, _data).count(None) != 2:
    535             raise TypeError("Exactly one of `id`, `url`, or `_data` must be provided.")
    536         self.comment_limit = 2048

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1476
   1477     def __nonzero__(self):
-> 1478         raise ValueError(
   1479             f"The truth value of a {type(self).__name__} is ambiguous. "
   1480             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: The way you tried to extract a list of IDs is wrong, just do something like:
IDs = df["id"].values.tolist()

A: After
IDs = []
for ID in [df["id"]]:
    IDs.append(ID) # Add IDs to ID list

IDS is not a list of int, but a list of pandas.Series. Containing exactly one Series, namely df["id"].
# This does what you were trying to do:
IDs = []
for ID in df["id"]:
    IDs.append(ID)

# Which can be shortened to
IDs = list(df["id"])

# But I think just passing the Series to your function, should work fine:

comments = return_comments_for(df["id"])

The real bug is that comments will be None after this, because return_comments_for doesn't return anything, so it will implicitly return None.


text:
Q: How to write to excel c# I am using this code to write data to excel file.
Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = true;
I am using this code to write to excel.

_Workbook workbook  = (_Workbook)(excelapp.Workbooks.Open(@"C:\Path\To\Your\WorkBook\ExcelWorkBook.Xls"));
_Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

worksheet.Cells[1, 1] = "Name";
worksheet.Cells[1, 2] = "Bid";

worksheet.Cells[2, 1] = txbName.Text;
worksheet.Cells[2, 2] = txbResult.Text;

excelapp.Visible = false;

This code works fine except that it works very slowly. I want a fastest way to write tot excel. If I run a loop to write to excel to write thousands of rows, then it works to  slowly. Is there any faster way to write the data to excel file like write a whole datatable to excel file of write datatable rows simultaneously rather than cell by cell ?

A: Try inserting an array to the excel instead:
    object[,] arr = new object[rowCount, columnCount];
    //Assign your values here

    Excel.Range c1 = (Excel.Range)worksheet.Cells[0, 1];
    Excel.Range c2 = (Excel.Range)worksheet.Cells[rowCount - 1, columnCount];
    Excel.Range range = wsh.get_Range(c1, c2);

    range.Value = arr;

Writing / Reading values to / from each cell is far too slow and will consume a lot of time, try doing it in memory.


text:
Q: MVC 3 default action without usng the MapRoute? My requirements are to be able to map a custom controller but have it built in that only one action can ever be called. So instead of this:
 context.MapRoute(
    "RouteName",
    "{controller}/{id}",
    new {
        controller = "MyCustomController",
        action = "DefaultAction", <- I want to remove this.
        id = UrlParameter.Optional
    }
 );

I want to do this:
 context.MapRoute(
    "RouteName",
    "{controller}/{id}",
    new {
        controller = "MyCustomController",
        id = UrlParameter.Optional
    }
 );

And to have it call "DefaultController" by well...default without having to specify declare it in the defaults argument of MapRoute.
Any help?

A: You can't do that. Your url doesn't contain an {action} token. This means that you absolutely should specify which action you want to invoke in the default values.
Put yourself on the place of the routing engine. You see the following request: Home/123. You look at the route definition and you see {controller}/{id}.
Great => now you know that you could instantiate the HomeController but that's all you know if an action is not specified as a default value. You have no idea which action to invoke on this HomeController and the story ends here.
You throw the following exception to the developer to inform him about the problem with his code:

The RouteData must contain an item named 'action' with a non-empty string value.

UPDATE:
You could write a custom extension method that will allow you to omit the default action in the declaration but it will add it behind the scenes:
public static class RouteExtensions
{
    public static Route MyMapRoute(this RouteCollection routes, string name, string url, object defaults)
    {
        var defaultValues = new RouteValueDictionary(defaults);
        if (!defaultValues.ContainsKey("action"))
        {
            defaultValues["action"] = "index";
        }
        var route = new Route(url, new MvcRouteHandler())
        {
            Defaults =  defaultValues,
            Constraints = new RouteValueDictionary(),
            DataTokens = new RouteValueDictionary()
        };
        routes.Add(name, route);
        return route;
    }
}

and then:
routes.MyMapRoute(
    "RouteName",
    "{controller}/{id}",
    new { controller = "MyCustomController", id = UrlParameter.Optional }
);


text:
Q: Where to perform validation related to length, format for mobile app: on server side or app side? We are developing Android mobile app that will have about 8-10 screens with about 10 fields on each screen. On each screen we need to "submit" data to server. Where we should perform validation related to length, format- on server side or app side? If we do it on app side, we have a limitation to do it using JavaScript. We want views in consideration to performance impact and ease of debugging.

A: You should validate both on the client side and server side.
Client side:
Validating on the client side makes you application snappier because you'll not have to wait for the response from the server before showing any information about incorrect format, length or required fields to the user. It also enables you to handle validation in real time which will result in a much UX. I don't understand why you would do it with javascript of you are writing an Android application. This article has some information about it.
Server side:
This is where you guard against incorrect data. The checks on the server side will almost never be needed because they've already been made by the client. The checks are simply there to prevent anyone from circumventing the client side checks and passing bogus data.
If you only want to or can implement one of these it should be the server side checking.

A: Complexity of UI logic is common problem. But it is obvious that you should organize your code in the way when you can add any checks. To debug application (running on phone) you can try to use Android 4.4 and remote debugging of WebView.
Also I guess you should perform validation on server side. Logic must accept or reject data incoming to chain of processing. Also it can be possible that somebody will call your logic, not only your own app.

A: The best solution is to perform a double validation, both on client and server side.
Assuming that data validation is a simple CPU bound operation, and can be quickly done by any mobile device in a reasonable time (i.e. not impact on performances), a first client-side validation prevent your app to perform potentially useless network requests, which means  network useless traffic generation and depending of the user's contract with his Telco operator may imply a cost. Plus, this is an extra effort for your backend system to process invalid data, and even if one single validation is a simple operation, since you may (hopefully) have many application instances installed  on several devices this effort will be multiplied and  cause a big load for the server.
Nonetheless you can't avoid a final server side validation, cause we live in the real world and not in an ideal one, and any client side operation can't ever be considered safe at all!
The technology you are using (javascript in your case) does not affect or influence the above considerations! All technologies provide sufficient ready-to-use validation and debugging tools!


text:
Q: Windows Server 2012 unable to access specific SSL page This problem really boggles the mind.
I have a standard Windows 2012 server with windows firewall enabled.
Using Chrome, I am unable to access a certain HTTPS website while other HTTPS websites can be accessed without problems. Error: Time out.
Cannot access: "https://www.onlinepayment.com.my/MOLPay/"
Can access: google.com, paypal.com
Onlinepayment.com.my is accessible from home/office PC without issue.
From the server, I can ping to Onlinepayment.com.my.
I have tried allowing 443 port, disabled the firewall, use different browser (IE) and it all doesn't open the page.
I have tried asking the hosting company if they have a firewall in between, they said nope.

A: This is years late... but for those who run into issues with SSL certificates. There are a couple tests you can run which will give insight to what your issue might be.
Testing SSL Installations Using Bash:

*

*Try to establish a connection with OpenSSL:
openssl s_client -connect www.onlinepayment.com.my:443

*Test for redirects that may have a CN or SAN that doesnt match the certificate:
curl -I -L https://www.onlinepayment.com.my/MOLPay/

Testing SSL Installations Using Windows:

*

*Per this stack, you can establish a connection to the server using powershell and get some information:
$response = Invoke-WebRequest -uri "https://www.onlinepayment.com.my/MOLPay/"
$response.BaseResponse
$response.RawContent.Split("`n")[0..20]

*Digicert has a free application for windows which can scan internal or external sites to check the installed certificate. Run the exe and go to Tools > Check Install.

Other Tools:

*

*Nmap is great for testing network issues:
nmap -sV --script ssl-enum-ciphers -p 443 www.onlinepayment.com.my

*The Qualys SSL Scanner can be used to review the quality and security of the connection. You can compare the results to Mozilla's recommended server configs if you're really zealous.

A: I just tried to hit that site from my machine and my firewall blocked it. I am not sure why you want to go to that site but I would make sure that you know what you are doing as it doesn't hit me as a site I would want to go to. :)
Can you ping the IPaddress?
It resolves to IP Address = 202.76.234.124
      Service Provider   = GTC MY PIP NET
      Domain Name        = GLOBALTRANSIT.NET
      ASN Number         =
      ASN Name           =
      Network Speed      = DSL
      Country CC         = MY
      Country            = MALAYSIA
      Region             = KUALA LUMPUR
      City               = KUALA LUMPUR
      Longitude          = 101.686531066895
      Latitude           = 3.14120006561279
      Zipcode            = -
      TimeZone           = +08:00
      BestAnswer         = 0

A: Try changing the DNS settings on your server to use Google's DNS server at 8.8.8.8.  You might be using a managed DNS server like OpenDNS that has policies applied to it.