Optimization of stochastic computer models

Question: This is a tough topic for myself to google since having the words optimization and stochastic in a search almost automatically defaults to searches for stochastic optimization. But what I really want to know are what methods exist for optimization of computer models when the computer model output is stochastic, i.e., not deterministic?
For example, if you consider a computer model where there is some unknown function $f(x)$ that represents the output of the computer model, then there exists many statistical methods for solving problems like
\begin{align*}
\min&\,\,\,\, f(x)\\
x&\in\mathcal{X}
\end{align*}
when $f(x)$ is deterministic.  But what happens when $f(x)$ is stochastic?  Is there a solution to the problem, or at best can we only solve
\begin{align*}
\min&\,\,\,\, \mathbb{E}[f(x)]\\
x&\in\mathcal{X}
\end{align*}
where $\mathbb{E}(\cdot)$ is the usual expectation operator.
Comment: It depends on your goal. $\mathbb{E}[f(x)]$ is only one of many possible choices. In some applications you might want to have a "reliable" solution, not just one which is "good on average". In this scenario you would optimize wrt to some quantile of the distribution of $f(x)$. [Bayesian optimization](https://en.wikipedia.org/wiki/Bayesian_optimization) deals with costly (and sometimes noisy) function evaluations. Check for example [this question](https://stats.stackexchange.com/questions/193306/optimization-when-cost-function-slow-to-evaluate/193391#193391).
Comment: This is a very interesting question. Optimization of $E[f(x)]$ is the only thing that will really possible. A statistical application related to this question is the MCEM algorithm, where the full likelihood function is only observable with MCMC error on top of it. Similarly, MCMC particle filter algorithms have the same problem. I haven't read up enough on either literature to know what the state of the art methods for answering this are though.
Comment: @lacerbi are any of those examples noisy? I think they are only deterministic.
Comment: @RustyStatistician: you're right, most examples are deterministic or talk about Bayesian optimization in general. See below for references more focussed on the "noisy" part.
Comment: Do you access to the computer program so you can run it yourself for choosen inputs $x$? Then methods for design of experiments become available for use! Search this site.
Comment: @kjetilbhalvorsen yes I do. Although I am not sure how that helps me....
Comment: Search for "response surface", maybe.
Comment: Are you talking about "shooting method" or its smarter variants (PSOt,...), model adaptive control, or similar?  Can you assert that inputs are bounded/finite?
Comment: @EngrStudent I don't think I am asserting any methods (I am trying to figure out what methods exist!), but yes I can assert that the inputs are bounded and finite.
Comment: If you provide more details of a specific or representative problem you want to solve, you might get more focused advice/answers. How many optimization variables (dimension)?  Are variables continuous?  What constraints? Are constraints deterministic? Is objective function differentiable (smooth) everywhere, or at least most places? Can you evaluate E(gradient of f(x))? For instance, by applying automatic or symbolic or complex step differentiation to your program? If so, you may be able to use (noisy) gradient based method. Can you do common numbers for different points and get + correlation?
Comment: Note that when I wrote "Is objective function differentiable (smooth) everywhere, or at least most places?" I'm referring to the unknown actual expected value, not the noisy evaluation. I know you can only evaluate E(f(x), and perhaps E(gradient of f(x)), with noise, but the properties of the underlying truth affect how you do the optimization.  if you can get high positive correlation of error in noisy evaluation of E(f(x)) for nearby points, that can help a lot.  Similarly for E(gradient(x)). Might be good to use same random numbers for objective function and gradient evaluation if possible.
Comment: You may get bonus points if you can do a noisy Hessian evaluation, but I don't think it's common that people would (be able) to do that. But if you can, it might help things.
Comment: @MarkL.Stone there is no application yet. I am approaching this question from a purely methodological point of view. So my assumptions are pretty open.
Answer: (Expanding my comment to a proper answer.)
As I mentioned, it depends on your goal.
The expected value $\mathbb{E}[f(x)]$ is only one of many possible choices for the optimization target. For example, assuming that the $f(x)$ are normally distributed, you could do:
$$
x^\text{opt} = \arg \min_x \left\{ \mathbb{E}[f(x)] + \kappa \sqrt{\mathbb{Var}[f(x)]} \right\}
$$
for some $\kappa \in \mathbb{R}$ that manipulates risk-sensitivity. If $\kappa > 0$ you are looking for a robust solution that is likely to be best and discourages large positive fluctuations. Vice versa, a negative $\kappa$ would favour an "optimistic" optimization that looks for large negative fluctuations (negative is good since we are minimizing). You can choose $\kappa$ based on quantiles of the normal distribution (see reference 2 below).
In general, Bayesian optimization (BO, which is related to Gaussian processes and kriging) deals with costly and sometimes noisy function evaluations; although most of the focus of the literature has been on the former part. You can find reviews for Bayesian optimization at this question.
Several people have applied BO to noisy functions.
As an introdution to the topic, David Ginsbourger gave a nice talk titled "Variations on the Expected Improvement" at the Workshop on Gaussian Processes for Global Optimization (Sheffield, Sept 17, 2015). You can find his talk here, and all the talks are available on this page (I also recommend all the other talks as an excellent general introduction to BO.)
As references, I would start with the work done by Ginsbourger and colleagues, and Gramacy and colleagues:

Picheny, V. and Ginsbourger, D., 2014. "Noisy kriging-based optimization methods: a unified implementation within the DiceOptim package". Computational Statistics & Data Analysis, 71, pp.1035-1053. (link)
Picheny, V., Ginsbourger, D., Richet, Y. and Caplin, G., 2013. "Quantile-based optimization of noisy computer experiments with tunable precision". Technometrics, 55(1), pp.2-13. (link)
Gramacy, R.B. and Lee, H.K., 2012. "Bayesian treed Gaussian process models with an application to computer modeling". Journal of the American Statistical Association. (link)
Gramacy, R.B. and Apley, D.W., 2015. "Local Gaussian process approximation for large computer experiments". Journal of Computational and Graphical Statistics, 24(2), pp.561-578. (link)

Both Ginsburger and Gramacy have R packages that implement their BO methods, respectively DiceOptim and tgp.
Comment: Where is $k$ in your answer, or do you mean $\kappa$?
Comment: One more algorithm, which I have not used* but wins in the amusing name department, is [SNOBFIT](http://www.mat.univie.ac.at/~neum/software/snobfit/). (* The author *is* notable in the optimization community however, and the software did OK on a [deterministic benchmark](https://scholar.google.com/scholar?cluster=13996631775177561404), so the recommendation isn't *just* based on the cool name!)
Answer: Let's say we're in a discrete probability space so that $f(x) \in \mathcal{R}^n$. Intuitively, you need some function $U: \mathcal{R}^n \rightarrow \mathcal{R}$ so you can optimize $U(f(x))$. You can only optimize a single objective!
Optimizing a single objective function may sound quite constraining, but it is not! Rather a single objective can represent incredibly diverse preferences you may have over what is a better or worse solution.
Skipping ahead, a simple place to start may be choosing a random variable $\lambda$ then solving:
$$
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $x$)} & E\left[\lambda f(x) \right]  \\
 \mbox{subject to} & x \in X
 \end{array}
$$
This is a simple linear re-weighting of $E[f(x)]$. Anyway, here's an argument for why collapsing multiple objectives to a single objective is typically ok.
Basic setup:

You have a choice variable $x$ and a feasible set $X$.
Your choice of $x$ leads a random outcome $\tilde{y} = f(x)$
You have rational preferences $\prec$ over the random outcome. (Basically, you can say whether you prefer one random outcome $\tilde{y}$ to another.)

Your problem is to choose $x^*\in X$ such that:
$$ \nexists_{x \in X} \quad  f(x^*) \prec f(x) $$
In English, you wan to choose $x^*$ so that no feasible choice $x$ leads to an outcome preferred to $f(x^*)$.
Equivalence to maximizing utility (under certain technical conditions)
For technical simplicity, I'll say we're in a discrete probability space with $n$ outcomes so I can represent random outcome $\tilde{y}$ with a vector $\mathbf{y} \in \mathcal{R}^n$.
Under certain technical conditions (that aren't limiting in a practical sense), the above problem is equivalent to maximizing a utility function $U(\mathbf{y})$. (The utility function assigns more preferred outcomes a higher number.)
This logic would apply to any problem where your choice leads to multiple outcome variables.
$$
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{maximize (over $x$)} & U(f(x)) \\
 \mbox{subject to} & x \in X
 \end{array}
$$
Giving more structure to utility function $U$: Expected Utility hypothesis:
If we're in a probabilistic setting and we accept the Neumann-Morgernstern axioms, the overall utility function $U$ has to take a special form:
$$U(\mathbf{y}) = E[u(y_i)] = \sum_i p_i u(y_i) $$
Where $p_i$ is the probability of state $i$ and $u$ is a concave utility function. The curvature of $u$ measures risk aversion. Simply substituting this specialized form of $U$ you get:
$$
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{maximize (over $x$)} & \sum_i p_i u(y_i) \\
 \mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
 \end{array}
$$
Observe that the simple case $u(y_i) = y_i$ is maximizing the expected value (i.e. no risk aversion).
Another approach: $\lambda$ weights
Another thing to do is:
$$
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{maximize (over $x$)} & \sum_i \lambda_i y_i \\
 \mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
 \end{array}
$$
Intuitively, you can choose weights $\lambda_i$ that are larger or smaller than the probability $p_i$ of a state occurring, and this captures the importance of a state.
The deeper justification of this approach is that under certain technical conditions, there exists lambda weights $\boldsymbol{\lambda}$ such that the above problem and the earlier problems (eg. maximizing $U(f(x))$) have the same solution.
Comment: But in this setup not all utility functions lead to the same answer correct?
Comment: And are there typical choices for utility functions? My problem is a stochastic computer simulator, which is actually a blackbox simulator, so I know no information about the underlying mechanics so can I even possibly assign it a utility function?
Comment: You need to think through the logic of your problem, what constitutes a good result, and then find some objective function that assigns better outcomes a higher number. (Or equivalently, you can set this up as a minimization problem and assign worse outcomes a higher number. eg. minimize some notion of squared error etc..)
Answer: The current answers focus on the proper (mathematical) definition of a stochastic optimization target - I want to provide a somewhat more applied perspective.
This problem occurs frequently when fitting stochastic models, e.g. using informal or synthetic likelihoods. Reference (1) provides you with a list of options that can be used to define the distance between a stochastic model and the data.
After having defined your target in this way, the issue that remains is finding the optimum of some mean of a noisy target. There are two routes to go, a) optimization, and b) MCMC sampling. You were asking specifically about optimization, but I want to bring in the MCMCs because they are often better behaved for this task.
a) If you stay with optimization, you need to make sure that you don't get stuck and that the optimizer can deal with a stochastic target. Chapter 4 in the PhD thesis of Matteo Fasiolo gives some hints, see (2).
b) As we note in (1), MCMCs are generally more robust against a stochastic target - under mild conditions regarding the distribution of the noise, the MCMC will average the noise away, and the sampled target will be indistinguishable from a non-noisy target with mean of the noisy target. However, MCMCs too can get stuck when encountering an evaluation that is particularly good. What you MUST NOT DO now is getting the following "obvious" idea: simply calculate both current and proposed value in each MCMC iteration. The keyword to look up here is "pseudo-marginal", see also here and here.
1) Hartig, F.; Calabrese, J. M.; Reineking, B.; Wiegand, T. & Huth, A. (2011) Statistical inference for stochastic simulation models - theory and application. Ecol. Lett., 14, 816-827.
2) Fasiolo, M. (2016) Statistical Methods for Complex Population Dynamics. University of Bath


Action App\Http\Controllers\KategoriController@store not defined

Question: I'm using Laravel 8, I wanna try to make an input form using Modals.
It's my first try, and I dunno what's wrong I did while I think I already copying the same as the tutorial.
Error Message

Action App\Http\Controllers\KategoriController@store not defined. (View: C:\xampp\htdocs\LARAVEL\Workshop\resources\views\back\kategori-produk\tampil.blade.php)

Category Controller
<?php

namespace App\Http\Controllers;

use App\Models\Kategori;
use Illuminate\Http\Request;

class KategoriController extends Controller
{
    // sesi FRONTEND
    public function index()
    {
        $kategoris = \App\Models\Kategori::all();
        return view('front.product',['kategoris' => $kategoris]);
    }

    // sesi BACKEND
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function indexBack()
    {
        $kategoris = \App\Models\Kategori::all();
        return view('back/kategori-produk/tampil',['kategoris' => $kategoris]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
        ]);

        $kategoris = new Kategori;
        $kategoris->nama = $request->input('nama');
        $kategoris->save();
        return back()->with('Success', 'Data Saved');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Kategori  $kategori
     * @return \Illuminate\Http\Response
     */
    public function show(Kategori $kategori)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Kategori  $kategori
     * @return \Illuminate\Http\Response
     */
    public function edit(Kategori $kategori)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Kategori  $kategori
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Kategori $kategori)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Kategori  $kategori
     * @return \Illuminate\Http\Response
     */
    public function destroy(Kategori $kategori)
    {
        //
    }
}

Category View Blade
Also, code "modal form" in here too.
@extends('back.index')

@section('content')

Tables

Dashboard

Tables

                @auth
                <button type="button" class="btn btn-info float-right" data-toggle="modal" data-target="#exampleModal">
                    Add
                </button>
                @endauth

Modal title

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                            </button>

                            <form action={{ action('App\Http\Controllers\KategoriController@store') }} method="GET">
                                @csrf

                                        <input id="nama" type="text" class="form-control col-md-8 @error('nama') is-invalid @enderror" name="nama" value="{{ old('nama') ?? $kategori->nama ?? '' }}" autofocus>
                                        @error('nama')

{{ $message }}

                                        @enderror

                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                        <button type="button" class="btn btn-primary">Save</button>

                            </form>

                                Id
                                Nama
                                Act

                        @forelse ($kategoris as $kategori)

                                {{$kategori->id}}
                                {{$kategori->nama}}
                                @auth

                                    {{--  $dosen->id])}}"
                                        class="btn btn-secondary" title="Edit Dosen">Edit
                                    <form action="{{route('dosens.destroy',['dosen' => $dosen->id])}}"
                                    method="POST" class="d-inline">
                                    @csrf  @method('DELETE')
                                    <button type="submit" class="btn btn-danger shadow-none btn-hapus"
                                    title="Hapus Dosen" data-name="{{$dosen->nama}}"
                                    data-table="dosen">Hapus</button>
                                    </form> --}}

                                @endauth

                        @empty
                        Tidak Ada Data ..
                        @endforelse

@endsection

Route in web.php
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\KategoriController;
use App\Http\Controllers\ProdukController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('front.welcome');
});

Route::get('/product', [KategoriController::class,'index']);

Route::get('/product-details', [ProdukController::class,'index']);

Route::get('/service', function () {
    return view('front.service');
});
Route::get('/rent', function () {
    return view('front.rent');
});
Route::get('/training', function () {
    return view('front.training');
});
Route::get('/facility', function () {
    return view('front.facility');
});
Route::get('/aboutUs', function () {
    return view('front.aboutUs');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::prefix('/kategori')->group(function () {
    Route::get('/', [App\Http\Controllers\KategoriController::class, 'indexBack']);
});

Answer: First of all, change this form attribute action from  <form action={{ action('App\Http\Controllers\KategoriController@store') }} method="GET"> to <form action={{url('getKategorie') }} method="GET"> then name the url in the routes file. Im sure thats where your problem is. As it stands , laravel is looking for that action in the web.php file and is cannot find it. Hence add something like this Route::get('getKategorie',[KategoriController,'store']);. Another thing you need to take note of is, you are using a resource controller, hence a GET http verb only read the index method not the store method.The store method works with POST http verb. Hope this answers your question.
Answer: You have used GET for submitting data, GET is used for retrieving data. You should use POST in place of GET. See my code and use it in your form and routes.
Category Controller
<?php
namespace App\Http\Controllers;

use App\Models\Kategori;
use Illuminate\Http\Request;
class KategoriController extends Controller {
    // sesi BACKEND
    public function __construct() {
        $this->middleware('auth');
    }

    // sesi FRONTEND
    public function index() {
        $kategoris = Kategori::all();
        return view('front.product',['kategoris' => $kategoris]);
    }

    public function indexBack() {
        $kategoris = Kategori::all();
        return view('back/kategori-produk/tampil',['kategoris' => $kategoris]);
    }

    public function create() {
        //
    }

    public function store(Request $request) {
        $this->validate($request, [
            'name' => 'required',
        ]);

        $kategoris = new Kategori;
        $kategoris->nama = $request->input('nama');
        $kategoris->save();
        return back()->with('Success', 'Data Saved');
    }

    public function show($category) {
        //
    }

    public function edit($category) {
        //
    }

    public function update(Request $request, $category) {
        //
    }

    public function destroy($category) {
        //
    }
}

Category View Blade
<form method="post" action="{{ route('category.store') }}">
    @csrf

</form>

web.php
Route::get('', 'KategoriController@index')->name('category.index');
Route::get('', 'KategoriController@indexBack')->name('category.indexBack');
Route::get('create', 'KategoriController@Create')->name('category.create');
Route::post('create', 'KategoriController@Store')->name('category.store');
Route::get('show/{category}', 'KategoriController@Show')->name('category.show');
Route::get('update/{category}', 'KategoriController@Edit')->name('category.edit');
Route::patch('update/{category}', 'KategoriController@Update')->name('category.update');
Route::delete('delete/{category}', 'Users\UserController@Destroy')->name('user.destroy');


Evaluating goodness-of-fit for GARCH models in R with QQ-plots (rugarch package)

Question: I'm currently working with multivariate GARCH representations of time-series for financial data using the rmgarch R package. This package in turn uses the well-known rugarch package to fit the 'marginal' GARCH processes.
Right now I'm evaluating the goodness-of-fit and parameter estimates when using different conditional distributions for the variance innovations. It seems that (skewed) student's t and skewed normal fit my data better as they present heavier-than-normal tails, skew, and excess kurtosis. In addition, the parameter estimates seem to become more significant (particularly the estimate for $\alpha_1$) when using non-normal distributions.
Typically, I would analyse the standardised residuals of my model (available in "fit object"@mfit$stdresid for a DCC-fitted model), and use for example a QQ plot against the theoretical distribution to examine the behaviour, along with an ACF plot to examine autocorrelations. This is easily done when assuming normal innovations as the standard qqnorm in R does the trick, however I'm less sure how to do this procedure for the skewed normal and (skewed) $t$ distributions.
Is there a good way to produce these kinds of QQ-plots in R? The GARCH package(s) will readily output estimates for skew and shape, but I'm not sure how to incorporate these into QQ-plots.
Also, as a side question: currently I'm fitting three time series. Two of them seem to want Student's $t$ distribution, and one skewed normal. For the joint innovations, however, I'm currently using a multivariate normal distribution. Does this make sense from a mathematical perspective? As you might tell, I'm relatively inexperienced with time-series models, but this seems akin to fitting a joint distribution normally but with non-normal marginal distributions, which seems odd.
Thanks for any help! :)
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. A helpful answer can also be upvoted by clicking on the upward-pointing arrow. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: To assess the distributional assumption of a GARCH model, you can look at the probability integral transform (PIT) of the standardized residuals. It can be obtained by pit(fit) where fit is a fitted model object from rugarch. If the model is a good approximation of the data, the PIT should be roughly Uniform[0,1]. If you want to do a QQ plot, you can use the qnorm function to go from uniform to standard normal and then use the qnorm function for the QQ plot. See p. 41-43 of the rugarch vignette for a more detailed discussion.
library(rugarch)
data(dmbp) # example data
spec=ugarchspec()
fit=ugarchfit(data=dmbp[,1], spec=spec)
pit=pit(fit)
hist(pit) # this should be approximately Uniform[0,1]
norm=qnorm(pit)
hist(norm) # this should be approximately standard normal
qqnorm(norm); abline(a=0, b=1) # this is your QQ plot

As to your side question, multivariate normal distribution does not make sense if the marginals are not normal. A possible fix for that is to use a copula-GARCH model (available in rmgarch). It does not yield a DCC-type dynamic, though.
On the other hand, I guess it should be possible to have different distributional assumptions for the different marginals in a DCC model in rmgarch (I have by now forgotten how these things are implemented there). After all, the DCC structure is built on top of the univariate GARCH models; it takes them as the starting point. The estimation might also be carried out in two steps: first the marginals and then the DCC part. So the "multivariate normal assumption" might be used for fitting the DCC structure, and it might act as a normal copula without affecting the marginals. But I am not sure about this.


What's the best way to center your HTML email content in the browser window (or email client preview pane)?

Question: I normally use CSS rules for margin:0 auto along with a 960 container for my standard browser based content, but I'm  new to HTML email creation and I've got the following design that I'd like to now center in the browser window without standard CSS.
http://static.helpcurenow.org/mockups/emails/2010/may-survey/survey.html
I seem to recall seeing somewhere that it can also be accomplished by wrapping your email table design in an outer table set to width:100% and using some inline style for text-align:center on the tbody or something like this to do it?
Is there a best practice for this?
Comment: "margin:0px auto" .. just FYI, when you use `0` of anything, you don't need to specify a unit :)
Answer: Align the table to center.

            Your Content

Where you have "your content" if it is a table, set it to the desired width and you will have centred content.
Comment: When you code for email layouts, you literally code like it's 1999.
Comment: Some email providers require this deprecated method of centering objects.  (I'm thinking of Apple Mail).
Comment: Is there a CSS property which does the same thing? `text-align: center` isn't doing the same thing.
Comment: This causes child tables to have centered `td`s as well in Outlook Web App (OWA), no matter if they have alignment set to `left` or not.
Comment: Does not work in gmail mobile. This answer below does however https://stackoverflow.com/a/38149673/129638
Comment: Have in mind that your email is not only going to display in modern clients like Gmail. They might be received by users/businesses who use outdated and small clients and email providers.
Answer: For googlers and completeness sake:
Here's a reference I always use when I need to go through the pain of implementing html email-templates or signatures:
http://www.campaignmonitor.com/css/
I'ts a list of CSS support for most, if not all, CSS options, nicely compared between some of the most used email clients.
For centering, feel free to just use CSS (as the align attribute is deprecated in HTML 4.01).

            Your Content

Comment: Doesn't work if you're centering a table or other block-level element.
Comment: Yeah I wasn't sure if all browsers would support it so went with the trusty but deprecated  tag.
Comment: You're right, I'm not sure if `margin: 0 auto;` is supported (in combination with a `width`), but that usually works for browsers, but I'm not sure if email-clients come along well in that situation.
Answer: table align="center" ... this aligns the table center of page.
Using td align="center" centers the content inside that td, useful for centered aligned text but you will have issues with some email clients centering content in sub level tables so using using td align as a top level method of centering your "container" table on the page is not the way to do it. Use table align instead.
Still use your 100% wrapper table too, purely as a wrapper for the body, as some email clients don't display body background colors but it will show it with the 100% table, so add your body color to both body and the 100% table.
I could go on and on for ages about all the quirks of html email dev. All I can say is test test and test again. Litmus.com is a great tool for testing emails.
The more you do the more you will learn about what works in what email clients.
Hope this helps.
Answer: I was struggling with Outlook and Office365. Surprisingly the thing that seemed to work was:

I only listed some of the key things that resolved my Microsoft email issues.
Might I add that building an email that looks nice on all emails is a pain. This website was super nice for testing: https://putsmail.com/
It allows you to list all the emails you'd like to send your test email to. You can paste your code right into the window, edit, send, and resend. It helped me a ton.
Comment: Thank you, this worked for me. I was trying to Center the email template i created using publisher in outlook
Answer: Here's your bulletproof solution:

    .

      CONTENT GOES HERE

    .

Just Try it out, Looks a bit messy, but It works Even with the new Firefox Update for Yahoo mail. (doesn't center the email because replace the main table by a div)
Comment: The small invisible "period" should be replaced with perhaps a   and the instructions to make the small invisible period invisible should be dropped. I couldn't even get a test email through to myself with those settings as they went straight to my providers spam hell :) Malware defences are making anything fishy smell even fishier... e.g.: `
`
Comment: This won't work in Gmail for especially long emails because Gmail clips the bottom portion of the HTML, removing the last , which causes the whole thing to right align.
Answer: CSS in emails is a pain. You'll probably need tables unfortunately, because CSS is not greatly supported in all email clients.
That said, use an HTML Transitional DOCTYPE, not XHTML, and use .
Answer: To center the table in the middle of the email use

            Your Content

To align the content in the middle use:

            Your Content

Answer: In some cases margin="0 auto" won't cut the mustard when center aligning a html email in Outlook 2007, 2010, 2013.
Try the following:
Wrap your content in another table with style="table-layout: fixed;" and align="center".

Comment: Why use a `table` for this if there's only going to be one row and one column?  You're not making use of any features of the `table` element.
Comment: you use a table in html email because the solution to any problem with html email that will work across almost all clients will somehow involve "add another table"


A condition in the definition of algebra over a ring

Question: This is an elementary question about definition, but I do not get answer in texts where I saw the definition (Atiyah-McDonald, Paolo Aluffi).

A ring $B$ is said to be an algebra over a commutative ring $R$ if there is a ring homomorphism from $R$ to $B$ such that image of $R$ is in the center of $B$.

I do not understand the requirement of last condition: "image of $R$ is in center of $B$".
Can one point out why it is required, by illustration of an example, in which a nice theorem fails by removal of this condition? Or can one illustrate the requirement of the last condition in some natural example of algebras?
Comment: [Related](https://math.stackexchange.com/q/643862/29335) though not a dupe. It asks what axiom of algebras the centrality condition relates to.
Answer: For an algebra, you want the coefficients to be able to commute with everything, so that you don't have to worry what side of elements they are written on.
It also forces the coefficient ring to be commutative, and so if you represent elements of $A$ as matrices (when $A$ is a free $R$ module) you can do determinants easily.
I don't know what kind of theorem failure will impress you. Perhaps that "every finite dimensional semisimple $\mathbb C$ algebra is a full matrix ring over $\mathbb C$"?
The failure is that the quaternions $\mathbb H$ would be a $\mathbb C$ algebra if we dropped the centrality condition, but it is NOT a full matrix ring over $\mathbb C$.
Comment: Thanks for clarifications; especially, I appreciate your points in second and last para.
Answer: In general a ring $R$ does not need to be commutative. Cf. Wikipedia for the definition of center.
For example consider the ring $R=\mathbb{Q}x\oplus\mathbb{Q}y$ given by bilinearily extending the product from the products of basis elements: $x^2=x, xy=y, yx=x, y^2=y$. This gives a non-commutative but associative ring without unit. The map $\mathbb{Q}\rightarrow R, q\mapsto qx$ is ringmorphism, whose image is the subring $\mathbb{Q}x\subset R$, but it does not make $R$ a $\mathbb{Q}$-algebra, since the center is $Z(R)=\{0_R\}$, as $xy=y\neq x=yx$.
Since here we do not require ringmorphisms to be unital, we could however consider $R$ as a $\mathbb{Q}$-algebra via the map $\mathbb{Q}\rightarrow R, q\mapsto 0_R$ - this is not very interesting, though.
If you require that (associative) rings $R$ must be unital, then $R$ can always be considered as a $\mathbb{Z}$-algebra, by the morphism induced by $1_{\mathbb{Z}}\rightarrow 1_R$, because the additive subgroup generated by $1_R$ is always in the center.
Answer: The statement "Multiplication in $B$ is bilinear over $R$" is false without the centrality condition.
Intuitively, we think of an algebra over $R$ as a module over $R$ that has a product that respects the module action.  For example, algebras over $\mathbb{R}$ are vector spaces over $\mathbb{R}$, equipped with a bilinear product.
Thus without the centrality condition, the definition would fail to capture the the fundamental intuition of what an algebra is.
Suppose we do not have the centrality condition, so some $a\in R$, has image $x\in B$, with $xy\neq yx$ for some $y\in B$.  Then $$(1.a)y=1xy=xy\neq yx=(1y).a,$$ so the product in $B$ is not bilinear over $R$.
Here the module action $.a,$ of $a\in R$, is given by right multiplication by the image of $a$ in $B$.
Comment: @ThomasPreu If there's a ring homomorphism from $R$ to $B$, which is the assumption in the OP, then $B$ is automatically both a left and right $R$-module.


What's the alternative for my failing PHP code about block visibility based on user?

Question: I would like to remove certain blocks, so that admin can not see them.
In block visibility settings - in pages tab, I try to put followng php code but with no effect. (In user tab there is no php field to put code.)
<?php
if(arg(0) == 'administrator' )
return true;
else
return false
?>

What I am doing wrong?
EDIT: On my other D6 site I use argument:
 user_access('access administration pages')

but on D7 site it does not work, what can be another way of doing it?
Comment: what I am going to assume and ignore to be copy/paste issues, the rest of your logic here is saying if the first argument of your path is administrator, return true otherwise return false.  so, that means true will be returned on www.yoursite.com/administrator, www.yoursite.com/administrator/foo, www.yoursite.com/administrator/foo/bar, etc.
Comment: @Jimajamma I need to hide a block from all pages if administrator is logged in. In D6 site I used user_access('access administration pages') argiment but in D7 it no longer works.
Answer: You could perhaps just set the "Roles" options under the block visibility settings.
Alternatively, something like:
global $user;
return in_array('administrator', $user->roles) ? FALSE : TRUE;

Comment: Even you restrict roles user with uid 1 can see everything.. :)
Comment: using roles does not do the trick because no matter what roles I check, administrator sees everything. I tried using your code inside php area on pages tab but without any result
Comment: Nikhil is right - that's why I always reserve uid 1 to service tasks under general name like Admin, and as soon as feasible move to my own username with minimal required set of roles needed.
Comment: Using **Rules** instead of "**Roles*** does work ... Refer to my answer here for more details ... Even for uid=1 ...
Answer: Just using "rOles" (as in the comments below the prior answer) is indeed not going to help/work. Instead, if you're willing to consider using "rUles", then there is a solution for this question, as further explained below.
Part 1: Rules block visibility
Have a look at the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the actual user who's using the site, i.e. if it is YES or NO (a boolean, right?) the user with uid = 1.
Part 2: Create an appropriate Rules Component
The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.
Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.
By looking at these samples, I was able to create another Rules Component which looks like so:
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You should be able to import this rule in your own environment.
What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the user's uid is YES or NO equal to 1.
With that, we're coming close to an actual answer to your question. But note that, as a variation, you could also have used a rules condition like "does this user yes or no have a role like administrator".
Part 3:
Head over to the "Block" settings for the block you want to hide for the user with uid = 1. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".
And guess what, in my case I just selected my Rules Component from Part 2
Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


How to change filename before it get saved without changing source URL using tamper plugin?

Question: I've URL which is mapped to file field (image) via Feed Ex.
I'm trying to change the filename before it's get saved using tamper plugins (e.g. concat or regex), however it is also changes the requesting URL causing saving the invalid image files which consist html with 404 error.
How do I use Feeds Tamper plugin to modify data (filename) after the file is downloaded but before it's get saved? Or I need to find some other alternative way of doing that?
Answer: It seems it's not possible using tamper plugins (as far as I've tried).
As workaround, this can be achieved by using hook_file_presave(), for example:
/**
 * Implements hook_file_presave().
 */
function mymodule_file_presave($file) {
  if ($file->filename == 'ShowImageXML.asp') {
    $filename = date("ymd", $file->timestamp) . '-' . $file->filesize . '.jpg';
    $uri = 'public://images/' . $filename;
    $file = file_move($file, $uri);
  }
}

See also a feature request: #2596841


How do I use another method in a method?

Question: I want to use the method preisProKilo() in the method gesamtpreis()? Its about calculating the total price of a product. preis pro kilo = price per kilo and gesamtpreis = total amount.
class Kaffeeladen {

  double preisProKilo(double grundpreis) {
        return (grundpreis + 2.19) * 1.19;
  }

  double gesamtpreis(int gewuenschteMenge, double preisProKilo) {
    return preisProKilo * gewuenschteMenge;
    //Here its not using the method "preisProKilo" from above.
  }

  public static void main(String[] args) {
    Kaffeeladen k = new Kaffeeladen();

    double preis1 = k.preisProKilo(3.00);
    System.out.println("Bei einem Grundpreis von 3,00 Euro kostet 1 kg Kaffee inklusive Steuern " + preis1 + " Euro.");

  }
}

Comment: Albeit the `return` way is not correct in `gesamtpreis(int, double)`. You are not calling that method here in the code anyways. That return could be like this: `return preisProKilo(preisProKilo)*gewuenschteMenge;`
Answer: You are getting confused because you named the method and variable the same thing.  Don't do this.
You are not calling a method at all, you are only using the variable.
It should be something like this:
double preisProKilo(double grundpreis) {
    return (grundpreis + 2.19) * 1.19;
}

double gesamtpreis(int gewuenschteMenge, double newValueName) {
    return preisProKilo(newValueName) * gewuenschteMenge;
}

You can change the name of newValueName to whatever you choose, just please try to use different names.
Additionally, I do not see anywhere you are actually using gesamtpreis(int, double), so you would need to use this as well by doing in your main something like this:
Kaffeeladen k = new Kaffeeladen();
double value = k.gesamtpreis(2, 3.00);

Answer: You probably wanted to give gewuenschteMenge that is the desired quantity and grundpreis that is the basic price in your gesamtpreis or full price method.
class Kaffeeladen {

  double preisProKilo(double grundpreis) {
        return (grundpreis + 2.19) * 1.19;
  }

  double gesamtpreis(int gewuenschteMenge, double grundpreis) {
    return preisProKilo(grundpreis) * gewuenschteMenge;
  }

  public static void main(String[] args) {
    Kaffeeladen k = new Kaffeeladen();

    double preis1 = k.preisProKilo(3.00);
    System.out.println("Bei einem Grundpreis von 3,00 Euro kostet 1 kg Kaffee inklusive Steuern " + preis1 + " Euro.");

  }
}

You are actually using preisProKilo variable over calling the method preisProKilo(double grundpreis) to do so you have to call it as shown in the code above.
Answer: I'm not sure exactly what you're trying to do here, as the naming of variables is the same as the method names, but to call a method, you need to use the syntax methodToCall(arg1, arg2).
It seems you have a lack of understanding of how methods work. One way to think of it is in terms of math functions. For example,
f(x)= x + 1

If x is 1, f(x) has a value of 2. If x is 2, f(x) has a value of 3, and so on.
So the same way to write that in Java would be as follows:
public int addOne(int x) {
  return x + 1;
}

And to call that method, you'd do this.
public int doWork(int value) {
  // doing work...
  value = addOne(value);
  // doing more work...
  return value;
}


Como eu passo o ponto e virgula que fica no final da linha de código HTML e CSS

Question: Estou aprendendo a programar agora. Contudo, estou com um pequeno incomodo em relação ao ponto e virgula no final da linha de código. Quando eu digito a linha de comando uso o autocomplete para me ajudar a completar o comando, entretanto no final da linha de código fica o ponto e virgula e toda vez eu tenho que usar as teclas de cima, baixo, esquerda, direita ou pegar no mouse para descer para próxima linha. Tem algum jeito ou atalho de teclado que possa sanar essa incomodo? Ou algo que eu possa ativar ou criar um atalho de teclado para não precisar usar as teclas, esquerda, direita ou o mouse?
Comment: qual editor você usa? apesar que a sua pergunta não atende os requisitos do site
Comment: Importante você `EDITAR` esta pergunta, explicando-a de forma clara, objetiva e direta, enfatizando a dificuldade encontrada. Além disso, nos forneça um [Exemplo mínimo, completo e verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) do problema, junto com sua tentativa de resolução. E mais, sugiro a leitura do [Guia de sobrevivência do Stack Overflow em Portugês](https://pt.meta.stackoverflow.com/questions/8045/guia-de-sobreviv%C3%AAncia-do-stack-overflow-em-portugu%C3%AAs) para entender melhor o funcionamento da plataforma e não ter maiores frustrações.
Answer: Caso esteja utilizando o VSCode como editor, você pode desativar nas configurações a opção de colocar o ponto e virgula automaticamente. Porém, terás que inserir o ponto e virgula de forma manual. =)
config: Completion: Complete Property With Semicolon


hooks call order and hooks dependency

Question: I try to implement hook_menu() in a module and the code inside of this hook depends on another hook implemented in the same module Example:
function mymodule_menu() {
   $streamwrapper = file_stream_wrapper_get_instance_by_scheme('myscheme');
   if($streamwrapper !== false) {
      $directory = $streamwrapper->getDirectoryPath();
       .....
   }
}

and another hook function in the same (mymodule) module
function mymodule_stream_wrappers() {
  retunr array( 'myscheme' => array(...)
}

Apparently, hook_stream_wrappers() is called after hook_menu(), and file_stream_wrapper_get_instance_by_scheme() returns false during module installation process.
So, the whole idea works because Drupla will call hook_menu eventually and by that time stream wrapper will be in place and ready, but it seems too unreliable, IMHO.
Anyway, is it possible to control hooks order somehow? Or is there a better way to achieve desired result - retrieve stream wrapper in hook_menu after is has been known by the system?
Answer: Your problem is actually the opposite of what you're thinking. A call to file_stream_wrapper_get_instance_by_scheme triggers hook_stream_wrappers() if it hasn't been called already.
However, the problem is that the stream wrapper hook was already called before your module was enabled and the information from that is statically cached. So you need to clear the static cache to get your own stream wrapper:
drupal_static_reset('file_get_stream_wrappers');

Comment: Thanks Berdir!
Right to the point - the problem is because of cache, but the only way to do what I want (without Drupal patching) is to call `drupal_static_reset` right before I call for my wrapper. Look like `file_get_stream_wrappers` is implemented:
Comment: I miss my chance to edit previous comment sorry...

`file_get_stream_wrappers()` checks entire cache, regardless of schema and calls the modules hooks if it is not set.

Means that any cached wrapper disables hooks for all of the rest. The cache is almost for sure is populated by "public" and "private" and "Clear all caches" in admin does not help. And if I call `drupal_static_reset()` I will set other modules in the same trouble.
Comment: This is just a static cache which means that it rebuilt on every request. So this really should only happen while your module is being installed. So it should be safe to call drupal_static_reset() (you could do it in your hook_enable() to prevent it from running on every subsequent menu rebuild). Most static caches in drupal are pretty dump and need to be explicitly cleared if know that there is more up to date information.
Comment: It really happens during install only. Thanks for the hook_enable() idea!
Answer: According the documentation, the function file_stream_wrapper_get_instance_by_scheme call another function that call the hook hook_stream_wrappers.
Logically your code should work.
I see here that you've a mistake in your return
function mymodule_stream_wrappers() {
  retunr array( 'myscheme' => array(...)
}

it may the cause of your problem.

hooks call order and hooks dependency


Creating a Java Desktop UI which can be understood by Eclipse and Netbeans

Question: Netbeans recently dropped support for Swing based Java Desktop Applications from version 7.1 onwards. Till that point I had always imagined that creation of Java Application User Interfaces would be cross platform. I thought that a Swing UI created in Netbeans designer could be easily understood and edited in Eclipse but apparently now I realize that it is not the case.
Is there a way to make the Java Application User Interface by not depending on IDE-specific Java UI designers? That is a form of UI description, can be XML or something that can be edited on the different IDEs that people would like to use.
Comment: See also this [Q&A](http://stackoverflow.com/q/11096999/230513).
Answer: That post starts..

I just installed NB 7.1 Beta, and tried to open one of our many Swing Application Framework-based applications, ..

OK.  You can stop reading there, sounds like JSR 296 which has been dying for years.  Pure Swing apps. should be fine.


Reversed continuity

Question: We know that if a function $f$ satisfies
$$\lim_{n\rightarrow\infty}f(x_n) = f(x_0),\qquad (1)$$
where $\lim_{n\rightarrow\infty}x_n = x_0$, than $f$ is continuous at the point $x_0$. But can we reverse this statement? What I mean by that is, if we already know that $f$ is continuous at $x_0$, can we say that $(1)$ must be true?
Comment: Do you mean to obtain from above $\epsilon - \delta$ definition?
Comment: That is the definition, so of course that if $f$ is continuous limit mentioned above must exist, again by definition. This is not $A \iff B$ statemend because you defined $B$ by $A$.
Comment: I've seen loads of questions like this on math.se. So this is likely a duplicate question.
Comment: There are a couple of issues with your question.  First, the initial statement is wrong---you are, at the very least, missing a quantifier.  If $\lim_{n\to \infty} f(x_n) = f(x_0)$ for all sequences of $x_n$ such that $x_n \to x_0$, then $f$ is continuous.  Second, answering your question requires that you first give a definition of continuity.  Of course, in many contexts, the statement I've given **is** the definition of continuity, so of course a continuous function satisfies this property.  If you define continuity differently, then you have to do a little more work.
Answer: Your statement is wrong ! Take $f=\boldsymbol 1_{\left\{\frac{1}{n}\mid n\in\mathbb N\right\}}$ and $x_n=\frac{\pi}{n}$. Then $f(x_n)\to f(0)$, but $f$ is not continuous at $0$.
The statement should be :

$f$ is continuous at $x_0$ if and only if for all $(x_n)$ s.t. $x_n\to x_0$, we have $$\lim_{n\to \infty }f(x_n)=f(x_0).$$
Comment: Yes but can you reverse it?
Comment: Does the bold 1 in the question mean the indicator function?
Comment: @Daniel: yes absolutely (prove it !)
Comment: @AdamRubinson: yes it is.
Answer: Yes, this is a definition, which should be interpreted as an "if and only if" statement rather than an "if" statement, even though definition are usually written using only "if". So $f$ is continuous at the point $x_0$ if and only if whenever $\lim_{n \to \infty} x_n = x_0$, we have $\lim_{n \to \infty} f(x_n)=f(x_0)$.
For another example, you'll often see the definition "$n$ is even if $n=2k$ for some integer $k$". But really $n$ is even if and only if $n=2k$ for some integer $k$. Whenever you are dealing with definitions, you should think of the condition as an "if and only if".
Comment: Exatcly. First statement is actually quite important and worth emphasizing
Comment: "Whenever you are dealing with definitions, you should think of the condition as an "if and only if"." Should I read that as "something is a definition if and only one should think of it as 'if and only if'"?
Comment: @Acccumulation No, I wouldn't say that. There is an integer solution to $a^n+b^n=c^n$ if and only if $n=1$ or $n=2$, but I wouldn't say that's a definition of the set $\{1,2\}$.
Answer: There is well known definition In terms of sequences by Eduard Heine, by which function is continuous in $x_0$ when for $\forall x_n \to x_0, \exists N, n>N, x_n \ne x_0$ (your initial statement leaks conditions on $x_n$) we have $\lim_{n\rightarrow\infty}f(x_n) = f(x_0)$ and it is equivalent to classical Cauchy $\epsilon - \delta$  definition.
So if function is continuous by Cauchy, then your (1) holds.

Reversed continuity


Swiftui specify double format

Question: Text("Värde \(Double(calc2, specifier: "%.2f").rounded())")

//ERROR
I am converting a Slider value that uses a double type, but i cant format specify it?
I get an error and xcode tells me to use signaling(?). I've tried putting it into an Int as well.
whats the right move here?
Answer: You can use
Text("Värde \(calc2, specifier: "%.2f")")

to convert it to 2 decimals.
To have greater flexibility you can use formatter and leverage appendInterpolation on string.  Use the below function or something to that effect

func customFormat(_ number: Double) -> String  {
   let customFormatter = NumberFormatter()
   customFormatter.roundingMode = .down
   customFormatter.maximumFractionDigits = 2

   return "\(number, formatter: customFormatter)"
}

Answer: I assume you want something like
Text("Värde \(String(format: "%.2f", calc2))")

Comment: Thats the old, compatible style. Looks like `specifier:` was added in SwiftUI
Answer: The problem is that Double(calc2, specifier: "%.2f") is optional
to handle it, for example, use Double(calc2, specifier: "%.2f")?.rounded() ?? 0.0

Swiftui specify double format


ASP.Net Application deployment process

Question: I am building an application in c#, webforms using sqlserver.
I need to deploy the project to a staging server daily.
I want to know whats best way to deploy a website and what are steps?
And can we automate this process?
Comment: You might want to specify if this is a website or WAP project template... people use the term "website" loosely when talking ASP.NET
Answer: Walkthrough: Publishing a Web Site:

You have the following options for copying the Web site:

Copy to a folder on the local computer.
Use a UNC share to copy to a shared folder that is on another computer on the network.
Use FTP to copy to a server.
Use the HTTP protocol to copy to a server that has FrontPage Server Extensions (FPSE) installed on it.

For automatic publish your should read about the Continuous intergation
Answer: Personally, I use JetBrains TeamCity, there's a free version of it and it might have a bit of a learning curve for you.
But this is a pretty broad question, there are tons of ways of doing this; from using batch files and MSBuild, to build servers like TeamCiry, CruiseControl.Net, or Microsoft's Team System.
Answer: You should find all the info you need here on Vishal Joshi's new blog post on the topic. They are only now starting to document this properly:
http://vishaljoshi.blogspot.com/2011/07/documenting-key-end-to-end-deployment.html

ASP.Net Application deployment process


Proper Scoring Rule in Optical Character Recognition

Question: Cross Validated likes to promote proper scoring rules in "classification" problems. That is, get accurate probability predictions. Then make the classifications, taking into account the cost of misclassifications. This works well for a situation like medical diagnosis, where, as Frank Harrell argues, the physician would be most interested in the probability. Even the task of spam email detection, which a computer handles automatically by sticking emails in discrete buckets, has a role for a probability calibration.
One place where I cannot see a role for a well-tuned probability, however, is optical character recognition. We stick a printed document into a scanner, and it turns the images of the letters into text of the letters. As far as I can tell, all we would care about is how accurate the resulting text is.

What would be the role of a proper scoring rule that seeks the true probabilities if my lone goal is to train an accurate classifier?

Does optical character recognition do the statistics and decision in one step?

Why would I even want to use a proper scoring rule as the loss function if I'm just going to assess the model based on its ability to assign the highest class probability to the correct character?
Answer: First off, I wouldn't say it's CrossValidated that "likes to promote proper scoring rules". It's more a few very vociferous users. Present company not excepted.
I would agree that the role of scoring rules is much smaller in optical character recognition (OCR) than in many other domains, like medical diagnostics. The reason, IMO, is that the signal to noise ratio is much higher in OCR. We teach five-year-olds to read, after all. Nobody makes a conscious effort to obfuscate our classifiers. We rather make sure to display the signal in a standardized way (the address almost always goes in the same position on the envelope, pages are usually in portrait orientation etc.), and incentives are aligned with making classifiers' life easier. Finally, there is a very small number of target classes: 26 letters, 10 numerals.
In contrast, spammers have an incentive to obfuscate classifiers. In medical diagnostics, the true disease lurks somewhere deep in a highly complex human-shaped black box. Anything beyond the most trivial use cases (the common cold, which we can usually diagnose ourselves and don't visit the doctor with) thus is interpreted by highly trained professionals (either the meat or the silicon version). Image recognition, apart from toy examples, has a limitless number of possible classes to classify an image into.
In a high signal-to-noise situation like OCR on Western scripts, most instances will be probabilistically classified as one class with very high probability, and this classification will usually be correct. It's simply not very interesting to train a classifier to better probabilistically distinguish a lowercase g from a 9, because it's usually easy to do so well enough already, based on context.
So I would say that the emphasis on proper scoring rules is more important in low signal to noise situations. And conversely, I sometimes have the impression that people who rely on accuracy have learned classification in high signal to noise situations (like OCR), and may have difficulties with their toolset when this ratio changes in a new situation.
Comment: Your "limitless possibilities" comment is related to what I mean [here](https://stats.stackexchange.com/q/586201/247274) about zero prior probability yet expecting positive posterior probability.


You are given an array of integers, A1, A2, ..., An

Question:
Possible Duplicate:
Finding three elements in an array whose sum is closest to an given number

You are given an array of integers, A1, A2, ..., An, including negatives and positives, and another integer S. Now we need to find three different integers in the array, whose sum is closest to the given integer S. If there exists more than one solution, any of them is ok. Is there an algorithm to find the three integers in O(n^2) time?
Comment: We are given? Personally I don't feel like I am given any array. I thought that you were given this array of integers.
Comment: It's fine to ask about algorithms, and to ask about homework (people here prefer when you are honest about it), but tagging your question `visual-c++` as if someone was going to give you a Visual-C++ program with the thought you have currently put into the problem is ludicrous.
Comment: Seems to be homework. What have you got so far?
Answer: Yes there is. You want to find a, b, c with a+b+c as close as possible to s.

Order the numbers in increasing order.
Try each a-value. For each a-value, do the following steps:
Start with b = the smallest (first) number and c = the largest (last) number. Decrease c, step by step, if that brings a+b+c closer to s.
Then increase b step by step, and each time you increase b, decrease c step by step if that brings a+b+c closer to s.
Comment: I don't think that this will work in all cases. The difference can be positive or negative (and the numbers to add as well - which is however not relevant to my objection here). So while decreasing c may get you closer for the absolute difference to the expected sum, it may be that after increasing b you'd need to increase c again to get even closer.
Comment: @Lucero: The method is correct. If b1 <= b2 and c1 is the best c for b1 and c2 is the best c for b2, then c2 <= c1.


How to prove that all elementary functions are continuous in their domain?

Question: In our course (Calc 1), our teachers write down a theorem that states that all elementary functions such as algebraic functions (polynomials, rational, irrational functions) and transcendental functions such as trigonometric and hyperbolic functions are continuous in their domains.
Strangely, a function such as $sin^x(x)$ defies this theorem (since it is discontinuous over the entire R), but our textbook does not bring this up.
The theorem is stated without a proof. My understanding is that this is confirmed by experience. The truth is to form is discontinuous functions, one has to recourse to piececwise defined functions, otherwise one has to wait for non-trivial examples of trignonometric series (Fourier series).
Is there a way to formally prove this theorem without recoursing to experience, even though it may seem obvious.
Comment: It is periodically discontinuous, so that's what I mean by discontinuous over the enitre R. The Dirichlet function is also a case where the function concerned is a trigonometric function: https://www.youtube.com/watch?v=LeGWPuRdetM&t=137s
Comment: I don't see the conflict... Is it not continuous over its domain? It's just that the domain is a reunion of disjoint intervals.
Comment: Here is the graph of the function, together with explanations: https://math.stackexchange.com/questions/2691611/is-the-function-sinxx-discontinuous-on-the-entire-mathbbr
Comment: Well, it is a minor point anyway
Comment: The function $\sin^{x}(x)$  is infinitely discontinuous. This means it is very different from most of the elementary function that is known to me. Most of elementary functions are only finitely discontinuous (if we rule out elementary piecewise defined function). The same can be said for $\cos^{x}(x), \tan^{x}(x)$ and $\cot^{x}(x)$
Answer: The definition:

The elementary functions (of $x$) include:

Powers of $x$ : $x$, $x^2$, $x^3$, etc.
Roots of x : $\sqrt{x}$, $\sqrt[3]{x}$, etc.
Exponential functions: $e^{x}$
Logarithms: $\log x$
Trigonometric functions: $\sin x$, $\cos x$, etc.
Inverse trigonometric functions: $\arcsin x$, $\arccos x$, etc.
Hyperbolic functions: $\sinh x$, $\cosh x$, etc.
All functions obtained by replacing $x$ with any of the previous functions
All functions obtained by adding, subtracting, multiplying or dividing any of the previous functions

For the first seven entries on that list, we just verify that they're continuous on their domains.
Then we allow arithmetic operations... hey, there's a theorem we can quote: sums, products, negatives, and reciprocals of continuous functions are continuous, except for the case of a reciprocal at points where that function is zero (which we'll drop from the domain).
Then we allow composition, and again there's a theorem: the composition of continuous functions is continuous.
So there it is - start with the basics, and induct on the number* of arithmetic operations and compositions from there.
*This must be finite. Infinite sums allow for basically anything, which takes us outside the domain of elementary functions.


Making this a loop without copy pasting over and over Javascript

Question: message.channel.send(embed1).then((msgg) => setTimeout(() => {
    const opponentData = userHit(opponentp, userPet.stats.strength, userPet, opponentPet, userp)
    const userData = opponentHit(userp, opponentPet.stats.strength, userPet, opponentPet, opponentp)

    if (opponentData.health >= 1) {
      msgg.edit(opponentData.embed)
    }

    if (userData.health >= 1) {
      msgg.edit(userData.embed)
    }
  }, 1000))
}

So ... I have this code, and I have been stumped for a few days. I need to loop these so they run one after the other until on hits 0 or lower without copy pasting them over and over. I need it to stop editing the message after it hits 0 or lower.
Comment: What exactly do you need to run multiple times?
Comment: ```if (opponentData.health >= 1) {
            msgg.edit(opponentData.embed)
          }

          if (userData.health >= 1) {
            msgg.edit(userData.embed)```

The message editing to new embed
Comment: is there something that triggers the function to run again? the part you dont want to repeat, is having these 2 `if`s? I'm not really understanding what you want
Comment: I want to find a way to trigger the two if statements to loop over and over one after the other until one returns 0 or lower ...
Comment: But to keep running it non-stop? If you keep running just the `if`s non-stop, it will never return 0, because it will block the rest of the code from executing, so the value will be static. When does the health actually changes? Thats when you should run your `if`s
Comment: My health changes in the ```const opponentData = userHit(opponentp, userPet.stats.strength, userPet, opponentPet, userp)
    const userData = opponentHit(userp, opponentPet.stats.strength, userPet, opponentPet, opponentp)``` part ... Those are two separate functions that update the arrays when run ...
Comment: So I got it to loop by changing setTimeout to setInterval but now I don't know how to clear the interval ...
Comment: Instead of returning a `setInterval` open brackets, then do `const interval = setInterval...`.
When you need to stop, just do a `clearInterval(interval)`
Answer: To loop this code you have to use simple do while method!Read more about this method here. Mozilla documentation is very helpful!I hope I helped you with this.Have a nice day!


Gostaria de usar corretamente function()

Question: Usei uma função quando executada mudasse a imagem que foi clicada, só que gostaria de realizar a mesma função em outras imagens. A única solução que me passou pela cabeça é realizar o mesmo processo em todas as imagens, mas acredito que seria o uso incorreto de função.

function changeImage() {
  let image = document.getElementById("Kled")
  if (image.src.match("Kled.jpg")) {
    image.src = "Imagens/Status01_Kled.jpg"
  } else {
    image.src = "Imagens/Kled.jpg"
  }
}

    Kled

    Wukong

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: O código pode utilizar de base o parâmetro id e o index que está atualmente. Onde o index seria a forma de você validar em qual exibição ele está. Exemplo:

0 = Imagem normal
1 = Vendo o Status

Segue exemplo de código a ser utilizado:

const baseUrl = "http://ddragon.leagueoflegends.com/cdn/img/champion/loading";

    function changeImage(championImage) {
      championImage.dataset.index = championImage.dataset.index == 0 ? 1 : 0;
      championImage.src = `${baseUrl}/${championImage.id}_${championImage.dataset.index}.jpg`;
    }
img {
float:left;
max-width: 100px;
padding: 10px;
}

Answer:

   <input type="submit" onclick="mostrarResultado()">

   var result = document.getElementById("resultado");

   function mostrarResultado() {
     result.innerHTML = "Hello, world!";
   }

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Otimizar impressão de grandes resultados do SQL-Server através do ASP

Question: Hoje tenho uma página em ASP clássico com um chain-select não convencional (leia-se "armengado") que retorna um select populado com alguns dados de um banco de dados sql-server (2005).
Seleciono o prédio e retorna o números de andares hábeis para entrega nesse prédio; simples.
Funciona muito bem hoje; O problema é que em breve terei que adicionar mais de 600 linhas nessa base e a consulta vai ficar muito lenta (uma vez que o ASP precisa imprimir todos os dados na página antes do javascript pegar e levar para o select.
Preciso saber se existe uma forma melhor de buscar esses dados - Eu consigo fazer uma interação SQL-SERVER -> JSON para que o dados venham mais rapidamente? Existe uma outra maneira em ASP para popular a página mais rapidamente? Preciso de melhores práticas nesse exemplo especifico.
HTML

    PREDIOS
    <%set RS = server.CreateObject ("ADODB.Recordset")
    RS.Open "select distinct PREDIOS from PI_AUTOCOMPLETAR_LOC ORDER BY PREDIOS",conn,1%>
    <select id="PREDIOS" name="PREDIOS" class="form-control" onchange="venha_lista();">
    <option value="">Selecione</option>
    <%If RS.bof And RS.eof Then
    response.write "Lista Vazia"
    Else
    While not RS.eof
    Response.Write "<option value='"&RS("PREDIOS").value&"'>"&RS("PREDIOS").value&"</option>"
    RS.movenext
    Wend
    End If%>
     </select>

Jquery
function venha_lista() {
    $.post("consulta_loc/atualizar_ANDAR.asp", $("#leva_servico").serialize(), function (data) {
        $("#ANDAR").html(data);
    });
};

atualizar_ANDAR.asp
<%set rs = server.CreateObject ("ADODB.Recordset")
PREDIO = REQUEST("PREDIO")
IF PREDIO = ""  THEN
PREDIO = "%"
end if
RS.Open "select distinct ANDAR from PI_AUTOCOMPLETAR_LOC WHERE PREDIO = '"&PREDIO&"' ORDER BY ANDAR",conn,1 %>
<select id="ANDAR" name="ANDAR" class="form-control">
<option value="">Selecione</option>
<% WHILE NOT RS.EOF %>
<option value="<%Response.write rs("ANDAR")%>"><%Response.write rs("ANDAR")%></option>
<% RS.MoveNext
    WEND    %>
</select>

Comment: Ao invés de escrever todo o código html em conjunto com o dado necessário, trabalhe com objetos JSON. Você vai retornar pouquíssimo volume de dados. Existem hoje funções que você executa a query nesta função e a mesma já retorna o objeto Json, exemplo: `QueryToJson(sql, conn)`. O Jquery compreende JSON o que facilita o trabalho.
Answer: Uma saída é usar o response.flush dentro do loop.
"Sete" response.buffer=true no início do seu código. No loop peça o response.flush para ir escrevendo o conteúdo do script a cada passo desse loop...


Setup view inside onCreateView vs onActivityCreated

Question: I am really curious about what is the best practice to setup views in a Fragment. This is what I have been doing ever since I started developing for android.
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_fragment, container, false);
    ListView listView = view.findViewById(...);
    listView.setAdapter(...);
    return view;
}

I have then read about the method onActivityCreated and read that I need to setup the view inside that and not onCreateView so I wrote my self some code to do the same
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.main_fragment, container, false);
}

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    View view = getView();
    if(view == null){
        throw new NullPointerException("View returned null inside onActivityCreated this shouldn't have happened!");
    }
    ListView listView = view.findViewById(...);
    listView.setAdapter(...);
}

I'm really curious what's the difference here? And which should be used? Which one does android recommend you to use?
Comment: Possible duplicate of [Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments](https://stackoverflow.com/questions/28929637/difference-and-uses-of-oncreate-oncreateview-and-onactivitycreated-in-fra)
Comment: @HarounHajem This isn't a duplicate, I am not asking about the difference between them. I am asking which is better.
Comment: Then you are asking an opinion based question. We don't question that on SO, all the opinion based questions gets deleted or locked e.g. "Is blue better then red?"
Comment: @HarounHajem that isn't totally true, That's like saying `String += String` rather then using a `StringBuilder` in a loop is opinion based. I am asking which is recommended way to setup views in. :)
Comment: Both setup the view but do it in different order. It's recommended in the document to use the latter for setting up states --> see here https://stackoverflow.com/questions/8041206/android-fragment-oncreateview-vs-onactivitycreated
Comment: What's `Latter`?
Comment: It means the last example. Pointing to `onActivityCreated`
Comment: Okay so I don't really get that answer, What does the person mean by static views?
Comment: @Diffy, he meant by static view that the view which is displayed to the user is nothing but the inflated xml layout. No modification in coding or at runtime.
Comment: They don't hold a state, as the Google documentation describes.  It's recommended to restore state in onActivityCreated
Answer: You can really use whatever you want, as long as it works.
However, I believe onViewCreated() is technically the "official" or recommended way to modify and reference your View after it's been created.
Comment: I see, I see some big applications set it inside `onCreateView` aswell. So I am gonna wait for more people to answer before I accept an answer.
Comment: Since no one answered over 11 days, I doubt anyone will soon. So i will just accept this


Postgres array_to_string() with array in JSONB field

Question: I want to get a TEXT of an array in JSONB field. The string that I expected are the following :
dom1.com,  dom2.com,  dom3.com

The JSONB field contains that :
{
    "id": 10,
    "domain_list": [
        "dom1.com",
        "dom2.com",
        "dom3.com"
    ]
}

I try to use the array_to_string() function by using the following code :
SELECT
    array_to_string(
        jsonb_array_elements(
            '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->'domain_list'
        ),
        ', '
    );

But it returns the error
ERROR:  function array_to_string(jsonb, text) does not exist
LINE 2:         array_to_string(
                ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

I also try this
SELECT string_agg(domain_list::text, ', ')
FROM json_array_elements(
    '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->>'domain_list'
) as domain_list;

But it returns the error
ERROR:  function json_array_elements(text) does not exist
LINE 2:     FROM json_array_elements(
                 ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

Answer: You must use -> operator (return value as json) and proper function for you type, jsonb_array_elements in this case:
SELECT
    string_agg(domain_list::text, ', ')
FROM jsonb_array_elements(
    '{"id": 10,"domain_list": [  "dom1.com",  "dom2.com",  "dom3.com"]}'::jsonb->'domain_list'
) as domain_list;

More info here.
Comment: Thank you. I forgotten to use **->** in this case
Comment: glad to help you @jedema


GuitarPro Notes Displaying One Octave Too Low

Question: I have been using the software GuitarPro, and the file I am working in has suddenly begin displaying the notes one octave too low. In short, it acts as if 8va is on, even though it isn't.
Everything has been working correctly up until now, but then I noticed that the notes were displaying incorrectly. They do still sound at the correct octave, though.
The file I am working in is about 140 bars long now and includes quite a few tempo changes and time signature changes (I am currently writing out a lot of riffs and exercises into a single file.)
I am using a custom tuning (All Fourths tuning.) I tried raising the octave in the custom tuning, and could tell by listening that the sound was now an octave too high, although the note displayed was now correct.
Things I've tried:
When I select a note and click 8vb, the note now displays correctly, (but with the 8vb symbol in the score, which is incorrect.)

I checked the custom tuning, it appears to be correct (All fourths tuning, only the top two strings are raised a semitone): E2 A2 D3 G3 C4 F4
Checked the Cleff... appears to be correct, G2 / Octave: regular. Toggling transpose has no effect.
If I select the entire track with ctrl+a, the toolbar shows no use of 8va or 8vb.

One more detail I noticed is that if I copy and paste the notes into a new file, they display at the correct octave again. This would be an ok way to fix the problem except I've noticed that GuitarPro seems to mess up notes pasted into new files, often changing which string notes are played on. (This is a separate issue I'd like to resolve at some point...)
Does anyone know of any other obscure settings I might have accidentally toggled while exploring the software? I've included some screenshots of my settings, in case that helps. Thanks.
Comment: I noticed I got a downvote for this question. Perhaps this seems too specific or off topic for this board, but I asked this question because I noticed there were other questions about Guitar Pro here already. I think I asked the question pretty thoroughly, with plenty of detail, and screenshots. As I have already figured out the answer, I'll leave both the question and answer here in case it helps someone else one day...
Answer: I figured out the answer to my own question. On the Track sidebar menu, a setting called "Transposition Tonality" needs to be set to "One Octave Lower" instead of "Same Octave". I don't actually know what this means, but it does appear to have been the problem. The default in a new file appears to be "One Octave Lower", whatever that means...
EDIT: TIL - The guitar is traditionally notated an octave higher than the actual pitch, presumably so it fits better on the stave. I guess what I was seeing before is the true pitch of the guitar, and this transposition setting is on by default to reflect the standard convention.


How to create a date column with conditional format in pandas

Question: I hope you can help me out with this one, which I think it's easy but I just can't manage to solve it.  I have a Dataframe with a datetime zone column as string and a country column. Date values for USA are in "%y-%d-%m" format and for the rest of the world is  "%y-%m-%d". What I want to do is to create another column with the same date format. Thing is that i have to use one format for USA and another one for the rest of the world, How can I Solve this?
data={"datetime":["2020-02-10 8:02:55 PM PST","2020-02-10 8:02:55 PM PST","2020-10-02 8:02:55 PM PST"],"country":["USA","USA","FRANCE"]}
df=pd.DataFrame(data)
df["date"]=pd.to_datetime(df["datetime"])
df["Month"]=pd.DatetimeIndex(df["date"]).month
df["Year"]=pd.DatetimeIndex(df["date"]).year
df

Here's the DataFrame I Get (i couldnt paste it with the DT Format, how do you do that, btw?). Thing is that for France it uses 2 as the month value. I tried to use python pd.series.dt.strftime but i can't manage to use it with the country coundition so I can use one format for usa and another one for the rest of the countries.
                    datetime country                date  Month  Year
0  2020-02-10 8:02:55 PM PST     USA 2020-02-10 20:02:55      2  2020
1  2020-02-10 8:02:55 PM PST     USA 2020-02-10 20:02:55      2  2020
2  2020-10-02 8:02:55 PM PST  FRANCE 2020-10-02 20:02:55     10  2020

thanks a lot!
Comment: To "how do you do that": (1) Select the pasted code that you'd like to make it a code block and press the `{}` button on the top of the editor. (2) enclose the section with triple backticks.
Answer: You can specify if the day comes first with the dayfirst keyword. The challenge here seems to be parsing PST correctly to time zone US/Pacific. You can do that with a mapping dict - however, pd.to_datetime doesn't support that (yet, v1.1.3) so you'll have to use dateutil instead.
import pandas as pd
import dateutil

df = pd.DataFrame({"datetime": ["2020-02-10 8:02:55 PM PST", "2020-02-10 8:02:55 PM PST", "2020-10-02 8:02:55 PM PST"],
                   "country": ["USA", "USA", "FRANCE"]})

# add column that specifies day first:
df['dayfirst'] = df['country'] == "FRANCE"

# create a mapping dict, mapping strings to time zones. add more if needed (e.g. PDT).
tzinfos = {'PST': dateutil.tz.gettz('US/Pacific')}

# create a function to parse the datetime strings
# this is not strictly needed but seems appropriate in terms of readability
def custom_parse_date(r):
    return dateutil.parser.parse(r['datetime'], dayfirst=r['dayfirst'], tzinfos=tzinfos)

df['parsed_dt'] = df.apply(lambda r: custom_parse_date(r), axis=1)

# df['parsed_dt']
# 0   2020-02-10 20:02:55-08:00
# 1   2020-02-10 20:02:55-08:00
# 2   2020-02-10 20:02:55-08:00
# Name: parsed_dt, dtype: datetime64[ns, tzfile('US/Pacific')]


PHP Calculating future date by adding days to a variable date

Question: I was looking at this post, and it is close to what I need:
PHP - How to count 60 days from the add date
However, in that post, the calculation is performed by adding 60 days to the current date. What I need to do is calculate the date based on a variable date (and not the current date).
Something like this:
$my_date = $some_row_from_a_database;
$date_plus_10_days = ???;

Anyone know how to do that?
Thanks
Comment: What's the date format in the database (timestamp)?
Answer: You can put something before the "+10 days" part:
strtotime("2010-01-01 +10 days");

Comment: +1 learnt a new thing today. Thanks. Probably the OP wants to convert back to some human readable string. So, something like date('Y-m-d',strtotime("2010-01-01 +10 days"));
Comment: `strototime` takes a timestamp as the second argument which will be used as the reference timestamp for what you put as first argument, so if the OP got a timestamp from the MySQL, he can just as well do `strtotime('+60 days', $timestampFromMySql);`
Answer: Use date_add
http://www.php.net/manual/en/datetime.add.php
$my_date = new DateTime($some_row_from_a_database);
$date_plus_10_days = date_add($my_date, new DateInterval('P10D'));

Comment: You should mention that this  is  only available from PHP 5.3.0 on.
Answer: You will have to look into strtotime(). I'd imagine your final code would look something like this:
$dateVariable      = strtotime('2017-01-29');//your date variable goes here
$date_plus_60_days = date('Y-m-d', strtotime('+ 60 days', $dateVariable));
echo $date_plus_60_days;

If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$date_plus_60_days = new DateTime("2006-12-12");
$date_plus_60_days->modify("+60 days");
echo $date_plus_60_days->format("Y-m-d");

Answer: I see you are retriving data from a database.
If you are using mysql you can do it on the select:
Example: you need the last date of the table and this date-7 days
select max(datefield) as ultimaf, DATE_SUB(max(datefield),INTERVAL 7 DAY) as last7
from table

It´s easy use curdate() if you want todays date.
If you need a dynamic between that selects the count of last 7 days:
select count(*) from table
where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=datefield"

Answer: date('Y-m-d H:i:s', strtotime("2014-11-24 06:33:39" +35 days"))

this will get the calculated date in defined format.
Answer: Suppose today's date is
date_default_timezone_set('Asia/Calcutta');
$today=date("Y-m-d");

And i can add 10 days in current date as follows :
$date_afte_10_days = date('Y-m-d', strtotime("$today +10 days"));


How are the weights of a CNN computed?

Question: I am trying to understand the logic behind convolutional neural networks. To my understanding, the weights used are nothing more than an $w \times h$ matrix (a filter)
and as with the normal neural networks, those filters are randomnly initialized.
My question is how are they updated? Is an optimization algorithm used to do so (e.g. SGD)? If yes, at which step of training is this happening (is there a backoprop step as in common neural networks)?
Comment: They are updated exactly the same as any other parameters. Could you tell us what is your understanding and where are you lost?
Comment: I'm lost because in most of the sources I've seen, they only discuss about initializing the filters and they seem to not care about their values during the backprop step.
Answer: Yes, they are updated using SGD (or SGD variants: RMSprop, Adam, etc) through backpropagation. To see this working with great animations and numerical examples (with code in python/numpy) I suggest you to see this amazing post by Andrej Karpathy: http://cs231n.github.io/convolutional-networks/

How are the weights of a CNN computed?


Geometry Puzzle - Largest circle on Chess

Question: The following puzzle was asked in company interview round.I have no idea ,how to do it?
<code>What is the diameter of the largest circle that can be drawn on a
chessboard so that its entire circumference
gets covered by the black squares and no part of the circumference
falls on any white space.
The side of the chess square is 2 cm.
</code>
How to solve this Puzzle?
Thank You!
Comment: I think it's $2\sqrt{10}$, this fits in to a 5x5 square grid with a black square in the middle, going through the corners of all the black squares. If it were any bigger, there would be no circle that would fit the corners of the black squares, that is,  the corners of the black squares would not be equidistant from an origin.
Answer: It's one that passes through $8$ black squares arranged in a diamond shape, passing through the corners of each. Any larger and it couldn't curve in one direction while passing only through corners, which is has to do to never hit a white square.
Any circular arc can be repeated on the board simply by reflecting it across each axis and diagonal. In other words, a circle can be considered fully defined by an $8^{th}$ of its circumference. Of course it could be defined by any section, but that's irrelevant since we want to use the board's eightfold symmetry. Our definition (on an $8^{th}$ circumference arc) involves centering the circle in a central  black square and specifying the radius to the single vertex the arc must pass through. We can clearly specify such an arc, and due to the symmetry of the board we know that the circle will also pass through all the other vertices we need it to.
Find the actual diameter by looking at opposite vertices. This involves going $2\ cm$ down and $6\ cm$ across (or equivalent), giving a diameter of $2\sqrt{10}$.


If $P(x)$ is a polynomial such that $P(\cos^2x)=P(\sin^2x)$ which of the following are true

Question: If $P(x)$ is a polynomial for all $x$ belongs to $[0,π/2]$ such that $P(\cos^2x)=P(\sin^2x)$ for all $x$ belongs to $[0,π/2]$  which of the following are true:

$P(x)$ is an even function
$P(x)$ is a polynomial of even degree
$P(x)$ can be expressed as a polynomial in $(2x-1)^2$

I tried evaluating it as
$$P(\sin^2x) = P(\cos^2x)$$
$$P(\sin^2x) = P(1-\sin^2x)$$
Let $\sin^2x  = y $
The equation becomes $P(y)=P(1-y)$ for all $x$ belongs to $[0,1]$.
Now I don't know how to further find the properties of this polynomial. Any help is appreciated :)
Comment: $P(y)=P(1-y)$ for all $y \in [0,1]$ implies $P(y)=P(1-y)$ for all $y \in \mathbb R$.
Answer: Since$$(\forall x\in\mathbb{R}):\sin^2(x)+\cos^2(x)=1,$$you know that$$(\forall x\in\mathbb{R}):P(x)=P(1-x).$$Let $Q(x)=P\left(x+\frac12\right)$. Then\begin{align}Q(-x)&=P\left(-x+\frac12\right)\\&=P\left(1-\left(-x+\frac12\right)\right)\\&=P\left(x+\frac12\right)\\&=Q(x).\end{align}So, $Q(x)$ is even, and therefore $Q(x)=R(x^2)$ for some polynomial $R(x)$. But then$$P(x)=Q\left(x-\frac12\right)=R\left(\left(x-\frac12\right)^2\right),$$and this is equivalent to the third item from your list.
Comment: #2 is also true.
Comment: @lhf Indeed it is.
Answer: $P(y)=P(1-y)$ for all $y \in [0,1]$ implies $P(y)=P(1-y)$ for all $y \in \mathbb R$.

False: $P(x)=x(1-x)$ satisfies the condition but is not an even function
True: If the degree of $P$ is $n$ and its leading coefficient is $a$, then the leading coefficient of $P(1-y)$ is $(-1)^n a$.
Has been answered nicely by José.


within awk how to check for a defined value before attempting a calculation

Question: The following awk line will fail when c15 is not defined or is 0. How to modify it so that in such cases it does not attempt the calculation, but instead provides an error message or does nothing:
cat formatted.dsv | awk -F"\t" '{ c12 = $12; c15 = $15; c17 = $17; c16 = $16; c4 = $4; c9 = $9; c5 = $5; c10 = $10; c14 = $14; c8 = $8; c7 = $7 } END { printf "%d\n", ((c12+c17+c16+c4+c9+c5+c10+c14+c8+c7))/c15)*1000 }'
Comment: `! c15 && {exit}` but better give a more simple example.
Answer: if a variable is undefined in awk(1) then it has a default value of null string or zero, depending on the context.
I think you can use this as follows:
if (c15) printf "%d\n", ((c12+c17+c16+c4+c9+c5+c10+c14+c8+c7))/c15)*1000
else print "C15: null or empty\n"


.NET C# Pass IIS app pool credentials as basic authentication Credentials to HTTPRequest

Question: I need to pass IIS app pool credentials as network credentials to a WebAPI call in a .NET application.
var request = (HttpWebRequest)WebRequest.Create("WEB API URL");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential("USERNAME","PASSWORD","DOMAIN");

This works fine.
My question is instead of passing hard coded credentials I need to pass IIS app pool credentials as a NetworkCredential object.
I have checked with below code but doesn't work for me.
WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
using (identity.Impersonate())
{
    var request = (HttpWebRequest)WebRequest.Create("WEB API URL");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Credentials = CredentialCache.DefaultNetworkCredentials;
}

Comment: *Don't* use basic authentication in this case. If you want to make a call as a Windows Account (which the pool account is), make sure the service *accepts* Windows authentication. The IIS App Pool user accounts are *special, local* accounts though that aren't visible to other computers on a domain. If you want to call one service from another use domain accounts
Comment: So could u plz guide me how to pass APP POOL user credentials to WEB API.?
Answer: There are only 2 options here that I can think of.
Change your authentication type to Windows authentication
You can often change this through your project. When you create a new project it will even ask if you'd like to authenticate users via Windows authentication.
Link up with Active Directory
Some organisations / companies will use Active Directory to manage their users. This is what allows you to log into specific machines in the office, or limits you to a single workstation, or lets the IT admins reset your password when you forget etc. It's an amazing tool, but a pain in the neck to work with. I'd recommend using a virtualized network using virtual machines to accomplish this.


How to access multiple IP-s of host from virtualbox guest windows

Question: I have a linux host with virtualhosts on 127.0.0.1 and 127.0.0.2 and 127.0.0.3 (the reason is that I need multiple domains with https) and I would like to access them from virtualbox in a windows guest. Now I know that 10.0.2.2 in the virtualbox gets to 127.0.0.1, but I need to get to the other IP-s of the host in order to enable IE to see my virtualhosts in https. How can I do it?
Answer: These IP addresses are loopback addresses. They aren't bound to your network card. To access your host through several IP addresses, you need several network cards, or virtual IPs. But this can't work with 127.0.0.X
Comment: thanks. I changed the IP-s on the host, added eth0:1 = 192.168.142.1, eth0:2 = 192.168.142.2, eth0:3 = 192.168.142.3, and I use these IP-s from the guest OS (and not 10.0.2.2)


Changing a Cloud DNS IP (Resource Record Type A) with no propagation time

Question: I have a GKE Cluster with istio installed. Istio ingress gateway automatically creates a load balancer with an IP.
I put this IP in Cloud DNS as image below (Fake IP with hidden DNS name). Everything work and I can access my cluster using the URL.

I know I can reduce TTL time to try reduce propagation time if I need to change the IP as described in documentation.

Propagation of changes
Changes are propagated in two parts. First, the change that you send
  through the API or command-line tool must be pushed to Cloud DNS's
  authoritative DNS servers. Second, DNS resolvers must pick up this
  change when their cache of the records expires.
The DNS resolver's cache is controlled by the time-to-live (TTL) value
  that you set for your records, which is specified in seconds. For
  example, if you set a TTL value of 86400 (the number of seconds in 24
  hours), the DNS resolvers are instructed to cache the records for 24
  hours. Some DNS resolvers ignore the TTL value or use their own values
  that can delay the full propagation of records.
If you are planning for a change to services that requires a narrow
  window, you might want to change the TTL to a shorter value prior to
  making your change. This approach can help reduce the caching window
  and ensure a quicker change to your new record settings. After the
  change, you can change the value back to its previous TTL value to
  reduce load on the DNS resolvers.

But as you can see this solution is not reliable because some DNS resolvers can not follow my TTL.
Is there any way to reduce this propagation time to zero? I tried to create a load balancer and a forwarding rule with no success.
Answer:
Is there any way to reduce this propagation time to zero?

Over the Internet? No. See also: How to shorten DNS propagation effect
Authoritative name servers may have some minimum TTL. Although often the minimum is just a few minutes. Google Cloud DNS can handle queries near its minimum TTL, load is less of an issue there.
A few resolvers have been observed to increase TTL. While these are a minority, the expectation that 100% of users will move by the TTL is not realistic.
Answer:
Is there any way to reduce this propagation time to zero?

No.
Assume that all other DNS servers will honor the TTL, because you can't control it nor influence their behavior if they don't. Set the TTL to whatever you think reasonable and whatever accomplishes your goals. If some DNS servers don't honor it there's nothing you can do about it anyway.