text:
Q: Validate username and password without postback in login form ASP.NET MVC I want to validate the entered username and password entered in the textboxes present in a form without Postback/Refresh. I know I am gonna need Javascript or AJAX for this purpose, but somebody please guide me through this like refer me to any tutorial or please explain me the code here.
My present code without this feature looks like this:
@using(Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.TextBoxFor(u => u.PPNumber, new { @class = "form-control", type = "number", placeholder = "Enter Number",@min="1" })
    @Html.ValidationMessageFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password", placeholder = "Password" })
    @Html.ValidationMessageFor(u => u.Password)
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}

A: You can use ajax.
When user submits the form, you need to hijack that event in javascript and stop that(prevent the normal full page form submit) and instead make an ajax call to the action method with the form data. This action method should have code to verify the user credentials and can return a JSON data structure which has a status property which says whether the credential validation is successful or not. You can inspect this response in your ajax call's success/done callback and act accordingly.
Here is a quick sample using jQuery $.post method.
Give an Id to your form so that we can use that to wire up the submit event.
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id="loginForm"))
{
    @Html.TextBoxFor(u => u.PPNumber)
    @Html.TextBoxFor(u => u.Password, new { @class = "form-control", type = "Password"})
    <input type="submit" value="Login" class="btn btn-primary btn-block" />
}

and the javascript code to hijack the submit event and do an ajax post instead.
$(function () {

    $("#loginForm").submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize())
            .done(function(response) {
                if (response.status === 'success') {
                    alert("Login successful.Do something else now");
                } else {
                    alert("Login failed");
                }
            });
    });
});

Assuming your Login action method in AccountController will return a Json response with a status property.
public ActionResult Login(string PPNumber,string password)
{
    if(PPNumber=="thisIsDemo" && password=="ButDoTheActualCheck")
    {
        return Json(new { status = "success" });
    }
    return Json(new { status = "failed" });
}

Here i just hard coded the usrename /password check to 2 static values. You can change that to check it against your db table/whatever your credentials checking mechanism is.


text:
Q: About the calculation of one-particle-irreducible two-point diagram This is derived from the answer and comments of this Phys.SE question concerning the calculation of two-point one-particle-irreducible diagram.
On the one hand, according to the discussion on P.236 of An introduction to quantum field theory by Peskin and Shroeder, the truncated two-point one-particle-irreducible diagram, $M^2(p^2)$, possesses an imaginary part for an unstable particle. Mathematically, this corresponds to the case when two internal lines go on-shell simultaneously, which can be visualized by a cut through the two propagators.
On the other hand, however, according to Eq.(11.90) in section 11.6 on P.381, the inverse propagator is related to the second functional derivative of the effective action. The matrix formed by the second order derivative is manifestly symmetric. In the classical case, the second derivative of the potential is directly related to the mass of the particle. When one considers the corrections of quantum fluctuations, the argument is similar, according to the textbook. In particular, if one takes $p=0$, the inverse propagator $p^2-m_0^2-M^2(p^2)$ ($=p^2-m^2$ when properly renormalized) gives $m^2$. Therefore, in the presence of quantum fluctuations, the physics is essentially the same. Mathematically, one can associate the second functional derivative of effective potential to the dressed mass of the particle by simply taking $p=0$.
Now, Adam's answer to the above-mentioned question seems to prove that the effective potential is always real via path integral calculations with the Wick rotation. To be specific, by changing the contour of the integral $t$ from $(-\infty\rightarrow+\infty)$ to $(+i\infty\rightarrow -i\infty)$, one shows that the exponent of the functional integral of Eq.(9.42) is positive definite in the sense that $\mathcal{L}_E(\phi)$ possesses the form of an energy which is real and bounded from below. Above positive definite matrix implies that its eigenvalue and subsequently the dressed mass is always positive, due to linear algebra. But now I have a contradiction, since the existence of resonance implies a pole in the complex plane, and therefore, if one substitutes $p=0$ into the truncated two-point one-particle-irreducible diagram, one gets its mass which is not real.
I understand that the Wick rotation is essentially a trick to evaluate a path integral by choosing a different contour for the time coordinate. So, before and after the Wick rotation, $Z$, $\Gamma(\phi_{cl})$ (as well as all its functional derivatives and their corresponding forms in momentum space) are the same functionals. Why do they seemly have different pole structures on the complex plane of $p$? How these two approaches can be understood consistently?
Edits

*

*I updated the above question to clarify my doubt according to Adam's answer below.

*It is noted that the assertion that $\mathcal{L}_E(\phi)$ possesses the form of an energy, when transformed to momentum space, implies the requirement that the components of four momentum being real, $p^2$ as well as the bare mass term being positive. This is not violated by taking $p=0$ afterwards.

*Part of my misunderstanding lies in the incorrect statement that substituting $p=0$ into $\Gamma^{(2)}$ gives the mass, which is not consistent with the renormalization condition. To be specific, Eq.(11.17) gives $\frac{d}{dp^2}(p^2-m_0^2-M^2(p^2))=0$ or $1-\frac{dM^2}{dp^2}=0$ at $p^2=m^2$. Therefore to the first order one has $p^2-m_0^2-M^2(p^2)=(p^2-m^2)\left(1-\frac{dM^2(p^2)}{dp^2}\right)$. By substituting $p=0$, the second term is not necessarily real. The whole expression being real implies both $m^2$ and $\frac{dM^2(p^2)}{dp^2}$ may be on the complex plane simultaneously.

A: The OP's problem comes from a slight misunderstanding on how to find the particle life-time and mass, and when the self-energy is real or complex.
After Wick rotation, such that $p_W^2\geq 0$ for all $p_W$, one can indeed show that the effective potential Hessian matrix is definite positive. For arbitrary momenta $p_W$, one has the inverse propagator (suppressing all internal indices)
$$
\Gamma^{(2)}(p_W)=p_W^2+m_0^2+M^2(p_W)
$$
where $m_0$ is the bare mass, and $M^2(p_W)$ is the self-energy.
(Quasi)-particles and resonances corresponds to poles (in $p$) of the propagator, or equivalently, to zeros of $\Gamma^{(2)}$. (Side remark : there might not be any resonance if the theory is strongly coupled. For example, at a critical point, $
\Gamma^{(2)}(p_W)\propto p_W^{2-\eta}$ with $\eta>0$.)
Going back to real momenta, i.e $i p_{W,0}\to E+i\epsilon$ (the imaginary part insures that we will obtain the retarded propagator), and at zero spatial momentum, we have in general
$$
\Gamma^{(2)}(E)=-E^2+m_0^2+M_R^2(E)+i M_I^2(E),
$$
where now the self-energy might have obtained an imaginary part $M_I^2$.
The zeros of $\Gamma^{(2)}(E)$ might happen at either real or complex energies, corresponding to stable and unstable particles.
To address directly the OP's question, there is no inconsistency between the fact that the self-energy can be complex, and that on the other hand, the effective potential hessian is positive definite. One discussion is done before Wick rotation, the second after.
EDIT : Note that the pole of the stable or unstable particle is not in $p=0$, nor in $p^2=0$, but (in the case of zero spatial momentum) in $p^2=-E^2$, thus not applying directly to the effective potential, unless one is truly interested in a zero momentum and energy state (i.e. Goldstone mode).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Почему код работает не полностью? Здравствуйте, скажите пожалуйста в чём проблема, есть код:
$(document).ready(function(){
    $("form").submit(function(){
        var id = $("input[name='ik_payment_id']").val();
        var url = $("input[name='url']").val();
        var image = $("input[name='image']").val();
        var plan = $("input[name='plan']").val();

        $.post("ban_inter.php", {cmd:"add_200", id:id, url:url, image:image, plan:plan});
    });
});

Так-вот, переменные получают значения, но ajax запрос не посылается, но стоит после запроса добавить
alert(1);

Как всё начинает работать, в чём может быть проблема?
A: Попробуйте вот так:
$(document).ready(function(){
    $("form").submit(function(eventObj){
        var id = $("input[name='ik_payment_id']").val();
        var url = $("input[name='url']").val();
        var image = $("input[name='image']").val();
        var plan = $("input[name='plan']").val();

        $.post("ban_inter.php", {cmd:"add_200", id:id, url:url, image:image, plan:plan}, function(){
            alert("Data sent");
        });

        eventObj.preventDefault(); // предотвращает стандартное поведение при отправке формы
    });
});

Ещё прочтите про .serialize()


text:
Q: Environment variables not used, even after reboot I modified some environment variables (using both setx and through the GUI: Control Panel--System Properties--Advanced--Environment Variable). The changes persist after rebooting, which I can see in the terminals, in regedit or through the GUI. But they are not picked up by powershell, cmd or gitbash. Why would that be?
Here's some excerpts from powershell using the example environment variable %HOMEDRIVE%, run immediately after rebooting:
PS H:\> Get-ItemProperty Registry::HKEY_CURRENT_USER\Environment\

AWP_LOCALE182      : en-us
HOMEDRIVE          : C:
...

PS H:\> Get-ItemProperty "Registry::HKLM\System\CurrentControlSet\Control\Session Manager\Environment"

...
HOMEDRIVE              : C:
...

PS H:\> $Env:HOMEDRIVE
H:

cmd is very similar, except that the scripts in the two answers here do successfully update the environment variables in cmd, but not for powershell or gitbash.
I have administrator privileges, but it is a work machine, so some restrictions still apply.


text:
Q: How to get the sum of another sum in an eloquent Laravel relationship I have the relations user->sales->detail_sales, a user has one or many sales, a sale has one or more details. What I'm trying to do is obtain with ELOQUENT, the total of all sales per user, that is, make a sum(totaldetails) of the calculated total with withCount.
Sale.php
public function detail()
{
    return $this->hasMany(Detail:class);
}

public function user()
{
    return $this->belongsTo('App\User');
}

DetailSale
public function sale()
{
    return $this->belongsTo(Sale::class);
}

User
public function sales()
{
    return $this->hasMany(Sale::class );
}

This query I currently have
return App\User::with(['sales' => function($query){
    // get total for detail_sales for sale
    $query->withCount(['detail as totaldetails' => function($que){
        $que->select(DB::raw('sum(subtotal)'));
    }]);
}])->get();

but I want that in the User model, to have a property like salestotal for example, is it possible?
@foreach($users as $user)
  {{ $user->salestotal}}
@endforeach

A: Why not just use the sum() function since it's all in a Collection?
@foreach($users as $user)
    {{ $user->sales->sum('totaldetails') }}
@endforeach

A: You can use withCount() with a HasManyThrough relationship:
class User extends Model
{
    public function details()
    {
        return $this->hasManyThrough(Detail:class, Sale::class);
    }
}

return App\User::withCount(['details as salestotal' => function($query) {
    $query->select(DB::raw('sum(subtotal)'));
}])->get();

@foreach($users as $user)
    {{ $user->salestotal }}
@endforeach

A: I hope this helps:
    return App\User::with(['sales' => function($query){
     // get total for detail_sales for sale
        $query->withCount(['detail as totaldetails' => function($que){
       $que->select(DB::raw("SUM(subtotal) as salestotal"));
       }]);
    }])->get();


text:
Q: php inside html div css style tag I am trying to insert a dynamic php value into a html style tag, I am not sure if i am doing the correct way?
<div class="status" style='background: <?php get_option("myoption_background_color") ?>'>

A: You forgot the semicolon and echo, check this:
<div class="status" style="background: <?php echo get_option("myoption_background_color"); ?>">

A: Most likely you also need echo:
<div class="status" style="background: <?php echo get_option("myoption_background_color"); ?>">

If a function is called getSomething then it likely returns the value, but not writes it to output.


text: Q: how the proxy object trigger your traps? Does anyone know how to explain how the Proxy Object captures the changes of a variable with traps? I thought it was related to get, set and/or observer, but after seeing this post I have no idea how it is triggered.


text:
Q: Replace tokens from list of lists with int value from Dictionary I have a list of lists with only tokens in every list.
grade_lists = [['Very good', 'good', 'okay'], ['sufficient', 'bad', 'very bad']]

and this dictionary with key = string, value = int
month_ids = {     'Very good': 1,
                  'good': 2,
                  'okay': 3,
                  'sufficient': 4,
                  'bad': 5,
                  'very bad': 6
                  }

Can I replace the tokens from my list of lists with the integers from the Dictionary?
grade_lists = [[1, 2, 3], [4, 5, 6]]

A: You could do that with list comprehensions:
grade_lists = [['Very good', 'good', 'okay'], ['sufficient', 'bad', 'very bad']]
month_ids = {'Very good': 1, 'good': 2, 'okay': 3, 'sufficient': 4, 'bad': 5, 'very bad': 6}
grade_lists2 = [[month_ids[grade] for grade in sublist] for sublist in grade_lists]
print(grade_lists2)

A: You can try to loop through each list
temp_list, new_list = [], []

for glist in grade_lists:
    temp_list = []
    for token in glist:
        temp_list.append(month_ids[token])
    new_list.append(temp_list)

Output:
>>> new_list
[[1, 2, 3], [4, 5, 6]]


text:
Q: Images and mask in OpenGL ES 2.0 I'm learning OpenGL ES 2.0 and I'd like to create an App to better understand how it works.
The App has a set of filter that the user can apply on images (I know, nothing new :P).
One of this filter takes two images and a mask and it mixes the two images showing them through the mask (here an image to better explain what I want to obtain)

At the moment I'm really confused and I don't know where to start to create this effect.
I can't understand wether I have to work with multiple textures and multiple FrameBuffers or I can just work with a single shader.
Do you have any hint to help me in doing this project?
EDIT--------
I've found this solution, but when I use as mask lines instead of circles the result is really "grungy", especially if lines are rotated.
precision highp float;

varying vec4 FragColor;
varying highp vec2 TexCoordOut;

uniform sampler2D textureA;
uniform sampler2D textureB;
uniform sampler2D mask;

void main(void){
    vec4 mask_color = texture2D(mask, TexCoordOut);

    if (mask_color.a > 0.0){
        gl_FragColor =  texture2D(textureA, TexCoordOut);
    }else {
        gl_FragColor =  texture2D(textureB, TexCoordOut);
    }
}

Is it probably better to use Stencil buffer or blending?

A: You can apply the mask in one line without using the costly if:
gl_FragColor = step( 0.5, vMask.r ) * vColor_1 + ( 1.0 - step( 0.5, vMask.r ) ) * vColor_2;

Or, better just interpolate between two colors:
gl_FragColor = mix( vColor_1, vColor_2, vMask.r );

In this case the mask can be smoothed (i.e. with Gaussian blur) to produce less aliasing. This will yield very good results compared to a single value thresholding.

A: There is no need for multiple shaders or framebuffers, just multiple texture units. Simply use 3 texture units which are all indexed by the same texture coordinates and use the Mask texture to select between the other two textures.  The fragment shader would look like this:
uniform sampler2D uTextureUnit_1;
uniform sampler2D uTextureUnit_2;
uniform sampler2D uTextureMask;
varying vec2 vTextureCoordinates;

void main()
{
    vec4 vColor_1 = texture2D(uTextureUnit_1, vTextureCoordinates);
    vec4 vColor_2 = texture2D(uTextureUnit_2, vTextureCoordinates);
    vec4 vMask = texture2D(uTextureMask, vTextureCoordinates);

    if (vMask.r > 0.5)
        gl_FragColor = vColor_1;
    else
        gl_FragColor = vColor_2;
}

You can see that using a third texture unit just to do a binary test on the Red channel is not very efficient, so it would be better to encode the mask into the alpha channels of Textures 1 or 2, but this should get you started.


text:
Q: Restoring saved values in a finally block? I've seen this pattern used in a few different places now, but I'm not sure exactly what it's for or why it's needed. Given that I have seen it in quality projects, I'm sure it's useful, but I'd like to understand it rather than just blindly following it. I've specifically seen this pattern in Servlet Filters and Struts2 Interceptors (very similar in concept to a Filter).
Here's an example from Google Guice (Servlet) 3.0:
Context previous = localContext.get();

try {
  localContext.set(new Context((HttpServletRequest) servletRequest,
      (HttpServletResponse) servletResponse));

  //dispatch across the servlet pipeline, ensuring web.xml's filterchain is honored
  filterPipeline.dispatch(servletRequest, servletResponse, filterChain);
} finally {
  localContext.set(previous);
}

What is the need or benefit for restoring the value in the finally block?

A: It's basically a way of scoping the changes only to the try block.  Regardless of whether or not the block successfully executes, you know that once you're out of it, you have restored the value to what it was when you went in.

A: This is a pattern that is very useful, and it effectively emulates non-lexical scoping in Java. Consider the local context being essentially a global variable, or, more commonly, a thread-local variable. You modify the global to a set value (because e.g. you don't want to pass to each and every method called the HTTP request and response), which can be retrieved later on, in methods deep in the call stack. If you want to nest these modifications, a single exception can throw you out of whack - hence this construct. No matter what happens (short of a VM crash or forced process termination by the OS), that finally block will be executed as the stack unwinds, and its job is to undo the modification to global variables, because the nesting of functionality is no longer needed.
See also Thread#setContextClassLoader().

A: I will try to give another example where we find this pattern useful. It is essentailly saying, "Restore the (usually) global resources to a predictable state after the try/catch block is done with using them".
The example: We are using DB connection pool => We understand creating new connections is expensive and we'd like to reuse a limited pool of connections. So the try block in some servlet class starts with a Connection, creates its Statement and ResultSet, writes results to an ObjectOutputStream, etc. These can cause SQLException (someone deleted a useless column in the db table and the sql fails now) and/or IOException (client http connection broke while servlet is still writing to it) that we catch in the catch block. Now, whether there is an exception thrown or not, we want to close the db Connection so other threads can use it. This closing is done in the finally block.
Hope that helps, - M.S.


text:
Q: Getting reproducible docker layers on different hosts Problem: I can't reproduce docker layers using exactly same content (on one machine or in CI cluster where something is built from git repo)
Consider this simple example
$ echo "test file" > test.txt
$ cat > Dockerfile <<EOF
FROM alpine:3.8

COPY test.txt /test.txt
EOF

If I build image on one machine with caching enabled, then last layer with copied file would be shared across images
$ docker build -t test:1 .
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM alpine:3.8
3.8: Pulling from library/alpine
cd784148e348: Already exists
Digest: sha256:46e71df1e5191ab8b8034c5189e325258ec44ea739bba1e5645cff83c9048ff1
Status: Downloaded newer image for alpine:3.8
 ---> 3f53bb00af94
Step 2/2 : COPY test.txt /test.txt
 ---> decab6a3fbe3
Successfully built decab6a3fbe3
Successfully tagged test:1

$ docker build -t test:2 .
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM alpine:3.8
 ---> 3f53bb00af94
Step 2/2 : COPY test.txt /test.txt
 ---> Using cache
 ---> decab6a3fbe3
Successfully built decab6a3fbe3
Successfully tagged test:2

But with cache disabled (or simply using another machine) I got different hash values.
$ docker build -t test:3 --no-cache .
Sending build context to Docker daemon  3.072kB
Step 1/2 : FROM alpine:3.8
 ---> 3f53bb00af94
Step 2/2 : COPY test.txt /test.txt
 ---> ced4dff22d62
Successfully built ced4dff22d62
Successfully tagged test:3

At the same time history command shows that file content was same
$ docker history test:1
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
decab6a3fbe3        6 minutes ago       /bin/sh -c #(nop) COPY file:d9210c40895e

$ docker history test:3
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
ced4dff22d62        27 seconds ago      /bin/sh -c #(nop) COPY file:d9210c40895e

Am I missing something or this behavior is by design?
Are there any technics to get reproducible/reusable layers that does not force me to do one of the following

*

*Share docker cache across machines

*Do a pull of "previous" image before building next

Ultimately this problem prevents me from getting thin layers with constantly changing app code while keeping layers of my dependencies in separate and infrequently changed layer.

A: After some extra googling, I found a great post describing solution to this problem.
Starting from 1.13, docker has --cache-from option that can be used to tell docker to look at another images for layers. Important thing - image should be explicitly pulled for it to work + you still need point what image to take. It could be latest or any other "rolling" image you have.
Given that, unfortunately there is no way to produce same layer in "isolation", but cache-from solves root problem - how to eventually reuse some layers during ci build.


text:
Q: Onion Architecture : Can UI depend on Domain I am making an ASP.NET MVC website with an Onion architecture. I have implemented a repository pattern and am now creating a Controller method in my project. This is my architecture:

*

*Domain : Entities / Domain Interfaces

*Repository : Generic repository (for now) using Entity Framework Code First

*Service : Generic Service that calls the Repository

*MVC

Now in my MVC project I need to access repository but according to Jeffrey Palermo, MVC is dependant from Service and Domain, but nothing is said of Repository.
Can i make my UI dependant of Repository?
I cannot do anything without the dependency right now, because Service creation depends on Repository. I have tried modifying Startup.cs to not directly use Repository objects in my Controllers, but it still means I need to add a reference to Repository (see http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/ )

A: At this point MVC (UI) is the composition root, which would need to know all the layers in order to register them with the DI container.
The start up would either refer to the implementations directly when registering them or indirectly via extension methods exposed from that layer. Either way the composition root needs to reference all lower layers if they are to be added to DI container.
The controllers should also be dependent on abstractions from lower layers and not concretions.
If injecting repositories directly into controllers then I suggest reviewing the design as that may indicate mixing of responsibilities.


text:
Q: Get numpy ndarray offset Question: How do I calculate the "offset" from a view of ndarray?
Example 1
Input:
a = np.arange(10, dtype=np.uint8)
b = a[1:]
# some procedure to get offset
print(offset)

Expected Output
1

because, uint8 is 1 byte object.
Example 2
Input:
a = np.arange(10, dtype=np.uint8)
b = np.ndarray((9,), a.dtype, a.data, offset=1)
# some procedure to get offset
print(offset)

Expected output:
1

This is (maybe) exactly the same procedure shown in Example 1.

A: In [485]: a = np.arange(10, dtype=np.uint8)
     ...: b = a[1:]

Compare these:
In [486]: a.__array_interface__['data'][0]
Out[486]: 38965232
In [487]: b.__array_interface__['data'][0]
Out[487]: 38965233


text:
Q: Can not change the display name of From email through smtp.office365.com using C# SmtpClient In the past few months, I used SmtpClient to send emails with host smtp.office.365.comn, and I could change the Display Name of From Email using
message.From = new MailAddress(email, displayName)

But recently the client has found out that they can no longer change that displayName, the mail they received only show email (username@domain.com) in the From
So, is there any change from Microsoft or any way I can custom the Display Name?
Because my code runs well with Gmail (smtp.gmail.com).
I would appreciate any help.
Thanks.

A: I just ran a test and sent an email from an address inside my organization, and the email message (displayed in Outlook) ignored the Display Name I had set, and instead used the display name that's set in our Active Directory for that account.  I then tested with a dummy email address, and it showed the Display Name I had set.  Could it be that?


text:
Q: Working with recursive anonymous blocks in Objective-C I love JavaScript's ability to define functions as variables and am trying to do something similar in Objective-C. In particular, I want to write a recursive function using an anonymous block that I can call on an object and have it work its way through a tree, applying a change at each node:
void ( ^setDetailsLoaded )( Product* ) = ^void ( Product* prod ) {
    prod.detailsLoaded = true;
    for ( Group* group in prod.groups ) {
        for ( Product* mod in group.mods )
            setDetailsLoaded( mod );
    }
};
setDetailsLoaded( product ); <-- error here

However, I'm getting the strange error error: address doesn't contain a section that points to a section in a object file[sic] when I run the program (which compiles fine).
I'm just wondering if perhaps I need to retain the block or something, or if I should just do this with function pointers instead of blocks.

A: Because of the way blocks are implemented—they make a const copy of all primitive type variables, and a strong reference to all object type variables referenced in them at creation time—attempting to recursively reference a block within itself will result in the crash that you saw.
You can solve this by using the __block annotation on the block variable itself:
__block void ( ^setDetailsLoaded )( Product* ) = ^void ( Product* prod ) {
    prod.detailsLoaded = true;
    for ( Group* group in prod.groups ) {
        for ( Product* mod in group.mods )
            setDetailsLoaded( mod );
    }
};

See @bbum's blog post on blocks for more details (specifically tip #7).


text:
Q: How to write code for generating checksum for paytm initiate transaction api How I should pass the values in this function
Paytm.Checksum.generateSignature(paytmParams, PayTmMKey)
I want to hit initiate transaction api after generating checksum.
what more values should I add for initiate transaction api.
This is how paytm doc says to implement checksum.
/* initialize an array */
Dictionary<string, string> paytmParams = new Dictionary<string, string>();

/* add parameters in Array */
paytmParams.Add("MID", "YOUR_MID_HERE");
paytmParams.Add("ORDER_ID", "YOUR_ORDER_ID_HERE");

/**
* Generate checksum by parameters we have
* Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
*/
String paytmChecksum = Paytm.Checksum.generateSignature(paytmParams, "YOUR_MERCHANT_KEY");
Response.Write("generateSignature Returns: " + paytmChecksum);

Link to it-https://developer.paytm.com/docs/checksum/

A: For initiate transaction API checksum should be generated from body of json string. Please refer the below code.
For more detail you can also use Java code under Initiate transaction API.
/* import checksum generation utility */
import com.paytm.pg.merchant.*;

/* initialize JSON String */
String body = "{"\mid\":"\YOUR_MID_HERE\","\orderId\":"\YOUR_ORDER_ID_HERE\"}";

/**
 * Generate checksum by parameters we have in body
 * Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
 */

paytmChecksum = PaytmChecksum.generateSignature(body, "YOUR_MERCHANT_KEY");
System.out.println("generateSignature Returns: " + paytmChecksum);

A: This is how we will make json string(json_for_checksum) for Initiate transaction api request and will pass this in generateCheckSumByJson function
string json_for_checksum = "{"requestType":"Payment","mid":"" + MID + "","orderId":"" + order_id + "","websiteName":"" + Website + "","txnAmount":{"value":"" + Amount + "","currency":"INR"},"userInfo":{"custId":"WE25622"}}";
string Check = paytm.CheckSum.generateCheckSumByJson(Merchant_key, json_for_checksum);
Assuming you know your basic parameters in json string and download paytm dll


text:
Q: How do I convert from a slice of interface{} to a slice of my struct type in Go? func GetFromDB(tableName string, m *bson.M) interface{} {
    var (
        __session *mgo.Session = getSession()
    )

    //if the query arg is nil. give it the null query
    if m == nil {
        m = &bson.M{}
    }

    __result := []interface{}{}
    __cs_Group := __session.DB(T_dbName).C(tableName)
    __cs_Group.Find(m).All(&__result)

    return __result
}

call
GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]CS_Group)

runtime will give me panic:
panic: interface conversion: interface is []interface {}, not []mydbs.CS_Group

how convert the return value to my struct?

A: You can't automatically convert between a slice of two different types – that includes []interface{} to []CS_Group. In every case, you need to convert each element individually:
s := GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]interface{})
g := make([]CS_Group, 0, len(s))
for _, i := range s {
    g = append(g, i.(CS_Group))
}

A: You need to convert the entire hierarchy of objects:
rawResult := GetFromDB(T_cs_GroupName, &bson.M{"Name": "Alex"}).([]interface{})
var result []CS_Group
for _, m := range rawResult {
   result = append(result,
       CS_Group{
         SomeField: m["somefield"].(typeOfSomeField),
         AnotherField: m["anotherfield"].(typeOfAnotherField),
       })
}

This code is for the simple case where the type returned from mgo matches the type of your struct fields. You may need to sprinkle in some type conversions and type switches on the bson.M value types.
An alternate approach is to take advantage of mgo's decoder by passing the output slice as an argument:
func GetFromDB(tableName string, m *bson.M, result interface{}) error {
    var (
        __session *mgo.Session = getSession()
    )
    //if the query arg is nil. give it the null query
    if m == nil {
        m = &bson.M{}
    }
    __result := []interface{}{}
    __cs_Group := __session.DB(T_dbName).C(tableName)
    return __cs_Group.Find(m).All(result)
}

With this change, you can fetch directly to your type:
 var result []CS_Group
 err := GetFromDB(T_cs_GroupName, bson.M{"Name": "Alex"}, &result)

See also: FAQ: Can I convert a []T to an []interface{}?


text:
Q: Create multiple lines of text with Snap.svg I have not been able to figure out how to create multiple lines of text with a single paper.text element in Snap.svg. I have tried using the techniques mentioned for raphael.js, such as \n, but that doesn't do a thing for snap.svg.
I have tried using , \n, and variations of that, but nothing works. I find it odd that it is so easy to do in raphael.js, (it's in the documentation), but yet snap.svg docs don't mention anything about this, and searching the web I found nothing.
Help would be very appreciated, thank you!
http://jsfiddle.net/f3mkqovm/
var myRect = paper.text(100, 100, ["Lorem",
    "<br>","ipsum dolor sit \n amet /n see ", "\n","amend"]).attr({
    fill : 'black'
});

EDIT: Here is a jsfiddle where \n is working for raphael. Since snap.svg is not built into jsfiddle, I don't know that the other fiddle will help anyone much. http://jsfiddle.net/yf8364mp/

A: To draw multi line text with Snap.svg is a bit bother.
When you call Paper.text method with string array, Snap.svg creates tspan elements under the text element.
If you want to display the text element as multi line, you should set position to each tspan element manually.
var paper = Snap(200,200);
paper.text({text:["Line1", "Line2", "Line3"]})
   .attr({fill:"black", fontSize:"18px"})
   .selectAll("tspan").forEach(function(tspan, i){
      tspan.attr({x:0, y:25*(i+1)});
   });

A: Rename plugin function to whatever you like:
Snap.plugin(function(Snap, Element, Paper, global) {
    Element.prototype.layoutTspans = function(xOffset, vSpacing) {
        this.selectAll("tspan").forEach(function(ts) {
            ts.attr({x: parseInt(ts.parent().attr("x")) + xOffset, dy: vSpacing});
        });
    };
});

Then invoke it from any ancestor element, such as a text element:
snap.select("#t1").layoutTspans(13, 20);

To apply same offset and spacing to multiple texts... (There may be a way to support selectAll directly via plugin, but I can find no documentation or examples of that).
snap.selectAll("g.badge").forEach(function(el) { el.layoutTspans(13, 20); });


text:
Q: Select statement on XML not returning desired output DECLARE @barcode XML

            SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>'

            --INSERT INTO #barcode
            SELECT      v.x.value('BCODE[1]','VARCHAR(15)') AS Barcodes
            FROM        @barcode.nodes('BCODES') v(x)

Result-->
Barcodes
a
I'm unable to get b,c and d in the output.

A: Just do this:
SELECT v.x.value('.','VARCHAR(15)') AS Barcodes
FROM @barcode.nodes('BCODES/BCODE') v(x)

The idea is first to get all BCODE nodes and then to extract its values.

A: You could try :
DECLARE @barcode XML;
SET @barcode = '<BCODES><BCODE>a</BCODE><BCODE>b</BCODE><BCODE>c</BCODE><BCODE>d</BCODE></BCODES>';

            --INSERT INTO #barcode

SELECT barcode = n.v.value('.[1]', 'NVARCHAR(128)')
FROM @barcode.nodes('BCODES/BCODE') AS n(v);

Result :
barcode
a
b
c
d


text:
Q: Deny access to php files but allow some other php files in subdirectory I have a directory named "template". There are some php files that I don't want people have direct access to them, So I wrote this in htaccess :
<Files *.php>
    Order Deny,Allow
    Deny from all
</Files>

Also there is some files that I want people have direct access to them, these files are named as:

switcher.php, switcher1.php, switcher2.php, switcher3.php, switcher4.php, switcher5.php

And located at template/styles/theme/
So I created a new htaccess file in that location and wrote this :
<FilesMatch "^switcher[1-5]?\.php$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

This works good on my localhost, but when I upload the script on a cPanel Shared Host, it didn't work there. Access to all php files denied.
What can I do to fix this problem?
I can't ask hosting to make changes, because this script should installed on at least 30 shared hosts with different configurations!

A: Check for REQUEST_URI in each file:
$file = basename(__FILE__);
if(preg_match("/$file/", $_SERVER['REQUEST_URI'])){
    die('This file cannot be accessed directly!');
}

A: If you have a directory containing PHP includes, that you do not wish to be accessed directly from the browser, there is a way of disabling the directory using Mod_Rewrite.
To enable this, create a .htaccess file following the main instructions and guidance, and include the following text:
## Enable Mod Rewrite, this is only required once in each .htaccess file
RewriteEngine On
RewriteBase /
## Test for access to includes directory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC]
## Test that file requested has php extension
RewriteCond %{REQUEST_FILENAME} ^.+\.php$
## Forbid Access
RewriteRule .* - [F,NS,L]

Where /includes/ is your includes directory.
Note: I strongly recommend to store your files, that you don't want to be accessed directly by the user, in a separate directory / folder. Don't worry, you can access these files using include method.


text:
Q: Why harmonic oscillator / motion / potential is called "harmonic"? As in the topic. Why force being proportional to displacement concludes the name as being "harmonic"? Question is purely about the name.

A: This is a good question. Harmonic vibrations (tones) actually mean sinusoidal vibrations with an integer multiple of a sinusoidal basic frequency. I did not find any explanation of the term, only that it is synonymous with an oscillator having this linear potential dependence, which of course has only one sinusoidal vibration. Perhaps one should look into an etymological dictionary.

A: Because simple harmonic motion does this:

It just repeats, undisturbed (in harmony). It probably goes back to some Latin word to describe a musical tone(s) that repeats, indifferent to everything around it.
Then the idea got transfered to any repeating/periodic physical process.
Dictionary definitions:
is the combination of simultaneously sounded musical notes to produce a pleasing effect.
"the piece owes its air of tranquillity largely to the harmony"
"the quality of forming a pleasing and consistent whole."
synonyms:balance, symmetry, congruity, consonance, coordination, blending, correspondence, compatibility
"the simplicity of the individual parts focused attention on the harmony of the whole structure"
Ideally, to me it just means it keeps moving evenly, for a mass on a spring say.
But if it has modes of vibration, they are also known sometimes as harmonics, as in musical instruments like guitar strings, which have a first, second, third,.....harmonic as you restrict the movement of the string at fixed intervals
There are other kinds of harmonic motion, such  as damped harmonic motion.


text:
Q: Best way to handle multiple currencies in Rails app I have an where users can create an account and then create an invoice.  More international users are using the app which means I need to allow them to set a currency from a dropdown and that's used on their invoices.  I'm using number_to_currency everywhere currently, but how do I use that if say the currency code for a user is ES using the relationship current_user.currencies.name?

A: Ok I figured it out

*

*Install this gem https://github.com/svenfuchs/rails-i18n

*From here always use this format now number_to_currency(100,:locale=>'en-GB') you can choose from the list of formats here: https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale


text:
Q: How can build CNN using Alexnet model? How can build Computer Vision based object identification system using Alexnet in python with keras and Tensorflow ?
Is there anyone who familiar with Alexnet, Please help me to build image classification using my custom image directory dataset using alexnet CNN model.

A: You can start with Squeeze Net, a simplified version of AlexNet:
SqueezeNet: AlexNet-Level accuracy with 50 X fewer parameters and < 0.5MB Model Size:
https://arxiv.org/pdf/1602.07360.pdf
Code:
import numpy as np
from keras.layers import Input, Dense, Lambda
from keras.models import Model
from keras import backend as K
from keras import objectives
from keras.datasets import mnist
from keras.layers.core import Reshape
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Concatenate
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D, UpSampling2D
from keras.utils import np_utils
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD
from keras.layers.advanced_activations import ELU
from keras.layers.pooling import GlobalAveragePooling2D
import pandas as pd
import matplotlib.pyplot as plt

(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))

x_train_CNN=x_train.reshape(60000,28,28,1)

y_train2=pd.get_dummies(y_train)

epochs=3
learning_rate = 0.07
decay_rate = 5e-5
momentum = 0.6

sgd = SGD(lr=learning_rate,momentum=momentum, decay=decay_rate, nesterov=False)

input_shape=(28,28,1)

input_img = Input(batch_shape=(None, 28,28,1))
squeeze=Lambda(lambda x: x ** 2,input_shape=(784,),output_shape=(1,784))(input_img)
squeeze=Reshape((28,28,1))(squeeze)
squeeze=Conv2D(64, 3,3,
                          border_mode='valid',
                        input_shape=input_shape)(squeeze)
squeeze=BatchNormalization()(squeeze)
squeeze=ELU(alpha=1.0)(squeeze)
squeeze=MaxPooling2D(pool_size=(2,2))(squeeze)
squeeze=Conv2D(32, 1, 1,
                            init='glorot_uniform')(squeeze)
squeeze=BatchNormalization()(squeeze)
squeeze=ELU(alpha=1.0)(squeeze)

squeeze_left=squeeze
squeeze_left=Conv2D(64, 3,3,
                          border_mode='valid',
                        input_shape=input_shape)(squeeze_left)
squeeze_left=ELU(alpha=1.0)(squeeze_left)

squeeze_right=squeeze
squeeze_right=Conv2D(64, 3,3,
                          border_mode='valid',
                        input_shape=input_shape)(squeeze_right)
squeeze_right=ELU(alpha=1.0)(squeeze_right)

squeeze0=Concatenate()([squeeze_left,squeeze_right])
squeeze0=Dropout(0.2)(squeeze0)
squeeze0=GlobalAveragePooling2D()(squeeze0)
squeeze0=Dense(10)(squeeze0)
squeeze0=Activation('sigmoid')(squeeze0)

model = Model(inputs = input_img, outputs = squeeze0)

model.compile(loss='categorical_crossentropy', optimizer=sgd,metrics = ['accuracy'])
model.summary()

model.fit(x_train_CNN,np.array(y_train2),
                nb_epoch=15,
                batch_size=30,verbose=1)

predictions=np.argmax(model.predict(x_train_CNN,verbose=1),axis=1)

Neural Network Architecture:
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_22 (InputLayer)           (None, 28, 28, 1)    0
__________________________________________________________________________________________________
lambda_39 (Lambda)              (None, 1, 784)       0           input_22[0][0]
__________________________________________________________________________________________________
reshape_39 (Reshape)            (None, 28, 28, 1)    0           lambda_39[0][0]
__________________________________________________________________________________________________
conv2d_144 (Conv2D)             (None, 26, 26, 64)   640         reshape_39[0][0]
__________________________________________________________________________________________________
batch_normalization_73 (BatchNo (None, 26, 26, 64)   256         conv2d_144[0][0]
__________________________________________________________________________________________________
elu_143 (ELU)                   (None, 26, 26, 64)   0           batch_normalization_73[0][0]
__________________________________________________________________________________________________
max_pooling2d_37 (MaxPooling2D) (None, 13, 13, 64)   0           elu_143[0][0]
__________________________________________________________________________________________________
conv2d_145 (Conv2D)             (None, 13, 13, 32)   2080        max_pooling2d_37[0][0]
__________________________________________________________________________________________________
batch_normalization_74 (BatchNo (None, 13, 13, 32)   128         conv2d_145[0][0]
__________________________________________________________________________________________________
elu_144 (ELU)                   (None, 13, 13, 32)   0           batch_normalization_74[0][0]
__________________________________________________________________________________________________
conv2d_146 (Conv2D)             (None, 11, 11, 64)   18496       elu_144[0][0]
__________________________________________________________________________________________________
conv2d_147 (Conv2D)             (None, 11, 11, 64)   18496       elu_144[0][0]
__________________________________________________________________________________________________
elu_145 (ELU)                   (None, 11, 11, 64)   0           conv2d_146[0][0]
__________________________________________________________________________________________________
elu_146 (ELU)                   (None, 11, 11, 64)   0           conv2d_147[0][0]
__________________________________________________________________________________________________
concatenate_34 (Concatenate)    (None, 11, 11, 128)  0           elu_145[0][0]
                                                                 elu_146[0][0]
__________________________________________________________________________________________________
dropout_28 (Dropout)            (None, 11, 11, 128)  0           concatenate_34[0][0]
__________________________________________________________________________________________________
global_average_pooling2d_21 (Gl (None, 128)          0           dropout_28[0][0]
__________________________________________________________________________________________________
dense_15 (Dense)                (None, 10)           1290        global_average_pooling2d_21[0][0]
__________________________________________________________________________________________________
activation_15 (Activation)      (None, 10)           0           dense_15[0][0]
==================================================================================================
Total params: 41,386
Trainable params: 41,194
Non-trainable params: 192
__________________________________________________________________________________________________


text:
Q: JSP exception in WSO2 IS 5.1.0 I tried following this link.
http://wso2.com/library/tutorials/2016/02/tutorial-how-to-enable-role-based-access-control-for-wso2-api-manager-using-xacml/
I am stuck at a place where there is figure 6 shown.
I am using IS 5.1.0
When I click on this search button there is an exception thrown in the backend on the jsp page.
[2016-05-27 11:18:17,262] ERROR {org.apache.catalina.core.ApplicationDispatcher} -  Servlet.service() for servlet bridgeservlet threw exception
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 384 in the jsp file: /entitlement/select-attribute.jspStacktrace:
        at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
        at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
        at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:485)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:379)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
        at org.apache.jasper.compiler.Compiler.compile(Compiler.java:341)
        at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
        at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
        at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
        at org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.include(RequestDispatcherAdaptor.java:37)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.include(ContextPathServletAdaptor.java:369)
        at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954)
        at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:688)
        at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:682)
        at sun.reflect.GeneratedMethodAccessor67.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.tiles.jsp.context.JspUtil.doInclude(JspUtil.java:87)
        at org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:88)
        at org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:82)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:465)
        at org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:140)
        at org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:117)
        at org.apache.tiles.jsp.taglib.RenderTagSupport.execute(RenderTagSupport.java:171)
        at org.apache.tiles.jsp.taglib.RoleSecurityTagSupport.doEndTag(RoleSecurityTagSupport.java:75)
        at org.apache.tiles.jsp.taglib.ContainerTagSupport.doEndTag(ContainerTagSupport.java:80)
        at org.apache.jsp.admin.layout.template_jsp._jspx_meth_tiles_005finsertAttribute_005f7(template_jsp.java:640)
        at org.apache.jsp.admin.layout.template_jsp._jspService(template_jsp.java:356)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
        at org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.forward(RequestDispatcherAdaptor.java:30)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.forward(ContextPathServletAdaptor.java:362)
        at org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198)
        at org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:185)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:419)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:370)
        at org.wso2.carbon.ui.action.ActionHelper.render(ActionHelper.java:52)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:101)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CSRFPreventionFilter.doFilter(CSRFPreventionFilter.java:88)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CRLFPreventionFilter.doFilter(CRLFPreventionFilter.java:59)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1698)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
[2016-05-27 11:18:17,503] ERROR {org.apache.catalina.core.ApplicationDispatcher} -  Servlet.service() for servlet bridgeservlet threw exception
java.lang.ClassNotFoundException: org.apache.jsp.entitlement.select_002dattribute_jsp
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:132)
        at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:63)
        at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:121)
        at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:172)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
        at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
        at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
        at org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.include(RequestDispatcherAdaptor.java:37)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.include(ContextPathServletAdaptor.java:369)
        at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:954)
        at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:656)
        at org.apache.tiles.jsp.context.JspUtil.doInclude(JspUtil.java:98)
        at org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:88)
        at org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:82)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:465)
        at org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:140)
        at org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:117)
        at org.apache.tiles.jsp.taglib.RenderTagSupport.execute(RenderTagSupport.java:171)
        at org.apache.tiles.jsp.taglib.RoleSecurityTagSupport.doEndTag(RoleSecurityTagSupport.java:75)
        at org.apache.tiles.jsp.taglib.ContainerTagSupport.doEndTag(ContainerTagSupport.java:80)
        at org.apache.jsp.admin.layout.template_jsp._jspx_meth_tiles_005finsertAttribute_005f7(template_jsp.java:640)
        at org.apache.jsp.admin.layout.template_jsp._jspService(template_jsp.java:356)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
        at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:486)
        at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:411)
        at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
        at org.eclipse.equinox.http.servlet.internal.RequestDispatcherAdaptor.forward(RequestDispatcherAdaptor.java:30)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor$RequestDispatcherAdaptor.forward(ContextPathServletAdaptor.java:362)
        at org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198)
        at org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:185)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:419)
        at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:370)
        at org.wso2.carbon.ui.action.ActionHelper.render(ActionHelper.java:52)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:101)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CSRFPreventionFilter.doFilter(CSRFPreventionFilter.java:88)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.CRLFPreventionFilter.doFilter(CRLFPreventionFilter.java:59)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1698)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

A: I solved the issue repacking the bugged jar.
Download it from here
You have to put the linked jar in this path: $wso2is-5.1.0/repository/components/plugins
Stop the WSO2 carbon server, put the jar and clean the working dir. At the end you'll be free of the bug!


text:
Q: What is Visual Studio's equivalent of Ctrl + Shift + O shortcut in Android development in Eclipse? I have been doing some Android development and found that Ctrl+Shift+O shortcut is quite handy for someone like me who is still getting used to what imports are necessary for different objects on the screen. I have also been doing vb.net development in Visual Studio 2008 and by mistake tried that shortcut however it tried opening a form or something similar. So my question is: is there a shortcut that lets us import all missing references or remove the unnecessary ones in Visual Studio 2008?

A: To Remove Unnecessary Import Directives
I can confirm that in Visual Studio 2012 and Visual Studio 2010 there is a context menu option for the code-editor to remove, sort or remove and sort using directives in either Visual Basic.NET or C#. I've actually never used Visual Studio 2008 but a quick search reveals that it is possible in 2008 too (source).

In order to hook this functionality up to a hotkey all you need to do is:

*

*Go to Tools > Options

*Expand the root node annotated 'Enviroment' and then click the node annotated 'Keyboard'

*Search for Edit.RemoveAndSort and assign your hotkey of choice.

To Add Unknown Import Directives
I use this plugin called ReSharper which presents me with an interface like this when I reference a class that does not have an appropriate import directive:

If you don't want to use ReSharper (it's pretty expensive) then Visual Studio has a slightly less productive but just as effective interface. You should see the class reference underlined in red and if you hover your mouse to the red line you should see a little dialog displaying the option to add a reference to the namespace. You can also press CTRL + . to show the dialog quickly.

A: From this link:
Automatic namespaces import
Looks like Shift + ALT + F10 will do the trick.


text:
Q: Deploy multi modules Play project I'm trying to deploy a Multi-Module Play project using SBT.
Our project have 5 modules [commons, channel , ...].
When I use sbt run in my local system every thing works fine.
For deploying in server I use sbt dist to build the project.
But when I run my application using script that is generated by sbt dist, the problems appears!
Here is one example of errors :
[error] error_handler - Unhandled Error
java.lang.IllegalArgumentException: No query defined for that name [automaticChannel.getTagByChannelId]
    at org.hibernate.internal.AbstractSharedSessionContract.buildQueryFromName(AbstractSharedSessionContract.java:770)
    at org.hibernate.internal.AbstractSharedSessionContract.createNamedQuery(AbstractSharedSessionContract.java:748)
    at org.hibernate.internal.AbstractSessionImpl.createNamedQuery(AbstractSessionImpl.java:23)
    at repositories.GenericRepository.namedQuery(GenericRepository.java:291)
    at repositories.GenericRepository.namedNativeQuery(GenericRepository.java:573)
    at repositories.AutomaticChannelRepository.getTagIds(AutomaticChannelRepository.java:63)
    at services.AutomaticChannelService.lambda$tagIds$6(AutomaticChannelService.java:159)
    at play.db.jpa.DefaultJPAApi.lambda$withTransaction$3(DefaultJPAApi.java:197)
    at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:138)
    at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:196)

The GenericRepository class exist in commons module and the AutomaticChannelRepository exist in channel module.
Part of buid.sbt file :
lazy val connector = (project in file("modules/connector"))
  .enablePlugins(PlayScala)
  .settings(
    commonSettings,
    libraryDependencies += "org.mindrot" % "jbcrypt" % "0.4"
  )

lazy val common = (project in file("modules/common"))
  .enablePlugins(PlayJava)
  .dependsOn(connector)
  .settings(
    commonSettings,
    libraryDependencies ++= Seq(
      javaJdbc,
      filters,
      guice,
      javaWs,
      ehcache,
      javaJpa,
      evolutions,
      "org.hibernate" % "hibernate-entitymanager" % "5.2.11.Final",
      "org.hibernate" % "hibernate-ehcache" % "5.2.11.Final",
      "org.hibernate.javax.persistence" % "hibernate-jpa-2.1-api" % "1.0.0.Final",
      "com.google.code.gson" % "gson" % "2.1",
      "com.oracle" % "ojdbc8" % "12.2.0.1",
      "commons-io" % "commons-io" % "2.4",
      "commons-lang" % "commons-lang" % "2.6",
      "org.apache.commons" % "commons-collections4" % "4.1",
      "org.hibernate" % "hibernate-core" % "5.2.10.Final",
      "org.apache.tika" % "tika-core" % "1.13",
      "org.apache.tika" % "tika-parsers" % "1.13" exclude("com.google.code.gson", "gson"),
      "org.apache.tika" % "tika-xmp" % "1.13",
      "org.jsoup" % "jsoup" % "1.10.1",
      "com.thoughtworks.xstream" % "xstream" % "1.3"
    )
  )

lazy val search = (project in file("modules/search")).enablePlugins(PlayJava).dependsOn(common).settings(commonSettings)
lazy val channel = (project in file("modules/channel")).enablePlugins(PlayJava).dependsOn(common, search).settings(commonSettings)
lazy val recommend = (project in file("modules/recommend")).enablePlugins(PlayJava).dependsOn(common, search).settings(commonSettings)

lazy val root = (project in file("."))
  .enablePlugins(PlayJava)
  .dependsOn(channel, recommend)
  .aggregate(channel, recommend)
  .settings(commonSettings)

I wonder what is the difference between sbt run and sbt dist ?
And what is the common and recommended way to deploy Multi-Module SBT projects?

A: It's a classpath problem. You have to put the following code in your build.sbt:
PlayKeys.externalizeResources := false

By default resources from the project are not packaged in the jar file created by sbt dist.


text:
Q: Installing Linux on Hardware Raid 0 I have an msi gs70 stealth pro, with two ssd's configured in hardware raid 0 as well as a hdd. I've always installed linux (dual boot with windows) on the hdd, to avoid raid complications, but after learning more about hardware vs software raid, I'm wondering if this makes a difference? Has anyone had any experience or knowledge about installing linux on hardware raid 0? Does it change the way I need to partition the drive? In the installer, when I go to manually configure partitions, all the entries on the raid drive are doubled. Do I need to mimic what I do for each entry? Also is there any chance the the raid 0 controller might not communicate with linux correctly?

A: It seems after messing with it for a while, that the hardware made doesn't affect things much in terms of partitioning. If you create a new partition in windows at least, unlike the default system partitions, it won't show up doubled in the linux installer. Now, depending on the distribution you use, it seems like need certain packages in order for linux to correctly use the raid partition. These are generally installed automatically and you never have to worry about them, but some distributions, KDE Neon in my case, try to automatically remove them.


text:
Q: How can I use variables as the pattern and the replacement of replaceAll() method? I have a form, and once the submit button is clicked, an object is generated. Each key-value pair is built following this pattern: inputId: inputValue, so the object looks like this:
let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

I then need to replace all instances of the inputIds inside a string. So the string looks like this:
let template = "My name is agentsName and this is my phone number: agentsPhone"

and I need to make it look like this:
"My name is John and this is my phone number: 000-000-0000"

The number of input fields is unknown (since it depends on other things) and they won't always be the same. So I'm trying to create a function to replace these placeholders dynamically. I'm trying to loop through the inputsObj and then replace each key with its value:
let finalTemplate

const getReplacements = () => {
   for (let replacement in inputsObj) {
       finalTemplate = template.replaceAll(replacement, inputsObj[replacement])
            return finalTemplate
   }
   return finalTemplate
}

For example, replacement would be agentsName and inputsObj[replacement] should be John (and it would loop through the entire object in order to get all of the key-value pairs).
But this doesn't work. I'm guessing it's because I'm trying to use variables as the pattern and the replacement (it did work when I tried using regular strings instead, so I know everything else is working fine). But I don't know how to solve this. Any ideas?
EDIT:
I tried using template literals and it didn't work

A: You can make replacement like this in your example, you should only return the result at the end of your function:

let inputsObj = {
   templateList: 'blank',
   agentsName: 'John',
   agentsPhone: '000-000-0000'
}

let template = "My name is agentsName and this is my phone number: agentsPhone"

const getReplacements = () => {
   for (let replacement in inputsObj) {
        template = template.replaceAll(replacement, inputsObj[replacement])
   }
   return template
}

console.log(getReplacements());

Alternatively you can get array of keys with Object.keys method and use reduce for shorter syntax:

let inputsObj = {
  templateList: 'blank',
  agentsName: 'John',
  agentsPhone: '000-000-0000'
};

let template = "My name is agentsName and this is my phone number: agentsPhone";

const getReplacements = () => Object.keys(inputsObj).reduce((acc, key) => acc.replaceAll(key, inputsObj[key]), template)

console.log(getReplacements())

A: *

*You can't return in first iteration of the loop

*You have to use replaceAll on finalTemplate

let inputsObj = {
  templateList: 'blank',
  agentsName: 'John',
  agentsPhone: '000-000-0000'
}

let template = "My name is agentsName and this is my phone number: agentsPhone"

const getReplacements = () => {
  let finalTemplate = template

  for (let replacement in inputsObj) {
    finalTemplate = finalTemplate.replaceAll(replacement, inputsObj[replacement])
  }
  return finalTemplate
}

console.log(getReplacements())

A: Simply use template littérals for that

let inputsObj =
  { templateList : 'blank'
  , agentsName   : 'John'
  , agentsPhone  : '000-000-0000'
  };

const getReplacements = ({agentsName, agentsPhone}) =>
  `My name is ${agentsName} and this is my phone number: ${agentsPhone}`;

console.log(getReplacements(inputsObj))


text:
Q: Batch file that calls a vsim command I have a batch file that calls vsim -c -do test.tcl, after it's done I want to execute some more code. The problem is that in the command line it stays in the vsim command and doesn't return to execute the next instructions in the batch file.
Like so:
vsim -c -do test.tcl  <---- stuck here
if exist test1 del test1 <--- cant execute this

A: You have to tell vsim to quit by putting the quit command at the end of test.tcl (assuming it is a simple straight line script). Otherwise it stays in interactive mode waiting for more commands.
The -do option has two variants. One takes a script file name as a parameter. The other takes a string of Tcl commands. If you ever want to run simulations manually in command line mode you can use the option -do "run -all; quit" to get the same effect without a script.

A: vsim -c -do "do test.tcl; quit -f"

or
vsim -batch -do "do test.tcl; quit -f"

A: You seem to assume that everyone is familiar with vsim. Please let me assure you, you are working under a grave misapprehesion.
What do you mean by "stays in the vsim command"? Does the batch terminate or not?
If vsim is a batch file, then the solution may be in what you've posted.
vsim -c -do test.tcl

should be
call vsim -c -do test.tcl

which will execute vsim and continue when vsim is finished.


text:
Q: Nuxt npm js package [Missing stack frames] I am trying to use format-unicorn npm package in my Nuxt app. But after importing it inside my Vue page I get the following errors:
Client: Missing stack frames
Server: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"

Initial approach
The following approach should work according to the plugins documentation:

Another way to use package without installing the module is by importing package direct in the

Unfortunately this approach gives me an error:
Missing stack frames (and no other useful info).
And in the node console: [Vue warn]: Error in render: "TypeError: this.currencyFormat.formatUnicorn is not a function"
But what is weird, is that this page actually opens without any error if I navigate with Nuxtlink there. But as soon as I hit refresh, the error persists.
Utilizing plugins approach
By creating format-unicorn.js file inside plugins directory I was still getting the same error:
//// plugins/format-unicorn.js
require('format-unicorn');

//// nuxt.config.js
// ...
plugins: [
    '~/plugins/format-unicorn.js'
//  applying mode: 'client' or 'server' doesn't help as well
  ],
// ...

Naive plugins appproach
I wanted to know if it's going to work at all, so I just pasted code from package repo there (And it worked) :
//// plugins/format-unicorn.js
String.prototype.formatUnicorn = function () {
  let str = this.toString()

  if (arguments.length) {
    const type = typeof arguments[0]
    const args = type === 'string' || type === 'number' ? Array.prototype.slice.call(arguments) : arguments[0]

    for (const arg in args) str = str.replace(new RegExp(`\\{${arg}\\}`, 'gi'), args[arg])
  }

  return str
}

//// nuxt.config.js
// ...
plugins: [
    '~/plugins/format-unicorn.js'
  ],
// ...

Conclusion
By this point you probably realize I am not satisfied with naive approach since I want to extend my app with 3rd party packages in future. And my question here is what am I doing wrong? Is there anything special in trying to extend a prototype from Nuxt plugin or I just missing something?

A: My nuxt error-message "Missing stack frames" was gone by stopping
npm run dev

with Control-C and start again.


text:
Q: django virtual host I'm new to django and am coming from the MAMP and PHP world.  How do you setup virtual hosts in django for a site?  For example, when you run the server, instead of going to 127.0.0.1:8000, I'd like to go to mysite.dev locally? I keep reading about wsgi for Apache, but am unsure if this is the easiest way.
Basically, how do you setup virtual hosts for django? Any links or code is appreciated!

A: Keep in mind that unlike PHP, you don't need Apache and virtual hosts to develop and test django applications as django comes with a built-in development server.
You would only need Apache when you are ready to deploy your application, and to set that up you should read how to deploy with wsgi.

A: I'm not sure why you would want to do this in development. The dev server doesn't manage anything like that, it just listens to the port you tell it to and runs Django code in response. That means you can just hack your hosts file to tell it that mysite.dev maps to localhost. You'd still need to access port 8000 though - unless you tell runserver to bind to port 80, for which you'll need to use sudo.
Alternatively, as you say you can set up Apache with mod_wsgi as if it were a production server - but then you'll lose the automatic code reloading, and will have to restart Apache after every change to your Python code (although there are ways around this, see the mod_wsgi documentation).
Seems like a lot of bother for almost no gain.


text:
Q: React onClick target.value undefined I'm using Antd to generate Tags and I want to modify state using onClick event.
My parent Component (Where I generate a List of Items)
onRiskClick(e) {
    e.preventDefault();
    console.log(e.target);
    console.log(e.target.value);
  }
[...]
render() {
return (
[...]

              <RenderingRiskMatrix
                risks={this.state.risks}
                impact="2"
                likelihood="5"
                color="red"
                onRiskClick={this.onRiskClick} <-- passing onRiskClick function as props
              ></RenderingRiskMatrix>

My Child Function RenderingRiskMatrix
<Tooltip key={risk.id} title={risk.name}>
            <Tag
              key={risk.id}
              color={props.color}
              onClick={(event) => props.onRiskClick(event)}
            >
              {risk.id}
            </Tag>
</Tooltip>

What I got in console :
R028
undefined

which means e.target exists and not e.target.value which should be R028 no ?
Thanks,

A: In this case, you already have the element, then to get the content inside the element you need to use e.target.innerHTML to get the tag content, other way is using e.target.textContent but is not supported on Firefox.

A: I think there is a simpler way to accomplish your goal. The value you want is a child, not the value. You already have access to the value you want though, so I would use it like this:
<Tooltip key={risk.id} title={risk.name}>
  <Tag
    key={risk.id}
    color={props.color}
    onClick={() => props.onRiskClick(risk.id)}
  >
    {risk.id}
  </Tag>
</Tooltip>

Then use it like this:
onRiskClick(value) {
  console.log(value);
}

This will be a more flexible solution than accessing the innerHTML from the event target. You can now display it any way you want (or even render another component), and you function will still get the value it needs.

A: you should call e.persist() before console.log
If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

A: Change your onclick function like this.you need to pass the event data to the function and use the data
const onRiskClick = e =>{
    function ....
}
.....
 <RenderingRiskMatrix
                    risks={this.state.risks}
                    impact="2"
                    likelihood="5"
                    color="red"
                    onRiskClick={e=>{
onRiskClick(e)
} <-- passing onRiskClick function as props
                  ></RenderingRiskMatrix>

A: I found a solved issue about the "undefined" value from e.target.value
here
https://github.com/facebook/react/issues/4745
the solution was to use e.currentTarget.value instead
HTH.


text:
Q: Homomorphisms from $S_4$ to $\mathbb Z_2$
Suppose $\phi : S_4 \rightarrow \mathbb Z_2$ is a surjective homomorphism. Find $\ker\phi$. Determine all homomorphisms from $S_4$ to $\mathbb Z_2$.

My solution: since $\phi$ is surjective, then by the first isomorphism theorem, $S_4/\ker\phi \cong \mathbb Z_2$. Therefore, by computation, $\ker\phi = A_4$.
Now, for the second part, I have some trouble since they ask for all the possible homomorphisms. I know that the map that takes even permutations to $0$ and odd permutations to $1$ is a homomorphism. But, my question is: How to make sure this is the only one?
thanks,

A: The kernel must contain $\frac{24}2=12$ elements and it must contain all even permutations. There's no room for choice.

A: If there is another surjective homomorphism other than the sign homomorphism then we would (putting the two of them together) have a surjective homomorphism $S_4\rightarrow Z_2 \times Z_2$ or equivalently we would have a surjective homomorphism $A_4\rightarrow Z_2$. This leads to a subgroup of order 6 in $A_4$. But it is easy to see this is impossible. So the sign homomorphism is the unique non-trivial homomorphism $S_4\rightarrow Z_2$


text:
Q: Invalid value for prop `reset` on  tag I was getting this warning:

react-dom.development.js:86 Warning: Invalid value for prop reset on  tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior

This came from my custom hook:
import { useState } from 'react'

export const useField = (type) => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return {
    type,
    value,
    onChange,
    reset
  }
}

The hook is used in a component:
const CreateNew = (props) => {
  const content = useField('text')
  const author = useField('text')
  const info = useField('text')

  const navigate = useNavigate()

  const handleSubmit = (e) => {
    e.preventDefault()

    props.addNew({
      content: content.value,
      author: author.value,
      info: info.value,
      votes: 0
    })
    navigate('/')
    props.setNotification(`a new anecdote ${content.value} created!`)
    setTimeout(() => {
      props.setNotification(null)
    }, 5000)
  }

  const handleReset = (event) => {
    console.log(content)
    content.onReset()
    author.onReset()
    info.onReset()
  }

  return (

create a new anecdote

      <form onSubmit={handleSubmit}>

          content
          <input {...content} />

          author
          <input {...author} />

          url for more info
          <input {...info} />

        <button type="submit">create</button>
        <button type="button" onClick={handleReset}>reset</button>
      </form>

  )
}

The warning disappeared when I change the name of the function reset to onReset, but I don't understand why.
Is onReset a special keyword for react or something? I changed it on pure luck and the problem was gone but I don't get why.

A: Issue
You are passing a reset prop/attribute to an input element that is an invalid attribute value, it's a function, not a string or a number.
const useField = (type) => {
  const [value, setValue] = useState("");

  const onChange = (event) => {
    setValue(event.target.value);
  };
  const reset = () => {
    setValue("");
  };

  return {
    type,
    value, // <-- is a function
    onChange,
    reset
  };
};

...
const content = useField('text'); // <-- includes reset function

...
<input {...content} /> // <-- reset spread to input, causes error

See input tag for a list of valid attributes.
The reason React doesn't flag the name onReset is because this is a valid event handler (but for form elements, not input), see Synthetic Events.

Your Question

Is onReset a special keyword for react or something? I changed it on
pure luck and the problem was gone but I don't get why.

If you follow the link in the warning, buried in the page is this note.

Note: attributes starting with on are not passed through as an
exception because this could become a potential security hole.

Additionally there's an issue in the handleReset callback that is referencing undefined properties and attempting to invoke them, which will obviously throw an error when the preceding issues are resolved.
const handleReset = (event) => {
  console.log(content);
  content.onReset(); // <-- onReset is undefined, should call content.reset()
  author.onReset();
  info.onReset();
};

Solution
Destructure the reset function from the useField hook's return value and spread the rest into a props object. Reference the correct reset function in handleReset.
Example:
const CreateNew = (props) => {
  const { reset: resetContent, ...content } = useField("text");
  const { reset: resetAuthor, ...author } = useField("text");
  const { reset: resetInfo, ...info } = useField("text");

  ...

  const handleReset = (event) => {
    console.log(content);
    resetContent();
    resetAuthor();
    resetInfo();
  };

  return (

create a new anecdote

      <form onSubmit={handleSubmit}>

          content
          <input {...content} />

          author
          <input {...author} />

          url for more info
          <input {...info} />

        <button type="submit">create</button>
        <button type="button" onClick={handleReset}>
          reset
        </button>
      </form>

  );
};

A: "reset" is a reserved prop for an input field to reset a form. You can't use reset as a function in your prop spread. try "clearValue" as a function name instead

export const useField = (type) => {
    const [value, setValue] = useState('')

    const onChange = (event) => {
      setValue(event.target.value)
    }
    const reset = () => {
        setValue('')
    }

    return {
      type,
      value,
      onChange,
      clearValue: reset
    }
  }


text:
Q: Find the probabilities of selling at least $n$ items using binomial distribution On average, 6 out of 15 customers buy a service plan. You expect to receive 100 customers tomorrow. Find the probabilities that you will sell: at least 1, at least 2, at least 3, ...., at least 20 service.
I used Excel to do =BINOMDIST(A2,100,40%,TRUE) then subtracted 1-answer but the numbers seem very off, what am I doing wrong?

A: Write the probability distribution function (PDF) of a binomial distribution with probability of success = $6/15$ ($40\%$), then sum the PDF up to a candidate value $n$ and then take 1.0 - that value.
Your answer should look like this:


text:
Q: how to write a script that will run commands after su, without using -c I'm trying to automate a standard activity on a system I do not have root access on.  The administrator of the systems have given me authority to run sudo su - 'user' command, and only that command.  I can not add a -c argument or sudo will fail.
My script will have to start with my permissions, and midway through change to running with the user's permissions.  I'm trying to figure out if there is a way to make a script do this for me in a single command?
Before anyone asks, trying to get my visudo permissions extended is quite difficult.  While I could probably su using the password I do not know the password of the user, don't want to change it, and really should hardcode it in my script anyways, so regular su without sudo isn't really an option.  It seems like there has to be some way to work with the command I'm authorized to use?

A: Put the commands that you want to run as the other user into a separate file,
user2commands, and then do
sudo su - user < user2commands
If you don't want to have a separate file, consider:

sudo su - user << EOF
    commands to be run as the other user
        ︙
EOF