text:
Q: Замена текста на изображение в c# Как можно заменить текст на изображение? Пытаюсь через буфер обмена-простое место вместо текста.
Clipboard.SetImage(Image.FromFile("E:\\Dropbox\\Фонд\\1310\\опрос\\1210\\Statistick_program\\Statistick_program\\bin\\Debug\\dig1.bmp"));
    // copy the image to the clipboard

  //  Clipboard.SetImage("^E:\\Dropbox\\Фонд\\1310\\опрос\\1210\\Statistick_program\\Statistick_program\\bin\\Debug\\dig1.bmp");

    app.Selection.Find.Execute(FindText: "<dig1>", ReplaceWith: Clipboard.GetImage());

    object SaveASFile = (object)Directory.GetCurrentDirectory() + "\\Temp57.doc";
    doc.SaveAs(SaveASFile, missing, missing, missing, missing);
    doc.Close(false, missing, missing);

A: А вот и ответ:
   var app = new Application();
        try {
            //This code creates a document based on the specified template.
            var doc = app.Documents.Add(
                Path.GetFullPath(@"Docs\foo.dotx"),
                Visible: false);

            doc.Activate();

            //for each keyword you want to replace.
            //************************************************
            var keyword = "angus-young";
            Console.WriteLine("Replacing keyword: {0} ...",keyword);
            var sel = app.Selection;
            sel.Find.Text = string.Format("[{0}]", keyword);
            sel.Find.Execute(Replace: WdReplace.wdReplaceNone);
            sel.Range.Select();

            //This code inserts the image
            var imgPath = Path.GetFullPath(string.Format(@"Img\{0}.jpg", keyword));
            sel.InlineShapes.AddPicture(
                FileName: imgPath,
                LinkToFile: false,
                SaveWithDocument: true);
            //************************************************

            //finally, save the doc.
            doc.SaveAs(Path.GetFullPath(@"Docs\foo.docx"));
            doc.Close();
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
        finally {
            app.Quit();
            sys.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
        }
        Console.WriteLine("Press [Enter] to exit");

Console.ReadLine();


text:
Q: Android application exiting abruptly during database query When I tried to do database query from my activity class, the application ended abruptly. I checked logcat, it showed 'Skipped this many frames. The application may be doing to much work on it's main thread'. Then I tried using Thread, but still it abruptly ends.
Code snippet
if(v == findViewById(R.id.btnlogin)) {
        if((tlogid.length()>0) && (tpwd.length()>0)) {

            final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading...");
            dialog.setCancelable(false);
            dialog.show();
            final DBQuery dbq = new DBQuery();
            Thread t = new Thread(){
                @Override
                public void run() {
                    dbq.queryforAccount(tlogid, tpwd, getApplicationContext());
                }
            };
            try {
                t.start();
            }
            catch (Exception e){
                e.printStackTrace();
            }

            final Cursor c = dbq.getCursor();

            if(c.getCount() > 0) {
                Bundle detail = new Bundle();
                detail.putString("Accountid", c.getString(0));
                detail.putString("Loginid", c.getString(1));
                detail.putString("Name", c.getString(2));
                i = new Intent();
                i.setClass(getApplicationContext(), Welcome_user.class);
                i.putExtras(detail);
                startActivity(i);
            }

But still the app ends, showing Null pointer exception in the Logcat.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamic creating controls in asp.net mvc4 I am trying to create controls dynamically in asp.net mvc4 but having some issues and need some suggestions as well. The following statement in the below is not working it shows me error line beneath "row.Options"
                               @for (var o in row.Options )
Beside this, can i dynamically create dropdownlist or dropdownlistfor if yes then how can i assign name and values according to current scenario?
View

            @foreach(var row in Model.Controls) {
                var i = 0;
                <div>
                     <label>@row.Caption</label>
                     @if (row.ControlType == "text") {
                        <input type="text" name="@row.Name" />
                     } else if (row.ControlType == "select") {

                        <select name="@row.Name">
                            @for (var o in row.Options ) {
                                <option value="@o.Value>">@o.Text</option>
                            }
                        </select>
                     }
                </div>
                i++;
            }
            </ul>

View Model
public List<SelectListItem> MembershipTypeList { get; set; }

public class Controls
{
    public string Caption {get; set;}
    public string ControlType {get; set;}
    public string Name {get; set;}
    public List<SelectListItem> Options { get; set; }
}

Controller Snippet
    public ActionResult Signup()
    {
        signup.MembershipTypeList.Add(new SelectListItem()
        {
            Text = "Student  £18.00",
            Value = "Student"
        });

        signup.MembershipTypeList.Add(new SelectListItem()
        {
            Text = "Associate  £18.00",
            Value = "Associate"
        });

        signup.Controls = new List<Controls>();
        signup.Controls.Add(new Controls() { Caption = "Age", ControlType = "text", Name = "txtage" });
        signup.Controls.Add(new Controls() { Caption = "Name", ControlType = "text", Name = "txtname" });
        signup.Controls.Add(new Controls() { Caption = "Membership", ControlType = "select", Name = "txtmembership", Options = signup.MembershipTypeList });

        return View("Signup", signup);
}

A: I think it might just be an extra angle bracket causing this, try changing to:
<option value="@o.Value">@o.Text</option>

A: For starters, your code is invalid here:
<select name="@row.Name">
    @for (var o in row.Options ) {
        <option value="@o.Value>">@o.Text</option>
    }
</select>

Remove the ">" from @o.Value>
Rendering as it is breaks the html.
Fix:
<select name="@row.Name">
    @foreach (var o in row.Options ) {
        <option value="@o.Value">@o.Text</option>
    }
</select>


text:
Q: CSRF Tokens.Are they really secure?
Possible Duplicate:
Doubt on prevention of CSRF

I have a few serious doubts :
We basically use random session tokens to check if a  POST request has originated from a desired page.  Suppose a malicious  user opens up the page,right clicks and views the source of the page.then he gets the token for the current session. He opens up another tab,and uses the token wit his own malicious script. This way,the session is intact, and the token has been stolen too! How can this be prevented ?
Like if an ajax function says :
$.post("abcd.php",{'uid':userid,'code':'<?php echo  md5($_SESSION['randcd']); ?>'}

Clearly, the token will be visible, to the hacker in the source code. And since the session isn't destroyed , the token will not change. Hence my doubts
I thank everyone here for being so  patient on this wonderful forum.
Thanks for all the help


text:
Q: Unblock AWS for logged in users with sufficient rep? Per this meta question, you can't connect to SO on a EC2 machine because of past abuse.
Is there a way to allow signed in/authenticated users to see SO?  Or is there something fundamental about the networking techniques being used to block EC2 that would prevent that.
It's not the end of the world to jump back from my remote machine to a local browser.  But then again, rep on the site should serve as a pretty easy check to prevent bad behavior...

A: Adding a captcha would be good .. that's how http://whirlpool.net.au deal with the issue


text:
Q: Setting a gradient background to a button automatically resizes it I am trying to set a gradient xml file as background to a button.But when i add the drawable xml file as background, the size of the button changes.The button is to the right of edittext and the size of the button becomes bigger than the edittext.
The code:
The button:
<Button
            android:id="@+id/btndob"
            android:layout_width="127dp"
            android:textColor="#FFFFFF"
            android:background="@drawable/button_clicked_selector"
            android:layout_height="fill_parent"
            android:text="SELECT DATE" />

button_clicked_selector.xml
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/button_gradient" />
<item android:state_pressed="true" android:drawable="@drawable/button_clicked_gradient" />
</selector>

button_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <!--  Gradient Bg for listrow -->
   <gradient
      android:startColor="#00aff0"
      android:endColor="#0081b0"
      android:angle="270" />
</shape>

button_clicked_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <!--  Gradient Bg for listrow -->
   <gradient
      android:startColor="#00aff0"
      android:endColor="#00aff0"
      android:angle="270" />
</shape>


text:
Q: Trying to load an app from a local file rather than from the website I have already created the app, but it needs to be connected to the internet to work. In essence it just displays the website through an app. I would like to have the website installed on the app so that it can load without requiring an internet connection.
I have downloaded my webpage while, and added it to the Android SDK. Its saved it under the Java section. Now the code I used to load the webpage while online was the following:
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("http://kuglerdesign.com/");
        mWebView.setWebViewClient(new MyAppWebViewClient());

I have searched on stackoverflow for a similar question, and have found the following lines of code:
URL url = this.getClass().getResource("/com/path/to/file.txt")

File file = new File(url.toURI());

and these from a different answer:
File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile());

My question is how to implement these to a file thats in the Android SDK. Do I just replace all the mWebView and WebSettings or do I still need them as its a HTML file?
Or would I be better off just to set the mWebView Url to a local file?
So replacing the following line of code:
mWebView.loadUrl("http://kuglerdesign.com/");

with this line :
mWebView.loadUrl("file:///kuglerdesign.html");

Any help would be greatly appreciated.
(sorry for being such a novice at Java :( ...)

A: You have to put your html-files into the assets directory.
d.android.com states for the assets folder:

You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

The WebView can directly load your files, by using file:///android_asset/ as URI path, which can be read here.
That would make your call as easy as mWebView.loadUrl("file:///android_asset/kuglerdesign.html");


text:
Q: Locally change the behavior of the underscore in the math mode to group all the successive characters in the subscript I would like to know if it is possible to have a switch (e.g. \myswitch) that:
1- changes the behavior of underscore _ only in math mode such that all the following characters are grouped into a single subscript while terminating the subscript processing when encountering the first white space.
2- locally affects the math mode inside the parent environment or group without interaction with any math content outside the parent environment or group in which it was switched on.
3- accepts an optional wrapping command. For example, \myswitch[1][\mathit] means that the all the subscript is wrapped in \mathit{<all the subscript characters>} by default, and \myswitch[] will not format the subscript but group the subscript characters as long as the switch is on.
4- is able to include white space in the subscript without treating it as the terminating character when the subscript is wrapped in a pair of curly braces {}.
For example,

\documentclass{article}
\usepackage{mathtools}
\usepackage[margin=1cm]{geometry}
\parindent0pt
\begin{document}

    Before switching it on\\
    \verb|$A_BCD$| should yield the same output of \verb|$A_B CD$|\\

    Enabling the switch inside an environment or group\\
    \verb*|\begin{some environemnt} or \begingroup|\\
    Switch it on here\\
    \verb|$A_BCD E_FGH$| should yield the same output of \verb|$A_\mathit{BCD} E_\mathit{FGH}$|\\

    Change the default \verb|\mathit| to wrap the subscript in, for example, \verb|\mathrm|\\
    \verb|$A_BCD E_FGH$| should yield the same output of \verb|$A_\mathrm{BCD} E_\mathrm{FGH}$|\\

    Spaces can be included if the subscript is wrapped in a pair of curly braces\\
    \verb|$A_{B CD}$| will yield the same output of \verb|$A_\mathit{B CD}$|\\

    Disabling the default optional argument will remove the effect of \verb|\mathit|\\
    \verb|$A_BCD E_FGH$| should yield the same output of \verb|$A_{BCD} E_{FGH}$|\\
    \verb*|\end{some environemnt} or \endgroup|\\

    Even it is left switched on in another environment/group, it has no effect outside it\\
    \verb|$A_BCD$| should yield the same output of \verb|$A_B CD$|\\

\end{document}


text:
Q: Send Push Notification To a Windows Phone 8.1 app Without submitting it to store I want to send to push notification to a windows phone 8.1 app that currently not submitted to store. is there a way for this situation?
I know that MPNS can send unauthenticated push notification (with some limits). but is there a way to send unauthenticated push notification through WNS (as I know cloud server must first authenticate  itself via Package SID and Client Secret)?
for the last question is this assumption is true?
windows phone 8 -> can only use MPNS
windows phone 8.1 Silverlight - > can use both MPNS and WNS
windows phone 8.1 Universal -> can use WNS

A: You can use push notifications before publishing by getting a packageSID and client secret to authenticate against WNS by just reserving a name for your app in the Store and then going to Services --> Push notifications. There's no way to use WNS unauthenticated but you don't need to submit your app to get that authentication working.
And yes, your assumptions are correct.


text: Q: Lower bounds of inner products in a real Hilbert spaces let $H$ be a real Hilbert space and let $x,y\in H$ such that the coordinates of the vectors $x$ and $y$ can be positive or negative, are there any theorems that deal with a lower bound of $<x,y>$? Is there a way to assure that $<x,y>\geqslant0$ (besides the trivial approach by which take the vectors $x$ and $y$ to be such that  their coordinates are either all positive or  either all negative)  or $<x,y>\leqslant0$


text:
Q: Ordering the $\binom{N}{2}$ slopes of chords of a convex function at $N$ points Recall the following :

Let $f:\mathbb{R}\to\mathbb{R}$ be a convex function, and let $x<y<z$ be distinct real numbers, then one has
  $$
\frac{f(y)-f(x)}{y-x}\leq
\frac{f(z)-f(x)}{z-x}\leq
\frac{f(z)-f(y)}{z-y}
$$
  Furthermore, if any two of these three slopes are equal, then all three are equal.

Let $N\geq 3$ be an integer, and let us identify the two element subset $\lbrace i<j\rbrace$ of $\lbrace 1,\dots,N\rbrace$ with the symbol $(ij)$.
Let $x_1<\cdots<x_N$ be $N$ distinct real numbers. Define a preorder on the set of two element subsets of $\{1,\dots,N\}$ by defining
$$
(ij)\preceq(kl)\iff s_{ij}\leq s_{kl}
$$
where, for all $1\leq i<j\leq N$
$$
s_{ij}:=\frac{f(x_j)-f(x_i)}{x_j-x_i},
$$
and $(ij) \sim (kl)$ if both $(ij)\preceq(kl)$ and $(kl)\preceq(ij)$ hold.

The above fact may be recast as follows :
  \begin{equation}
\forall~1\leq i<j<k\leq N,
\quad
(ij)\preceq(ik)\preceq(jk)
\end{equation}
  and $(ij)\sim(jk)\iff(ij)\sim(ik)\iff(jk)\sim(ik)\iff (ij)\sim(jk)\sim(ik)$.

Question 1 : Suppose $\preceq$ is a preorder on the set of all two element subsets of $\{1,\dots,N\}$ satisfying the above condition. Does there exist a convex function $f$ and $N$ points that define the same preorder by the definition outlined above ?
Question 2 : Suppose $\preceq$ can be realized with a strictly convex function $g$, can one then realize $\preceq$ using the map $f(x)=x^2$ ?

A: As a complement to Dap's answer, here is an answer to question 2 by a slightly different method (it does not rely on equality of some slopes).
Consider six points $M_k(x_k,y_k) (1\leq k \leq 6)$ in the plane, defined as follows :
$$
\begin{array}{|c|c|c|c|c|c|c|}
\hline
k & 1 & 2 & 3 & 4 & 5 & 6 \\
\hline
x_k & 1 & 2 & 3 & 4 & 7 & 8 \\
\hline
y_k & 0 & 0 & 1 & 6 & 30 & 42 \\
\hline
\end{array}
$$
If we denote by $\sigma_k=\frac{y_{k+1}-y_k}{x_{k+1}-x_k}$ the slope from $M_k$
to $M_{k+1}$, we see that the sequence $(\sigma_k)_{1\leq k\leq 5}$ is increasing :
$$
\begin{array}{|c|c|c|c|c|c|}
\hline
k & 1 & 2 & 3 & 4 & 5  \\
\hline
\sigma_k & 0 & 1 & 5 & 8 & 12  \\
\hline
\end{array}
$$
So there is a strictly convex map $g$ such that $g(x_k)=y_k$ for $1\leq k\leq 6$. The pre-order realized by $g$ satisfies :
$$
(14) \prec (23), (25) \prec (34), (36) \prec (45), \textrm{ but } (34) \prec (16). \tag{1}
$$
This cannot be realized by $f(x)=x^2$ because in that case
$$
s_{34}-s_{16}=\big(s_{23}-s_{14}\big)+\big(s_{34}-s_{25}\big)+\big(s_{45}-s_{36}\big) \tag{2}
$$

A: As you mention in a comment, Pascal's theorem gives an extra requirement. In particular we have the special case where the Pascal line is the line at infinity:

Given points A, B, C, D, E, F lying on a conic, if AB is parallel to DE, and BC is parallel to EF, then CD is parallel to FA.$\tag{*}$

For question 1, the answer is no at least for $N=7.$ Let $A,C,E,X,D,F,B$ denote the points $(x_1,f(x_1)),\dots,(x_7,f(x_7))$ respectively. Take the relation describing the preorder defined by a configuration meeting the hypotheses of (*) with the degenerate conic $y=|x|$ and $X=(0,0)$ - for example $x_1,\dots,x_7=-4,-2,-1,0,1,2,4$ and $f(x)=|x|.$ Then modify it by requiring that the slope of CD is greater than the slope of FA instead of equal. To satisfy this preorder, $A,C,E,X$ are forced to lie on one line, and $X,D,F,B$ are forced to lie on a different line. This doesn't destroy either of the conditions on $\preceq.$ The union of the two lines is a degenerate conic, so (*) applies and so there is no configuration of points that defines this preorder.
For question 2, the answer also no at least for $N=6.$ Let $A,C,E,D,F,B$ denote the points $(x_1,f(x_1)),\dots,(x_6,f(x_6))$ respectively, and as before take the preorder defined by a reference configuration of points on the curve $y=x^2$ meeting the hypotheses of (*), but then move $A$ slightly to the left. I haven't worked out the actual co-ordinates, but there should be a fairly simple configuration determined by $C,E,D,F=(4,-2),(1,-1),(1,1),(4,2).$ Moving $A$  modifies the preorder by requiring that that the slope of CD is greater than the slope of FA instead of equal. The requirement that the points lie on a conic means that (*) applies and so there is no configuration of points on $y=x^2$ that defines this preorder.


text:
Q: Not able to fit a function with scipy.optimize.curve_fit() I would like to fit the following function:
def invlaplace_stehfest2(time,EL,tau):
    upsilon=0.25
    pmax=6.9
    E0=0.0154
    M=8
    results=[]
    for t in time:
        func=0
        for k in range(1,2*M+1):
            SUM=0
            for j in range(int(math.floor((k+1)/2)),min(k,M)+1):
                dummy=j**(M+1)*scipy.special.binom(M,j)*scipy.special.binom(2*j,j)*scipy.special.binom(j,k-j)/scipy.math.factorial(M)
                SUM+=dummy
            s=k*math.log(2)/t[enter image description here][1]
            func+=(-1)**(M+k)*SUM*pmax*EL/(mp.exp(tau*s)*mp.expint(1,tau*s)*E0+EL)/s

        func=func*math.log(2)/t
        results.append(func)
    return  [float(i) for i in results]

To do so I use the following data:
data_time=np.array([69.0,99.0,139.0,179.0,219.0,259.0,295.5,299.03])
data_relax=np.array([6.2536,6.1652,6.0844,6.0253,5.9782,5.9404,5.9104,5.9066])

With the folowing guess:
guess=np.array([0.1,0.05])

And scipy.optimize.curve_fit() as folow:
  Parameter,Covariance=scipy.optimize.curve_fit(invlaplace_stehfest2,data_time,data_relax,guess)

For A reason that I don't understand I am not able to fit the data correctly. I get the following graph.
Bad fitting
My function is undoubtedly correct since when I use the correct guess:
guess=np.array([0.33226685047281592707364253044085038793404361200072,8.6682623502960394383501102909774397295654841654769])

I am able to fit correctly my data.
Expected fitting
Any hint on why I am not able to fit correctly? Should I use another method?
Here is the hole program:
##############################################
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.pylab as mplab
import math
from math import *
import numpy as np
import scipy
from scipy.optimize import curve_fit
import mpmath as mp

############################################################################################
def invlaplace_stehfest2(time,EL,tau):
    upsilon=0.25
    pmax=6.9
    E0=0.0154
    M=8
    results=[]
    for t in time:
        func=0
        for k in range(1,2*M+1):
            SUM=0
            for j in range(int(math.floor((k+1)/2)),min(k,M)+1):
                dummy=j**(M+1)*scipy.special.binom(M,j)*scipy.special.binom(2*j,j)*scipy.special.binom(j,k-j)/scipy.math.factorial(M)
                SUM+=dummy
            s=k*math.log(2)/t
            func+=(-1)**(M+k)*SUM*pmax*EL/(mp.exp(tau*s)*mp.expint(1,tau*s)*E0+EL)/s

        func=func*math.log(2)/t
        results.append(func)
    return  [float(i) for i in results]

############################################################################################

###Constant###

####Value####
data_time=np.array([69.0,99.0,139.0,179.0,219.0,259.0,295.5,299.03])
data_relax=np.array([6.2536,6.1652,6.0844,6.0253,5.9782,5.9404,5.9104,5.9066])

###Fitting###
guess=np.array([0.33226685047281592707364253044085038793404361200072,8.6682623502960394383501102909774397295654841654769])
#guess=np.array([0.1,0.05])
Parameter,Covariance=scipy.optimize.curve_fit(invlaplace_stehfest2,data_time,data_relax,guess)
print Parameter
residu=sum(data_relax-invlaplace_stehfest2(data_time,Parameter[0],Parameter[1]))

Graph_Curves=plt.figure()
ax = Graph_Curves.add_subplot(111)
ax.plot(data_time,invlaplace_stehfest2(data_time,Parameter[0],Parameter[1]),"-")
ax.plot(data_time,data_relax,"o")
plt.show()

A: Non-linear fitters such as the default Levenberg-Marquardt solver used in scipy.optimize.curve_fit(), like most iterative solvers, can stop in a local minimum in error space. If error space is "bumpy" then initial parameter estimates become very important, as in this case.
Scipy has added the Differential Evolution genetic algorithm to the optimize module, which can be used to determine initial parameter estimates for curve_fit(). Scipy's implementation uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, requiring parameter upper and lower bounds within which to search. As you can see below, I have used this scipy module to replace the hard-coded values for the value named "guess" in your code. This does not run quickly, but a somewhat slower correct result is much better than a fast wrong result. Try this code:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.pylab as mplab
import math
from math import *
import numpy as np
import scipy
from scipy.optimize import curve_fit

from scipy.optimize import differential_evolution

import mpmath as mp

############################################################################################
def invlaplace_stehfest2(time,EL,tau):
    upsilon=0.25
    pmax=6.9
    E0=0.0154
    M=8
    results=[]
    for t in time:
        func=0
        for k in range(1,2*M+1):
            SUM=0
            for j in range(int(math.floor((k+1)/2)),min(k,M)+1):
                dummy=j**(M+1)*scipy.special.binom(M,j)*scipy.special.binom(2*j,j)*scipy.special.binom(j,k-j)/scipy.math.factorial(M)
                SUM+=dummy
            s=k*math.log(2)/t
            func+=(-1)**(M+k)*SUM*pmax*EL/(mp.exp(tau*s)*mp.expint(1,tau*s)*E0+EL)/s

        func=func*math.log(2)/t
        results.append(func)
    return  [float(i) for i in results]

############################################################################################

###Constant###

####Value####
data_time=np.array([69.0,99.0,139.0,179.0,219.0,259.0,295.5,299.03])
data_relax=np.array([6.2536,6.1652,6.0844,6.0253,5.9782,5.9404,5.9104,5.9066])

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    return np.sum((data_relax - invlaplace_stehfest2(data_time, *parameterTuple)) ** 2)

###Fitting###
#guess=np.array([0.33226685047281592707364253044085038793404361200072,8.6682623502960394383501102909774397295654841654769])
#guess=np.array([0.1,0.05])

parameterBounds = [[0.0, 1.0], [0.0, 10.0]]
# "seed" the numpy random number generator for repeatable results
# note the ".x" here to return only the parameter estimates in this example
guess = differential_evolution(sumOfSquaredError, parameterBounds, seed=3).x

Parameter,Covariance=scipy.optimize.curve_fit(invlaplace_stehfest2,data_time,data_relax,guess)
print Parameter
residu=sum(data_relax-invlaplace_stehfest2(data_time,Parameter[0],Parameter[1]))

Graph_Curves=plt.figure()
ax = Graph_Curves.add_subplot(111)
ax.plot(data_time,invlaplace_stehfest2(data_time,Parameter[0],Parameter[1]),"-")
ax.plot(data_time,data_relax,"o")
plt.show()


text:
Q: How can I do like the following route which is in codeigniter in laravel 4 or 4.1? My current website is in Codeigniter: http://www.tenders.af I want to convert it to
Laravel 4.1
I faced this problem with routing and I could not solved it yet any help will be appreciated.
my routes in codeigniter:
 $route['afghanistan-tenders/(:any)'] = 'home/details/$1';

how can I write like the above route in Laravel 4 or 4.1

A: Route::get('/afghanistan-tenders/{id}', ['uses' => 'HomeController@details']);

Then in your HomeController
public function details($id)
{
    echo $id;
}

Edit: based upon your comment below - can you just do this?
Route::get('/afghanistan-tenders/{id}/school-development', ['uses' => 'HomeController@details']);

or
Route::get('/afghanistan-tenders/{id}/{name}', ['uses' => 'HomeController@details']);


text:
Q: cordova geolocation plugin doesnt work I'm trying to use the plugin cordova-plugin-geolocation, but does not work, I get the following error:
Uncaught ReferenceError: geolocationSuccess is not defined

I have the plugin and permissions in the manifest correctly, simply does not work. If anyone knows the solution, I thank you for the help.
Android manifiest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>

Javascript
navigator.geolocation.getCurrentPosition(geolocationSuccess,
                                         [geolocationError],
                                         [geolocationOptions]);

var onSuccess = function(position) {
    alert('Latitude: '          + position.coords.latitude          + '\n' +
          'Longitude: '         + position.coords.longitude         + '\n' +
         ');
};
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);

A: change
navigator.geolocation.getCurrentPosition(geolocationSuccess,
                                     [geolocationError],
                                     [geolocationOptions]);

to
navigator.geolocation.getCurrentPosition(onSuccess,
onError,
{
    maximumAge: 3000,
    timeout: 5000,
    enableHighAccuracy: true
}
);


text:
Q: Can't find git folder in TFS 2015 build agent folder I'm trying to configure git settings on a TFS 2015 build agent so that I can add a new certificate as described in TFS Build Agent failing to connect to HTTPS git in TFS 2017 when running as service
When I go to the "agent" folder, there is no "externals" folder. I've tried searching and haven't found the "git" folder or any git executables under the TFS agent.
Git isn't installed on the build agent machine, but it is attempting to clone the repository when I run a build - so git must be there somewhere.
How can I find where the git installation is so that I can change the configuration for it?
Can I just install git in the standard location and make global changes? And, if so, will this be picked up by the TFS build agent?

A: As explained in "Commit to Git: Source Control in Visual Studio 2015":

The Visual Studio 2015 IDE relies on the LibGit2 API and the LibGit2Sharp communication layer to implement all of the Git features it exposes in its front-end tooling.

*

*LibGit2 is a zero-dependency, cross-platform, open source Git core engine written entirely in C.

*LibGit2Sharp is a library written in C# that runs as a managed process under the Microsoft .NET Framework.
  It serves as a .NET-friendly interface between Visual Studio and LibGit2 and it dramatically simplifies the programming effort required by the Visual Studio development team to establish a communication pipeline to and from the LibGit2 library.

So it would not need a separate Git installation.


text:
Q: Why does EM wave propagate perpendicular to cavity wall in Rayleigh-Jeans Law derivation I'm trying to follow the derivation of the Rayleigh-Jeans law in my textbook by Eisberg and Resnick. A cubic cavity is considered and the following is said of wave's orientation relative to the wall:

Now, since electromagnetic radiation is a transverse vibration with the electric field vector E perpendicular to the propagation direction, and since the propagation direction for this component is perpendicular to the wall in question, its electric field vector E is parallel to the wall.

The rest of the derivation is hinged on this idea but I don't follow. In his explanation he has assumed the direction of propagation is perpendicular to the cavity walls. Why would we expect this?


text:
Q: Online messaging system I'm building a website at the moment and now i stand in a crossroad to chose which kind of messaging system to choose.
The website is build in asp.net, so using c# and other microsoft technologies i want to build a very simple messaging system between different users.
My question is how to do that, and what is the best way?
One option which i see is to use a database, to store the messages and then let the messaging page, every second refresh and perform code to retrieve the message, altho i tried it and i dont really like, because it isn't the proper way ... letting the page refresh and yeah retrieve the messages it is not very good.
But i dont really know the alternative i tried to search but didnt find any other possible solution only use of database and refreshing of the page.
My question is, what are any other possibilities to implement a very simple messaging system to a website, where for example 2 users can private message each other?
I dont need alot of explanation just some direction where to search ...
Thanks in advance for reading and replying to me, and for admins not to close the thread.

A: This should get you started.
Simple Chat Application in ASP.NET
Here's another one that looks promising...
LiveChat Starter Kit

A: Use jQuery and Ajax to get rid of the "refresh" page http://api.jquery.com/category/ajax/.
Regarding if you should use DB or not. Its really up to you, to whatever you are comfortable with. It dosen't sound that you have a lots of requirement.
If I would do it by myself and its a micro project I think I just would store the messages in the HttpContext...


text:
Q: FPGA netlist parser In almost all synthesis tools for FPGA the output of HDL synthesis is some kind of EDIF format. E.g. in Synopsys such format has an extension .edn. However, this format is already FPGA-technology dependent (depends on the FPGA-type chosen before synthesis and its cells). Meanwhile in all synthesis tools I can see the gate level representation with simplest OR, AND gates and DFF, but the output files with this level of representation are encrypted.
I have to get the lowest level (AND,OR, DFF) netlist after FPGA synthesis process. Since generated EDIF files are technology/cells dependent, it is not very easy to parse them (I need the library of FPGA cell descriptions). Can I anyhow with any synthesis programs get lowest level netlist representation?
Thank you in advance for attention.

A: If you want a low-level gate netlist, you need to synthesise to a target library which has those elements.  Because FPGAs do not have raw gates within them, when the synthesiser targets them, it (somewhat obviously) creates elements which are available to it.
If you use an ASIC tool, that will use low level gates, as that is what that target has available.

A: I'm not sure if I have understood why you need that edif netlist to be parsed.  But could it help you if you export the netlist after syntesis as VHDL or Verilog and parse that language?  Most synthesis tools have this export option to re-simulate the design after synthesis.


text:
Q: webpack can't parse material ui button in a child component I'm trying to bundle some React components with webpack.
But when I launch webpack --mode=development, i get this error :

Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const OwnButton = () => {
|   return (     <Button color='secondary' variant='outlined'

This is my webpack config :
const path = require('path');

module.exports = {
   entry: './src/app.js', // relative path
   output: {
      path: path.join(__dirname, 'public'), // absolute path
      filename: 'js/bundle.js' // file name
   },
   module: {
      rules: [
         {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
         }
      ]
   }
};

This is my app.js config :
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Button from '@material-ui/core/Button';
import OwnButton from './Components/OwnButton';

const template = <Button>Hello from react jsx</Button>;

ReactDOM.render(template, document.getElementById('root'));
ReactDOM.render(<OwnButton/>, document.getElementById('React-OwnButton'));

And the wanted component (index.jsx) :
import Button from '@material-ui/core/Button';

const OwnButton = () => {
  return (
    <Button color='secondary' variant='outlined'>
      Hello from my own component
    </Button>
  );
};

export default OwnButton;

And my .babelrc
{
   "presets": ["@babel/preset-env", "@babel/preset-react"]
}

I don't understand how the  call l.6 on app.js can work but not the  on index.jsx l.6.
Where must I put the loader for this, in babel?

A: The problem is that you configured the Babel Loader to only intervene for .js files.
Try changing: test: /\.js$/ -> test: /\.((js)|(jsx))$/
This will make the loader work for .jsx files too.


text:
Q: Generating Line between two draggable Divs using jquery dynamically I need to join the two given elements ( Say double click / highlight two elements and join them using a line )
I heard this could be achieved using jsplumb and raphealjs. Any other straight way to succeed in this or by using Kineticjs. Please find my fiddle below in the comment.
Thanks in advance.


text:
Q: 2 Node Redis HA I have two nodes which I want to run as servers in active-active mode and also have HA capability i.e if one is down, the other one should start receiving all the requests but while both are up, both should be taking all the requests. Now since Redis doesn't allow active-active mode for the same hash set and I don't have option to run Sentinel as I can't have a third node, my idea is to run the two nodes in replication and myself decide if master node is down and promote the slave to master. Are there any issues with this? When the original master comes back up, is there a way to configure it as slave?
Does this sound like a good idea? I am open to suggestions other than Redis.

A: Generally running two node is never a good idea because it is bound to have split brain problem: When the network between the two node is down for a moment or two, the two node will inevitably think each other is offline and will promote/keep itself to be master and start accepting requests from other services. Then the split brain happens.
And if you are OK with this possible situation, then you can look into setup a master-slave with help of a script file and a HA service like pacemaker or keepalived.
Typically you have to tell the cluster manager through a predefined rule that when two machine rejoins under split brain condition, which one is your preferred master.
When a master is elected, execute the script and basically it execute slaveof no one on itself and execute slaveof <new-master-ip> <port> on the other node.
You could go one step further in your script file and try to merge the two data sets together but whether that's achievable or not is entirely down to how you have organized your data in Redis and how long you are prepared to wait for to have all the data in sync.
I have done this way myself before through pacemaker+corosync.

A: Ok, partial solution with SLAVEOF:
You can manually promote slave to master by running:
SLAVEOF NO ONE

You can manually transition master to slave by running:
SLAVEOF <HOST> <port>

Clustering should be disabled.

A: If you brought the replica online manually by changing it to replicaof no one, you need to be careful to bring the failed master back online as a replicaof the new node so you dont overwrite more recent data. I would not recommend doing this manually. You want to minimize downtime so automated failover is ideal
You mention being open to other products. Check out KeyDB which has the exact configuration you are looking for. It is a maintained multi-threaded fork of redis which offers the active-replica scenario you are looking for. Check out an example of it here.
Run both nodes as replicas of each other accepting reads and writes simultaneously (depending on upfront proxy config). If one fails the other continues to take the full load and is already sync'd.
Regarding the split brain concern, KeyDB can handle split brain scenarios where the connection between masters is severed, but writes continue to be made. Each write is timestamped and when the connection is restored each master will share their new data. The newest write will win. This prevents stale data from overwriting new data written after the connection was severed.

A: I would recommendation to have at least 3 nodes with Sentinel Setup for enabling gossip/quorum for auto promotion of slave to master when current master node goes down.

A: I believe it is possible to create a cluster with two nodes with the commands below:
$ redis-cli --cluster create <ip-node1>:7000 <ip-node1>:7001 <ip-node2>:7000 <ip-node2>:7001 --cluster-replicas 1

To resolve the split-brain problem. you can add a third node without data:
$ cluster meet #IP_node3#:7000

$ cluster nodes
I think it works.


text:
Q: Is it possible to use ranges adaptors to revert the projected member to the original class object? C++20 brings a very powerful projection utility. Some range adaptors such as transform_view and elements_view allow us to easily project operations to the member variable of the origin class object (godbolt):
auto historical_figures = vector{
    pair{"Lovelace"sv, 1815},
    {"Turing"sv, 1912},
    {"Babbage"sv, 1791},
    {"Hamilton"sv, 1936}
};

// view of ints
auto birth_years = historical_figures
                 | views::transform(&pair<string_view, int>::second);

But can we reproject the projected member variable back to the original class object? For example:
// views of pair<string_view, int>
auto origin_figures = historical_figures
                    | views::transform(&pair<string_view, int>::second)
                    | views::reproject<pair<string_view, int>>;

The reason I ask this is that the projection function is a member object pointer of type int pair<string_view, int>::*, which seems to save the type information of the projected class, so it may have some potential conversion relationship with the original object.
Is this theoretically feasible? If possible, can we use ranges adaptors to construct this reprojection? If it is not possible, is it possible to just reproject std::pair?

A: It's not in general possible to identify an object based on the identity of one of its subobjects, even if you know which subobject it is rather than just its type (which might leave multiple possibilities).  The pointer arithmetic model just doesn't allow it, partly because it allows certain aliasing optimizations when the compiler can see that one object isn't "reachable" from another.


text:
Q: Detecting two arduinos coming in proximity of each other I want to hook up LEDs to two arduinos and then have them turn their LEDs on if they are within about 3 feet of each other, what module would I use to detect this? I was thinking NFC like a RFID but those usually need to be as close as 10cm.
Bonus if I could also access the received signal strength.
Could I do this with two esp8266 using one as an ad hoc Network and attempting to connect with the other one? Would I like that give me received signal strength?
I want one to be worn by me and one by another person and when we get in some proximity have the Arduinos know and do stuff


text:
Q: Recursion issues with VBscript I am trying to implement some recursion in vbscript.
Function largest_prime_factor (ByVal num)

    For i = 2 to num/2
        If num mod i = 0 Then   'this number is not prime
            largest_prime_factor (num / i)
        End If
    Next

    largest_prime_factor = num ''if at this point, we have reached the largest prime

End Function

As you can see, it is a script that is basically designed to give me the largest prime factor of a number. However, this script still spits back the imputed number at me when I run a print. After debugging, I have found that the script will indeed enter the conditional inside the for loop, but then it will NOT recurse (ie: it will keep running through the for loop and then just end after that point)
What did I miss about recursion in VBscript? I also tried something to the effect of
largest_prime_factor = largest_prime_factor (num / i)

Inside the conditional and this didn't work either.

A: In code posted above, you have made two minor mistakes

*

*You have created function that returns number, while calling it recursively you should get that number in variable 'num' for further processing.

*Second mistake you have made that you have not exited from loop after you getting desired output. That causes to looping further until i = num  & you will have your answer as 1 in all cases.

working code  ---
Function largest_prime_factor (ByVal num)
 For i = 2 to num/2
        If num mod i = 0 Then   'this number is not prime
              num= largest_prime_factor (num / i)
              Exit For
        End If
 Next
largest_prime_factor = num ''if at this point, we have reached the largest prime
End Function


text:
Q: How to check column for duplicate values, then merge adjacent columns if found? I am trying to create a macro that checks for duplicate values in a column, then merges those rows if found.
I have tried using a loop to check each cell and cell.Offset(1,0) and if they are equal, merge them. Then copy the formatting from that column to an adjacent column.
This image shows what I am trying to accomplish.

I am only trying to merge one column (E) but the issue is it only checks two cells at a time, so it doesnt merge 5 of the same values. It also messes up if the last row is merged. Once the checked column is merged I am just going to copy formatting to the adjacent appropriate columns.

Sub Merge()

Dim lastRow As Long
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Application.DisplayAlerts = False

    For Each cell In Range("E1:E" & lastRow)
        If cell.Offset(1, 0).Value = cell.Value Then
           Range(cell, cell.Offset(1, 0)).Merge
        End If
    Next cell
End Sub

A: merge cells vertically
This code checks the cells of each row and merges cells vertically, if they have the same value (also formulas whith same resulting value!):
Sub MergeCellsVertically()
    Dim ws As Worksheet
    Dim currentRng As Range
    Dim usedRows As Long, usedColumns As Long
    Dim currentRow As Long, currentColumn As Long

    Set ws = ActiveSheet
    usedRows = ws.Cells.Find(What:="*", After:=ws.Cells(1), LookIn:=xlFormulas, _
        SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    usedColumns = ws.Cells.Find(What:="*", After:=ws.Cells(1), LookIn:=xlFormulas, _
        SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

    Application.DisplayAlerts = False
    For currentColumn = 1 To usedColumns
        For currentRow = usedRows To 2 Step -1
            Set currentRng = ws.Cells(currentRow, currentColumn)
            If currentRng.Value <> "" Then
                If currentRng.Value = currentRng.Offset(-1, 0).Value Then
                    currentRng.Offset(-1, 0).Resize(2, 1).Merge
                End If
            End If
        Next currentRow
    Next currentColumn
    Application.DisplayAlerts = True

    Set currentRng = Nothing
    Set ws = Nothing
End Sub

As your example shows a non-uniform structure, this may be a good solution. If you just want to decide by one row, which neighbor-cells to merge, keep in mind, that only the content of the upper left cell of a merged area "survives".
If you want to address the content of a merged area, then currentRng.MergeArea.Cells(1) will always represent the first cell of the merged area, where the content is.
unmerge
Sub UnmergeCells()
    Dim ws As Worksheet
    Dim usedRows As Long, usedColumns As Long
    Dim currentRng As Range, tempRng As Range
    Dim currentRow As Long, currentColumn As Long

    Set ws = ActiveSheet
    usedRows = ws.UsedRange.Cells(1).Row + ws.UsedRange.Rows.Count - 1
    usedColumns = ws.UsedRange.Cells(1).Column + ws.UsedRange.Columns.Count - 1

    For currentRow = 1 To usedRows
        For currentColumn = 1 To usedColumns
            Set currentRng = ws.Cells(currentRow, currentColumn)
            If currentRng.MergeCells Then
               Set tempRng = currentRng.MergeArea
               currentRng.MergeArea.UnMerge
               currentRng.Copy tempRng
            End If
        Next currentColumn
    Next currentRow

    Set tempRng = Nothing
    Set currentRng = Nothing
    Set ws = Nothing
End Sub

As the Find function is bad in finding the last used column or row in merged cells, I use the standard UsedRange instead. Be aware, that unmerged (duplicated) formulas may be unexpected.


text:
Q: Basemap is not getting installed I want to plot a map using Basemap. When I run
from mpl_toolkits.basemap import Basemap

I get
ModuleNotFoundError: No module named 'mpl_toolkits.basemap'

I tried to do
conda install -c conda-forge basemap-data-hires

but still getting the same no module thing as before, I did try the things from this post ModuleNotFoundError: No module named 'mpl_toolkits.basemap' but still no results

A: Open your terminal and try this -
python -m pip install basemap

If working on a notebook, try using -
!python -m pip install basemap

Refer to https://github.com/matplotlib/basemap#installation for more installationrelated support.


text:
Q: SQL select row count by unique ID group by range Given that I have the following two tables:
User
-------
UserID

UserLikes
----------
UserID
OtherUserID

When a user likes another user, the user performing the like gets stored as UserID and the user receiving the like gets stored as OtherUserID.
How can I get a distribution showing a count of how many users that have given:
0 likes
1-10 likes
11-50 likes
51-100 likes
101 + likes

A: For example, people that liked between 1 and 10:
SELECT T.userID,count(*) as TotalLikes
FROM UserLikes t
GROUP BY T.userID
HAVING COUNT(*) between 1 and 10

To change the range, just change the having clause
HAVING COUNT(*) = 0
HAVING COUNT(*) between 1 and 10
HAVING COUNT(*) between 11 and 50
HAVING COUNT(*) between 51 and 100
HAVING COUNT(*) > 100

If you meant you want the results to be:
0 likes | 1-10 likes | ....
   3          5         ....

Then:
SELECT sum(case when TotalLikes = 0 then 1 else 0 end) as No_Likes,
SELECT sum(case when TotalLikes between 1 and 10 then 1 else 0 end) as One_To_ten_likes,
SELECT sum(case when TotalLikes between 11 and 50 then 1 else 0 end) as Eleven_To_Fifty_Likes,
.......
FROM(
    SELECT T.userID,count(*) as TotalLikes
    FROM UserLikes t
    GROUP BY T.userID)


text:
Q: Housing Machine Learning Error: "Supported target types are: ('binary', 'multiclass'). Got 'multilabel-indicator' instead" So I'm trying to make a machine learning algorithm that tests the cross_val_score of some housing data to determine which algorithm is the most accurate at determining housing value. I'm using an outline displayed in a previous project I did to predict the species of iris, although this dataset is much larger with much more categories to take into consideration (this is 506x14, the last was 150x4).
I was expecting X to be the array of all of the values not including the final column which is the house median value, Y. Did a simple splitter and originally attempted to pass those values immediately through a cross_val_score. However, I got an error that the function only took binary or multiclass and it was receiving continuous. An answer on Stack said to use keras.utils.to_categorical to make the data binary so I attempted that with the values. It threw the error Supported target types are: ('binary', 'multiclass'). Got 'multilabel-indicator' instead The only solution I found was to put to_categorical after StratifiedKFold but that hasn't seemed to fix the error.
# Load dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/housing.csv"
names = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
dataset = read_csv(url, names=names)
# Split-out validation dataset
array = dataset.values
X = array[:, 0:13]
y = array[:, 13]
X_train, X_validation, Y_train, Y_validation, = train_test_split(X, y, test_size=0.20, random_state=1, shuffle=True)
# Spot check Algorithms
models = []
models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('SVM', SVC(gamma='auto')))
# evaluate each model in turn
results = []
names = []
for name, model in models:
    kfold = StratifiedKFold(n_splits=10, random_state=1, shuffle=True)
    # convert class vectors to binary class matrices
    X_train = keras.utils.to_categorical(X_train, 0)
    X_validation = keras.utils.to_categorical(X_validation, 0)
    Y_train = keras.utils.to_categorical(Y_train, 0)
    Y_validation = keras.utils.to_categorical(Y_validation, 0)
    cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))
# Compare Algorithms
pyplot.boxplot(results, labels=names)
pyplot.title('Algorithm Comparisons')
pyplot.show()

Any help would be greatly appreciated in order to figure out why my data isn't being passed through the scorer correctly.

A: First of all, I must say that the classification and regression are different problems in machine learning which you can know more about them here.
Now you are solving a regression problem (Housing) using a solution developed for a classification problem (Iris).
You have two options

*

*Solve the problem as Regression (some of the models you used may not
have a regression version)

*Convert your problem to classification (which has been asked here!)

This is my implementation of the first solution, which was achieved with minor changes to your code ;)
models = []
models.append(('LR', LinearRegression()))
# models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsRegressor()))
models.append(('CART', DecisionTreeRegressor()))
models.append(('NB', GaussianProcessRegressor()))
models.append(('SVM', SVR(gamma='auto')))
# evaluate each model in turn
results = []
names = []
for name, model in models:
    regr = model
    cv_results = cross_val_score(regr, X, y, cv=5)
    results.append(cv_results)
    names.append(name)
    print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))
# Compare Algorithms
pyplot.boxplot(results, labels=names)
pyplot.title('Algorithm Comparisons')
pyplot.show()

Finally, the train_test_split and cross_val_score are two alternative methods for evaluating the quality of the model. The simultaneous use of both is not recommended!

A: for regression, you have to use KFold instead of StratifiedKFold. So it would be,
kfold = KFold(n_splits=10, random_state=1, shuffle=True)


text:
Q: Disable live reload from yeoman angular project for ie9 I believe the generators for an angular app include a grunt task of live reload. That doesn't seem to be working when hooked up to IE9 because IE9 does not support web sockets. Is there a way to disable live reload only for IE9? Or would you recommend poly filling if possible?

A: IE9 does support it, or should. You could set livereload to false in your Gruntfile.js though


text:
Q: How to modify view.alphaValue at runtime and take effect I modified the alphaValue at runtime but has not any effect , what is the problem. how to modify the alphaValue at runntime ?
I want to adjust the alphaValue of view  at runtime
Xcode 10.2.1   Swift 4.2
//
//  ViewController.swift
//  macosappalphaValuetest
//
//  Created by miller on 2019/7/25.
//  Copyright © 2019 miller. All rights reserved.
//

import Cocoa

class ViewController: NSViewController {

    @IBAction func btnclick1(_ sender: Any) {
       self.view.alphaValue = 0.8

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    override func viewWillAppear() {
        super.viewWillAppear()
        view.window?.isOpaque = false
        view.window?.backgroundColor = NSColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
        self.view.alphaValue = 0.4
        }

    }

A: In NSViewController's viewWillAppear method your view's window is probably nil. You can check it by printing print(view.window). So you need to get the correct instance of your window. See below method:
func validWindow() -> NSWindow? {
    var window = NSApplication.shared.mainWindow
    if (window == nil) {
        window = NSApplication.shared.windows.first
    }
    return window
}

And just write below code to make your window transparent:
guard let window = self.validWindow() else { return }
window.alphaValue = 0.5

It works well for me.
Output:

Increasing and Decreasing alpha value recursively:
func decreaseAlpha(_ window: NSWindow) {
    let alpha = window.alphaValue - 0.1
    if alpha < 0.0 {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            self.increaseAlpha(window)
        }
        return
    }

    window.alphaValue = alpha
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
        self.decreaseAlpha(window)
    }
}

func increaseAlpha(_ window: NSWindow) {
    let alpha = window.alphaValue + 0.1
    if alpha > 1.0 {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
            self.decreaseAlpha(window)
        }
        return
    }

    window.alphaValue = alpha
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
        self.increaseAlpha(window)
    }
}

And write this in viewDidLoad: method:
guard let window = self.validWindow() else { return }
decreaseAlpha(window)

Output:

A: alphaValue is the Objective-C version of alpha. Applying alpha on the viewController view will make it slightly transparent and possible show the viewController that is beneath it if there is one. If there are no
view controllers beneath it, it will lean towards a darker background as the default background is black.


text:
Q: All pairs maximally disjoint paths algorithm Suppose that there are multiple source destination pairs in an undirected graph. I want to generate disjoint paths for multiple pairs. What would be the complexity of such problem? Is there any polynomial heuristic for finding edge-disjoint paths for these pairs? (i.e. path between s1 and d1 should not have any common edges with the path between s2 and d2)

A: This looks like a variant of the multi-commodity flow problem:  http://en.wikipedia.org/wiki/Multi-commodity_flow_problem
Treat each source/sink pair as a new commodity, and give your edges unit weights to enforce disjoint paths.  Now search the literature for approximations to this class of MCFP with unit capacities.

A: Your problem is NP-hard, even for the case of two sources and two sinks.  It becomes polynomially solvable if you stop caring which source matches with which sink.


text:
Q: Custom adapter does not called getVIew Here is the code of my custom adapter... it doesn't call my get view... returns only white blank page without nothing. I don't know what is the problem. Does anybody can help. Thanks a lot previously!
   public class ProductShopsAdapter extends ArrayAdapter<ProductShop> {

    private Context cntx;
    private ArrayList<ProductShop> shopValues;
    ProductShopsHolder holder = null;

    public ProductShopsAdapter(Context context, int textViewResourceId,  ArrayList<ProductShop> stringValues) {
        super(context,textViewResourceId);
        shopValues = stringValues;
        cntx = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            holder = new ProductShopsHolder();

            LayoutInflater layoutInflater = (LayoutInflater)cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.shops_list, null);

            //Holder Elements initialization
            holder.setShopName((TextView)convertView.findViewById(R.id.shop_name));
            holder.setPrice((TextView)convertView.findViewById(R.id.shop_part_price));

            convertView.setTag(holder);
        } else {
            holder = (ProductShopsHolder) convertView.getTag();
        }
        holder.getShopName().setText(getItem(position).getShopName());
        holder.getPrice().setText(getItem(position).getPrice());

        return convertView;
    }
}

and here is my XML
 <?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProductShopsActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/footer"
        android:padding="0dp" >
    </ListView>

    <include
        android:id="@+id/footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@android:id/list"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        layout="@layout/footer_menu" />

</RelativeLayout>

and single view :
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#f2f2f2"
    android:orientation="horizontal"
    android:padding="10dp" >

    <TextView
        android:id="@+id/shop_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Technomarket"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/shop_part_price"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="30 лв."
        android:textSize="18sp" />

    <TextView
        android:id="@+id/details_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableRight="@drawable/rightarrow"
        android:gravity="center"
        android:text="Детайли"
        android:textColor="#289bd6"
        android:textSize="14sp" />

A: You don't need ArrayList inside your ArrayAdapter - ArrayAdapter can store items itself. And that's why getView() doesn't get called - default implementation of getCount() returns the number of items in ArrayAdapter itself. If you keep your items in your own ArrayList, at least override getCount() to return shopValues.getCount(). Otherwise it is always 0 and  the ListView to which your adapter is bound doesn't even know there are any items to dsplay at all.


text:
Q: py4j.protocol.Py4JJavaError: An error occurred while calling o49.csv I'm new to pyspark. I'm running pyspark in the local machine. I'm trying write to CSV file from pyspark data frame. So I wrote the following code
dataframe.write.mode('append').csv(outputPath)
But I'm getting an error message
Traceback (most recent call last):
  File "D:\PycharmProjects\pythonProject\org\spark\weblog\SparkWebLogsAnalysis.py", line 71, in <module>
    weblog_sessionIds.write.mode('append').csv(outputPath)
  File "C:\spark-3.1.2-bin-hadoop3.2\python\pyspark\sql\readwriter.py", line 1372, in csv
    self._jwrite.csv(path)
  File "C:\spark-3.1.2-bin-hadoop3.2\python\lib\py4j-0.10.9-src.zip\py4j\java_gateway.py", line 1304, in __call__
  File "C:\spark-3.1.2-bin-hadoop3.2\python\pyspark\sql\utils.py", line 111, in deco
    return f(*a, **kw)
  File "C:\spark-3.1.2-bin-hadoop3.2\python\lib\py4j-0.10.9-src.zip\py4j\protocol.py", line 326, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o49.csv.
: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.createDirectoryWithMode0(Ljava/lang/String;I)V
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.createDirectoryWithMode0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.createDirectoryWithMode(NativeIO.java:560)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkOneDirWithMode(RawLocalFileSystem.java:534)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkdirsWithOptionalPermission(RawLocalFileSystem.java:587)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkdirs(RawLocalFileSystem.java:559)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkdirsWithOptionalPermission(RawLocalFileSystem.java:586)
    at org.apache.hadoop.fs.RawLocalFileSystem.mkdirs(RawLocalFileSystem.java:559)
    at org.apache.hadoop.fs.ChecksumFileSystem.mkdirs(ChecksumFileSystem.java:705)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.setupJob(FileOutputCommitter.java:354)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.setupJob(HadoopMapReduceCommitProtocol.scala:178)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:173)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:188)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:108)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:106)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:131)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$execute$1(SparkPlan.scala:180)
    at org.apache.spark.sql.execution.SparkPlan.$anonfun$executeQuery$1(SparkPlan.scala:218)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:215)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:176)

Can you suggest me to rectify this error?

A: Problem got resolve by deleting hadoop.dll file from winutils folder and using lower version of Spark


text:
Q: Modify slinghttpresponse through wrapper I am trying to override default sendredirect funtionality in AEM.
I would like to redirect to https urls from my server.
FOr the same I have implemented a sling filter. Implemented SlingHttpServletResponseWrapper class and overridden  sendredirect function.
However, in filter when I try to
final SlingHttpServletResponse slingResponse = (ModifyLocResponse) response;
At runtime I get
org.apache.sling.security.impl.ContentDispositionFilter$RewriterResponse cannot be cast to com.adobe.acs.samples.filters.wrappers.ModifyLocResponse

A: Instead of casting, try instantiating it by something like this:
final SlingHttpServletResponse slingResponse = new ModifyLocResponse(response);

Of course you'll need to make sure the constructor for that class has this pattern too:
class ModifyLocResponse extends SlingHttpServletResponseWrapper {
    public ModifyLocResponse(SlingHttpServletResponse response) {
        super(response);
    }
    ...
}


text:
Q: Spring Boot Initializr: Maven project or Maven POM? I want to set up a Spring Boot project using the Spring Initializr (https://start.spring.io) but I was wondering about the difference in the project type you can choose between: Maven Project or Maven POM?
What is exactly the difference between these two types?

A: Maven POM creates only the pom.xml file.
Maven Project creates the pom.xml file and a sample project including src folder:
> src:
    > main:
        > java:
            > com.example:
                Application.java
        > resources:
            application.properties
    > test:
        > java:
            > com.example:
                ApplicationTest.java
> pom.xml

A: Maven Project is the type which we use to create a common Spring Boot application. It seems Maven POM is for downloading build scripts only.

A: Basic difference that you even experience it by selecting the maven project option and say download, you get a maven which includes sample spring boot application
Other case you have existing project and want to add spring boot then you can simply get the configuration to include spring boot artifacts


text:
Q: How to change value of red/green/blue/alpha values from pixels I'm working on a processing image software and now i want to change white balance and add some saturation on my photos, so i have to work with each pixel value.
I've tried to transform my BitmapImage to WritableBitmap and then I've tried this code. But if i run it, my image turns to green.
I want to take pixels from that image and then set them to new values.
I've searched many solutions but found none, so maybe someone can help me with my code. Thanks.
    public static WriteableBitmap Colors(Bitmap Image)
    {
        int width = Image.Width;
        int height = Image.Width;
        byte[,,] pixels = new byte[height, width, 4];
        WriteableBitmap wbitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);

        var target = new Bitmap(Image.Width, Image.Height);

        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                pixels[i, j, 1] -= 30;
                pixels[i, j, 3] -= 30;
            }

        }
        byte[] pixels1d = new byte[height * width * 4];
        int index = 0;
        for (int row = 0; row < height; row++)
        {
            for (int col = 0; col < width; col++)
            {
                for (int i = 0; i < 4; i++)
                    pixels1d[index++] = pixels[row, col, i];
            }
        }
        Int32Rect rect = new Int32Rect(0, 0, width, height);
        int stride = 4 * width;
        wbitmap.WritePixels(rect, pixels1d, stride, 0);
        return wbitmap;
    }

And then I'm running it like this:
    private void run_OnClick(object sender, RoutedEventArgs e)
    {
       // Contrastt(BitmapImage2Bitmap(bitmap), 10);
       // MedianFilter(BitmapImage2Bitmap(bitmap),5);

        WriteableBitmap writeableBitmap = new WriteableBitmap(imageX);
        BitmapImage colored = ConvertWriteableBitmapToBitmapImage(Colors((BitmapImage2Bitmap(bitmap))));
        ImageBrush brush = new ImageBrush();
        brush.ImageSource = imageX ;
        CanvasProcessedImage.Background = brush;

    }

A: Assuming that you already have a BitmapSource (or an instance of a derived class like BitmapImage) in a source variable, you would first create a BitmapSource with a known pixel format, and then create a WritabelBitmap from that:
// source is a BitmapSource with whatever PixelFormat
var format = PixelFormats.Bgra32;
var temp = new FormatConvertedBitmap(source, format, null, 0); // force BGRA
var bitmap = new WriteableBitmap(temp);

Now you could either directly manipulate the data in the WriteableBitmap's BackBuffer property, or first do it a bit simpler and create a copy of the buffer like this:
var width = bitmap.PixelWidth;
var height = bitmap.PixelHeight;
var stride = bitmap.BackBufferStride;
var buffer = new byte[stride * height];
bitmap.CopyPixels(buffer, stride, 0);

Then manipulate the buffer and write it back to the WriteableBitmap. Since you have specified the PixelFormat, you know which byte of each 4-byte pixel value is B, G, R and A respectively.
for (int i = 0; i < buffer.Length; i += 4)
{
    // Blue
    //buffer[i + 0] = ...

    // Green
    buffer[i + 1] = (byte)Math.Max(buffer[i + 1] - 30, 0);

    // Red
    buffer[i + 2] = (byte)Math.Max(buffer[i + 2] - 30, 0);

    // Alpha
    //buffer[i + 3] = ...
}

bitmap.WritePixels(new Int32Rect(0, 0, width, height), buffer, stride, 0);

When you have assigned the WriteableBitmap to the Source property of an Image element, or the ImageSource property of an ImageBrush, you can call WritePixels later (and as often as necessary) without needing to reassign it it to the Source/ImageSource property. It is changed "in place".


text:
Q: Least square means confidence interval with Tukey adjustment balloons unrealistically wide in mixed model I have data from an experiment with two fully crossed treatments. Response variables were measured in two separate years. I fit a linear mixed effects model to a log-transformed response variable, with the two main fixed effects, interaction fixed effect, and random effect of year (using lmer() from the R package lme4). Then, I used the function emmeans::emmeans() to get the estimated marginal means for one of the treatments, and multcomp::cld() to do the Tukey adjustment and see whether any of the treatments differ. My issue is that with the log transformation, the Tukey adjustment causes the 95% confidence interval around the treatment means to become incredibly wide, many orders of magnitude higher and lower than any observed data value. This seems unrealistic. I was wondering whether this is an issue with my R syntax or whether I've set up the tests incorrectly.
Here is a slightly fuzzed version of the dataset, with names of factor levels anonymized and some random noise added to the data (as it's private) for a reproducible example.
Load packages and data.
library(lme4)
library(emmeans)
library(multcomp)

dat_reprex <- structure(list(Year = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                                      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
                                      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                                      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                                      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
                                      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Plot = c(1001, 1003, 1009,
                                                                                1010, 1011, 1014, 1016, 1022, 1023, 1024, 1027, 1029, 1035, 1036,
                                                                                1037, 1040, 1042, 1048, 1049, 1050, 1053, 1055, 1061, 1062, 1063,
                                                                                2001, 2003, 2009, 2010, 2011, 2014, 2016, 2022, 2023, 2024, 2027,
                                                                                2029, 2035, 2036, 2037, 2040, 2042, 2048, 2049, 2050, 2053, 2055,
                                                                                2061, 2062, 2063, 3001, 3003, 3009, 3010, 3011, 3014, 3016, 3022,
                                                                                3023, 3024, 3027, 3029, 3035, 3036, 3037, 3040, 3042, 3048, 3049,
                                                                                3050, 3053, 3055, 3061, 3062, 3063, 1001, 1003, 1009, 1010, 1011,
                                                                                1014, 1016, 1022, 1023, 1024, 1027, 1029, 1035, 1036, 1037, 1040,
                                                                                1042, 1048, 1049, 1050, 1053, 1055, 1061, 1062, 1063, 2001, 2003,
                                                                                2009, 2010, 2011, 2014, 2016, 2022, 2023, 2024, 2027, 2029, 2035,
                                                                                2036, 2037, 2040, 2042, 2048, 2049, 2050, 2053, 2055, 2061, 2062,
                                                                                2063, 3001, 3003, 3009, 3010, 3011, 3014, 3016, 3022, 3023, 3024,
                                                                                3027, 3029, 3035, 3036, 3037, 3040, 3042, 3048, 3049, 3050, 3053,
                                                                                3055, 3061, 3062, 3063), Trt1 = structure(c(3L, 3L, 4L, 1L, 2L,
                                                                                3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L,
                                                                                3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L,
                                                                                4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L,
                                                                                1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L,
                                                                                2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L,
                                                                                3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L,
                                                                                3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L,
                                                                                4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L,
                                                                                1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L, 2L, 3L, 3L, 4L, 1L,
                                                                                2L), .Label = c("control", "level1", "level2", "level3"), class = "factor"),
                             Trt2 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                                                3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
                                                5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
                                                2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                                                3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L,
                                                5L, 5L, 5L, 5L, 5L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                                                3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L,
                                                5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
                                                2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                                                3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L,
                                                5L, 5L, 5L, 5L, 5L), .Label = c("control", "level1", "level2",
                                                                                "level3", "level4"), class = "factor"), Y = c(2158.59905970595,
                                                                                1251.4727731083, 1790.19817919615, 1597.19282719814, 1687.0106965681,
                                                                                1720.75607746878, 1564.15753862752, 1505.82507506224, 1607.45705437054,
                                                                                1570.36888939712, 1305.95650235435, 1233.34290117997, 1440.36874372446,
                                                                                1209.82514463767, 1801.6777811149, 1548.6815875682, 1808.21301292584,
                                                                                1442.22647693023, 1514.35463381467, 1658.26138464109, 1309.91739898201,
                                                                                1710.5053649517, 1406.81202399823, 1233.84694614133, 1523.13259673538,
                                                                                1340.63244495632, 1336.91901503359, 1868.83212405745, 966.156768650265,
                                                                                772.39479816532, 838.530758532424, 1674.51520638795, 1997.39554060529,
                                                                                1565.87718877466, 1422.75213461409, 813.229634449323, 1013.53380296962,
                                                                                2158.55146827853, 2022.86437017822, 1439.1910289597, 921.481485470946,
                                                                                1171.54630364696, 2043.22666236862, 1597.97904932079, 1674.86250712198,
                                                                                1471.74181876526, 1579.25893093279, 2310.6112810042, 1942.56675761732,
                                                                                1738.1611751111, 1965.92272530422, 2218.76071019398, 2069.38801363651,
                                                                                1740.44642106525, 1479.38268171168, 1596.78675731629, 2087.53773652064,
                                                                                2187.30823864764, 1892.06356745912, 1502.64027585401, 1570.65804767824,
                                                                                1572.770955274, 2470.56820319357, 2114.27120093182, 1692.52887244199,
                                                                                1343.34761356524, 1563.32633474988, 2263.51826447082, 2088.28208660775,
                                                                                1884.99379164318, 1682.63161008498, 1608.09824983156, 2005.59693333264,
                                                                                1989.74208915916, 2063.48565368801, 4087.35614940249, 3221.39128174976,
                                                                                3511.60850378984, 3312.70958631815, 2970.00203271205, 3924.25537269975,
                                                                                4059.0383884004, 3489.88303736939, 3764.75925683024, 2892.7642548966,
                                                                                3749.5717873939, 3225.41521326006, 3698.37915484814, 2488.68187948746,
                                                                                1638.01249594836, 3601.60167217308, 3946.39929365291, 3127.45486313203,
                                                                                2540.92642036889, 2577.01180410805, 3895.47710383669, 3924.81526007975,
                                                                                2863.00503003766, 2367.2490438887, 2122.59795071745, 4216.63325128058,
                                                                                4752.55394742371, 3101.96796396627, 2976.86553176957, 2686.22237849168,
                                                                                3387.60400274547, 3304.85510168601, 3486.77455705152, 3345.00280941006,
                                                                                3391.75323528612, 3531.80514761301, 3528.52241670405, 3572.2370720877,
                                                                                3258.38960287764, 3438.79078961425, 4325.86549340203, 2766.72375854368,
                                                                                3140.26873373657, 2963.30088543439, 3589.23886653641, 3711.42299265126,
                                                                                3411.76855792187, 2977.88964743111, 3528.89001371156, 3904.40755581469,
                                                                                4272.61145419705, 3704.68025651859, 3440.39876615046, 3382.23008003269,
                                                                                3694.68849971889, 3291.59326651953, 3387.51868191258, 3477.14997107478,
                                                                                3425.66753942855, 3983.9954520286, 3563.393971622, 3753.18202786702,
                                                                                2892.42937739966, 3146.63511644724, 2866.05355993634, 3561.36950588379,
                                                                                3560.02686268737, 3347.43624676822, 3722.73867296726, 3757.75260207119,
                                                                                3750.18381722575, 3198.38828218515, 3024.21870303111, 3304.45898172044,
                                                                                3141.58457659908)), row.names = c(NA, -150L), class = "data.frame")

Log-transform response, fit model, and get adjusted 95% CIs for treatment 1.
dat_reprex$logY <- log10(dat_reprex$Y)
fit <- lmer(logY ~ Trt1 * Trt2 + (1|Year), data = dat_reprex)
emmeans_trt1 <- emmeans(fit, specs = 'Trt1', mode = 'kenward-roger', transform = 'log10', type = 'response')
cld_trt1 <- cld(emmeans_trt1, adjust = 'tukey', Letters = letters)

# Back transform confidence interval
transform(cld_trt1,
          lower.CL.backtransform = 10 ^ lower.CL,
          upper.CL.backtransform = 10 ^ upper.CL)

The final output shows very unrealistic bounds for the confidence intervals:
     Trt1 response        SE       df  lower.CL upper.CL .group lower.CL.backtransform upper.CL.backtransform
2  level1 3.337662 0.1615288 1.103493 0.6030081 18.47402      a               4.008742           2.978669e+18
1 control 3.354987 0.1615297 1.103493 0.6115121 18.40673      a               4.088012           2.551095e+18
3  level2 3.363528 0.1611005 1.048960 0.4493374 25.17779      a               2.814086           1.505895e+25
4  level3 3.396371 0.1615217 1.103493 0.6320819 18.24974      a               4.286294           1.777235e+18

A: For starters, there is a difference between transform and tran. If we use tran instead of transform, we get
> ### Output 1 ###

> emmeans_trt1 <- emmeans(fit, specs = 'Trt1', mode = 'kenward-roger', tran = 'log10', type = 'response')
NOTE: Results may be misleading due to involvement in interactions

> cld(emmeans_trt1, adjust = 'tukey', Letters = letters)
Note: adjust = "tukey" was changed to "sidak"
because "tukey" is only appropriate for one set of pairwise comparisons
 Trt1    response  SE   df lower.CL upper.CL .group
 level1      2177 810 1.02 5.64e-05 8.40e+10  a
 control     2266 843 1.02 5.87e-05 8.74e+10  a
 level2      2310 857 1.01 3.17e-05 1.68e+11  a
 level3      2491 927 1.02 6.46e-05 9.61e+10  a

Results are averaged over the levels of: Trt2
Degrees-of-freedom method: kenward-roger
Confidence level used: 0.95
Conf-level adjustment: sidak method for 4 estimates
Intervals are back-transformed from the log10 scale
P value adjustment: tukey method for comparing a family of 4 estimates
Tests are performed on the log10 scale
significance level used: alpha = 0.05
NOTE: Compact letter displays can be misleading
      because they show NON-findings rather than findings.
      Consider using 'pairs()', 'pwpp()', or 'pwpm()' instead.

These (correct) results are a lot different. Also, notice from the annotations that the intervals are already back-transformed.
What happened when you used transform is that, due to a timing issue, the initial results were viewed as not being on a log scale, then were converted to the log scale -- giving you results on the log-log scale.
It is really more straightforward and safer to incorporate the transformation in the model itself:
> ### Output 2 ###

> fit2 <- lmer(log10(Y) ~ Trt1 * Trt2 + (1|Year), data = dat_reprex)
> emm2_trt1 <- emmeans(fit2, specs = 'Trt1', mode = 'kenward-roger', type = 'response')
NOTE: Results may be misleading due to involvement in interactions
> cld(emm2_trt1)
 Trt1    response  SE   df lower.CL upper.CL .group
 level1      2177 810 1.02     23.1   204783  1
 control     2266 843 1.02     24.1   213127  1
 level2      2310 857 1.01     22.2   240105  1
 level3      2491 927 1.02     26.5   234347  1
... etc. ...

Now, why are the CIs so wide? One reason is that with the K-R d.f. method, the d.f., as shown, are all near 1, which essentially means that the sampling distribution of the EMMs is Cauchy -- very fat tailed, so fat that the mean and variance don't even exist.
But another aspect of this is that the d.f. for comparisons is much larger:
> ### Output 3 ###

> pairs(emm2_trt1)
 contrast         ratio     SE  df null t.ratio p.value
 control / level1 1.041 0.0559 129    1   0.744  0.8793
 control / level2 0.981 0.0456 129    1  -0.415  0.9758
 control / level3 0.909 0.0489 129    1  -1.767  0.2939
 level1 / level2  0.942 0.0438 129    1  -1.274  0.5812
 level1 / level3  0.874 0.0469 129    1  -2.511  0.0630
 level2 / level3  0.927 0.0431 129    1  -1.625  0.3682

Results are averaged over the levels of: Trt2
Degrees-of-freedom method: kenward-roger
P value adjustment: tukey method for comparing a family of 4 estimates
Tests are performed on the log10 scale

We have 129 d.f. for each comparison. If you prefer to see pairwise differences rather than ratios, you have to re-grid the results to the response scale. This uses the original d.f. of the means rather than that of the comparisons, so we have to override the d.f.:
> ### Output 4 ###

> pairs(regrid(emm2_trt1), df = 129, infer = TRUE)
 contrast         estimate  SE  df lower.CL upper.CL t.ratio p.value
 control - level1     88.7 124 129     -233      411   0.717  0.8903
 control - level2    -44.2 107 129     -324      235  -0.412  0.9764
 control - level3   -225.6 153 129     -623      172  -1.477  0.4543
 level1 - level2    -132.9 114 129     -431      165  -1.161  0.6524
 level1 - level3    -314.3 171 129     -760      131  -1.836  0.2614
 level2 - level3    -181.4 132 129     -524      161  -1.379  0.5149

Results are averaged over the levels of: Trt2
Degrees-of-freedom method: user-specified
Confidence level used: 0.95
Conf-level adjustment: tukey method for comparing a family of 4 estimates
P value adjustment: tukey method for comparing a family of 4 estimates

These intervals are reasonable-looking.
One additional reason that compact letter displays are so misleading is that it doesn't show important information about the comparisons, such as that the d.f. are dramatically different.
Addendum
Later, I noticed that outputs 1 and 2 have the same estimates, but different intervals; and those in Output 1 are very much wider. That's because of the adjust argument, which was applied to both the pairwise comparisons and the confidence intervals. For the CIs, the Tukey method is not appropriate because those means themselves aren't pairwise comparisons, and the adjust method was changed to "sidak", as noted before the output. You can confirm that if you simply list emmeans_trt1, you will get the same intervals as in Output 2, and that if you do confint(emmeans_trt1, adjust = "sidak"), you get the intervals in Output 1. The Sidak-adjusted intervals are a whole lot wider because we are reaching for lower and higher quantiles of the t distribution (0.0063 and 0.9937 in lieu of 0.025 and 0.975) with about 1 d.f., and as noted earlier, the tails of that distribution are extremely fat.


text:
Q: What is $Z:=XY$ for random vector $(X,Y)$? The stochastic vector $(X,Y)$ has a continuous distribution with pdf:
$$f(x,y) =
\begin{cases}
xe^{-x(y+1)}  & \text{if $x,y>0$} \\[2ex]
0 & \text{otherwise}
\end{cases}$$
Define $Z:=XY$.
I would like to know what exactly $XY$ is. It seems to me that the function $f(x,y)$ has but one output, so what does $XY$ mean here? I feel like I'm missing something obvious. Thanks in advance.

A: Hint
$$\mathbb P\{Z\leq t\}=\iint_{\{(x,y)\mid xy\leq t\}}f_{(X,Y)}(u,v)dudv.$$

A: Possibly clarifying some confusion. You are not telling us what is $X$ and what is $Y$. You are telling us their joint density $$\mathbb P[(X,Y)\in (dx,dy)]:=f_{(X,Y)}:=f: \mathbb R\times\mathbb R\to[0,\infty).$$
Quite fundamentally, a density has to have only one output. Knowing $Z:=XY$ means knowing its law, which is a consequence of knowing its density $f_{Z}$ (when it exists). As $X$ and $Y$ are real valued, $Z$ is real valued, so you should expect that $f_Z:\mathbb R\to [0,\infty)$. You can compute  $F_Z$ via the hint of Surb above (extra hint, you know what is $\mathbb E [\phi(X,Y)]$, then pick $\phi(x,y)=\mathbf 1_{xy\le t}$).


text:
Q: Uninterruptible Backup Process on Solaris =========== System Details ===========
OS: Solaris 10, update 11
CPU_ARCH: SPARC (sparcv9)
HW: Sun Fire V490 (Yeahhhh baby old school)
KERNEL_REV: 150400-40
Program: bpbkar32 (Symantec's Netbackup)
TL;DR: Can't kill processes even with kill -9 due to SUSPENDED zpool due to possibly not two good paths.
Issue:
We have a bunch (16) of un-killable processes on the system; we were notified by the backup team that they couldn't kill these jobs from the NB Master server, nor generate new backups so we hopped on and attempted a ./bp.kill_alland received:
bash-3.2# ./bp.kill_all

Looking for NetBackup processes that need to be terminated.
  Killing bpbkar processes...
The following processes are still active
     root 20346     1   0 02:02:33 ?           0:00 bpbkar32 -r 2678400 -ru root -dt 1047868 -to 0 -bpstart_time 1481767648 -clnt n
     root 18689     1   0   Dec 09 ?           0:00 bpbkar32 -r 8035200 -ru root -dt 0 -to 0 -bpstart_time 1481325879 -clnt nerp323
     root 12618     1   0   Dec 07 ?           0:00 bpbkar32 -r 2678400 -ru root -dt 357484 -to 0 -bpstart_time 1481077264 -clnt ne
     root 29693     1   0   Dec 09 ?           0:00 bpbkar32 -r 2678400 -ru root -dt 529430 -to 0 -bpstart_time 1481249210 -clnt ne
     root 10168     1   0   Dec 09 ?           0:00 bpbkar32 -r 2678400 -ru root  -dt 530349 -to 0 -bpstart_time 1481250129 -clnt ne
     root  1950     1   0   Dec 14 ?           0:00 bpbkar32 -r 2678400 -ru root -dt 962300 -to 0 -bpstart_time 1481682080 -clnt ne
  Do you want this script to attempt to kill them? [y,n] (y) y
  Killing remaining processes...
  Waiting for processes to terminate...
  Waiting for processes to terminate...
  Waiting for processes to terminate...
  Waiting for processes to terminate...
  Waiting for processes to terminate...
  There are processes still running.

... truncated output for readability.
Leading us to then proceed to attempt to kill those processes with extreme prejudice, via kill -9, also to no avail.
I've looked at How to kill a task that cannot be killed (uninterruptable?) and What if 'kill -9' does not work? as well as searched on "Solaris uninterruptable process" with partial results.  Reboot seems to be the common theme and one that looks to be our "bang-head-against-desk-here" solution as well.
That being said, I'd like to:
- validate my logic and reasoning of what the root cause is
- See if there's a better way to determine where the process is stopped/what sys call it's attempting to execute
- Resolve the I/O without a reboot if at all possible, and subsequently those processes that can't be killed.
  Pretty much just a root cause analysis and some sort of "In the future don't do switch work while backups are running or if you don't have two working paths" mitigation.
Here's what I got/what I'm thinking:
1) Popping into the /proc/1950/ directory and looking at the status. No dice with understanding that output, even with strings.  Spews random characters.
Thing of note is that 'cwd' shows a link to nothing, and attempting to resolve it via ls -alL /proc/1950/cwd will hang the terminal and also create drumroll another uninterruptible process.
2) Running a pstack 1950 will generate some useful info but nothing I can't see from a ps -eaf or that I can understand. All zeroes though, looks bad as we don't see addresses or syscall like I do with a working pid.
bash-3.2# pstack 1950

1950:   bpbkar32 -r 2678400 -ru root -dt 962300 -to 0 -bpstart_time 1481682080
   0000000000000000 ???????? (0, 0, 0, 0, 0, 0)

3) Running a truss will hang if attempted on the running process, ditto for pfiles generating an error of "pfiles: cannot control process 1950".  Interesting, but expected.
4) Running a strace just tells me that a "tracer already exists"
5) running a pwdx to print the cwd returns:
bash-3.2# pwdx 1950

1950:   /bucket

This is interesting as our df does include it...
df -h /bucket

Filesystem             size   used  avail capacity  Mounted on
  bucket                 1.9T    31K   1.9T     1%    /bucket

... but attempting to cd into /bucket and do an ls produces the same hanging effect.
bash-3.2# zpool list

NAME     SIZE  ALLOC   FREE  CAP     HEALTH  ALTROOT
  bucket  1.94T   308K  1.94T   0%  SUSPENDED  -
  rpool    136G  58.0G  78.0G  42%     ONLINE  -

bash-3.2# umount /bucket

cannot open 'bucket': pool I/O is currently suspended

bash-3.2# zpool export bucket

cannot unmount '/bucket': Device busy

bash-3.2# zpool status -x

pool: bucket
  state: SUSPENDED
  status: One or more devices are faulted in response to IO failures.
  action: Make sure the affected devices are connected, then run 'zpool clear'.
    see: http://www.sun.com/msg/ZFS-8000-HC
  scan: none requested
  config:
        NAME                      STATE     READ WRITE CKSUM
         bucket                    SUSPENDED     0     0     0  experienced I/O failures
           c3t50060E80102B1F5Ad78  FAULTED      2     0     0  too many errors

Sooo... I'm sensing that we are dead in the water, and really that when that "switch work" was happening, there were NOT two active/healthy paths to the SAN, and so we ended up pulling the rug from underneath the vdev and it just so happened that backup was working there when it died but any process, like my ls, would of had the same behavior.
Anyone have any last saving thoughts of "run this unknown command that will save you a reboot"???

A: As suggested by Jeff, the zpool clear should help resolve the issue if the path(s?) have returned.  Since it sounds like it didn't the server probably cannot see the LUN(s).
A zpool clear -F -n bucket will also tell you if the pool could be imported by discarding the last set of transactions (the -F option).`
You mentioned switch work, so you may want to check what work was done, and if one of the changes removed the or any of the paths.  Have you looked at your `luxadm display /dev/rdsk/c<____>s2 output?  Or tried reconfiguring the paths with cfgadm?  Or sending a forcelip event down a path?
The full output of a zpool status bucket might also be useful to determine the type of pool (mirror, cat, stripe, ...).  I'm assuming not a mirror based on the issue.
I realize it's easy for me to say since I'm not in the mix, but don't panic quite yet as the data should still all be present on the array assuming it's not the issue.  But you may end up having to reimport with some of the transactions rolled back.
Best of luck!

A: You can see your SAN status (assuming FC SAN) with the following:
for port in `fcinfo hba-port | grep Port | awk '{ print $4 }'`; do
> fcinfo remote-port -ls -p $port
> done

Also, read the man page for mpathadm.  You can use mpathadm show lu LUN to show the status of a LUN.