text:
Q: How do I replace a harddrive that is in a two-way mirror storage space on Windows 8? I have a storage space in Windows 8 doing a two-way mirror on three harddrives. The sizes are 297GB, 189GB, and 70GB. I would like to replace the 70GB HD with a larger one. My thought was to remove that drive from the space via the Storage Space control panel, shutdown, replace HD with bigger drive, reboot, add new HD to the storage space.
I can't find any options to remove a HD from a storage space in the control panel. Should I just shutdown and swap out the small drive or is there another process for safely replacing the old HD? (By the way, the old HD is still operational.)

A: Here is what I found on the Building Windows 8 blog:

Q) How do I replace a working drive with a bigger one (or just cycle
drives)? Does it require a "rebuild"?
As long as you have created mirrored or parity spaces, you can always
simply remove a physical disk within the pool, and add a different
(perhaps larger) one. Within a short period of time, the impacted
spaces will automatically be resynchronized (the Storage Spaces design
optimizes this operation to be faster than traditional RAID rebuilds).
You can determine whether all spaces are healthy – i.e. data has been
resynchronized so as to maintain the designated number of copies
–either via Control Panel or via PowerShell commands.

Virtualizing storage for scale, resiliency, and efficiency
So, my understanding is to just pull the drive, replace, and let it do its thing.

A: If your mirror is setup with the 297GB drive mirrored to the 189GB+70GB, you could break the mirror, replace the 70GB drive and recreate the mirror. I would suggest replacing the 70GB drive with something larger than 297GB so that you are not mirroring onto JBOD.
Please confirm the configuration of the mirror before removing any drive. You can find this out by the capacity of the logical volume; it should be less than 189+70 (259GB). If that is correct, you should have no problems performing the swap. If instead, your logical volume is 189+70+297 (556GB), you actually have a JBOD array, not a mirror. This means no redundancy, and removing any drive from the array would provide complete data loss. For this scenario, use a disk cloning utility (ghost/dd) to clone the data to the larger replacement drive and then create a RAID1 mirror from that drive to your other drives.


text:
Q: How to query Athena string to date in hadoop.hive.serde2.OpenCSVSerde format Hi I have created following schema in AWS Athena to read csv file from AWS S3
CREATE EXTERNAL TABLE IF NOT EXISTS axlargetable.mine (
  createdate string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'
WITH SERDEPROPERTIES (
   'separatorChar' = ',',
   'quoteChar' = '\"',
   'escapeChar' = '\\'
   )
LOCATION 's3://ax-large-table/test/'
TBLPROPERTIES ('has_encrypted_data'='false')

"createdate" column holding following values
7/01/2017 5:40:05 PM
7/03/2017 5:40:05 PM
7/04/2017 5:40:05 PM
7/05/2017 5:40:05 PM
7/06/2017 5:40:05 PM
7/31/2017 5:40:05 PM
7/31/2017 5:40:05 PM
7/31/2017 5:40:05 PM
7/31/2017 5:40:05 PM

How can I query "createdate" column value as date format?  sample query like
Select * from axlargetable.mine
where createdate between '7/03/2017' and '7/31/2017'

Thanks

A: I'm afraid the OpenCSVSerDe does not support parsing date types with some non-ISO formatting. The only way you can circumvent this behavior is, that you translate the string into a date within your query.
In that case, you would need to use the parse_date function.
select * from axlargetable.mine
where date_parse(createdate, '%m/%d/%Y %h:%i:%s %p')
          between DATE'2017-03-07' and DATE'2017-07-31';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Pygame Trasparency showing as black I am trying to blit an image with transparencies on top of a Surface with the rest of the map. ( This is the second layer. ) When I blit it, it shows with the transparency as black. Is there a way to fix this. I included the code related to it.
lily_tex = spritesheet.get_sprite(1, 4).convert_alpha()

This gets the image from the spritesheet.
    img = pygame.Surface((self.tilesize, self.tilesize))
    img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))
    return img.convert()

And this is what pulls it from the sprite sheet.
Below is what blits it to a surface to be blitted to the screen buffer.
def create_map(self):
    for map_data in self.map_data:
        for row in range(len(map_data)):
            for column in range(len(map_data[row])):
                if map_data[row][column] == 0:
                    continue
                texture = self.key.get(map_data[row][column])
                self.map_img.blit(texture, (column * self.tilesize, row * self.tilesize))

Thank you

A: When you call convert() the pixel format of the image is changed. If the image format has per alpha pixel, this information will be lost.
Use convert_alpha() instead of convert():
return img.convert()
return img.convert_alpha()

If the image has no per pixel alpha format you must set the transparent color key with set_colorkey():
img = pygame.Surface((self.tilesize, self.tilesize))
img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))
img.set_colorkey((0, 0, 0))

Alternatively you can create a surface with per pixel alpha format with the SRCALPHA flag:
img = pygame.Surface((self.tilesize, self.tilesize), pygame.SRCALPHA)
img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))


text:
Q: creating multiple variables/lists/functions via a loop (Maxima) below I have listed some ways to create variables/lists/functions via a for loop in Maxima,
but how, via a for loop, to do:
f1(x) := x^1$
f2(x) := x^2$
f3(x) := x^3$

example code:
for i : 1 thru 10 do
(x : concat ('a, i), x :: i)$
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];

for i : 1 thru 3 do
(x : concat ('L, i), x :: [(3*i)-2,(3*i)-1,3*i])$
[L1, L2, L3];

/* good, but not quite what I want to do */
for i : 1 thru 3 do
f[i](x) := x^i$
[f[1](2), f[2](2), f[3](2)];

/* is there a way, via a for loop, to create */
f1(x) := x^1$
f2(x) := x^2$
f3(x) := x^3$
[f1(2), f2(2), f3(2)];

EDIT: further code:
/* is there a way, via a for loop, to create */
f(x) := x^1$
g(x) := x^2$
h(x) := x^3$
[f(2), g(2), h(2)];

for tmp1 : 1 thru 10 do
(tmp2 : parse_string(ascii(96+tmp1)), tmp2 :: tmp1)$
[a, b, c, d, e, f, g, h, i, j];

for tmp1 : 1 thru 10 do
(tmp2 : concat(parse_string(ascii(96+tmp1)), tmp1), tmp2 :: tmp1)$
[a1, b2, c3, d4, e5, f6, g7, h8, i9, j10];

EDIT 2: original problems solved (any code improvements/simplifications welcome):
for i : 1 thru 3 do
eval_string(concat("f", i, "(x) := x^", i))$
[f1(2), f2(2), f3(2)];

for i : 1 thru 3 do
eval_string(concat(ascii(96+5+i), "(x) := x^", i))$
[f(2), g(2), h(2)];

sum:0$
for i : 1 thru 3 do
sum:sum + eval_string(concat("f", i, "(2)"))$
sum;

sum:0$
for i : 1 thru 3 do
sum:sum + eval_string(concat(ascii(96+5+i), "(2)"))$
sum;

A: What is your larger goal here? In general using subscripted symbols e.g. a[1] instead of a1 is to be preferred. When you define a subscripted function, you only define it once, not for every value of the subscript. E.g.
(%i1) f[i](x) := x^i $
(%i2) [f[1], f[2], f[3]];
                                            2                3
(%o2)         [lambda([x], x), lambda([x], x ), lambda([x], x )]
(%i3) [f[1](u), f[2](v), f[3](w)];
                                       2   3
(%o3)                             [u, v , w ]

If that doesn't work for you, maybe you can explain about what you're trying to achieve.

A: I have collected here, various ways of creating multiple variables/lists/functions via a loop in Maxima,
as an answer to the question, '[f1(2), f2(2), f3(2)]' explicitly answers the original question:
for i : 1 thru 10 do
(x : concat ('a, i), x :: i)$
[a1, a2, a3, a4, a5, a6, a7, a8, a9, a10];

for i : 1 thru 3 do
(x : concat ('L, i), x :: [(3*i)-2,(3*i)-1,3*i])$
[L1, L2, L3];

for tmp1 : 1 thru 10 do
(tmp2 : parse_string(ascii(96+tmp1)), tmp2 :: tmp1)$
[a, b, c, d, e, f, g, h, i, j];

for tmp1 : 1 thru 10 do
(tmp2 : concat(parse_string(ascii(96+tmp1)), tmp1), tmp2 :: tmp1)$
[a1, b2, c3, d4, e5, f6, g7, h8, i9, j10];

for i : 1 thru 3 do
eval_string(concat("f", i, "(x) := x^", i))$
[f1(2), f2(2), f3(2)];

for i : 1 thru 3 do
eval_string(concat(ascii(96+5+i), "(x) := x^", i))$
[f(2), g(2), h(2)];

f[i](x) := x^i$
[f[1], f[2], f[3]];
[f[1](2), f[2](2), f[3](2)];
[f[1](u), f[2](v), f[3](w)];


text:
Q: What is the use of mfunction and elmul? I was converting a program from Octave to Python, I used OMPC for this to try and see if it works, and when I get the conversion of the code for Python at the top there is a line that says @mfunction("") which I'm not sure what is for and I haven't found a lot of information about it. Also about elmul which I also don´t know what it is for and haven't found information about it.
This is the code on Octave
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
%   J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
%   parameter for logistic regression and the gradient of the cost
%   w.r.t. to the parameters.

% Initialize some useful values
m = length(y); % number of training examples

% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));

% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
%               You should set J to the cost.
%               Compute the partial derivatives and set grad to the partial
%               derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
% Use sigmoid function previously programed
hypothesis = sigmoid(X*theta); % Hypothesis for logistic regression
Weight = 1/m;

J = -Weight*sum( ( y.*log(hypothesis) + (1 - y).*log(1 - hypothesis) ) );

for i = 1 : m
    grad = grad + (hypothesis(i) - y(i)) * X(i,:)'; % X must be transposed
end

grad = Weight*grad;

% =============================================================

end

This is the code produced by OMPC:
@mfunction("J, grad")
def costFunction(theta=None, X=None, y=None):
    #COSTFUNCTION Compute cost and gradient for logistic regression
    #   J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
    #   parameter for logistic regression and the gradient of the cost
    #   w.r.t. to the parameters.

    # Initialize some useful values
    m = length(y)  # number of training examples

    # You need to return the following variables correctly
    J = 0
    grad = zeros(size(theta))

    # ====================== YOUR CODE HERE ======================
    # Instructions: Compute the cost of a particular choice of theta.
    #               You should set J to the cost.
    #               Compute the partial derivatives and set grad to the partial
    #               derivatives of the cost w.r.t. each parameter in theta
    #
    # Note: grad should have the same dimensions as theta
    # Use sigmoid function previously programed
    hypothesis = sigmoid(X * theta)# Hypothesis for logistic regression
    Weight = 1 / m

    J = -Weight * sum((y *elmul* log(hypothesis) + (1 - y) *elmul* log(1 - hypothesis)))

    for i in mslice[1:m]:
        grad = grad + (hypothesis(i) - y(i)) * X(i, mslice[:]).cT    # X must be transposed
        end

        grad = Weight * grad

        # =============================================================

        end

A: Both @mfunction and elmul are OMPC-defined functions. The first one is to correctly deal with the special marray type defined by OMPC, the second one is for doing element-wise multiplication on the aforementioned marrays. They are intended to leverage the semantic differences between NumPy and MATLAB.
However, these differences are difficult to translate in full generality, especially so because often MATLAB code relies on these semantic details.
That is why MATLAB-to-Python converters cannot be used reliably in production code.
I would translate the Octave code above into something like (assuming NumPy arrays inputs):
def cost_function(theta, x, y):
    m = np.size(y)
    grad = np.zeros(theta.shape)

    hypothesis = sigmoid(x @ theta)

    j = -np.sum((y * np.log(hypothesis) + (1 - y) * np.log(1 - hypothesis))) / m

    for i in range(m):
        grad = grad + (hypothesis[i] - y[i]) @ x[i, :].transpose().conjugate()

    grad = grad / m
    return j, grad

Please carefully check that x[i, :].transpose().conjugate() is actually needed (it depends on what x and hypothesis actually are).


text:
Q: Confirming eclipse is running a correct version of Scala for Play This should be easy. I've installed play 2.3.7 with the typesafe activator, and later followed https://www.playframework.com/documentation/2.3.x/IDE to set up the demo project of it for eclipse (eclipse Kepler). While the demo project runs as intended, things look a bit quirky inside eclipse, and I suspect my eclipse uses Scala 2.10 whereas Play jars are 2.11.
How do I confirm and resolve this?
Oddly enough by the way, eclipse seems to keep showing and resolving errors in the Problems pane, e.g many errors like:

*

*akka-actor_2.11-2.3.4.jar is cross-compiled with an incompatible version of Scala (2.11). In case of errorneous report, this check can be disabled in the compiler preference page.

*play-functional_2.11-2.3.7.jar is cross-compiled with an incompatible version of Scala (2.11). In case of errorneous report, this check can be disabled in the compiler preference page.

A nice explanation about how eclipse doesn't crash altogether trying to use 2.11 class files using a 2.10 compiler would also be much appreciated :)


text:
Q: I get unreasonable results with math.h (Windows/Eclipse/CDT/MinGW) I'm writting a code on C++, as IDE I use Eclipse/CDT and as compiler I use g++.
This was working fine, but after some modifications, I have got a problem with the header
Indeed, I get unreasonable results for exp,log and sqrt. (For example, exp(0)=2 or log(1)=17565120)
I have checked similar issue. But as you can see in the log of the build, the linker contain the reference to the library libm.a.
Part of the message in the log :
g++ -shared -Wl,--output-def=definition.def -o toto.dll toto1.o toto2.o toto3.o toto4.o toto5.o toto6.o toto7.o -lpthreadGC2 -lm
So, I don't understand why I get these errors.
Moreover, if I do for example : nm toto.dll | find "exp" I get : "68c0de38 T _exp". So, it lets me think that the function exp has a reference.
I haven't get warning message concerning  during the build and the header  is in one of my headers file which is called by others.
If I do a left click on the "#include ", the file math.h will be open.
What could I do in purpose of determining the origin of my problem?
P.S : I can see reading comment, that my description was not really clear.
The problem appeared using the following formula : -log(at * exp(-bt * rt))/remainingLife
In this formula, at,bt,rt and remainingLife are double. -bt*rt=-0.0011072580657125247 and exp(-bt*rt)=32.
I have just add some example that I get using the expression functionality of eclipse.
P.S 2 : When I do nm toto.dll | find "exp" I get also : "68c2b1ec I __imp__exp"
P.S 3 : When I build with option -E, I can see in each file .o that there is only one line with declaration of function exp, it's  "double attribute((cdecl)) exp (double);" which come from MinGW\Include\math.h.
Thanks for your help.

A: You are converting the return values from exp and log to integers. Don't do that.

A: The T in the output of nm indicates that your DLL defines a "text symbol" with the name _exp. It does not mean that _exp is referenced: that would use a U instead. Most likely, this definition interfers with the functions from the standard C library.
The defined symbol clearly has C-linkage as it doesn't include any aspect of mangled functin parameters. That is, it is either defined as extern "C" in a C++ file, possibly getting the declaration from <math.h> and the definition not using extern "C", or it is defined in a C file.

A: Actualy, problems come from the utilisation of windows "Expressions" of Eclipse/CDT, it returns wrong results in this case.
Matt McNabb was right,  is not the problem in my code. There is another bug.
Thanks for your help.


text:
Q: Unable to deserialize when inheriting from IList or IEnumerable I've got the following class which is used to deserialize an XML feed....
[Serializable]
[XmlRoot("forecast")]
public class ForecastCollection : IList<Weather>
{
    private List<Weather> _List = new List<Weather>();

    #region Implementation of IList<T>

    public IEnumerator<Weather> GetEnumerator()
    {
        return _List.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(Weather item)
    {
        _List.Add(item);
    }

    public void Clear()
    {
        _List.Clear();
    }

    public bool Contains(Weather item)
    {
        return _List.Contains(item);
    }

    public void CopyTo(Weather[] array, int arrayIndex)
    {
        _List.CopyTo(array, arrayIndex);
    }

    public bool Remove(Weather item)
    {
        return _List.Remove(item);
    }

    [XmlIgnore]
    public int Count
    {
        get { return _List.Count; }
    }

    public bool IsReadOnly
    {
        get { throw new NotImplementedException(); }
    }

    public int IndexOf(Weather item)
    {
        return _List.IndexOf(item);
    }

    public void Insert(int index, Weather item)
    {
        _List.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _List.RemoveAt(index);
    }

    [XmlIgnore]
    public Weather this[int index]
    {
        get { return _List[index]; }
        set { _List[index] = value; }
    }

    #endregion

    public Weather Today
    {
        get
        {
            if (Count > 0)
            {
                return this[0];
            }

            throw new IndexOutOfRangeException("Could not retrieve todays weather from forecast");
        }
    }

    [XmlArray("simpleforecast")]
    [XmlArrayItem("forecastday")]
    public List<Weather> Forecast
    {
        get { return _List; }
        set { _List = value; }
    }
}

When I deserialize the feed, it doesn't seem to set the Forecast property so when I access Today, the exception is thrown. However, if I remove the inheritance from this class, it deserializes correctly.
EDIT: So to reiterate, it appears as though it only deserializes correctly when ForecastCollection doesn't inherit from something which implements IEnumerable
Can anyone point out where I've gone wrong and the best way to fix this?
Thanks

A: With a blank Weather class:
[Serializable]
public class Weather
{
    // Nothing
}

following code works:
ForecastCollection collection = new ForecastCollection();
ForecastCollection collection2 = null;

collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());
collection.Add(new Weather());

XmlSerializer xs = new XmlSerializer(typeof(ForecastCollection));
using (Stream stream = new MemoryStream())
{
    xs.Serialize(stream, collection);
    stream.Seek(0, SeekOrigin.Begin);
    collection2 = (ForecastCollection)xs.Deserialize(stream);
}

Boolean success = (collection2.Count == 5); // True

A: I think it's because of that whenever you use IEnumerable<T> ,an iterator class would be generated by compiler in behind and that class is not serializable.


text:
Q: How do I obtain the standard errors for Ornstein Uhlenbeck parameter estimates? I have used least squares estimation to obtain estimates for parameters to be used in Ornstein Uhlenbeck process. Now, I would like to compute the standard errors of estimates.
$=(−)+$ (Ornstein Uhlenbeck process and parameters to be estimated)
The regression is as follows:
$S(t+1)=a*S(t)+b+$
The estimates for parameters are obtained from the regression coefficients as follows:
$=−(ln)/Δ, =/(1−)$
and
$=sd() * \sqrt{2/(1−^{−2Δ})}$
I can obtain the standard errors for a and b, but how would I be able to obtain standard errors for the parameters?
Any help is greatly appreciated, I apologize the messy layout of formulas.

A: If you are reporting to physicists or chemicists, I would recommend the Gaussian error propagation law, because that is what they usually apply in such cases:
$$(\Delta f)^2 = \left(\frac{\partial f}{\partial a} \Delta a\right)^2 + \left(\frac{\partial f}{\partial b} \Delta b\right)^2 + \ldots$$
If you are reporting to statisticians, a resampling method like the bootstrap or the jacknife might raise fewer eyebrows ;-) The jackknife is easier and yields reproducibale results, whilst the bootstrap yields a random (albeit not much different) result.


text:
Q: Why does plotting of overlying lines in R have an effect on the plot quality? I've noticed that plotting of plot elements more that once will cause a noticeable change in quality. I.e. a line or points plotted on top of themselves will usually thicken the line and appear more pixelated. Does anyone have an explanation for this? Below is an example of this phenomenon in a png output, but similar results can be found on other graphical devices. I would have expected that since these objects should be perfectly aligned, that there should be no visible effect.
Example:
set.seed(1)
n <- 20
x <- runif(n)
y <- 10*x + rnorm(n)
fit <- lm(y ~ x)

png("01_line.png", width=2, height=2, units="in", res=400, type="cairo")
par(mar=c(2,2,1,1))
plot(x,y, t="n")
points(x, y)
abline(fit)
dev.off()

png("10_line.png", width=2, height=2, units="in", res=400, type="cairo")
par(mar=c(2,2,1,1))
for(i in seq(10)){
    if(i == 1) plot(x,y, t="n")
    points(x, y)
    abline(fit)
}
dev.off()

Here is a closeup comparison of the single line (left) versus the 10 line (right) versions:


text:
Q: Visual Studio 2022 not working for Azure Functions I can't seem to get Azure functions running for Visual Studio 2022 for mac.
I am able to run the functions ok in Visual Studio Code.
The functions come up ok in the terminal for Visual Studio 2022, but when I invoke the function I get this error:
An unhandled host error has occurred.
[2022-10-03T00:50:25.613Z] Microsoft.Azure.WebJobs.Host: 'yourFunctionName' can't be invoked from Azure WebJobs SDK. Is it missing Azure WebJobs SDK attributes?.
Tried uninstalling and reinstalling but no luck

A: I reintalled visual studio.
I installed .net core and the .net tools.
It still was not working.
Then I cleaned the project and it started working.


text:
Q: How to arrive at irq base for an mfd device? In an MFD device. I wanted to understand, how do we arrive at irq base. Is it a random number.?
Please some one explain.

A: Basically one first needs to associate a particular IRQ number with an actual physical hardware interrupt before attempting to register an ISR for that IRQ number. This is commonly done in the Linux kernel using irq_domain_add_linear().

In the past, IRQ numbers could be chosen so they matched the hardware IRQ line into the root interrupt controller (i.e. the component actually firing the interrupt line to the CPU) nowadays this number is just a number.
The irq_alloc_desc*() and irq_free_desc*() APIs provide allocation of irq numbers, but they don't provide any support for reverse mapping of the controller-local IRQ (hwirq) number into the Linux IRQ number space.
The current design of the Linux kernel uses a single large number space where each separate IRQ source is assigned a different number. This is simple when there is only one interrupt controller, but in systems with multiple interrupt controllers the kernel must ensure that each one gets assigned non-overlapping allocations of Linux IRQ numbers.

More details in the Linux-kernel Documentation/IRQ-domain.txt.


text:
Q: how do i get 5 dates of current week with php or jquery? i have this and yesterday it worked fine, but not today.
$current_dayname = date("l");
$datemon = date("m-d-Y",strtotime('monday this week'));
$datetue = date("m-d-Y",strtotime("tuesday this week"));
$datewed = date("m-d-Y",strtotime("wednesday this week"));
$datethu = date("m-d-Y",strtotime("thursday this week"));
$datefri = date("m-d-Y",strtotime("friday this week"));

yesterday, $datemon through $datefri would get the values of 1-20-2014 through 1-24-2014, but today only tuesday through friday is working and monday is getting the date for next monday, not yesterday.
how can i get the dates of the 5 weekdays of the current week?  so if it's wednesday for example, the 5 variables should be 2 for 2 days past, 1 for current day, and 2 for future days.  know what i mean?
i'm going to guess that someone will ask if week starts with monday or sunday.  doesn't really matter as long as script works, but the week starting on a monday is preferable.

A: An easier way to get those dates might be something like this:
$today = time();
$wday = date('w', $today);
$datemon = date('m-d-Y', $today - ($wday - 1)*86400);
$datetue = date('m-d-Y', $today - ($wday - 2)*86400);
$datewed = date('m-d-Y', $today - ($wday - 3)*86400);
$datethu = date('m-d-Y', $today - ($wday - 4)*86400);
$datefri = date('m-d-Y', $today - ($wday - 5)*86400);

I would also recommend using an array instead of 5 different variables, but that's a separate concern.

A: Simple DateTime::setISODate() example:
$dt = new DateTime();
$dates = [];
for ($d = 1; $d <= 5; $d++) {
    $dt->setISODate($dt->format('o'), $dt->format('W'), $d);
    $dates[$dt->format('D')] = $dt->format('m-d-Y');
}
print_r($dates);

will output:
Array
(
    [Mon] => 01-20-2014
    [Tue] => 01-21-2014
    [Wed] => 01-22-2014
    [Thu] => 01-23-2014
    [Fri] => 01-24-2014
)

demo


text:
Q: How to push Angular model to array while changing values using index? I have an Angular Model and I am trying to push it to an array to create repeater fields. The array is then iterated to create html fields in a component. However, while pushing to the array, an undefined error is thrown .
Here is the Model code:
export class TierModel {
    feeName: string;
    feeDescription: string;
    unit: string;
    tierStart: number;
    tierEnd: number;
    rate: number;
};

And here is the code that pushes Model to array:
addForm()
  {
      const obj = new TierModel()

      obj[0].feeName = 'test';
      obj[0].unit = 0;

      this.dataarray.push(obj);
  }

The aim is to use an index with the object and then push it to the array so that any modification is to be done before pushing it to the array would be done here using index.
Any help would be more than

A: try the following
addForm()
{
    const obj = new TierModel()
    obj.feeName = 'test';
    obj.unit = 0;
    this.dataarray.push(obj);
}

your const obj is an object so there is no need for obj[0].

A: This is all messed up,
There is no obj[0], obj is not an array, its an instance of class, that has no constructor.
And pay attention to types, you are defining unit as string but giving it value of number.
Additionally, you dont even need to export class for this. Creating something with new <class>() is confusing when in reality its just an object. If you are declaring object you need to see {}, this is how you make it understandable for anyone on the first look.
This is how you do what you are trying to do
export interface TierModel {
  feeName: string;
  feeDescription: string;
  unit: number;
  tierStart: number;
  tierEnd: number;
  rate: number;
}

export class AppComponent implements OnInit {
  objArray: TierModel[] = [];

  constructor() {}
  ngOnInit(): void {
    this.addForm();
    console.log(this.objArray);
  }

  addForm() {
    let obj = <TierModel>{};
    obj.feeName = 'aaa';
    obj.unit = 1;
    this.objArray.push(obj);
  }
}


text:
Q: Typescript: Arrow function - TS2339: Property does not exist on type '{}' Using Angular, I often get typescript compile errors when using fat arrow functions inside an rxjs stream.
I can still run the app and it does transpile, but I would like to know how to get rid of the error and understand it.
Given:
this.data$ = this.route.params
        .switchMap(params =>
             Observable.forkJoin([
                 Observable.of(params),
                 this.http.get('/api', { param1: params.param1, param2: params.param2 })
        ])
        //**Errors from this part below**
        .map(([params, data]) => data.prop1 + ' - ' + params.param1)

I get the errors:

ERROR in [at-loader]
  file.ts:xx:xx
      TS2339: Property 'prop1' does not exist on type '{}'.
ERROR in [at-loader]
  file.ts:xx:xx
      TS2339: Property 'param1' does not exist on type '{}'.

Why does it complain about this?

A: Try this one:
this.data$ = this.route.params
    .switchMap((params: any) =>
         Observable.forkJoin([
             Observable.of(params),
             this.http.get('/api', { param1: params.param1, param2: params.param2 })
    ])
    //**Errors from this part below**
    .map(([params, data]: [any, any]) => data.prop1 + ' - ' + params.param1)


text:
Q: All possible combinations of two columns in a DataFrame while keeping the rest of the columns the same I have a Pandas Dataframe such as:
  Column_1   Column_2   Column_3   Column_4
0.   a          d          d1         d2
1.   b          e          e1         e2

and I need to make all possible combinations of Column_1 and Column_2 such that Column_3 and Column_4's values remain the same as the row that contains Column_2. This should be the output:
  Column_1   Column_2   Column_3   Column_4
0.   a          d          d1         d2
1.   a          e          e1         e2
2.   b          d          d1         d2
3.   b          e          e1         e2

Can anybody help me out with this?

A: I think you are looking for reindex with multiple index from product
col=df.columns
df.set_index(['Column_1','Column_2'],inplace=True)
idx=pd.MultiIndex.from_product([df.index.get_level_values(0),df.index.get_level_values(1)])
df=df.reindex(idx,method = 'ffill').reset_index()
df.columns=col
df

  Column_1 Column_2 Column_3 Column_4
0        a        d       d1       d2
1        a        e       d1       d2
2        b        d       d1       d2
3        b        e       e1       e2


text:
Q: Itunes on Ubuntu 64 bit I really need to get Itunes on Ubuntu for jailbreaking purposes, but none of the other solutions on this website seem to work. I have Ubuntu 14.04 (64 bit) on my HP Chromebook 14, but I have recently discovered that Itunes only works on 32 bit versions of Ubuntu. I have wine installed and have downloaded the 64 bit version of Itunes but it still doesn't work. I also have playonlinux but when I download it from there it asks me to download the 32 bit version from Apple's website. So I do and when it finishes installing nothing happens and it crashes.
Please show me how to get Itunes on a 64 bit version of Ubuntu.

A:
Comment moved to this answer.

iTunes does not work on Ubuntu even via Wine or PlayOnLinux anymore.
You will need to set up a Windows VM on your system, install iTunes in that, and set up USB pass through so the device can be connected to it via USB.
Short of this, or using a Windows box there is no other solution to make iTunes work, and believe me I have tried.


text:
Q: indexing/linking rows to a unique identifier My data:
id<-c(1,1,1,1,1,1,1,2,2,2)
start<-c(0,1,3,5,7,8,10,0,0,1)
end<-c(1,3,5,7,8,9,12,0,1,4)
mydata<-data.frame(id,start,end)

Question:
What code would I use to indicate that rows 1-7 are linked to the unique id(1), and rows 8-10 are linked to id(2)? The output should look as follows:
Indexes[1:2]
$ '1'
1 2 3 4 5 6 7
$ '2'
8 9 10`

Attempt:
I have looked around StackOverflow but don't really see this being done. I did try
split(mydata,mydata$id)

I know that if I say:
which(mydata$id==1)

It will tell me rows 1-7. But don't know how to use this to my advantage to get the output above.
but that certainly doesn't work.

A: You were almost there.  split can be used on the rownames as well. Since they'll be character values, you coerce them to numeric with as.numeric
> Indexes <- split(as.numeric(rownames(mydata)), mydata$id)
> Indexes[1:2]   ## or just 'Indexes' for your sample data
## $`1`
## [1] 1 2 3 4 5 6 7

## $`2`
## [1]  8  9 10


text:
Q: Spring boot doesnt read my data.sql file? Hei guys, im pretty new to SpringBoot and i have 1 problem.
When i start the app the spring read the schema.sql and make the tabels but the data.sql is not read, so i dont have no data on my db.
this is my app.prop
spring.datasource.url = jdbc:mysql://localhost:3306/garagesaledb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy
spring.jpa.hibernate.naming.physical-strategy= org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.sql.init.mode=always
spring.datasource.schema = classpath:db/schema.sql
spring.datasource.data = classpath:db/data.sql
spring.jpa.hibernate.ddl-auto=update
spring.liquibase.drop-first=true
spring.jpa.defer-datasource-initialization=true

schema.sql
create table asset
(
    id bigint not null auto_increment,
    category varchar(255),
    price decimal(10,2),
    quantity integer,
    purchaseOrder_id bigint,
    primary key(id),
);

data.sql
INSERT INTO garagesaledb.asset(category, price, quantity,purchaseOrder_id) VALUES
('MOUSE', 10.0, 1, null);

It's just a simple app and query but it doesnt read it.

A: Add this property to app.prop spring.datasource.initialization-mode=always
Refer Link : https://docs.spring.io/spring-boot/docs/2.1.0.M1/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-spring-jdbc
Spring Boot automatically creates the schema of an embedded DataSource. This behaviour can be customized by using the spring.datasource.initialization-mode property. For instance, if you want to always initialize the DataSource regardless of its type:
    spring.datasource.initialization-mode=always

I hope this helps.

A: Either you put the file somewhere outside the resources (external file) or provided the location wrongly, - please check the logs
To confirm that, change below line
spring.datasource.data = classpath:db/data.sql
to :
spring.datasource.data = file:<full-path>db/data.sql
OR
in some spring-boot versions,
spring.sql.init.data-locations=classpath:db/data.sql


text:
Q: Is voltage and electric potential actually the same thing? If not, why? Before I get roasted in the comments, let me say I recently got a BS in electrical engineering, so I'm not a newbie in these concepts. I've studied electric potential energy, electric potential, voltage (a.k.a. electric potential difference, electric tension, electric pressure), time-varying/non-conservative electromagnetic fields, Maxwell's equations, etc. I've read textbooks on university physics, on electromagnetic theory, on circuit analysis/theory. (But I haven't studied quantum mechanics or relativity.)
Before explaining why I think voltage and electric potential actually describe the same physical phenomena/process, first I'll briefly recall certain facts about the two, so that you can see I have some standard understanding on these concepts.
Electric potential

*

*Electric potential is the electric potential energy, per unit charge, at a point in space. Recall that electric potential energy is a type of potential energy (i.e. energy that a particle has by virtue of its position in space or in a field, it is energy that could be used to do work), associated with the position of a charged particle.

*Electric potential is defined at a point in space, provided we've previously defined the zero electric potential point (usually Earth ground or a point infinitely far from the region of space under study). Since the potential is defined at any point in space (at least for conservative electric fields), and since it is a scalar value at each point, then we say the electric potential is a scalar field. It makes perfect sense. I can say "the electric potential at point $P_0$ is $\phi_0$".

*We sometimes use the electric potential (a scalar field) to calculate a static electric field (a vector field) as the negative of the gradient of the electric potential, because the former is easier to calculate than the latter.

*Electric potential is the quantity in which Laplace's equation and Poisson's equation are described.

*We can plot the electric potential as a 2D or 3D scalar field.

*We can write Maxwell's equations in terms of the electric potential and the magnetic vector potential.

*Physicists use the term electric potential more often than voltage.

*Etc.
Voltage or electric potential difference

*

*Voltage is defined as the work to be done (or energy to be transferred), per unit charge, to move a charged particle with unit charge, from one point in space to another point in space, along some path or trajectory. So voltage is a quantity between two points, while electric potential is a quantity at a single point.

*In the presence of conservative electric fields only, voltage can also be calculated as the difference of the electric potential at the two points, thus the name electric potential difference.

*Voltage is usually thought of as a scalar, without being a (scalar) field like electric potential. It makes perfect sense. I can say "the voltage between point (or node in the context of circuits) $a$ and point $b$ is $V_{ab}$". But it wouldn't make sense to say "the voltage at point $c$ is $V_c$", because we're not specifying with respect to which other point we're measuring it, unless it is implicitly obvious.

*Voltage (and current), not electric potential, is the quantity in which Ohm's law, the voltage-current relationship for inductors, capacitors, and diodes, are written.

*Voltage, not electric potential, is the quantity in which Kirchhoff's voltage law is described.

*In the presence of conservative electromagnetic fields only (zero currents [electrostatics] or constant currents [magnetostatics]), the work to be done between two points is independent of any of the possible paths connecting the two points, and so the work to be done in moving a charge around a closed loop is zero, and since voltage is work per charge, then voltage is also independent of path in such case. But in the presence of non-conservative electromagnetic fields (time-varying currents [electrodynamics], for example AC circuits, with non-negligible leakage electromagnetic fields outside circuit elements/devices such as inductors), the work to be done in moving a charge from one point to another does depend on the path, and so the work to be done in moving a charge around a closed loop is in general not zero, and so voltage also depends on the path.

*Electrical/electronics engineers use the term voltage more often than electric potential.

*Etc.
Why I think voltage and electric potential are the same
Okay, now to my question. I recently had an online discussion with someone, where I said voltage and electric potential were not the same, while the person said they were. I explained them in a similar manner I just did above. But after talking and me thinking, I think those two quantities are really describing the same thing. Below I'll try to convince you, or at least explain you why to me those quantities seem the same.
Suppose I choose one point in space, which I'll call the reference point, with respect to which I measure the voltage at all other points in space. Isn't that, then, the same as electric potential? For example, I could choose the reference point to be the Earth ground or a point infinitely far from us, thus the voltage would seem to have the same meaning as electric potential.
And since I've chosen one reference point for voltage measuring, then at each point in space the voltage has a certain scalar value. Thus voltage is now a scalar field, like electric potential. So, we can also compute a conservative electric field from this voltage "field", and we can write Maxwell's equations in terms of this voltage "field" (and the magnetic vector potential), just like we could with the electric potential.
And this idea of choosing a reference point for voltage measuring is not uncommon. It is widely used in a method of circuit analysis known as nodal analysis; all or most circuit simulators use that method; it is also used in power systems analysis to obtain the admittance matrix that mathematically describes the electrical behavior of a power system; even using oscilloscopes in real-life electronic circuits is the same, because we attach the negative probe to one node (usually called ground in electronics) of the circuit and then only move the positive prove for measuring the voltage.
So, as you can see, the electric potential at a point is the voltage measured at that point with respect to the zero-potential reference point, so potential is the same as voltage. Or equivalently, the voltage measured between any two points $a$ and $b$ is the electric potential at point $a$ by choosing the zero-potential reference point to be point $b$ (in other words, to obtain voltage from potential, the zero-potential point is not fixed for measuring all potentials), so voltage is the same as potential.
Please note I'm suggesting that voltage (electric tension, electric pressure, electric potential difference) and electric potential are the same thing, not that any of them is the same as electric potential energy. I know the former two are not the same as the latter.

I searched if this question had been already asked, but didn't find any. I found the following which ask different questions:

*

*Difference between voltage, electrical potential and potential difference

*Electric potential and voltage

*Why is voltage described as potential energy per charge?

*What is the difference between electric potential, potential difference (PD), voltage and electromotive force (EMF)?

*Voltage and potential

*Potential difference and voltage

*Is voltage electric potential or electric potential difference?

*Voltage about potential difference

Edit after accepted answer: further clarification on why I say voltage and potential are the same
So far some people have answered/commented that the difference between electric potential and voltage is that the latter is a difference in potentials (which is true), in other words, that voltage is between two points (which is true) while potential is only at one point (which is not exactly true). Let me explain. You may say potential is a quantity only a point, right? Well, if you please look at equations (2.21) (for electric potential) and (2.22) (for electric potential difference, a.k.a. voltage) of David Griffiths' Introduction to Electrodynamics (3rd edition), both on page 78, you will see Griffiths defines electric potential and electric potential difference (a.k.a. voltage) as follows. (In the same manner as Roger's answer, and unlike Griffith, I'll denote voltage as $V$ and electric potential as $\phi$.)
$\phi = - \displaystyle\int_{\mathcal O}^{\mathbf r} {\mathbf E} \cdot {\mathrm d} {\mathbf l} \tag {2.21}$
$V_{ab} = \phi(\mathbf a) - \phi(\mathbf b) = \displaystyle\int_{\mathbf a}^{\mathbf b} {\mathbf E} \cdot {\mathrm d} {\mathbf l} \tag {2.22}$
Now look at the rightmost-hand side of both equations. They both are the line integral of the electric field vector from one point to another point along some path or trajectory. Aha! So electric potential is in general a quantity between two points, just like voltage!
Yes, I know that for electric potential (eq. 2.21), we usually choose the zero-potential reference point $\mathcal O$ to be at infinity, so that the potential then is a quantity at a point. But we can also choose the reference point $\mathbf b$ in the voltage (eq. 2.22) to be also at infinity (if you disagree, please explain), so that voltage is now also a quantity at a point. And as I said earlier, it is actually very common in electrical engineering to talk about the voltage at a point in electric circuits, because we choose one node as the reference node (a.k.a. ground), with respect to which we measure all voltages at the other non-reference nodes.
After discussing with Roger in the comments of his answer, it looks like indeed voltage and electric potential are the same thing, but simply different names for the same thing depending on context (engineering or physics, respectively), with the only tiny difference being that all potentials are measured with respect to a fixed reference point, while voltage can be measured with respect to an arbitrary point (although in nodal analysis we also fix such reference point to be a node, similar to potential).
Edit 2: Why my question is not this question
I've got two suggestions saying that my question is the same as the linked question in the subtitle, so I'll explain why it's not the same question. I'll refer to user11266's answer.
The first and third paragraph of user11266's answer only talk about the reason for confusion in the two terms, and what should be done instead, so those paragraphs are irrelevant to my question.
The second paragraph of user11266's answer talks about potential and potential difference (a.k.a. voltage). He/she says "Each point in space has assigned to it a value for electric potential", which is true because from Griffiths' equation (2.21) it is clear that, for a fixed reference point $\mathcal O$, the potential depends on $\mathbf r$. But guess what? You can also fix $\mathbf b$ in Griffiths' equation (2.22) (potential difference a.k.a. voltage), and now you have the exact same thing as potential: a scalar value at each point in space. And in case you say "no-one fixes a point for measuring voltage", then let me tell you that's actually extremely common: 1) we use it for nodal analysis, the most used method for solving circuits; 2) all circuit simulators use it; and 3) oscilloscopes read voltages by fixing the reference point.
And yes, I know that in the potential equation (2.21) the reference point $\mathcal O$ is usually at infinity, while in my example of circuits the reference point $\mathbf b$ for the voltage equation (2.22) is not at infinity but instead a node of the circuit. But as far as I know, there's nothing prohibiting us from choosing  $\mathbf b$ to be also at infinity, in which case equations (2.21) and (2.22) become the same, and thus voltage and potential are the same thing.
And in case you say "potential is more general than voltage because voltage only applies to circuits, so your circuit example is not valid", my reply would be that simply ignore my examples, and instead focus on equation (2.22) from Griffiths and set $\mathbf b = \mathcal O$ and $\mathbf a = \mathbf r$, then swap the integral bounds/limits by adding a negative sign in front of the integral, and now you get $V_{ab} = \phi$. Et voilà, voltage is the same as potential, or potential is the same as voltage, so they're the same thing. Thus my statements in the previous paragraph hold.

A: In physics voltage is usually defined as potential difference between two points of a circuit:
$$V_{ab}=\phi_a-\phi_b.$$
In other words:

*

*potential is a potential energy per unit charge measured in respect to an agreed reference point (e.g., an infinitely remote point), i.e. work done when bringing the charge from this point

*voltage is the work done when moving a charge between the two specified points.

One typically has the same reference point for all the potentials, but voltages can be defined between any two points.
Finally, potential is an extremely general concept, used to describe electric and electromagnetic phenomena well beyond circuit theory, whereas voltage is a term mainly limited to specific applications.
Update
The question has been further discussed in the comments, and it was agreed that much of my answer indeed reiterates the information already given in the OP. I therefore state below the main point, as it came out of the discussion:

One can say that potential is a voltage between the point of interest and the reference point. I think the real difference is indeed the usage: one will rarely speak of voltage in atomic or nuclear physics, but in case of semicodnuctor nanostructures the term is rather used. Some may say that potential is "more scientific term", as opposed to engineering.

A: No, when they are properly defined (see the IEC definitions below) voltage and potential difference are in general not the same, even though they can be considered the same in the majority of situations in electronics and quite often even in physics.  The root of their difference resides in the presence (and relevance) of changing magnetic fields within the considered system.
Let's start from the physical quantity they are both intended to represent: the work per unit charge that is done against the field E (hence the minus sign) in order to go from point A to point B. This quantity is computed as a path integral and is in general path dependent, therefore we will have to specify the particular path $\gamma_{A->B}$  along which the integration takes place.
$$
 - \int_{\gamma_{A->B}}\vec{E}.\vec{dl}
$$
Following the IEC (if we ignore the sign convention) we will call this general path dependent quantity "voltage" and we will denote it by the symbol V with a subscript that specifies the path:
$$
V_{\gamma_{A->B}}= - \int_{\gamma_{A->B}}\vec{E}.\vec{dl}
$$
Note that the electric field $\vec{E}$ that appears inside the integral is the one and only electric field a charge experience along a specific point along the path. We could call this the 'total electric field' (the reason for this specifier will be made clear shortly.)
Conservative fields: voltage and PD are the same
If our physical system resides in a region of space where there are no changing magnetic fields, the electric field is conservative and we can introduce a potential function $\phi$ such that
$$
\vec{E}=\vec{E}_{c}=-\nabla\phi
$$
and the above path integral will be a function of the endpoints alone and not the path joining them.
$$
V_{\gamma_{A->B}}= - \int_{\gamma_{A->B}}\vec{E}_{c}.\vec{dl}=- \int_{A}^{B}-\nabla\phi.\vec{dl}=\int_{A}^{B}\nabla\phi.\vec{dl}=\phi_B-\phi_A
$$
That is, in the conservative case, voltage (the path integral of E along a path joining two points) can be expressed as a potential difference (the difference in the values assumed by the electric scalar potential $\phi$  at the endpoints.) In this sense, the scalar electric potential is a specialization of the more general concept of voltage.
In lumped circuit theory, where we deal with conservative electric fields (and we hide the nonconservative part inside the lumped inductive and magnetic components) there is no difference between V and phi and the (scalar) potential difference is the same thing as the voltage along any path joining A and B: since it does not depend on the path, we can use the term 'voltage difference' to denote the work per unit charge done on a charge that goes from point A to point B. It is also customary to (ab)use the same symbol V (which denotes voltage) for the scalar potential $\phi$, so that the above scalar potential difference can be written $V_B-V_A$ or, in short, $V_{BA}$.
The path independence implies that the circulation of a conservative field $\vec{E_c}$ along any closed path be zero:
$$
\oint_{any \ closed \ path}\vec{E}_{c}.\vec{dl}=\int_{A}^{A}\nabla\phi.\vec{dl}=\phi_A-\phi_A=0
$$
Nonconservative fields: PD is not enough
But the above relation is not true in general. In fact, for a generic nonconservative electric field $\vec{E}$ in a non-motional context, the relevant Maxwell equation in integral form is
$$
\oint_{\Gamma} {\vec{E}.\vec{dl}}=-\frac{\partial}{\partial t}\iint_{\Sigma}{\vec{B}.{dS}}
$$
where the closed path $\Gamma$ is the boundary of the surface $\Sigma$. Note that here $\vec{E}$ is the total electric field that can be seen,  according to Helmoltz's decomposition theorem, as the composition of an irrotational (conservative) and a solenoidal (non conservative) part
$$
\vec{E} = \vec{E}_{irr} + \vec{E}_{sol} = \vec{E}_c + \vec{E}_{nc}
$$
If we substitute this generic decomposition of E into the above equation, since the conservative part has a circulation that is zero, we get
$$
0 +\oint_{\Gamma} {\vec{E}_{nc}.\vec{dl}} = -\frac{\partial}{\partial t}\iint{\vec{B}.{dS}}
$$
or, by expressing the magnetic field B in terms of its vector potential A and invoking Stokes' theorem
$$
\oint_{\Gamma} {\vec{E_{nc}}.\vec{dl}} = -\frac{\partial}{\partial t}\iint{\nabla\times \vec{A}.{dS}}=-\frac{\partial}{\partial t}\oint{\vec{A}.{dl}}
$$
In a non-motional context where the closed path $\Gamma$ does not change its shape the above relation tells us that $\vec{E}_{nc} = -\partial{\vec{A}}/\partial{t}$.
With this expression for the non-conservative component of the total electric field,  we have
$$
\vec{E}=\vec{E_c}+\vec{E_{nc}}=-\nabla\phi-\partial{\vec{A}/\partial{t}}
$$
Substituting this in the general expression of voltage as the path integral of the total field along a path gamma (in a non-motional context) we get:
$$
V_{\gamma_{A->B}}= - \int_{\gamma_{A->B}}\vec{E}.\vec{dl}
=- \int_{\gamma_{A->B}}\vec{E_c}.\vec{dl}- \int_{\gamma_{A->B}}\vec{E_{nc}}.\vec{dl} \\ =\int_{A}^{B}\nabla\phi.\vec{dl}+\int_{\gamma_{A->B}}\partial{\vec{A}}/\partial{t}.\vec{dl}
$$
The first integral is the difference in scalar potential, so we conclude that, in presence of a variable magnetic field:
$$
V_{\gamma_{A->B}}=(\phi_B-\phi_A)+\int_{\gamma_{A->B}}\partial{\vec{A}}/\partial{t}.\vec{dl}
$$
That is, voltage (the path integral of the total electric field along a specific path) is the sum of the electric scalar potential difference (which is the path integral of the conservative part ) and the contribute to the emf along that path (which is path-dependent integral of the non-conservative part).
If one wants to recover the emf, they need to specify a closed path - the potential difference will go to zero and the result is the emf associated with that particular closed path.
If one is interested in the scalar potential difference alone, they need to remove the non-conservative component $\vec{E}_{nc}$ from the total electric field $\vec{E}$ and compute the path integral of
$$
\vec{E_c}=\vec{E}-\vec{E_{nc}}=\vec{E}-(-\partial{\vec{A}}/\partial{t}) \\
=\vec{E}+\partial{\vec{A}}/\partial{t}
$$
That plus sign before the time derivative of A makes it seem that the Ec field is somewhat some sort of resultant field, while in reality it is just a component of the total field E.
Conclusion
The confusion around the concepts of voltage and scalar potential stems from the fact that so many engineering books use the same symbol (usually V) to denote the path integral in the conservative and nonconservative cases. Defining voltage as above is a simple way to make the two terms coexist with each other in a way that is consistent with Helmoltz's decomposition theorem.  Apart from a sign convention, the above definitions of voltage, potential difference and emf are those given by the International Electrotechnical Commission (IEC):
IEC definition of voltage
IEC definition of (scalar) potential difference
IEC definition of induced voltage
(in the IEC definition of induced voltage - the path integral of the nonconservative part - it is contemplated the possibility of motional induction).
To summarize: voltage as the path integral of the total electric field is the more general quantity (and it comes from the definition of work done on a charge), while the (scalar) potential difference is a specialization that is valid only where the electric field is conservative. In lumped circuit theory we can afford the luxury of confusing these two quantities (there is a way to treat the emf contribute of a coil as if it were a voltage drop), but there are unlumpable circuits - like the Lewin ring - where this is no longer the case.

A: I think there is a semantic distinction to be made between potential and voltage/potential difference. The former is a property associated to a single point, while the latter is a property associated to an ordered pair of points.  You argue that these are the same because the former still requires some zero point to be specified, but that's not quite true.
For example, consider the electric potential due to a point charge at the coordinate origin, $\phi(\mathbf r) = \frac{q}{4\pi\epsilon_0 |\mathbf r|}$, where I've chosen $\lim_{|\mathbf r|\rightarrow \infty} \phi(\mathbf r) = 0$.  Note that there are in fact no points in space where $\phi(\mathbf r)=0$. On the other hand, the voltage between any two points at the same distance from the origin is equal to zero.
You might say, "well, $\phi(\mathbf r)=0$ at infinity, which I consider to be a point." However, it is generally not possible to do this, e.g. if the potential doesn't approach the same limit in every direction as $|\mathbf r|\rightarrow \infty$, or if the potential doesn't approach any limit at all, as is the case for an infinite wire.  Even if you can do this, there's no reason that you should have to choose the potential to vanish there; for example, the choice $\phi(\mathbf r) = \frac{q}{4\pi\epsilon_0 |\mathbf r |}+V_0$ (with $V_0>0$) is also a perfectly valid choice for the electric potential due to a point charge at the origin, but now it's not zero anywhere even if we do include the point at infinity.
Now, you could certainly say that it's always possible to choose some $\phi(\mathbf r)$ to vanish somewhere (say, $r_0$), and that the potential at a point $\mathbf r$ is equal to the voltage between the points $\mathbf r$ and $\mathbf r_0$.  However, (i) you certainly don't need to do this, and (ii) even if you do, the fact remains that potential is a property of a single point while voltage is a property of two points, which (at least to me) is a perfectly clear reason to say that potential and voltage are two distinct things which are very, very intimately related to one another.


text:
Q: Could not register pre-delete validatation plugin step for the Team entity in MS Dynamics CRM 2011 I want to add validation before Team entity deletion. In order to do that, I need to add Pre-validation plugin step for the Delete message and Team entity.
Nevertheless, when I'm trying to do it via the Plugin Registration Tool, I'm getting an error:

Invalid Entity Name
Invalid Primary Entity or Secondary Entity specified. Please re-enter the data.

Here is the data I'm filling in the Register New Step:

*

*Message: Delete

*Primary Entity: team

*Secondary Entity: none

*Run in User's Context: Calling User

*Execution Order: 1

*Eventing Pipeline Stage of Execution: Pre-validation

*Execution Mode: Synchronous

*Deployment: Server

I'm using Microsoft Dynamics CRM 2011.
I could not find any explanation for that. What I'm asking is:

*

*What is the reason for that?

*What is the intended way of applying custom validations during the deletion of the Team entity?

A: That's because Delete Message for Team Entity in CRM 2011 is not supported

Whereas when you look for CRM 2016 and above Team Entity does support delete Message

Summary: CRM 2011 Team Entity does not support Delete Message

A: It is possible to enable registering the plug-in by updating the corresponding SdkMessageFilterBase record.

*

*Connect to your DB server.

*Navigate to your %ORGANIZATION_NAME%_MSCRM DB.

*Run the script:

  SELECT
      [dbo].[SdkMessageFilterBase].[PrimaryObjectTypeCode],
      [dbo].[SdkMessageFilterBase].[CustomizationLevel],
      [dbo].[SdkMessageFilterBase].[SecondaryObjectTypeCode],
      [dbo].[SdkMessageFilterBase].[IsCustomProcessingStepAllowed],
      [dbo].[SdkMessageFilterBase].[Availability],
      [dbo].[SdkMessageFilterBase].[SdkMessageId],
      [dbo].[SdkMessageFilterBase].[IsVisible]
  FROM
      [dbo].[SdkMessageFilterBase]
      INNER JOIN [dbo].[SdkMessageBase]
          ON [dbo].[SdkMessageFilterBase].[SdkMessageId] = [dbo].[SdkMessageBase].[SdkMessageId]
  WHERE
      [dbo].[SdkMessageBase].[Name] = 'Delete' AND
      [dbo].[SdkMessageFilterBase].[PrimaryObjectTypeCode] = 9 -- Team entity code is 9

*Check the result. If IsCustomProcessingStepAllowed field is set to 0, it is preventing you from registering the plug-in step.

*Update IsCustomProcessingStepAllowed to 1 to be able to register custom plug-in step.

This solution worked for me.
Articles describing such solution:

*

*Enabling plug-in for Change Business Unit and Change Manager for systemuser entity


text:
Q: Is there a way to force the mouse to act like a touchscreen? I'm getting very annoyed at the way Windows behaves differently depending on whether or not it thinks you have a touch screen.
Using the mouse is very clunky and I would like to get the mouse to imitate touch but I cannot find a setting or options to get Windows to behave the way I want it to. what I mean by this is that when you hold down the left mouse button (in a default setup) and move the mouse it should act as if you were touching the screen with a single fingertip.
Example 1: On a touch screen I can swipe from right to left to get the charms to appear, with a mouse I have to bash it down to the bottom corner and wait for the charms to appear. The actions should be the same but they are not.
Example 2: On a touch screen I can swipe the All Apps screen to move left/right. with a mouse I have to click in the scrollbar on the bottom of the screen.
Counter Example 3: Perversely the lock screen works exactly how I'd expect it to. I can swipe with a touch screen and swipe with a mouse.
It's especially annoying on the multi monitor and multi-PC systems I have been using for the last five years.
So is there a way to force Windows 8 to accept mouse input as if it were touch input?
Edit: In case it's a specific mouse/laptop issue I'm using an HP Probook 4540s with a budget Microsoft wired mouse
Update: Please do not suggest keyboard alternatives. I already know what they are. I'm trying to find a way to do things without using the keyboard.

A: I quite sure that it isn't possible to have a mouse function in the way you wanted it to, unless you could somehow find a pen tablet driver that is compatible with mice as well as tablets while having the same functionality between the two (which I'm quite sure doesn't exist). The closest I'd say you are to getting touchscreen functionality is actually getting a touch screen- or the next best thing, a tablet, like this one here: http://www.wacom.com/products/pen-tablets/bamboo/bamboo-capture. They come in varying sizes and prices, and provide touchscreen-like capabilities. The tablet that I linked to (above) is compatible with Windows Touch input and therefor can be programed to function exactly like a touch display.

A: If you haven't already you might look into mouse gestures.  You generally make gestures by holding right-click and then move the cursor. StrokeIt is old but does this sort of thing pretty well on Windows 7.
I found this page on makeusof.com that describes a different gesture to get to the charms menu.  It's not similar and to the touch gesture and I agree that it should be.
For the record, the charms gesture is a move to the top-right down and then swipe down.


text:
Q: How can I overwrite my file images in laravel I would like to ask how can i overwrite/update my images inside the form and store in database? I tried doing it but it is not working, i get the id correct but when i upload new image and text, it is not updating my old file. Below i attached my code.
company controller
 public function update(Request $request, $id)

{

    $this->validate($request, [
        'company_logo' => 'required|image|max:2048',
        'company' => 'required',

    ]);
//    dd(123);
    $company = Company::find($id)->first();
    // dd($company);

    // $company = Company::where(['companies.id' => $id])->first();
    if($request->file != '')
    {
        $path = public_path().'/uploads/images/';
        $file = $request->file;
        $filename = $file->getClientOriginalName();
        $file->move($path, $filename);

        $company->update(['file' => $filename]);
        return redirect()->route('company.index');
        $company->file = $path.$filename;
    }

    $company->company = $request->company;
    $company->save();

    return redirect()->route('company.index');

}
public function insert_logo(Request $request)
{
    $company = new Company();

    $company->company    = request('company');
    $company->company_logo    = request('company_logo|file|image|max:10,485,760');

    // uploading image file to database
   if
   ($file = $request->hasFile('company_logo')) {
       $file = $request->file('company_logo');

       $filename = time() . '.' .$file->getClientOriginalName();
       $destinationPath = public_path('/uploads/images/');

       $file->move($destinationPath, $filename);
       $company->company_logo = $filename;
   }
   $company->save();
   return back();

}

edit modal for company

            Edit Company

    <form action="{{ route('company.update', $company->id) }}" method="post">
        @csrf
        @method('PUT')

                Company Logo

                                <input type="file" name="company_logo"/>

                    <input type="text" placeholder="Company Name" name="company"
                    class="input w-full border col-span-4 form-control tail-select" value="{{ $company->company}}">

                    <button type="button" data-dismiss="modal"
                    class="button w-24 border text-gray-700 dark:border-dark-5 dark:text-gray-300 mr-1">Cancel</button>
                    <button type="submit" class="button w-24 bg-theme-1 text-white">Update</button>

    </form>

I might be wrong inside the function but I am not sure where it went wrong. so far only the company name is showing, but still even if I change my company name, and click button update, it wont overwrite my old one

A: Form Tag missed enctype="multipart/form-data"
<form enctype="multipart/form-data" action="{{ route('company.update', $company->id) }}" method="post">

once you called find then no need first so remove ->first()
 $company = Company::find($id);

It should be $request->company_logo not $request->file
  $company = Company::find($id);
     if($request->hasFile('company_logo'))
        {
            $path = public_path().'/uploads/images/';
            $file = $request->company_logo;
            $filename = $file->getClientOriginalName();
            $file->move($path, $filename);

            $company->company_logo =$path.$filename;

        }
       $company->company = $request->company;
       $company->save();
       return redirect()->route('company.index');

Usually full path is not saved in db.Better only save filename so that you can keep base path in filesystem configuration.


text:
Q: Remove duplicates from data downloaded from query in Excel using Excel VBA I have made a query to download data from a website which has record of past 60 days data. But i need to store values of past 240 days after that whenever new data is fetched the oldest data should get automatically deleted. For that to happen i tried moving 60 days data(Originally recieved in A4:A63) to a new location (A184:A243) and cleared contents A4:A63 first.... then next batch of Data recieved in A4:A63 is moved to location (A124:A183) and cleared contents A4:A63...... then next batch of Data recieved in A4:A63 is moved to location A64:A123 and Cleared contents A4:A63. In this way 240 days of data is stored. After that whenever new batch of Data is fetched from website the latest data gets stored and the oldest one gets deleted its just like First in First out. Here is the code that i made
`
Sub ShiftData()
Dim i As Integer
If IsEmpty(Range("A4").Value) = True Then                      '<== To Check new data is present
MsgBox ("No Input to shift")
Else
If Range("A" & 243).Value = "" Then                            '<== Data shifted to last place
Range("A243:A184") = Range("A63:A4").Value
Range("A63:A4").ClearContents
ElseIf Range("A" & 183).Value = "" Then   '<== If last place is occupied data shifted to lastmost empty place
Range("A183:A124") = Range("A63:A4").Value
Range("A63:A4").ClearContents
ElseIf Range("A" & 123).Value = "" Then
Range("A123:A64") = Range("A63:A4").Value '<== If last place is occupied data shifted to lastmost empty place
Range("A63:A4").ClearContents
End If
If Not IsEmpty(Range("A4:A63").Value) = True Then
If Range("A243") <> "" And Range("A183") <> "" _
And Range("A123") <> "" And Range("A63") <> "" Then '<== To check if all places are filled.
Range("A243:A124") = Range("A183:A64").Value       '<== Shifted all data to flush out oldest data
Range("A123:A64") = Range("A63:A4").Value
Range("A4:A63").ClearContents
End If
End If
End If
End Sub`

The problem i am facing here is that with every feed from website i get only one to four rows of new data i.e 60th day rest of the data (59 days) is same. So if i stack like this i am getting multiple duplicates which is creating problem in my analysis. I want to get only fresh data to stack up and ignore duplicate data. Let me explain this with an example taking 3 new rows at a time so as to make easy understanding. enter image description here


text:
Q: How to calculate a distance in python on 2 words I have to extract a database and put it in a script in python.  I did it for all name of database.
Now I have to calculate the difference of letter between the name 1 and the name 2   and between the name 1 and the name 3 .... and between the name  2 with the name 3 .....
I did it for the moment.
I show you what a little part about what  I did who gives me a problem :
valeur = []

c.execute("""SELECT  NAME FROM AUTHORS""")
rows = c.fetchall()
for row in rows:
    valeur.append(row)
x=0
liste=[]
for x in range(len(valeur)):
    for i in range(x+1,len(valeur)):
        ed = nltk.edit_distance(valeur[x],valeur[i])
        dico={"titre":valeur[x],"titre_compare":valeur[i], "distance":ed}
        dico["titre"],"&&",(dico["titre_compare"]),"&&",(dico["distance"])
        print(dico["titre"],"&&",(dico["titre_compare"]),"&&",(dico["distance"]))

And the result is here

('Khālid Muḥammad ʻAlī al-Ḥājj',) && ('K. Hardono',) && 1
('Khālid Muḥammad ʻAlī al-Ḥājj',) && ('Nūr al-Dīn Ṣammūd',) && 1
('Khālid Muḥammad ʻAlī al-Ḥājj',) && ('Mawlūd Qāsim Nāyit Bulqāsim',) && 1
('Khālid Muḥammad ʻAlī al-Ḥājj',) && ('Ali Ak',) && 1
('Khālid Muḥammad ʻAlī al-Ḥājj',) && ('Nazamī Rāmajī',) && 1

My problems are why I have only 1  at the end of the comparaison between the 2 words and why I have a "," at the end of the words,  It should be different and I don't unterstand why I got this.  I did the same code of a different database with tittle of books and it worked.
Thanks you very much if you can help me !

A:
why I have a "," at the end of the words

You have tuples that contain a single string, instead of just having the strings. The reason you have these is because you got them from a database query, which gives you each row in a tuple, no matter how many columns there are.

why I have only 1 at the end of the comparaison between the 2 words

This appears to have the same cause: nltk is being given the wrong sort of data. It would compare strings character by character; it compares tuples element by element. There is one element in each tuple, and they are different between the two tuples, so of course the result is 1.

A: your issues are caused by the fact cursor.fetchall() returns all the rows as a list of tuples, to solve this  you can use:
valeur = [r[0] for r in rows]

@KarlKnechtel already explained why you get your output in that form

A: Thanks for your answer,  So I dit it :
valeur=[]

req = "select * from AUTHORS"
result = c.execute(req)
print(type(result))
for row in result:
    #print(row[1])
    #print(row[2])
    valeur.append(row[0])

x=0
liste=[]
for x in range(len(valeur)):
    for i in range(x+1,len(valeur)):
        ed = nltk.edit_distance(valeur[x],valeur[i])
        dico={"titre":valeur[x],"titre_compare":valeur[i], "distance":ed}
        (dico["titre"],"&&",(dico["titre_compare"]),"&&",(dico["distance"]))
        double=dico["distance"]+dico["distance"]
        print(dico["titre"],"&&",(dico["titre_compare"]),"&&",(double))

and it works perfectely  but  I have not the name, I have it :
/authors/OL1022167A && /authors/OL1022282A && 6
/authors/OL1022167A && /authors/OL102236A && 4
/authors/OL1022167A && /authors/OL102364A && 6
/authors/OL1022167A && /authors/OL1023681A && 8

But me I want the name and here it's not the name. SO I tried to say
"select name from authors"
But when i said it , it doesn't work. So I tried other things but it always doesn't work. I would like to know How I can do like I did but only for  name and not for key.
Thanks again and thanks for your previous answer !!!!


text:
Q: How to feed mysql queries from bash I'm trying to make a bash script that creates a mysql user and database but I can't find a way to feed the sql into mysql, I'm trying with this format:
mysql < echo "query"

But that is not working, see the example below:
mysql --host=localhost --user=user --password=password < echo "CREATE USER 'testuser'@'localhost' IDENTIFIED BY  'jakdJxct8W';
CREATE DATABASE IF NOT EXISTS 'testuser_dev' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON  'testuser_dev' . * TO  'testuser'@'localhost';
CREATE DATABASE IF NOT EXISTS 'testuser_qa' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON  'testuser_qa' . * TO  'testuser'@'localhost';"

How to feed mysql with the queries?

A: Have you tried mysql -e query?

A: Try like this:
echo "select 1" | mysql

A: Try using a here document like this:
mysql --host=localhost --user=user --password=password << END

CREATE USER 'testuser'@'localhost' IDENTIFIED BY  'jakdJxct8W';
CREATE DATABASE IF NOT EXISTS 'testuser_dev' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON  'testuser_dev' . * TO  'testuser'@'localhost';
CREATE DATABASE IF NOT EXISTS 'testuser_qa' DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
GRANT ALL PRIVILEGES ON  'testuser_qa' . * TO  'testuser'@'localhost';

END

Alternatively place all you commands in text file and run it:
mysql --host=localhost --user=user --password=password < commands.sql

A: mysql --batch --silent -e 'SHOW TABLES';

Batch and silent are handy if you are planning to pipe the output

A: The reason your attempt did not work was because the < expects a file name and you fed it a string. You would have to do something like
echo "YOURQUERYSTRINGHERE">tmpfile
mysql --host=localhost --user=user --password=password dbname <tmpfile

ken's suggestion of
 mysql  --host=localhost --user=user --password=password -e "QUERY" dbname

can work, but if you try to use bash variables in your query you can fall foul of parameter expansion. eg
QUERY="select * from $MYTABLE WHERE name=\"silly@place.com\";"
mysql --host=localhost --user=user --password=password -e "$QUERY" mydbname

may not do what you expect.
One option is use
echo "$QUERY"|mysql --host=localhost --user=user --password=password mydbname

which works if the query string contains appropriate quoting. Another option is the "here" document as suggested by dogbane.

A: cat <<EOD | mysql [-u user] [-ppassword] [database]
  select 1;
  select 2;
  select 3;
EOD

in your case
cat <<EOD | mysql -u root -p
    CREATE DATABASE IF NOT EXISTS testuser_dev DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
    GRANT ALL PRIVILEGES ON  testuser_dev.* TO  "testuser"@"localhost";
    CREATE DATABASE IF NOT EXISTS testuser_qa DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
    GRANT ALL PRIVILEGES ON  testuser_qa.* TO  "testuser"@"localhost";
    FLUSH PRIVILEGES;
EOD

A: For big queries in a bash script, you can try:
read -d '' SQL_QUERY_1 << EOF

SELECT prod.id as id, prod.title as title, comp.name as company, pho.id as photo_id, pho.image as photo_name
FROM products as prod
JOIN accounts as comp
ON comp.id = prod.account_id
JOIN photos as pho
ON pho.id = prod.featured_photo_id;

EOF

echo ${SQL_QUERY_1} | mysql


text:
Q: My React Native app is not working ,getting Failed on executing 77% - (Task :react-native-payments:compileDebugJavaWithJavac FAILED) I am working on app , it is opening before a few days ago but now it is getting failed on executing after 72% and showing below error.
------------------ Error -----------------------
What went wrong:
Execution failed for task ':react-native-payments:compileDebugJavaWithJavac'.
Task :react-native-payments:compileDebugJavaWithJavac FAILED

A: This error occurs when some plugin has old android support dependencies instead of using the new AndroidX equivalent.
To fix this issue, Migrate to AndroidX by the help of jetifier by running following command
npx jetify

from root of your project folder before taking build.


text:
Q: исключение обратной взаимосвязи в Django Есть модель пользователя:
class Person(models.Model):
    name = models.CharField('Имя', max_length=100)
    surname = models.CharField('Фамилия', max_length=100)
    patronymic = models.CharField('Отчество', max_length=100)

Есть модель ресурсов:
class Resource(models.Model):
    title = models.CharField('Название', max_length=30)
    slug =  models.SlugField('Slug', max_length=30, unique=True)
    persons = models.ManyToManyField(Person, blank=True, related_name='resource')

Требуется написать функцию во views, которая будет делать выборку всех пользователей, у которых еще нет ресурса:
def res_creater(request):
    person_list = Person.objects.filter(status='A').exclude()
    return person_list

Знаю, что написал related_name='resource', но не могу понять как вывести обратную связь. В шаблоне спокойно использую data.persons.all для вывода всех пользователей, имеющих ресурсы. Подскажите, пожалуйста, что писать в exclude() ?

A: Вот пример, который я использовал в своём проекте, общепринятая практика.
# Выберет всех Person, у которых resource отсутствует.
person_list = Person.objects.filter(resource__isnull=True)

Требуется написать функцию во views, которая будет делать выборку всех полььзователей, у которых еще нет ресурса

Проверено.

A: Не уверен что это самый лучший вариант, но вашу проблему скорее всего решит
person_list = Person.objects.exclude(id__in=Resource.objects.values_list('persons__id', flat=True))

A: Немного разобравшись, пришел к такому коду:
def res_creater(request, slug):
    i = Resourсe.objects.get(slug=slug)
    person_list = Person.objects.filter(status='A').exclude(resource__id=i.id)
    return person_list

Возможно есть еще вариант решения?


text:
Q: General formulation of the product arbitrary moment generating functions X and Y Given that X and Y are independent random variables, with moment generating functions M and N, respectively, is there a generic formula to produce the moment generating function of X*Y?

A: You could use the law of total expectation. For instance, if $Y$ is a discrete r.v
\begin{align}
M_{XY}(t) = \mathbb{E}[e^{tXY}] &= \sum_{y} \mathbb{E}[e^{tXY}|Y=y]\mathbb{P}[Y=y] \\
&=\sum_{y} \mathbb{E}[e^{tXy}]\mathbb{P}[Y=y] \\
&=\sum_{y} M_{X}(ty) \mathbb{P}[Y=y],
\end{align}
where the second equality follows from the independency of $X$ and $Y$. Similarly, for a continuous r.v $Y$ with density $f_Y$,
$$M_{XY}(t) = \int_{y} M_X(ty)f_Y(y)dy.$$


text:
Q: How to translate QgsMapCanvas coordinates to wgs-84? My application uses QgsMapCanvas.
I've got point coordinates in wgs-84 crs and i need to add this point to vector layer (represents postgis table) inside of the canvas.
Have no idea how to transform correctly wgs-84 coordinates to canvas/layer crs.
Can anyone help me? Is there any python/c++ examples?


text:
Q: How to prove the equivalence of these two equations in modular arithmetics? We have to prove that $$ x^4 \equiv -1 \pmod p $$ iff $$ p \equiv 1 \pmod 8 $$where $p$ is an odd prime.
I am stuck at proving that $$ \gcd(4, p - 1) \mid (p-1)/2 $$ is equivalent to $$ 8 \mid (p - 1). $$

A: It's fairly obvious, to me, the question is not intended for you to prove it for all $x \neq 0 \pmod p$ since, for $x = 1$, you have $x^4 = 1$. This means $x^4 \equiv -1 \pmod{p}$ can only be true for the prime $p = 2$.
Instead, I believe a more appropriate wording of what the question intended is that for odd prime $p$, there exists an integer $x$ where $x^4 \equiv -1 \pmod{p} \iff p \equiv 1 \pmod{8}$.
For the $\implies$ direction, you have the right idea, as also indicated in the question comments. Squaring gives
$$x^8 \equiv 1 \pmod{p} \tag{1}\label{eq1A}$$
This means the multiplicative order of $x$ modulo $p$ must divide $8$. Since the only smaller factors of $8$ are $1$, $2$ and $4$, where $x$ to any of those powers can't be congruent to $1$, you get $8$ must be the multiplicative order of $x$ modulo $p$.
Since the multiplicative order must divide the Euler's totient function value, which is $p - 1$ for primes, means you have
$$8 \mid p - 1 \implies p \equiv 1 \pmod{8} \tag{2}\label{eq2A}$$
For the $\impliedby$ direction, since $p$ is a prime, there is an element $g$ which is a primitive root and, thus, also generator of the multiplicative group of non-zero remainders. This means there exists an integer $1 \lt j \lt p - 1$ where
$$g^{j} \equiv -1 \pmod{p} \implies g^{2j} \equiv 1 \pmod{p} \tag{3}\label{eq3A}$$
As $g$ is a primitive root, this means its multiplicative order is $p - 1$ so $p - 1 \mid 2j$. However, $j \lt p - 1 \implies 2j \le 2(p - 1)$, means
$$2j = p - 1 \tag{4}\label{eq4A}$$
Since $p \equiv 1 \pmod{8}$, there exists a positive integer $k$ such that $p = 8k + 1$. Using this in \eqref{eq4A} gives
$$2j = 8k \implies j = 4k \tag{5}\label{eq5A}$$
Thus, \eqref{eq3A} gives
$$g^{4k} \equiv -1 \pmod{p} \implies (g^k)^4 \equiv -1 \pmod{p} \tag{6}\label{eq6A}$$
You therefore have $x \equiv g^k \pmod{p}$ satisfying $x^4 \equiv -1 \pmod{p}$.


text:
Q: Всплывающее меню поверх Acticity Я хочу сделать всплывающее меню/окно, которое не закрывает полностью активити(есть отступы) + при нажатии кнопки в этом самом меню оно закрывалось бы

A: DialogFragment
Ну и упрощенный пример.
Создаем подкласс DialogFragment, в рамках вопроса важными являются методы onStart() и onCreateDialog(), ими определяются размеры, вид, поведение диалога. Передачу данных в диалог, осуществляем аналогично обычным фрагментам, опять же по простому, в демонстрационных целях, newInstance(...), onCreateDialog(...)
public class SomeDialogFragment extends DialogFragment {
    private static final int MARGIN_H = 100;
    private static final int MARGIN_V = 200;

    private String name;

    static SomeDialogFragment newInstance(String text) {
        SomeDialogFragment fragment = new SomeDialogFragment();
        Bundle args = new Bundle();

        args.putString("name", text);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        //dialog.setCancelable(true);
        //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //dialog.getWindow().setBackgroundDrawable(?);

        name = getArguments().getString("name");

        return dialog;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_something, container, false);

        setupUI(name);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        if (getDialog() != null) {
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            int width = displayMetrics.widthPixels;
            int height = displayMetrics.heightPixels;

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(getDialog().getWindow().getAttributes());
            lp.height = height - MARGIN_V;
            lp.width = width - MARGIN_H;
            // На "весь" экран, поверх Activity, с отступами от края экрана
            getDialog().getWindow().setAttributes(lp);
        }
    }

    private void setupUI(String name){
        //UI

    }

}

Когда надо вызываем:
void showSomeDialog() {
    DialogFragment someDialog = SomeDialogFragment.newInstance("Привет, я dialog fragment, как ты хотел");
    someDialog.show(getFragmentManager(), "somedialog");
}

А "кнопку" добавить, думаю не проблема.


text:
Q: MySQL Count of Grouped data joined across multiple tables As a SQL novice just trying to piece things together, I feel there is a more elegant solution to this that I cannot seem to come up with. I've found many examples that seem similar but not exact, and despite that, my query always ends up a mess and doesn't work out. The structure I am dealing with is three tables as outlined in the following with brief examples. A users table with unique id's and various chapter numbers and a member_status of either "SN", "SC', or "GS". A chapters table with unique id's and various province id's. My third table that would be referenced would be my provinces table with the only contributing factor being a list of unique province id's. My user table is an extremely large data set and I am concerned about any use of subqueries or other issues that may affect speed. Some promising examples use Distinct with the Count, but I can't get it organized correctly if so.
My ultimate goal is also exampled below but is to get a Count of all members with a status IN ("SC","SN") who are in chapters that are in a specific province. I know that I have to have my table_users.chapter JOINED to table_chapters.id. I think I also need to have my table_chapters.province_id JOINED to table_provinces.id. Between the potential Count and Group By aspects, I just get lost and any help would be appreciated. I'd be happy to supply additional information if requested.
I've taken a shot at loading my data in SQLFiddle if it helps.
Check here for SQLFiddle schema
Data Schema
table_users
id | chapter | member_status
---------------------
1  |   101   |   GS
2  |   101   |   SN
3  |   101   |   SC
4  |   102   |   SN
5  |   102   |   GS
6  |   103   |   SC
7  |   103   |   SC
8  |   104   |   SN
9  |   104   |   SN
10 |   104   |   SC
11 |   105   |   GS
12 |   105   |   SC

table_chapters
id   | province_id
-------------------
101  |     1
102  |     2
103  |     2
104  |     1
105  |     3

table_provinces
table_provinces just with sequential list by id

Desired Output
Province id | Count of Members
------------------------------
      1     |       5
      2     |       3
      3     |       1

Notice the output ignores status of "GS"

A: If I understand you correctly, you want the count of all user record matched with chapter in other table.
Try this:
select c.province_id,count(u.member_status) as member_count from users u
inner join chapters c on u.chapter=c.id
where u.member_status in ('SC','SN')
group by c.province_id

SQL Fiddle: http://sqlfiddle.com/#!9/4da100/5


text:
Q: Ansible, concatenating files I have an ansible playbook with different roles. In each role I would like to add several lines to the same configuration file. For example, adding sections to a ini file:

[section]
param1=value1
param2=value2

What would be the best way to accomplish this?
Is it possible to concatenate template pieces? For example:

[section]
param1={{ value_var1 }}
param2={{ value_var2 }}

A: By your example i would do like this
- name: Checking is applied aleady
  shell: grep "ANSIBLE_ROLE_X_APPLIED" /path/to/file
  ignore_errors: yes
  register: grep_role_x_applied

- name: Applying changes in file
  lineinfile: dest=/path/to/file line='{{ item }}'
  when: grep_role_x_applied.stdout == ""
  with_items:
    - '; ANSIBLE_ROLE_X_APPLIED'
    - '[section]'
    - 'param1=value1'
    - 'param2=value2'

Of course in each role you have diferent tags like ANSIBLE_ROLE_X_APPLIED
Or something based on this idea
EDIT: If this is really ini file - i better play with ansible core module ini_file


text:
Q: most efficient method of loading images for image gallery page I'm working on an asp.net mvc project that includes a page with an image galley. The page will load with one main medium sized image and 12 thumbnails. If a user clicks on a thumbnail, the image will display in the medium sized image div. If a person clicks on the medium sized image, a larger sized image will open in a popup window. Potentially the page could require 36 images (12x thumbnail, 12x medium, 12x large). I'm wondering what logically the most efficient way (performance vs. user experience) to load the three sized images would be?

*

*Do I pass all three sizes of the images needed on the page to the view upon the initial page load?

OR

*Do I load only the images required for the initial view, and retrieve the additional images 'as-needed' via AJAX?

A: The best approach often depends on your goals and the bandwidth of your clients and how that bandwidth is billed to the client.
If you go with option one, I'd recommend only loading the required images at first and then after the page renders, then asynchronously loading the remaining images via javascript.  That way you don't end up slowing down the visible images to load initially invisible ones.
But the downside to loading all the images (whether part async or not) is that mobile users who may have bandwidth costs for the extra images will be forced to download all the images even if they never use most of them.
So especially if you will have mobile visitors, option 2 if often more appealing.  The only downside is that when a non-loaded image is needed it will take a bit longer to display it since it has to be downloaded first.  Often this is an acceptable tradeoff to preloading all the images, at least on mobile devices.
But as I say, it all depends on what the website should be optimized for.  For desktop visitors (i.e non mobile), the best experience is often to load the needed images, render the page, then async load the other images.  This gives them a fast initial rendering of the needed images, and if they later needs one of the other images it's available for display instantly since it was preloaded in the background.
Hope that helps.


text:
Q: WxPython. ListCtrl. Insert button - Python 1) It is possible to insert somehow the button in each line of the certain column of object wx.ListCtrl?
2) Why is it possible to edit the value of a string only in the first column? Initializing wx.ListCtrl:
self.m_listCtrl_number = wx.ListCtrl(self.panel, wx.ID_ANY, wx.DefaultPosition, (450, 80),
                                             wx.LC_REPORT | wx.BORDER_SUNKEN | wx.LC_EDIT_LABELS | wx.LC_SINGLE_SEL)
self.bsizer_textCtrl.Add(self.m_listCtrl_number, 0, wx.ALL, 5)
self.m_listCtrl_number.InsertColumn(0, 'Min', format=wx.LIST_FORMAT_CENTER, width=wx.LIST_AUTOSIZE)
self.m_listCtrl_number.InsertColumn(1, 'Max', format=wx.LIST_FORMAT_CENTER, width=wx.LIST_AUTOSIZE)
self.m_listCtrl_number.InsertColumn(2, 'Fill', format=wx.LIST_FORMAT_CENTER, width=wx.LIST_AUTOSIZE_USEHEADER)

Adding an item:
self.m_listCtrl_number.InsertItem(self.index_numer, '0')
self.m_listCtrl_number.SetItem(self.index_numer, 1, '1')
self.m_listCtrl_number.SetItem(self.index_numer, 2, 'qwerty') # fixme Button!!!
self.index_numer += 1

A: You will have to use ultimatelistctrl.
Here is a hacked version of one of the demonstration programs:
import wx
from wx.lib.agw import ultimatelistctrl as ULC

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldfont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldfont.SetWeight(wx.BOLD)
        boldfont.SetPointSize(12)

        self.ulc = ULC.UltimateListCtrl(self, agwStyle = wx.LC_REPORT
                                         | wx.LC_VRULES
                                         | wx.LC_HRULES
                                         | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)

        info = ULC.UltimateListItem()
        info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT | ULC.ULC_MASK_CHECK
        info._image = []
        info._format = 0
        info._kind = 1
        info._text = "Artist Name"
        self.ulc.InsertColumnInfo(0, info)

        info = ULC.UltimateListItem()
        info._format = wx.LIST_FORMAT_RIGHT
        info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT | ULC.ULC_MASK_FONT
        info._image = []
        info._text = "Title"
        info._font = boldfont
        self.ulc.InsertColumnInfo(1, info)

        info = ULC.UltimateListItem()
        info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
        info._format = 0
        info._text = "Genre"
        info._font = font
        info._image = []
        self.ulc.InsertColumnInfo(2, info)

        self.button1 = wx.Button(self.ulc, -1, "Button1")
        self.button2 = wx.Button(self.ulc, -1, "Button2")
        self.button3 = wx.Button(self.ulc, -1, "Button3")
        index = self.ulc.InsertStringItem(3, " ")
        self.ulc.SetItemWindow(index, 0, self.button1)
        self.ulc.SetItemWindow(index, 1, self.button2)
        self.ulc.SetItemWindow(index, 2, self.button3)

        self.Bind(wx.EVT_BUTTON, self.OnButton)

        self.ulc.InsertStringItem(0, "Newsboys")
        self.ulc.SetStringItem(0, 1, "Go")
        self.ulc.SetStringItem(0, 2, "Rock")

        self.ulc.InsertStringItem(1, "Puffy")
        self.ulc.SetStringItem(1, 1, "Bring It!")
        self.ulc.SetStringItem(1, 2, "Pop")

        self.ulc.InsertStringItem(2, "Family Force 5")
        self.ulc.SetStringItem(2, 1, "III")
        self.ulc.SetStringItem(2, 2, "Crunk")

        self.ulc.SetColumnWidth(0, 150)
        self.ulc.SetColumnWidth(1, 200)
        self.ulc.SetColumnWidth(2, 100)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.ulc, 1, wx.EXPAND)
        self.SetSizer(sizer)

    def OnButton(self,event):
        b= event.GetEventObject()
        print(b.GetLabel(),"pressed")

########################################################################
class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="MvP UltimateListCtrl Demo")
        panel = TestPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App()
    frame = TestFrame()
    app.MainLoop()


text:
Q: Best way of changing authentication mechanism with ASP.NET MVC I need to read, generate and keep updated an authentication cookie that is different from formsauthentication one.
I saw many options like using IHttpHandlers, IHttpModules, custom Authorization filters, etc.
How would you deal with it?

A: If you need to mess with the authentication cookie, in your Global.asax, use the Application_AuthenticateRequest event
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}


text:
Q: Spring ModelAndView not working with ajax call Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.
Ajax
 $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                });

Controller
@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView();
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}

After running the code it does not show any error. Going through the  code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

A: I think in your ajax call you need to add the success parameter. You can simply modify your call as
 $.ajax({
            type:"GET",
            url:"employee_edit",
            data:{"eid":eid},
            success:function(data){
            }
       });

or you can also add only the success parameter in your code
$.ajax({
            type:"GET",
            url:"employee_edit?eid="+eid
            success:function(data) { }
       });

But I prefer the first one. Its more clear.
This should complete the ajax call and your program should work.

A: When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation @ResponseBody
@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public @ResponseBody Employee RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  return employee;
}

After that upon successful call, you will get the response inside success callback.
$.ajax({
    type:"GET",
    url:"employee_edit?eid="+eid,
    success: function(data) {
        //here data is the employee object
        //process it here and redirect using window.location
    }
});


text:
Q: Register GlobalConfiguration.Configuration.DependencyResolver in autofac I'm trying to register the current IDependencyResolver in autofac using delegate registration
builder.Register(c => GlobalConfiguration.Configuration.DependencyResolver).As<IDependencyResolver>();
builder.RegisterType<AService>();

So I can inject it like:
public class AService
{
    public AService(IDependencyResolver resolver)
    {
        ...

The problem is that, this seems to work fine the first time AService is resolved, but the second time I get the following Autofac error:
"Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."
If I register AService as delegate:
builder.Register(c => new AService(GlobalConfiguration.Configuration.DependencyResolver);

Everything works fine.
My guess is that the delegate registration for GlobalConfiguration.Configuration.DependencyResolver returns the same instance every time, but I'm not sure if that's the case.
Is there a way to register this global dependency resolver ?

A: Most likely you'll need to use something like this:
builder.RegisterInstance(GlobalConfiguration.Configuration.DependencyResolver).As<IDependencyResolver>().ExternallyOwned().SingleInstance()

It's a good idea in general to specify desired lifetime explicitly when registering your stuff (and someone else's too :))