text:
Q: Cart discount for a product category based on quantity calculations I wan to add a function to woocommerce that will calculate a 10% discount when 12-23 items from one category is added to the cart.
Then if 24 - 47 items of the category are added it would be a 15% discount.
Last if 48+ items from this category are added it would be a 20% discount.
actual code example would be awesome as I am new to woocommerce

A:
Updated — Corrected code mistakes and added enhancements in the outputted discount text

Here is the function hooked in woocommerce_cart_calculate_fees hook that is going to make the discount for that particular category (or subcategory too) based on cart item quantity calculations.
This is the code:
add_action( 'woocommerce_cart_calculate_fees', 'cart_items_quantity_wine_discount', 10, 1 );
function cart_items_quantity_wine_discount($cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Set HERE your category (can be an ID, a slug or the name)
    $category = 34; // or a slug: $category = 'wine';

    $category_count = 0;
    $category_total = 0;
    $discount = 0;

    // Iterating through each cart item
    foreach($cart_object->get_cart() as $cart_item):

        if( has_term( $category, 'product_cat', $cart_item['product_id']) ):
            $category_count += $cart_item['quantity'];
            $category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price)
        endif;

    endforeach;

    $discount_text = __( 'Quantity discount of ', 'woocommerce' );

    // ## CALCULATIONS ##
    if ( $category_count >= 12 && $category_count < 24 ) {
        $discount -= $category_total * 0.1; // Discount of 10%
        $discount_text_output = $discount_text . '10%';
    } elseif ( $category_count >= 24 && $category_count < 48 ) {
        $discount -= $category_total * 0.15; // Discount of 15%
        $discount_text_output = $discount_text . '15%';
    } elseif ( $category_count >= 48 ) {
        $discount -= $category_total * 0.2; // Discount of 20%
        $discount_text_output = $discount_text . '20%';
    }

    // Adding the discount
    if ( $discount != 0 && $category_count >= 12 )
        $cart_object->add_fee( $discount_text_output, $discount, false );

    // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}

Note: Last argument in add_fee() method is related to applying the tax or not to the discount…

Code is tested and fully functional.
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

Other similar: Discount for Certain Category Based on Total Number of Products


text:
Q: Where does WWW-Authenticate header get added when using WindowsAuthenticationModule If I set Windows Authentication to true in IIS7 and set Anonymous Authentication to false, I will get a WWW-Authenticate header.  I assume this is the cue to the browser to popup the authentication dialog.  I'm trying to figure out where in the ASP.NET pipeline the WWW-Authenticate header gets set (and what class is responsible for setting it it).  I've done quite a bit of Googling and looking at WindowsAuthenticationModule and UrlAuthorizationModule in reflector but can't seem to pinpoint it!

A: Several modules in IIS 7 perform tasks related to security in the request-processing pipeline. In addition, there are separate modules for each of the authentication schemes, which enable you to select modules for the types of authentication you want on your server.
The one you are looking for is the WindowsAuthenticationModule, which performs NTLM integrated authentication. It is located in Inetsrv\Authsspi.dll.
The picture below shows the HTTP request processing pipeline mechanism of IIS7.

For a complete in-depth elaboration, including the above material, visit: http://learn.iis.net/page.aspx/101/introduction-to-iis-7-architecture/
That should answer all your questions :-)

A: If you have Windows Authentication set in IIS the authentication will occur between the client and IIS.
.NET may access the details when  is set in the web.config but IIS sends the WWW-Authenticate header and manages credential exchange.
See more:
https://www.owasp.org/index.php/Authentication_In_IIS
http://msdn.microsoft.com/en-us/library/ff647405.aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: 2 way databinding in Aurelia custom elements - bind custom element to parent viewmodel In my application I have made a lot of "services" which I can inject in my viewmodels to save som redundancy and time.
Now I'm looking to take it 1 step further, and make those form elements (select, text, checkboxes - a select dropdown for starters) and turn them into custom elements, injecting the service in only the custom element.
I can get it working to some extent. The custom element (select in this case) is showing when I require it in the "parent" view, however when I change the selected value of the custom select element, it does not bind to the "parent" viewmodel, which is my requirement.
I want to be able to bind my selected value from the custom element to a property on the "parent" viewmodel via the bind attribute in it's template.
I'll update which a little code snippet in a few minutes.
create.js (what I refer to as parent viewmodel)
import {bindable} from 'aurelia-framework';
export class Create{
    heading = 'Create';
    @bindable myCustomElementValue = 'initial value';
}

create.html (parent view)
<template>
    <require from="shared/my-custom-element"></require>
    <my-custom selectedValue.bind="myCustomElementValue"></my-custom>

The output of ${myCustomElementValue} should ideally be shown and changed here, as the select dropdown changes

</template>

my-custom.js
import { inject, bindable} from 'aurelia-framework';
import MyService from 'my-service';

@inject(MyService )
export class MyCustomCustomElement {
    @bindable selectedValue;

    constructor(myService ) {
        this.myService = myService ;
    }

    selectedValueChanged(value) {
        alert(value);
        this.selectedValue = value;
    }

    async attached() {
        this.allSelectableValues = await this.myService.getAllValues();
    }
}

What happens is initially the create.html view outputs "initial value", and as I change the value of the custom element select, the newly selected value gets alerted out, but it does not update the bound parent variable, which is still just displaying "initial value".

A: There are a couple of issues here:

*

*You need to kebab-case any property names in the DOM due to case-insensitivity
selected-value.bind="property"
not
selectedValue.bind="property"

*You need to bind two-way. When creating a @bindable using the decorator, one of the arguments is BindingMode which you use to set the default binding mode.
Aurelia sets some sensible defaults, e.g. the default for input value.bind=".." is two way without being explicit
If you don't want to set a default binding mode, you can just be explicit with your binding:
selected-value.two-way="prop"
Hope this helps :)
Edit: I think the API changed a little after this answer.
The @bindable decorator has the following sig:
bindable({
  name:'myProperty',
  attribute:'my-property',
  changeHandler:'myPropertyChanged',
  defaultBindingMode: bindingMode.oneWay,
  defaultValue: undefined
})

One of the best places to check for quick reference is the Aurelia cheat-sheet in the docs:
http://aurelia.io/docs/fundamentals/cheat-sheet


text:
Q: Synchronous function is operating asynchronously in Nodejs I am implementing refresh tokens with jwt in NodeJS, and storing the refresh token in a MongoDB collection (I'm using mongoose). I have an access token and refresh token being generated on a user's login, using the email as a payload. Both are being sent back to the user, and the refresh token is stored in the database. When the user makes a request for a page, I have middleware to check their access token. If it's still valid, all is well and they proceed to the page. If it's expired, then another method is called, which checks the refresh token against the database, which is where the list of 'logged on' users is. If it finds the refresh token in the list of logged in users, it generates a new access token and sends both the new access token and the same refresh token back to the user.
My problem is this. My function to check the access token is spotting the expired token. It then calls the function to check the refresh token. That function starts, then as soon as it hits the query line, the call returns to the access token function. It checks for the new access token, which at the moment is undefined, and returns an error. The call then returns to the second function, where the query is executed (by then it's too late). Here's the code:
    export async function checkAccessToken(req, res, next) {
    const authHeader = req.headers['accesstoken'];
    const token = authHeader && authHeader.split(" ")[1];
    const refToken = req.headers['refreshtoken'];
    const user = req.headers['uemail'];
    const email = user;

    if(token && refToken){
        console.log("Line 62 Token is: " + token);
        jwt.verify(token, ACCESSTOKEN_TEST_SECRET, async (err, tokenstring) => {
            console.log("Line 64 reached");
            if(err){
                console.error('before the refresh access token')
                const newAccessToken = await refreshAccessToken(refToken, email);
                console.log(newAccessToken)
                    if(newAccessToken){
                        console.log("Line 70 NewAccessToken: " + newAccessToken);
                        res.locals.accessT = newAccessToken;
                        res.locals.refreshT = refToken;
                        console.log("Line 73 The access token was refreshed: " + newAccessToken);
                        next();
                    } else{
                        console.log("Line 76 New Access Token is: " + newAccessToken);
                        return res.status(401).json({message: 'Authorization1 Failed'});
                    }
            } else{
                res.locals.accessT = token;
                res.locals.refreshT = refToken;
                next();//token is still valid, we can proceed
            }
        })
    } else{
        return res.status(401).json({message: 'Authorization Failed'});
    }
    }

    function refreshAccessToken(refreshToken, email) {
    console.log("Line 97 RefToken in refreshAccessToken method: " + refreshToken);
    console.log("Line 98 email: " + email);

    RefToken.findOne({token: refreshToken}, function (err, token){
        if(err){
            console.log("Line 102 Error in RefToken.findOne()");
            console.log(err);
            return null;
        }
        if(token){
            console.log("Line 107 DB contains refresh token");
            jwt.verify(refreshToken, REFRESHTOKEN_TEST_SECRET, (err, result) => {
                if(err) {
                    console.log("Line 111 Something happened in jwt.verify. refreshToken: " + refreshToken);
                    return null;
                } else {
                    console.log("Line 114 Token verified");
                    console.log(`Result: ${result}`)
                    const newAccessToken = jwt.sign({email: email}, ACCESSTOKEN_TEST_SECRET, {expiresIn: "2m"});
                    console.log("Line 117 New Access Token from refreshAccessToken: " + newAccessToken);
                    return newAccessToken;
                }
            });
        }
    });
}

Now, I'll be the first to admit that I don't have a firm grasp on async await. My understanding was that calling 'await function' stops the code call in the bigger function until the awaited one is complete. I could be wrong though. But when I simply run everything synchronously, no await or async anywhere in the code at all, it does the same thing. Here is the output to the terminal:
  DB Connect was was a success!
 Server is running on http://localhost:4000
Line 62 Token is: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpvaG5zbWl0aEBnbWFpbC5jb20iLCJpYXQiOjE2NDUwNTM1MzAsImV4cCI6MTY0NTA1MzY1MH0.fn0dMszNioidsLbSJzxgrTa0bCouHYRnj7H_k79rHX0
Line 64 reached
before the refresh access token
Line 97 RefToken in refreshAccessToken method: eyJhbGciOiJIUzI1NiJ9.am9obnNtaXRoQGdtYWlsLmNvbQ.beNdGuRcM6b29v3GgkxfTzXI7qXJkr7ntZoVLB0DOoU
Line 98 email: johnsmith@gmail.com
undefined
Line 76 New Access Token is: undefined
Line 130 DB contains refresh token
Line 137 Token verified
Result: johnsmith@gmail.com
Line 140 New Access Token from refreshAccessToken: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpvaG5zbWl0aEBnbWFpbC5jb20iLCJpYXQiOjE2NDUwNTc3NjIsImV4cCI6MTY0NTA1Nzg4Mn0.eyET-fN9gAr2Lp4rxk2Ne1VP_yekR6jtgV-CJZh53gA

I would greatly appreciate if someone could point out where I've gone wrong here.


text:
Q: How to write a scrollable MFC custom control? I want to write my own chart control which requires scrolling.
I found that there is a CScrollView but nothing like this for a control.
Other toolkits like Cocoa, QT or GTK offer me a base class where i can set a content view which is displayed in a viewport and saves me from writting all of the scrolling code.

A: The code for custom scrolling isn't that much. Create the scrollbars, write the message handlers and remember one rectangle for the current visible part.
I would just try it. If you have problems, we are here to help :-)


text:
Q: What's an alternative to throwing an exception when managing pattern matching with guards? What's an alternative to throwing an exception when managing pattern matching with guards?
[<Literal>]
let Objective = 33

let (|NotGame|IsGame|) p =
    match p with
    | LessThanGame v when v <  Objective -> NotGame v
    | Game         v when v >= Objective -> IsGame  v

Warning:

Incomplete pattern matches on this expression

I don't want any complaints from the compiler.
As a result, what I don't want to do is this:
let (|NotGame|IsGame|) p =
    match p with
    | LessThanGame v when v <  Objective -> NotGame v
    | Game         v when v >= Objective -> IsGame  v
    | _ -> failwith "idk..."

What I would rather do is this:
let (|NotGame|IsGame|) p =
    match p with
    | LessThanGame v when v <  Objective -> NotGame v
    | Game         v when v >= Objective -> IsGame  v
    | _ v                                -> IsGame  v

The entire code is here:
// ***********
// Game of 33
// ************************************************************
(*Types*)
// ************************************************************
type Player =
    | Player1
    | Player2

type Shot =
     | TwoPointer
     | ThreePointer
     | FoulShot
     | TwoFoulShots
     | ThreeFoulShots

type PlayerScore = {Player:Player; Points:Points}

and Points =
    | LessThanGame of int
    | Game of int

type Posession = Posession of Player

[<Literal>]
let Objective = 33

// ************************************************************
(*Active Patterns*)
// ************************************************************
let (|NotGame|IsGame|) = function
    | LessThanGame v when v <  Objective -> NotGame v
    | Game         v when v >= Objective -> IsGame  v
    | _ -> failwith "idk..."

// ************************************************************
(*Functions*)
// ************************************************************
let makeShot shot (shooter, defender) =

    let ballHandler = shooter.Player
    let points = shooter.Points

    let shotValue = match shot with
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3
                    | FoulShot                      -> 1

    match points with
    | NotGame p ->  if p + shotValue < Objective then
                         { Player=ballHandler; Points=LessThanGame (p + shotValue) }, defender
                    else { Player=ballHandler; Points=Game         (p + shotValue) }, defender

    | IsGame  p -> { Player=ballHandler; Points=Game p }, defender

let startGame =

    let player1Score = { Player=Player1; Points=LessThanGame 0 }
    let player2Score = { Player=Player2; Points=LessThanGame 0 }

    (player1Score, player2Score)

// ************************************************************
(*Client*)
// ************************************************************
let player1Score, player2Score = startGame

let player1, player2 = (player1Score, player2Score) |> makeShot TwoPointer
let shooter, defender = player2, player1

let final = (shooter, defender) |> makeShot ThreePointer
                                |> makeShot FoulShot

                                |> makeShot ThreePointer
                                |> makeShot TwoFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreeFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer

Resolution:
As Guy Coder advised, I use if/else conditions as an alternative. Thus, this removed the need for me to throw an exception.
// ************************************************************
(*Types*)
// ************************************************************
type Player = | Player1 | Player2

type Shot =
     | TwoPointer| ThreePointer
     | FoulShot  | TwoFoulShots | ThreeFoulShots

type PlayerScore = {Player:Player; Game:Game}

and Game =
    | Underway of int
    | AlmostGame of int
    | GameTime of int

[<Literal>]
let Objective = 33

[<Literal>]
let MaxFoulShots = 3

let (|Underway|AlmostGame|Game|) (score,shot) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective

    | GameTime   s,v -> Game s

// ************************************************************
(*Functions*)
// ************************************************************
let makeShot shot (shooter, defender) =

    match (shooter.Game, shot) with
    | Underway p   -> { shooter with Game=Underway p }, defender
    | AlmostGame p -> { shooter with Game=AlmostGame p }, defender
    | Game p       -> { shooter with Game=GameTime p }, defender

let startGame =

    let player1Score = { Player=Player1; Game=Underway 0 }
    let player2Score = { Player=Player2; Game=Underway 0 }

    (player1Score, player2Score)

// ************************************************************
(*Client*)
// ************************************************************
let player1Score, player2Score = startGame

let player1, player2 = (player1Score, player2Score) |> makeShot TwoPointer
let shooter, defender = player2, player1

let final = (shooter, defender) |> makeShot ThreePointer
                                |> makeShot FoulShot

                                |> makeShot ThreePointer
                                |> makeShot TwoFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreeFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer

                                |> makeShot FoulShot
                                |> makeShot FoulShot
                                |> makeShot ThreeFoulShots

A: If I understand your problem correctly you are trying to classify the input into just two buckets and the conditional is less than.
If so then forgo the pattern matching and just use an if statement. There is no rule that says to be functional one must use a pattern matching for all decisions.


text:
Q: How do I modify Kadane's algorithm to find out the subarray elements that contribute to the maximum sum? What I've done so far:
I've found out the sum using Kadane's algorithm.
I created a vector "res" that stores the elements when conditions are satisfied.
Problem:
For example, when the input is an array: {-2, -3, 4, -1, -2, 1, 5, -3}
The result array contains the right subarray elements along with 1 extra element which is added when the condition fails.
tldr: The code returns the output subarray as : {4 -1 -2 1 5 -3}
whereas, the correct output should be {4, -1, -2, 1, 5}
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int i, a[10], n, temp_sum=0, final_sum=0;
    vector<int> res;
    cin >> n;                               //getting array size input
    for(i=0; i<n; i++)
    {
        cin >> a[i];                        //getting array elements input
    }
    temp_sum=a[0];                          //initializing to first element
    final_sum=a[0];
    for(i=1; i<n; i++)
    {
        if(a[i]>temp_sum+a[i])       //if element is greater than sum so far
        {
            temp_sum = a[i];
            res.clear();
            res.push_back(a[i]);
        }
        else
        {
            temp_sum = a[i] + temp_sum;
            cout << temp_sum << " " << final_sum << " " << a[i] << "\n";
            res.push_back(a[i]);
        }
        if(temp_sum>final_sum)
        {
            final_sum = temp_sum;
        }
    }
    cout << final_sum << "\n";                  //displaying maximum sum
    for(i=0; i<res.size(); i++)                 //displaying result vector
    {
        cout << res[i] << " ";
    }
    return 0;
}

A: Note that you execute
res.push_back(a[i]);

in any case and don't refresh res if if(temp_sum>final_sum) failed
By the way, condition if(a[i]>temp_sum+a[i]) is equal to  temp_sum <0  (does not influence the result)


text:
Q: Servlet unable to get parameter from ajax request I have an AJAX request in a JSP which has other nested AJAX requests.
AJAX bit:
var boxval = new Array();
boxval = getcheckval();
for (var i = 0; i < boxval.length; i++) {
  $.ajax({
      type: "get",
      url: "myservlet",
      beforeSend: function() {
        $('#text1')
          .css({
            "color": "red"
          });
        $('#text1')
          .text(
            "Running Graph");
      },
      data: {
        "boxval": boxval[i]
      },
      success: function(
        responseText) {
        $('#text1')
          .css({
            "color": "green"
          });
        $('#text1')
          .text(
            responseText);
      },
      complete: function() {
        $.ajax({
            type: "get",
            url: "ConnectServlet",
            beforeSend: function() {
              $('#text2')
                .css({
                  "color": "red"
                });
              $('#text2')
                .text(
                  "Copying Files and preparing pSet");
            },
            data: {
              val: boxval[i]
            },
            success: function(
              responseText) {
              $('#text2')
                .css({
                  "color": "green"
                });
              $(
                  '#text2')
                .text(
                  responseText);
            },
            complete: function() {
              $.ajax({
                  type: "get",
                  url: "CopyServlet",
                  beforeSend: function() {
                    $('#text3')
                      .css({
                        "color": "red"
                      });
                    $('#text3')
                      .text(
                        "Running Dynamic Diff Graph");
                  },
                  data: {
                    box: boxval[i]
                  },
                  success: function(
                    responseText) {
                    $('#text3')
                      .css({
                        "color": "green"
                      });
                    $('#text3')
                      .text(
                        responseText);
                  },
                  complete: function() {
                    $('#summary')
                      .show();
                  }
                });
            }
          });
      }
    });
}

In my first AJAX request the servlet is able to receive the data I am sending as a parameter:
data : {
            "boxval" : boxval[i]
        },

String graphName=request.getParameter("boxval");

However in all my nested ajax requests the servlet is unable to receive the data I am sending as a parameter:
data : {
           "val" : boxval[i]
       },

String graphName=request.getParameter("val");

The parameter returns null.
Why is this happening? What am I doing wrong?


text:
Q: How can I show a generated image on when the UWP app is opened? I'm trying to generate a fractal image and show the image when the app is loaded. It works for events like clicking a button and resizing the window, but not when the app is first opened.
The XAML is:
<Viewbox Grid.Row="1" x:Name="Scenario4ImageContainer"  VerticalAlignment="Stretch" HorizontalAlignment="Stretch" PointerPressed="Scenario4ImageContainer_PointerPressed">
    <Image x:Name="Scenario4Image" />
</Viewbox>

The code is:
private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        generator.Width = (int)imageColumn.ActualWidth; ;
        generator.Height = (int)imageRow.ActualHeight; ;
        generator.InitMap();
        generator.Generate();

        fractalBitmap = await colorer.Color(generator.Map);

        Scenario4Image.Source = fractalBitmap;
        fractalBitmap.Invalidate();

        //This works...
        //Scenario4Image.Source = new BitmapImage(new Uri("ms-appx:///Assets/LockScreenLogo.scale-200.png"));
    }

A: Do you wait for the Windows to be activated ?
You could expose a method in your App.xaml.cs file using a TaskCompletionSource :
private static TaskCompletionSource _waitActivation =new TaskCompletionSource<bool>();

public static Task WaitWindowActivationAsync(){
    return _waitActivation.Task;
}

private void OnLaunched(...){

 ...

 Windows.Current.Activate();

_waitActivation.TrySetResult(true);

}

Then in your handler, you call it :
private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
       await App.WaitWindowActivationAsync();
       ...
    }

You could also add a wait to Task.Yield(); :
private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
       await Task.Yield();
       await App.WaitWindowActivationAsync();
       ...
    }


text:
Q: Decreasing learning rate with online/streaming learning I was reading those papers by Facebook and Google on Click-Through Rate predictions and something kept bothering me.
I understand that to fully take advantage of data freshness or simply because we work at massive scale it is interesting to learn/update our model in an online/streaming fashion. I also understand that using a decreasing learning rate might yield better models.
But I don't understand intuitively how these two can mesh well without human interaction: in this setting we're talking about billions of training examples per day and with a decreasing learning rate at iteration $t$ of the form $\alpha/\sqrt{t}$, that learning rate would be so small at the end of day that it would kill any chance of learning anything forever.
So what happens next in practice? Do we have to restart the learning rate at $\alpha/\sqrt{1}$ with the last set of coefficients (having a logistic regression in mind)? Is my understand of "iteration" wrong? Is my intuition simply wrong?

A:
in this setting we're talking about billions of training examples per day and with a decreasing learning rate at iteration $t$ of the form $\alpha/\sqrt{t}$, that learning rate would be so small at the end of day that it would kill any chance of learning anything forever.

From the first paper you cite {1}:

We lower bound the learning rates by 0.00001 for continuous
  learning

References:

*

*{1} He, Xinran, Junfeng Pan, Ou Jin, Tianbing Xu, Bo Liu, Tao Xu, Yanxin Shi et al. "Practical lessons from predicting clicks on ads at facebook." In Proceedings of the Eighth International Workshop on Data Mining for Online Advertising, pp. 1-9. ACM, 2014. https://pdfs.semanticscholar.org/daf9/ed5dc6c6bad5367d7fd8561527da30e9b8dd.pdf


text:
Q: How find the $\angle B$
In $\Delta ABC$ such $I$ is incentre,and $$\angle A=80^{0},AI+IB=BC$$,
find the $\angle B$
my idea:let $AB=c,AC=b,BC=a$ then we have
$$\dfrac{AI}{ID}=\dfrac{AB}{AD}=\dfrac{AC}{DC}=\dfrac{AB+AC}{AD+DC}=\dfrac{b+c}{a}$$
and
$$AD^2=AB\cdot AC-BD\cdot DC=bc-BD\cdot DC$$
$$BD=\dfrac{ac}{b+c},DC=\dfrac{ab}{b+c}$$
$$\Longrightarrow AD=\sqrt{bc-\dfrac{a^2bc}{(b+c)^2}}$$
so
$$AI=\dfrac{b+c}{a+b+c}AD$$
and
$$BI=\dfrac{a+c}{a+b+c}BE$$
so
$$AI+BI=BC\Longleftrightarrow \dfrac{b+c}{a+b+c}AD+\dfrac{a+c}{a+b+c}BE=a$$
 then I have ugly,and can't work,Thank you someone can have other methods.

A: Hint: Apply sin rule to $BIC$, get $BC$ in terms of $BI$.
Hint: Apply sin rule to $BIA$, get $AI$ in terms of $BI$.
Now substitute these into $AI + BI = BC$, you will get a trigonometric equation in terms of $\angle IBC$. Solve it to determined that $\angle IBC = 20^\circ$.


text:
Q: document.getqueryselector and getelement by class not working I have checked other questions and they have helped a bit.
But for me it's still not showing much success:
const ajaxRequest = new XMLHttpRequest();
const handleResponse = function() {
  //have we got a response from the server
  if (ajaxRequest.readyState === 4) {
    //did we find the requested resource?
    if (ajaxRequest.status === 200) {
      //  console.log(ajaxRequest.responseText); //testing file
      let data = JSON.parse(ajaxRequest.responseText)
      let ul1 = document.querySelectorAll('.ajax')[0];
      let ul2 = document.querySelectorAll('.ajaxCheck');
      for (let i = 0; i < ul2.length; i++) {
        ul2[i].style.display = 'none';
        console.log(i);
      }
      if (document.querySelectorAll('.ajax')[0]) {
        ul1.innerHTML = displayOutput(data, false);
      } else {
        ul2.innerHTML = displayOutput(data, true);
      }
      //displayOutput_compare(data);
    }
  }
}

Specifically the ajaxCheck class as it has more than 1.
What am I doing wrong?
here's the HTML for the 2nd class,
it doesn't load any of the data:

A: ul2 is a collection, not a single element. You need to loop over it when setting innerHTML, just like you did when setting style.
if (ul1) {
    ul1.innerHTML = displayOutput(data, false);
} else (
    let output = displayOutput(data, true);
    for (let i = 0; i < ul2.length; i++) {
        ul2[i].innerHTML = output;
    }
}


text:
Q: Trying to SUM a formula field based on constraints from another field A little background on the report:
This is a productivity report for our employees working at our business. We determine their productivity based on the duration of the visits with clients. Some of our employees offer group sessions. They charge each client within the group, even though they are only giving, for example, one hour of service, they can bill for 10 hours if there are 10 people in the group. We determine what service they gave by service codes.
So, I have two fields in this formula, a service code field and a duration field.
The duration field is initially a STRING field from the database, even though it only gives number data, so I change it to a numberVar. The service code field is also a string field, and it sometimes does contain characters and numbers.
What I need Crystal Reports to do is take the sum of the duration. However, if the service code is, say, "1000", it must first divide the duration by 3 before summing it. This is where I get caught up.
Here's my code for the duration:
local numbervar num1;
If GroupName ({billing_tx_charge_detail.v_SERVICE_CODE})="1530" then
    num1 := ToNumber({billing_tx_charge_detail.v_duration})/3
else num1 := ToNumber({billing_tx_charge_detail.v_duration})

Then I do a separate formula for the sum, named sumDuration:
Sum(@duration)

I get the error that this field cannot be summarized. After searching Google for two days I have found that Crystal cannot summarize fields or formulas involving constants. If I simply say:
local numbervar num1;
num1 := ToNumber({billing_tx_charge_detail.v_duration})

then I can summarize @duration. What am I missing? It has to be something simple, but I'm just not seeing it. Is there a way to create a custom function to accomplish what I am trying to get here? Or is it even simpler than that?
One person suggested creating a SQL command in order to do the calculations before the data gets to the report. I am a SQL newb so I had no idea where to even begin with that.

A: If you are grouping by Service Code and placing the above formula in the footer you will only be computing {billing_tx_charge_detail.v_duration} for the last record in the group. If you are intending to use the formula and sum the results and place the results in the Service Code footer try the following. (basically remove the reference to group name)
If {billing_tx_charge_detail.v_SERVICE_CODE}) = "1530" then
ToNumber({billing_tx_charge_detail.v_duration})/3 else
ToNumber({billing_tx_charge_detail.v_duration})

You can use variables (num1) if you want to but they are not needed.
You can still use the second formula you referred to and place in the group footer OR you can place the first formula in details section, right click and insert a summary to the group footer. You can also place in the report footer if you need it to total there as well.


text:
Q: Transmission of energy in medium and wave nature (periodicity)? Is there any example of a transmission of energy in a medium that does not show wave nature?

A: Yes, for example heat energy is transferred through three different means:

*

*Radiation (which is wave like)

*Conduction (which is not wave like)

*Convection (which is not wave like)

Of course, according to the Standard Model, everything has wave-like properties, so in a way there's no escape from waves, but I believe that your question is best answered with classical phenomena.

A: Three basic kinds of energy transfer are usually mentioned. However I don't quite agree with Sklivvz's answer so here is my take on this issue.

I'll start with radiation because it is the most fundamental of the three and so most easily answered. It is governed by Maxwell equations which are equivalent to classical wave-equations. So all radiative effects are manifestly wave-like in nature. Nevertheless, it has to be mentioned that by using various optical materials one can obtain also dissipative solutions and lots of non-linear dispersive effects.
One could say that conduction doesn't have wave-like properties because it is governed by parabolic heat equation. However, this equation surely isn't correct because it allows for infinite speed of propagation. There exists also relativistic heat equation which admits wave-like solutions (as one would expect for any relativistic system).
As for convection, this is usually governed by some kind of fluid equation from continuum mechanics (like Navier-Stokes) and I suppose that also here one could easily obtain wave-like solution (for specific system and initial conditions).
Now to give an answer to your question: yes, there exist many situations where energy is transferred in a non-wave-like fashion (like exponential decay) but I believe it's not correct to say that any kind of above three energy transfers is or isn't wave-like in general. It depends on precise situation one is dealing with and the level of approximation one is using (like taking relativity into account).


text:
Q: What are the rules for function returning pointer in c++ did I miss something in my code? I want to create a function which generates an array(filled with random numbers) of the size I give as an input and the function returns the address of the first element of the generated array. I wrote the code as best as possible without any errors or warning. But at the runtime, the program crashes. I try to debug it but the debugger also froze and do nothing. I think the problem is in returning the pointer. Please help.
     #include<iostream>
     #include<cstdlib>

    using namespace std;

    int** the_gen(int num)
    {

          srand(1000);
          int *ptr= new int(num);
              int** const dptr=&ptr;

          for(int i=0;i<num;i++)
          {
           *ptr= rand();
            ptr++;

          }
              return dptr;

    }

    int main()
       {
          cout<<"Size of array:"<<endl;
          int size_of_array;
          cin>>size_of_array;

          int **a;

          a=the_gen(size_of_array);

          for(int i=0;i<size_of_array;i++)
         {
                 cout<<**a<<",";
                 a++;
         }

    }

A: you were using int** unnecessarily. only need to use that if you're creating an array of int pointers or a 2d array of int's:
the following code does what you're after i think:
#include<iostream>
#include<cstdlib>

using namespace std;

int* the_gen(int num)
{

    srand(1000);
    //edit
    int *ptr = new int[num];
    int* const dptr = ptr;

    for (int i = 0; i < num; i++)
    {
        *ptr = rand();
        ptr++;

    }
    return dptr;

}

int main()
{
    cout << "Size of array:" << endl;
    int size_of_array;
    cin >> size_of_array;

    int *a;

    a = the_gen(size_of_array);

    for (int i = 0; i < size_of_array; i++)
    {
        cout << *a << ",";
        a++;
    }
}

A: I think returning pointer is always bad idea, we should take memory pointers as a parameter as the follow
void the_gen(int num, int** arry)
{
  srand(1000);
  int *ptr = new int[num];
  *arry = ptr;

  for (int i = 0; i < num; i++)
  {
    ptr[i] = rand();
  }
}

int main()
{
  cout << "Size of array:" << endl;
  int size_of_array;
  cin >> size_of_array;

  int *a;
  the_gen(size_of_array, &a);

  for (int i = 0; i < size_of_array; i++)
  {
    cout << a[i] << ",";
  }
}


text:
Q: Ubiquitous language and resource based REST API? I have posted a question regarding Ubiquitous language and maturity level in REST API.
Ubiquitous language and maturity level in REST API?
After some extensive coding I realized that further questions can be derived from this post.
For example, if I am using resource based API, so the API endpoint looks like
http://domain.com/products/555 for a basic GET.
In case I want to update a resource it should look like this
http://domain.com/products/555 PUT
expecting a payload such as
{
id: 555,
name: "Sample product",
availability: 111
}

In order to use all of the capabilities of DDD and ubiquitous language, domain model should contain methods such as

*

*UpdateProductName

*ChangeAvailability

*BlockProductFromFurtherSale etc..

So if API expects this payload, I am thinking of two possible solutions.
a) Split this single update endpoint into multiple such as:

*

*
http://domain.com/products/555/UpdateProductName PUT
{
id: 555,
name: "Sample product"
}

*
http://domain.com/products/555/ChangeAvailability PUT
{
id: 555,
availability: 111
}

*
http://domain.com/products/555/BlockProductFromFurtherSale PUT
{
id: 555
}

b) Have additional logic in application layer in order to

*

*compare current domain with new payload

*detect values that are changed and need to be updated

*call appropriate domain methods based on changed values

Is there a recommended way to handle this scenaio?

A: I will try to be exhaustive about the possible solutions that you might use.
As you wrote, I consider that a product has the following attributes : id, name, availability
1. Designing a resource for each attributes

*

*/products/555/name: GET returns the current name of the product id 555. PUT newname modify the current name of the product id 555 with newname

*/products/555/availability: GET returns the current availability. PUT 99 modify the current availability to99.

... and so on ...
Notice that the resources are not "method oriented", they correspond to a concept (name, availability, etc. of a product) that could be updated, retrieved, deleted, etc. and not restrained to a particular function.
Notice also that i'm not describing what are the different internally method call when a resource receive a GET or PUT request. That's totally orthogonal. I will write a little note about it, at the end of the answer.
Major drawback of this approach: to update x attributes, a client needs to send x requests... You clearly see that it could be tedious for a client to do that and also bandwidth consuming. But if it's ok, then go ahead.
2. A resource with all of the attributes

*

*/products/555 : contains every attributes of a product (name, availability, etc.). A GET returns these attributes. For updating them, you have 2 possibilities:

2.1 updating with PUT
PUT method is intended to fully update the resource representation. It means that your client needs to sends every attributes of a product in the payload.
Imagine that the current representation of resource /products/555 is :
{ "name": "bread", "availability": 10 }

If you want to update just the availability to 99, you need to send the full representation of the resource, like that:
PUT /products/555 { "name": "bread", "availability": 99 }

Major drawback of this approach: A client that want to update one field will need to send the whole representation of the resource.
2.2 updating with PATCH
PATCH verb aims to partially update a resource representation.
Considering the current representation of the product is { "name": "bread", "availability": 10 }. If a client want to update only the availability, it will send :
PATCH /products/555 { "availability": 42 }

Be careful, because PATCH is not idempotent. It means that this request:
PATCH /products/555 { "availability": 42 }

can leads to have the following resource representation :
{ "name": "bread", "availability": 42 }

or
{ "name": "sugar", "availability": 42 }

Thus, it breaks idempotency... that PUT guarantee :) ! (since with PUT you send the full representation in the request body)
You could also update several attributes, if your product resource have it. That's obviously less bandwitdh consuming that the solution described in 1.
Note: Underlying methods call
As said previously, methods call are orthogonal to the design of your resources.
In your case, you have some fine grained method to update just one attribute of the Product class... that's ok.
But you could encapsulate this one in a coarse-grained method, something like this:
Product updateProduct(Product p) {
  p.updateName();
  p.changeAvailability();
  ...
  return p;
}

A:
Is there a recommended way to handle this scenaio?

You need to review Jim Webber's talk on DDD for Restful systems.
The basic plot - to modify your aggregates, you deliver documents (aka messages) to your HTTP endpoints, and the changes made to your aggregates are a side effect of the document manipulation.
So solution (a) is heading the right direction.
I believe that you should have a separate resource for each command - by which I mean you should be able to distinguish a repeated command from two commands that happen to have the same arguments (on the happy path, it doesn't matter much -- but it can be important if you are sending commands on an unreliable network, like TCP/IP).
In practice, this means that each command has its own, client generated unique identifier, that is used in the URI, much the same way that the product id is used in identifying your product resource.
Since you'll be delivering a complete representation of the command each time, the appropriate method is PUT (or post, if PUT is not supported).
After that, it's just a matter of URI design; subject to the constraint that the URI has to make up for any data you choose to elide from the body of the message itself.  But any of the following could be suitable
PUT /commands/a3a14d61-5343-442f-8c2b-febc4d9d8164
PUT /products/555/commands/a3a14d61-5343-442f-8c2b-febc4d9d8164
PUT /products/555/{commandType}/a3a14d61-5343-442f-8c2b-febc4d9d8164
PUT /products/555/commands/{commandType}/a3a14d61-5343-442f-8c2b-febc4d9d8164
PUT /products/555/{commandType}/commands/a3a14d61-5343-442f-8c2b-febc4d9d8164

REST doesn't care what color the bike shed is, so go with whatever fits best with your existing guidelines.


text:
Q: why has JVM been given the name so? Is it because it acts as hardware like CPU? 1.Does JVM execute certain instructions without taking any help of CPU or it take help of CPU for all the instruction?
2.Is it like when JVM use JIT compiler then only it uses CPU for execution otherwise it executes the instruction itself when it uses interpreter?

*If JVM executes some instruction without CPU then give example of such kind of instruction and also instruction which can be executed by CPU only.
Please explain the process of execution when JVM use interpreter and when it uses JIT compiler?

A:
Why has JVM been given the name so?

JVM stands for Java Virtual Machine. It has been named so, because it is a Virtual Machine designed for the purpose of running Java bytecode.

Does JVM execute certain instructions without taking any help of CPU or it take help of CPU for all the instruction?

The JVM itself is being run by the CPU. Do you consider that to be "taking help"? If so, then yes.
When the JVM runs bytecode in "interpreted mode", it will take the action required without converting the bytecode to machine code that the CPU runs. As such, it can be considered to not "take help" of CPU. The interpreter itself is of course run by the CPU, so it's a toss-up what answer you're looking for.

Is it like when JVM use JIT compiler then only it uses CPU for execution otherwise it executes the instruction itself when it uses interpreter?

See previous answer.

If JVM executes some instruction without CPU then give example of such kind of instruction and also instruction which can be executed by CPU only?

All bytecode instructions can be interpreted. None of them must be JIT compiled to machine code.

Please explain the process of execution when JVM use interpreter and when it uses JIT compiler.

Way out of scope for StackOverflow to explain all that. There are books written for that.

A: Java Virtual Machine is a middleman - it understand compiled Java code and machine code of your processor, too. It translate compiled Java code to machine code. Compiled Java code is different from e. g. compiled C/C++ code as compiled C/C++ code is directly machine code for the processor of your computer (it is slightly simplified, of course).
Another approach:
Result of C/C++ compilation is .exe file (in Windows), while Java compiler produces .class files (in all operating systems). Java Virtual Machine translate this .class files to machine code for your processor.
Yet another explanation:
Your processor understand only one particular language, e. g. Lithuanian.
Java is something as universal language, as English is. Almost all people understand English, so it is smart enough to write your stories in English.
And JVM in your computer is your local translator - it translates English to Lithuanian.
(In another computer, e.g. Hungarian, is other JVM which translates English to Hungarian.)


text:
Q: Why is "tuple([0])" printed as "(0, )"? While converting lists to tuples in python 2, I noticed that converting any list with a single item to a tuple produces a comma after the item.
>>> tuple([0])
(0,)
>>> tuple(['i'])
('i',)

What is the reason for the comma being shown?
Does it cause any unexpected behaviour other than how it is printed?
I also noticed that a single tuple must be declared with a comma.
>>> (0)
0
>>> (0,)
(0,)

Presumably this is to make an expression like
>>> 5 * (2 + 3)
25

instead of
>>> 5 * (2 + 3)
(5, 5, 5, 5, 5)

A: It's so that the output is a valid Python representation of the object, which is what repr is supposed to produce. (str is the same as repr in the case of tuple, since there's no compelling reason for them to differ.) The trailing comma is necessary, otherwise it is not actually a representation of a tuple.
From the Python docs about repr:

Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.

>>> eval(repr(tuple([0])))
(0,)

If the comma was not produced, this would not hold.


text:
Q: http://localhost:8080/jenkins shows 404 i have just installed Jenkins & http://localhost:8080 worked fine, i could see the dashboard of the jenkins, next i followed this tutorial. htm to setup tomcat, there was not issue in installing that but after that i am seeing
HTTP Status 404 - /jenkins

type Status report
message /jenkins
  description The requested resource is not available.
Apache Tomcat/9.0.0.M11

so I am not sure what is the issue.

A: How did you install Jenkins? Did you download the file or install it using the installer?
From the tutorial you listed it looks like it's using Tomcat to host the jenkins.war file, ie just copy the jenkins.war file into <tomcat-location>/webapps and it should be working assuming Tomcat is up and running. You can check http://localhost:8080/manager/ for further information about what apps are running.
EDIT
To access the Tomcat manager you might have to add a role to your <tomcat-location>/conf/tomcat-users.xmlfile, like this:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="admin" password="password" roles="manager-gui,manager script" />

A: i have uninstalled tomcat by doing C:> tomcat9 //DS//Tomcat9, re installed jenkins & after instillation i have given new admin password. my issue is resolved.
thanks everyone.


text:
Q: beamer cambridgeus theme - title color How to make the title color in the beamer cambrigeus theme as red. Here is the MWE:
\documentclass[12pt]{beamer}
\usetheme{CambridgeUS}
\usecolortheme{beaver}
\title[Semantic Web ranking]{Ranking of Web Documents using Semantic Similarity}
\author{Subham Soni}
\date{19.8.2014}
\begin{document}
\maketitle
\end{document}

A: You can change the color of the title by
\setbeamercolor{title}{fg=green}

However for me the example produces a red title.


text:
Q: How to trace the history of all the domains used an IP that I know? I have an IP. Now I want to see all the domains used this ip. Where and how can I see that?

A: You can search on bing.com
IP:193.2.2.2

Will return you all the domains indexed by bing and hosted by that ip.


text:
Q: TypeError: 'DataFrame' object is not callable when using pd.Series.map For:
df = pd.DataFrame({'a': (1,1,2,3,3), 'b':(20,21,30,40,41)})

Why is only this working
df['b_new'] = df.a.map(df.groupby('a').b.nth(-1))

but not:
>>df['b_new'] = df.a.map(df.groupby('a').nth(-1))
...
TypeError: 'DataFrame' object is not callable

although both:
>>df.groupby('a').b.nth(-1)

    b
a
1  21
2  30
3  41

and
df.groupby('a').nth(-1)

-
    b
a
1  21
2  30
3  41

do deliver quite similar results.
(see also: https://stackoverflow.com/a/47924467/7450524

A: If you want to understand why my answer works, then this is why.
Consider -
df.groupby('a').nth(-1)

    b
a
1  21
2  30
3  41

nth is applied to each column of each group, resulting in a dataframe. In your case, there is only one column.
However, in this case -
df.groupby('a').b.nth(-1)

a
1    21
2    30
3    41
Name: b, dtype: int64

nth is applied only to b, so the result is a series.
Now, take a look at the docs for map, in particular, what you can pass to it -

arg : function, dict, or Series

A callable, dict, or pd.Series object. You cannot pass a dataframe! What map does, is it uses the index of the series as the indexer into the series you call map on, and replaces it the corresponding value for that index.

A: There is difference - if not specify column it return DataFrame:
print (df.groupby('a').nth(-1))
    b
a
1  21
2  30
3  41

And with specify return Series:
print (df.groupby('a').b.nth(-1))
a
1    21
2    30
3    41
Name: b, dtype: int64

Error means map working with Series, not with DataFrame, although it is only one column df.


text:
Q: How do I get around chrome always "failing validation" on a Windows install? When I ever I try to download Google Chrome at www.google.com/chrome I get a "failed validation." Why? And, how do I get around this problem?

A: This problem occurs because of networking or transport errors between the Chrome download utility and the install. Unfortunately, there is no easy way to "fix" this issue. If you run into it however you can get around the problem by downloading the full off-line Chrome installer yourself. Google doesn't make this easy, and they don't expose this through a link or an API. In addition they expire the offline-copies on every release.

*

*Go to http://googlechromereleases.blogspot.com/

*Look for a full version number in a post: something like this aa.b.cccc.ddd an example may be 18.0.1025.151 (current as of the time of writing).

*Take the cccc.ddd and insert them into a link like http://dl.google.com/chrome/install/cccc.ddd/chrome_installer.exe. As per the above example it should be http://dl.google.com/chrome/install/1025.151/chrome_installer.exe.

Now until the next release you may use http://dl.google.com/chrome/install/1025.151/chrome_installer.exe
This answer was inspired by a post in 2010

A: Try one of the offline installers listed here.  They are standalone and don't use the chrome download manager but instead pack the entire install into a single .exe.  There is a single account version which is the default type of install only on your user account or a version which installs for all users.


text:
Q: How to Check and Filter out Row in Dataframe if "." exists in df Cell I tried to reference this SF answer: How to check if character exists in DataFrame cell
It gave a seemingly good solution but it doesn't appear to work for a period character "." Which of course is the character I'm trying to filter out on.
df_intials = df['Name'].str.contains('.')

Is there something specific about filterting through a dataframe that every value in the column has a "."?
When I convert to a list, and write a simple function to append strings with the character "." to it works correctly.

A: pd.Series.str.contains uses regex expressions as default, so you can either use the escape character backslack or parameter regex=False:
Try
df_intials = df['Name'].str.contains('\.')

or
df_intials = df['Name'].str.contains('.', regex=False)


text:
Q: In AEM SiteAdmin, how can I use 'name' instead of 'title' in the left navigation pane? From the SiteAdmin view, the "Websites" tab in the left-hand navigation pane displays the "Title" attribute from nodes, but sorts according to the "name" attribute. Which file(s) would need to be edited to output the "name" value in that pane instead of "title"?

A: The script responsible for rendering siteadmin is - /libs/cq/ui/widgets/source/widgets/wcm/SiteAdmin.js
If you look at line number 340, it has configuration like -

The call /bin/wcm/siteadmin/tree.json is handled by SiteAdminTreeServlet which generates the JSON used in rendering the tree (and sorting it). You could overlay this to use your own Servlet that gives the result in the sorted order of field you need (not recommended unless you know the nitty–gritty of this servlet).
If you still want to proceed with the changes you need to do two things -

*

*Add configurations to disable SiteAdminTreeServlet, use OSGI component disable logic to achieve this or you could refer to AEM ACS Commons here

*Provide your own implementation as Servlet to handle the requests to the path /bin/wcm/siteadmin/tree and handle json extension explicitly (path based servlet will ignore extensions).

You can try invoking this servlet as http://localhost:4502/bin/wcm/siteadmin/tree.json?path=/content

A: In CQ/AEM /libs/cq/ui/widgets/source/ext/override/widgets/tree/TreeNodeUI.js script renders the left hand side of siteadmin. You can directly make a minor change in this script to display page name instead of page title in the CQ siteadmin.
Click here to look at the code
CQ.shared.XSS.getXSSValue(n.text.replace(/</g, "<")) should be changed to CQ.shared.XSS.getXSSValue(n.attributes.name.replace(/</g, "<")) at line number 71 in /libs/cq/ui/widgets/source/ext/override/widgets/tree/TreeNodeUI.js and it works great


text:
Q: Random vector and the correlation You got a random vector $X = (x, y)$, the random variables $x$ and $y$ consist of $40$ objects.
$x \sim \text{normal distribution}(23, 48)$
$y = 23x + U$
$U \sim \text{normal distribution}(0, 29)$
You need to find the correlation coefficent. What should I start doing? We need to do it inside excel, but for correlation dont I need some points and so on? Right now i just got definitions of the random variables, how should i proceed?
Pardon my english
Edit:
the correlation is for (x, y).
What I did try was make a table in excel with integers from 0 to 40 and then for x, this is what I used to get the table:
=NORM.DIST(i;23;48;TRUE), where i is the current integer. Then from that I just made the y-s as well following similar logic with U, ended up with a correlation coefficent of 1 which I dont think is right and I think i made something wrong

A: \begin{align}
\operatorname{Cov}(X,Y)&=\mathbb{E}[(X-\mathbb{E}[X])(Y-\mathbb{E}[Y])]\\
&=\mathbb{E}[(X-\mathbb{E}[X])((23X+U)-\mathbb{E}[23X+U])]\\
&=\mathbb{E}[(X-\mathbb{E}[X])(23(X-\mathbb{E}[X]+(U-\mathbb{E}[U])]\\
&=23\mathbb{E}[(X-\mathbb{E}[X])(X-\mathbb{E}[X])] +\mathbb{E}[(X-\mathbb{E}[X])(U-\mathbb{E}[U])]\\
&=23\operatorname{Var}(X)+\operatorname{Cov}(X,U)
\end{align}
So you just substitute the definition of $Y$ into the expression and use linearity of the expectation value and basic algebraic transformations to get to the last expression. If you actually want the correlation you will have to divide by the standard deviation of Y and X. Calculating the Variance of Y will be similar to the Covariance - again plug in the definition and transform it until it is an expression of known things such as the variance of $X$ or $U$.
And if you are just supposed to simulate a bunch of those variables and calculate the empirical values - well do that. But I don't think you would need excel otherwise.

A: $\newcommand{\cov}{\operatorname{cov}}\newcommand{\var}{\operatorname{var}}$
\begin{align}
\cov(x,y) & = \cov(x,23x+U) \\[10pt]
& = \cov(x,23x) + \cov(x,U) \\[10pt]
& = 23\cov(x,x) + 0 \\
& \qquad\text{if }x,U \text{ are independent (but you withheld that information from us).} \\[10pt]
& = 23\var(x). \\[10pt]
\var y & = \var(23x+U) \\[10pt]
& = \var(23x) + \var U + 2\cov(23x,U) \\[10pt]
& = 23^2 \var x + \var U \\
& \qquad \text{(again, if independence holds).} \\[10pt]
\operatorname{correlation}(x,y) & = \frac{\cov(x,y)}{\sqrt{\var x}\sqrt{\var y}}.
\end{align}


text:
Q: Bundle Products Not Showing Summary No Summary is getting generated when configuring a bundled product on my Magento installation. I have been debugging the /vendor/magento/module-bundle/view/frontend/web/js/product-summary.js file but all I can tell is that it is getting fired on each event. I can get the file to log the names of the products added to the bundle ect just nothing is added to the bundle summary.
The bundle-summary container is present and there are no errors in the console. Has anyone else experienced this?

A: I had used a script found on Stack Exchange similar to below to defer javascript similar to below:
preg_match_all('#()#is', $html, $matches);
$js = '';
foreach ($matches[0] as $value):
    $js .= $value;
endforeach;
$html = preg_replace('#()#is', '', $html);
$html = preg_replace('##',$js.'',$html);

Magento 2: How to Solve Defer parsing of JavaScript on CDN?

Issue
This was moving the below script that was needed for the bundle summary to work correctly:

Solution
It is a bit of a messy solution but got around it with a simple if statement to stop the moving of these types of script:
preg_match_all('#()#is', $html, $matches);
$js = '';
foreach ($matches[0] as $value):
if (strpos($value, 'type="text/x-magento-template"') === false) {
    $js .= $value;
    $html = str_replace($value, '', $html);
}
endforeach;
$html = preg_replace('##',$js.'',$html);


text:
Q: Swift - Passing DynamoDB Paginated Output results to function in another class I am trying to pass the results of a DynamoDB function set-up in my Amazon.swift 'AWS' class back to my ViewController. The aim is to use the data to create GPS points on a map (the ViewController has the full MapKit / mapView setup).
This is the DynamoDB function:
func read_multipin_data() -> AWSDynamoDBPaginatedOutput {

    let cond = AWSDynamoDBCondition()
    let v1   = AWSDynamoDBAttributeValue(); v1.S = ADate
    cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
    cond.attributeValueList = [ v1 ]

    let exp = AWSDynamoDBScanExpression()
    exp.scanFilter = [ "date" : cond ]

    self.scan(exp).continueWithSuccessBlock({ (task: BFTask!) -> BFTask! in
        let results = task.result as AWSDynamoDBPaginatedOutput
        return results // Error: 'AWSDynamoDBPaginatedOutput' is not convertible to 'BFTask'
    })
}

    func scan(expression : AWSDynamoDBScanExpression) -> BFTask! {

        let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
        return mapper.scan(AWS.self, expression: expression)
    }

The second function which currently merely attempts to recover the data in my ViewController is:
    @IBAction func refresh_db_pins(){

    let all_annotations_in: AWSDynamoDBPaginatedOutput = AWS().read_multipin_data()

    }

The error I am getting when I try to return the results is:
'AWSDynamoDBPaginatedOutput' is not convertible to 'BFTask'
I have tried many different approaches including converting the JSON formatted data into arrays, dictionaries, alas nothing worked.
Many thanks in advance for your help!

A: You can rewrite your read_multipin_data method to something like:
func read_multipin_data() -> BFTask {

    let cond = AWSDynamoDBCondition()
    let v1   = AWSDynamoDBAttributeValue()
    v1.S = ADate
    cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ
    cond.attributeValueList = [ v1 ]

    let exp = AWSDynamoDBScanExpression()
    exp.scanFilter = [ "date" : cond ]

    return self.scan(exp);
}

Inside of continueWithSuccessBlock, you need to return either an instance of BFTask or nil, but you are returning an instance of AWSDynamoDBPaginatedOutput. That is why the compiler is complaining.


text:
Q: Visual Studio unit test detect failure So I am writing tests in Visual Studio 2015, and executing using MS UnitTesting to run it. What I want to do is write some code then when the test it done I can update a rally test case. What I am looking for is how to detect if the test case that just ran passed or failed. I have been looking at reflection but not seeing an option for the test
[TestCleanup()]
public void MyTestCleanup()
{
    // Code to check if test passes or fails

    Common.DriverQuit();
}

Then based off that answer I can write the rest of the code. I just need to figure how to gain access to test results if possible.

A: The MSTest framework has a TestContext class which holds all the information relating to the current test. You can access it by declaring a same-named property, which is then automatically set by the framework:
[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    ...

Having declared that, you can directly access the information you need:
[TestCleanup]
public void Cleanup()
{
    if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
    {
        // whatever...
    }
}

A: So I figured out the solution. What I was looking for was the TestContext.
TestContext.CurrentTestOutcome

This will give me a string of either pass or failed


text:
Q: Getting and replace values from numpy array based on list of index is it possible to get values from numpy array based on list of indexes like i.e 1 and 3? Then, I want to put another values instead of them.
Here is example:
import numpy as np

array = np.array([0, 1, 2, 8, 4, 9, 1, 2])
idx = [3, 5]

So I want to replace X[3] = 8 and X[5] = 9 with another values but I do not want to this in a loop because I could have large array. Is it a way or maybe a function to do operations like this but not in a loop?

A: You should use array[idx] = new_values. This approach is much faster than native python loops. But you will have to convert 'idx' and 'new_values' to numpy arrays as well.
import numpy as np

n = 100000
array = np.random.random(n)
idx = np.random.randint(0, n, n//10)
new_values = np.random.random(n//10)

%time array[idx] = new_values

Wall time: 257 µs
def f():
    for i, v in zip(idx, new_values):
        array[i] = v
%time f()

Wall time: 5.93 ms

A: Use np.r_:
larr = np.array([0, 1, 2, 8, 4, 9, 1, 2])
larr[np.r_[3, 5]]

Output
array([8, 9])

As @MadPhysicist suggest, using larr[np.array([3, 5])] will work also, and is faster.


text:
Q: Long touch (touch and wait) on the cells in tableView i have a tableview and i want to when I touch on the cells to be navigate to the editViewController and when I Long touch (touch and wait) on the cells to be navigate to the DetailsViewController

A: 1) Add a UILongPressGestureRecognizer to you cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        //add longPressGestureRecognizer to your cell
        UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
                                              initWithTarget:self action:@selector(handleLongPress:)];
        //how long the press is for in seconds
        lpgr.minimumPressDuration = 1.0; //seconds
        [cell addGestureRecognizer:lpgr];

    }

    return cell;
}

2) Handle the longPress and push to you editViewController
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{

    CGPoint p = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    }
    else
    {
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
        {
            NSLog(@"long press on table view at row %ld", (long)indexPath.row);

            editViewController *editView = [self.storyboard instantiateViewControllerWithIdentifier:@"editView"]; //dont forget to set storyboard ID of you editViewController in storyboard
            [self.navigationController pushViewController:editView animated:YES];
        }
    }

}

3) Normal press push to your DetailsViewController
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailsViewController *detailView = [self.storyboard instantiateViewControllerWithIdentifier:@"detailView"]; //dont forget to set storyboard ID of you editViewController in storyboard
    [self.navigationController pushViewController:detailView animated:YES];
}


text:
Q: addTarget not firing any event I have the following code and the doneButton handler is never invoked. Any idea what might be going wrong?
I have tried many different formats for the selector, also with and without parameters. I also made sure that the UIView received touch events by manually setting userInteractionEnabled = true. Thanks for any help in advance!
*** UPDATE: I have refactored the code completely, but same behaviour:
My Protocol:
import Foundation

protocol CustomDatePickerDelegate {
    func dataPickerDone(date: NSDate)
    func dataPickerChanged(date: NSDate)
}

my class:
import Foundation
import UIKit

class CustomDatePicker{

var delegate: CustomDatePickerDelegate?
var datePicker : UIDatePicker = UIDatePicker()

func CreateDatePicker(sender: UITextField) {

    if (delegate is UIViewController)
    {
        let _self = delegate as! UIViewController

        let _view = UIView(frame: CGRectMake(0, 0, _self.view.frame.width, 220))

        let datePickerView  : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 40, 0, 0))
        datePickerView.datePickerMode = UIDatePickerMode.Date

        let _toolbar = UIToolbar()
        let _doneButton = UIBarButtonItem(title: "DONE", style: UIBarButtonItemStyle.Done, target: self, action: #selector(CustomDatePicker.doneButton))
        _toolbar.translucent = false
        _toolbar.sizeToFit()

        _doneButton.accessibilityLabel = "DoneToolbar"
        let _spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)

        _toolbar.setItems([_spaceButton, _doneButton], animated: false)
        _toolbar.userInteractionEnabled = true
                    datePickerView.addTarget(self, action: #selector(CustomDatePicker.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)

        _view.addSubview(datePickerView)
        _view.addSubview(_toolbar)

        sender.inputView = _view
    }
}

@objc func handleDatePicker(sender:UIDatePicker) {
    delegate?.dataPickerChanged(datePicker.date)
}

@objc func doneButton(){
    delegate?.dataPickerDone(datePicker.date)
}

}
How I use it from the ViewController:
let _dataPicker : CustomDatePicker = CustomDatePicker()
    _dataPicker.delegate = self
    _dataPicker.CreateDatePicker(dataUI)

func dataPickerDone(date: NSDate) {
    dataUI.text = DataFormatejada(date)
    dataUI.resignFirstResponder()
}

func dataPickerChanged(date: NSDate) {
    dataUI.text = DataFormatejada(date)
}

A: I found a way to resolve the problem after many hours of try-error. The problem is with the target:self reference in the lines:
let _doneButton = UIBarButtonItem(title: "DONE", style: UIBarButtonItemStyle.Done, target: self, action: #selector(CustomDatePicker.doneButton))

and
_toolbar.userInteractionEnabled = true
                    datePickerView.addTarget(self, action: #selector(CustomDatePicker.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)

so what I have done is to create a new property in MyDatePicker class:
var instance : CustomDatePicker?

change those addTarget methods as:
let _doneButton = UIBarButtonItem(title: "DONE", style: UIBarButtonItemStyle.Done, target: instance, action: #selector(CustomDatePicker.doneButton))
 _toolbar.userInteractionEnabled = true
                    datePickerView.addTarget(instance, action: #selector(CustomDatePicker.handleDatePicker), forControlEvents: UIControlEvents.ValueChanged)

and I use it from the ViewController as:
let _dataPicker : CustomDatePicker = CustomDatePicker()
    _dataPicker.delegate = self   <---- **this made the trick**
    _dataPicker.instance = _dataPicker
    _dataPicker.CreateDatePicker(dataUI)

but this is not elegant and it is a patch for a more fundamental issue. Why self is not providing the instance of the object and I have to manually pass it back when I create the object?
thanks!


text:
Q: Issues while create a file in shell scripting in jenkins pipeline script I am trying to create a multi line file in Jenkins pipeline script using the below commands.
    sh "echo \"line 1\" >> greetings.txt"
    sh "echo \"line 2\" >> greetings.txt"
    echo "The contents of the file are"
    sh 'cat greetings.text'
    sh 'rm -rf greetings.txt'

Unforunately , I am not able to create the file named greetings.txt. Can any one please let me know, where I am going wrong.
Results in Jenkins console:
[tagging] Running shell script
+ echo 'line 1'
[Pipeline] sh
[tagging] Running shell script
+ echo 'line 2'
[Pipeline] echo
The contents of the file are
[Pipeline] sh
[tagging] Running shell script
+ cat greetings.text
cat: greetings.text: No such file or directory

Any suggestions would be helpful.
Thanks!

A: It's not finding a file named greetings.text because you didn't create one (a litte typo in the extension in your cat line). Try sh 'cat greetings.txt', or even better adjusted your script:
sh "echo \"line 1\" >> greetings.txt"
sh "echo \"line 2\" >> greetings.txt"
echo "The contents of the file are"
sh 'cat greetings.txt'
sh 'rm -rf greetings.txt'

If you want to use multiline commands, you can also use this syntax:
sh """
echo \"line 1\" >> greetings.txt
echo \"line 2\" >> greetings.txt
echo "The contents of the file are:"
cat greetings.txt
rm -rf greetings.txt
"""

From the last example, this should generate an output like:
Running shell script
+ echo 'line 1'
+ echo 'line 2'
+ echo 'The contents of the file are:'
The contents of the file are:
+ cat greetings.txt
line 1
line 2
+ rm -rf greetings.txt

A: This can be solve this by using single quotes with sh, so you don't need to use escaping. Also you have to create an initial file with > and add content with >>:
pipeline{
    agent any

    stages{
        stage('write file'){
            steps{
                sh 'echo "line 1" > greetings.txt'
                sh 'echo "line 2" >> greetings.txt'
                echo "The contents of the file is"
                sh 'cat greetings.txt'
                sh 'rm -rf greetings.txt'
            }
        }
    }
}

output:
[test] Running shell script
+ echo line 1
[Pipeline] sh
[test] Running shell script
+ echo line 2
[Pipeline] echo
The contents of the file is
[Pipeline] sh
[test] Running shell script
+ cat greetings.txt
line 1
line 2
[Pipeline] sh
[test] Running shell script
+ rm -rf greetings.txt
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS


text:
Q: Format JSON file in R: lexical error with character encoding I have data that I retrieved from a server in JSON format. I now want to pre-process these data in R.
My raw .json file (if opened in a text editor) looks like this:
{"id": 1,"data": "{\"unid\":\"wU6993\",\"age\":\"21\",\"origin\":\"Netherlands\",\"biling\":\"2\",\"langs\":\"Dutch\",\"selfrating\":\"80\",\"selfarrest\":\"20\",\"condition\":1,\"fly\":\"2\",\"flytime\":0,\"purpose\":\"na\",\"destin\":\"Madrid\",\"txtQ1\":\"I\'m flying to Madrid to catch up with friends.\"}"}
I want to parse it back for further use to its intended format:
`{

"id": 1,

"data": {

  "unid": "wU6993",

  "age": "21",

  "origin": "Netherlands",

  "biling": "2",

  "langs": "Dutch",

  "selfrating": "80",

  "selfarrest": "20",

  "condition": 1,

  "fly": "2",

  "flytime": 0,

  "purpose": "na",

  "destin": "Madrid",

  "txtQ1": "I'm flying to Madrid to catch up with friends."

}

}`

Using jsonlite I can't read it in at all:
parsed = jsonlite::fromJSON(txt = 'exp1.json')

Error in feed_push_parser(readBin(con, raw(), n), reset = TRUE) :
  lexical error: inside a string, '\' occurs before a character which it may not.
          in\":\"Madrid\",\"txtQ1\":\"I\'m flying to Madrid to catch u
                     (right here) ------^

I think the error tells me that some characters are escaped that should have been.
How can I solve this and read my file?

A: You have extra quotes around the nested braces defining "data", the value of which is actually stored as one huge string instead of valid JSON. Take them out, and
my_json <- '{"id": 1,"data": "{\"unid\":\"wU6993\",\"age\":\"21\",\"origin\":\"Netherlands\",\"biling\":\"2\",\"langs\":\"Dutch\",\"selfrating\":\"80\",\"selfarrest\":\"20\",\"condition\":1,\"fly\":\"2\",\"flytime\":0,\"purpose\":\"na\",\"destin\":\"Madrid\",\"txtQ1\":\"I\'m flying to Madrid to catch up with friends.\"}"}'

my_json <- sub('"\\{', '\\{', my_json)
my_json <- sub('\\}"', '\\}', my_json)

jsonlite::prettify(my_json)
# {
#     "id": 1,
#     "data": {
#         "unid": "wU6993",
#         "age": "21",
#         "origin": "Netherlands",
#         "biling": "2",
#         "langs": "Dutch",
#         "selfrating": "80",
#         "selfarrest": "20",
#         "condition": 1,
#         "fly": "2",
#         "flytime": 0,
#         "purpose": "na",
#         "destin": "Madrid",
#         "txtQ1": "I'm flying to Madrid to catch up with friends."
#     }
# }


text:
Q: Is open graph facebook login api currently working? We are experiencing a failure of the old v2 facebook login interface.
https://developers.facebook.com/bugs/506823259335622?browse=search_50895412246979226453540
I am trying to find out if the open graph version of this interface is working as of 10/25 10am PST.

A: you will need to update the library with the new files for PHP SDK to work
check out this link


text:
Q: Positive to Negative range in ruby I found out a function that reads a row of an excel sheet:
self.rows[start_row..-1]

where start_row is 12.
I want to know the output of print [12..-1]. I tried these codes:
[12..-1].each{|n| puts n}
(12..-1).each {|n| puts n}

but found no luck. I get
[12..-1]
# [12..-1]
[12..-1].each {|x| puts x}
# >> 12..-1
# => [12..-1]
(12..-1).each {|x| puts x}
# => 12..-1

What is the range when it goes in negative direction from positive? How can I print such range in the console?

A:
What is the range when it goes in negative direction from positive?

I assume that rows is an array. In this case, -1 denotes the last element, -2 the penultimate, -3 the antepenultimate, and so on:
array = ['a', 'b', 'c', 'd', 'e', 'f']

array[2..-1] #=> ["c", "d", "e", "f"]
array[2..-2] #=> ["c", "d", "e"]
array[2..-3] #=> ["c", "d"]

Array#[] (among others) allows you to specify both, positive indices counting from the start and negative indices counting from the end:
# 0    1    2    3    4    5
#-6   -5   -4   -3   -2   -1
['a', 'b', 'c', 'd', 'e', 'f']

Implementation-wise, you can think of array[-5] as array[array.length-5].
So both, 1 and -5 reference "b":
array[1]  #=> "b"
array[-5] #=> "b"

just like 4 and -2 reference "e":
array[4]  #=> "e"
array[-2] #=> "e"

and moreover, all of these ranges return the same subarray (for an array of length 6):
array[1..4]   #=> ["b", "c", "d", "e"]
array[1..-2]  #=> ["b", "c", "d", "e"]
array[-5..4]  #=> ["b", "c", "d", "e"]
array[-5..-2] #=> ["b", "c", "d", "e"]

Your example:
rows[start_row..-1]

is equivalent to:
rows[start_row..rows.length-1]

To answer your other question

How can I print such range in the console?

You can use downto:
12.downto(-1) { |i| puts i }

Output:
12
11
10
9
8
7
6
5
4
3
2
1
0
-1

However, note that these are different indices than those returned by rows[12..-1]:
array = ['a', 'b', 'c', 'd', 'e', 'f']

array[3..-1]
#=> ["d", "e", "f"]

array.values_at(3, 2, 1, 0, -1)
#=> ["d", "c", "b", "a", "f"]

A: Ranges don't work going downward (either positive -> lesser positive, positive -> negative, or negative -> lesser negative) because:

Methods that treat the range as a sequence (#each and methods inherited from Enumerable) expect the begin object to implement a succ method to return the next object in sequence.

and the Integer#succ method:

Returns the successor of int, i.e. the Integer equal to int+1.

So you can't add one to a number and end up at a lesser number. The reason that self.rows[start_row..-1] works is because, while it's a Range, the Array#[] doesn't actually iterate through the range, and, the negative number at the end of the range isn't really treated as a negative number, but a negative index that tells the array to count backwards from the end of the array.
Array#[] actually ends up converting the Range into a beginning index and a length and returning length number of elements starting from beg.

As a sidenote, to print all numbers going from 12 -> -1, you can do
12.downto(-1) { |x| puts x }

but that isn't what the Array#[] method is doing, it treats the range as just a begin and an end and converted any negative numbers as counting backwards from the end of the array, with -1 being the last element.

A:
How can I print such range in the console?

If you want to use range and that in positive to negative order:
> (-1..12).to_a.reverse
#=> [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1]

range in negative to positive order:
> (-1..12).to_a
#=> [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


text:
Q: How to check multiples in php to abstract the following sequence of numbers I have a for loop, and I want to write a function to abstract the following sequence:
1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16
.............

So, in a somewhat "pseudo" code, the function would have to check multiples like so:
$i = 0;

for (condition) {
    $i++

    if ($i is 1, 5, 9, 13) do something
    if ($i is 2, 6, 10, 14) do something
    if ($i is 3, 7, 11, 15) do something
    if ($i is 4, 8, 12, 16) do something
}

Any ideas?

A: Use the modulo operator. 1, 5, 9 or 13 modulo 4 is always 1.
Also you may want to use a switch / case statement, to avoid repeating the modulo 4 part.
<?php
switch ($remainder = $i % 4) {
    case 0:
        // and do another thing too
    break;
    case 1:
        // do something
    break;
    case 2:
        // do something else
    break;
    case 3:
        // do yet another thing
    break;

    default:
        throw new \UnexpectedValueException(sprintf(
            'the remainder is %d, this is very strange!',
            $remainder
        ));
}


text:
Q: Legend R: not printing some data I am trying to plot a legend in R and I
dfk <- subset(df, df$V2 != -1 & df$V5>-50 & df$V5< 0 &  df$V6>-50 & df$V6<0)
plot(dfk$V5,dfk$V6, main = "1880 - 1 - 1/4", sub = NULL, xlab = "LON",
     ylab = "LAT", ylim=c(-50,0),xlim=c(-50,0),
     col = rainbow(length(dfk$V2))[rank(dfk$V2)],
     pch=c(1:25)[rank(dfk$V2)],cex=2)
legend('topright',legend=dfk$V2[!duplicated(dfk$V2)],
       col=rainbow(length(dfk$V2))[ rank(dfk$V2)[!duplicated(dfk$V2)] ],
       pch=c(1:25)[rank(dfk$V2)[!duplicated(dfk$V2)]],
       cex=2)

and here the data
V2  V3 V4  V5    V6
16  1  2 -29.5 -10.5
16  1  6 -30.5 -11.5
16  1 10 -30.5 -11.5
16  1 14 -30.5 -11.5
16  1 22 -32.5 -13.5
119  1 22 -30.5 -12.5
16  2  2 -32.5 -13.5
119  2  2 -31.5 -14.5
16  2  6 -33.5 -14.5
119  2  6 -31.5 -14.5
16  2 10 -33.5 -14.5
119  2 10 -31.5 -14.5
16  2 14 -33.5 -14.5
119  2 14 -31.5 -14.5
119  3  2 -32.5 -15.5
119  3  6 -33.5 -17.5
325  3 10 -32.5 -16.5
327  3 10 -31.5 -17.5
325  3 14 -32.5 -17.5
327  3 14 -31.5 -18.5
327  3 18 -31.5 -18.5
325  3 22 -32.5 -17.5
327  3 22 -31.5 -18.5
325  4  2 -32.5 -17.5
327  4  2 -31.5 -19.5
325  4  6 -32.5 -18.5
327  4  6 -31.5 -19.5
325  4 10 -32.5 -18.5
325  4 14 -32.5 -19.5
327  4 14 -31.5 -20.5
327  4 18 -31.5 -20.5

The problem is that it prints out the legend with the three categories(16-119-325-327) but it doesn't print the data of the 327 category!
Thanks

A: There are 25 available pch symbols to chose from and the highest rank of V2 is 27.5 so there was no match to a symbol. You could try dividing the rank by 2 and you will match to a pch symbol
plot(dfk$V5,dfk$V6, main = "1880 - 1 - 1/4", sub = NULL, xlab = "LON", ylab = "LAT",
         ylim=c(-50,0),xlim=c(-50,0), col = rainbow(length(dfk$V2))
         [rank(dfk$V2)],pch=c(1:25)[rank(dfk$V2)/2],cex=2)

legend('topright',legend=dfk$V2[!duplicated(dfk$V2)],col=rainbow(length(dfk$V2))
         [rank(dfk$V2)[!duplicated(dfk$V2)]],pch=c(1:25)
         [rank(dfk$V2)[!duplicated(dfk$V2)]/2],cex=2)


text:
Q: Using YQL to extract data from a page? In this table how would I use YQL/Xpath to get all data members of the column "Complex"?

A: my solution is as follows:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url=%22http://housing.byu.edu/offcampus/compdata/largeComplexes.php%22%20and%20xpath=%22/html/body/table[2]/tr/td[2]/table//tr[not%28contains%28@bgcolor,%278495A9%27%29%29]//td[1]//p%22

every Complex-member is enclosed with a <p>-tag


text:
Q: How can I change update into updateIn when I use immutable.js I'm trying to make my code neat by using immutable.js.
But I don't know how to replace the update into updateIn. Please help me.
[SET_COLOR]: (state, action) => {
  const counters = state.get("counters");
  const { color, index } = action.payload;

  return state.set(
    "counters",
    counters.updateIn([index, "color"], color => /*I got stuck here*/ )
  );
}

I've tried {color}, ({color}), color, color = color...
This is the original one.
const initialState = Map({
  counters: List([
    Map({
      number: 0,
      color: "black"
    })
  ])
});

(...)

[SET_COLOR]: (state, action) => {
  const counters = state.get("counters");
  const { color, index } = action.payload;

  return state.set(
    "counters",
    counters.update(index, counter => counter.set("color", color))
  );
},

A: You should try setIn instead:
[SET_COLOR]: (state, action) => {
  const { color, index } = action.payload;

  return state.setIn(["counters", index, "color"], color);
}

updateIn would only be useful if the updated value depended on the current value located at the path supplied to updateIn. For example:
const immutableObject = Immutable.fromJS({ outerProp: { innerCount: 1 } });
immutableObject.updateIn(['outerProp', 'innerCount'], count => count + 1);


text:
Q: How to reload a page if 504 gateway timeout error appears anytime in an automated process on Python? Selenium related I'm trying to automate a process within a website using Selenium on Python3.x, and sometimes the Error 504 Gateway time-out appears as shown below:

I would like to know if there's a way I can tell my program to reload the page (after several seconds have passed) in case this error appears anytime during the automated the process, as it is kind of random but after 1 or 2 refreses everything is back to normal.
Any ideas?


text:
Q: How do I get the application name from within a dll? If I had a dll (foo.dll) that was LoadLibrary'd into an application (bar.exe), how do I get the string "bar.exe" from within foo.dll?

A: Pass NULL as the first parameter to GetModuleFileName().


text:
Q: Format email message in Django I'm trying to send email message in one of my views and would like to format the body of the message, such that it shows in different lines.
This is a snippet code in views.py:
  body = "Patient Name: " +  patient_name + \
                   "Contact: " + phone + \
                   "Doctor Requested: Dr. " +  doctor.name + \
                   "Preference: " + preference

  email = EmailMessage('New Appointment Request', body, to=['ex@gmail.com'])
  email.send()

The email is shown like this:
Patient Name: AfrojackContact: 6567892Doctor Requested: Dr. IrenaPreference: Afternoon

How do I make it show like this:
Patient Name: Afrojack

Contact: 6567892

Doctor Requested: Dr. Irena

Preference: Afternoon

A: you should add '\n' for newlines.
or you could try this:
body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)

or, if you are using python >= 3.6:
body = f'''Patient Name: {patient_name}
Contact: {phone}
Doctor Requested: Dr. {doctor.name}
Preference: {preference}'''

A: I suggest to use the django template system to do that.
You could do:
```
from django.template import loader, Context

def send_templated_email(subject, email_template_name, context_dict, recipients):

    template = loader.get_template(email_template_name)

    context = Context(context_dict)

    email = EmailMessage(subject, body, to=recipients)
    email.send()

```

The template will look like: this could for example be in the file myapp/templates/myapp/email/doctor_appointment.email:
```

Patient Name: {{patient_name}}

Contact: {{contact_number}}

Doctor Requested: {{doctor_name}}

Preference: {{preference}}
```

and you will use it like
```
context_email = {"patient_name" : patient_name,
    "contact_number" : phone,
    "doctor_name":  doctor.name,
    "preference" :  preference}

send_templated_email("New Appointment Request",
                     "myapp/templates/myapp/email/doctor_appointment.email",
                     context_email,
                     ['ex@gmail.com'])
```

This is very powerfull, because you can style all the email in the way you want,
and you re-use the same function over and over, just need to create new template
and pass appropriate context/subject and recipietns

A: You are going right but you just missed a letter n
body = "Patient Name: " +  patient_name + "\n"
                   + "Contact: " + phone + "\n"
                   + "Doctor Requested: Dr. " +  doctor.name + "\n"
                   + "Preference: " + preference

This will add new line after each and every line and most probably solve your problem.

A: this should do the trick for breakline:
\n


text:
Q: Bulk filter & parse ONIX data (XML) in Excel I have 3000 ONIX-style xml URLs with book metadata.
I would like to filter a few nodes out of these files and parse them into Excel rows in a single worksheet.
This is an example of a XML-path:
http://btsoep.appspot.com/rest/book/9789082516425
I would like to filter this XML data on things as
<Product>
 <Title>
  <TitleText>

and
<Product>
 <Contributor>
  <PersonName>

I need the retrieved Data in an Excel worksheet where every URL has it's own row. So the URLs are in row A, TitleText is in row B and PersonName is in row C.
How would I go by doing this?
EDIT 1:
What I've tried so far is:
-using wget to download all the xml data first and then try to bulk parse this is excel. This could work but is unnecessary.
-using the default XMLimport function in Excel. I can't seem to run this in a batch.
I don't have any experience with filtering XML files and parsing this in an Excel worksheet. I'm not asking anyone to fix this for me or write code for me, but I would like a step in the good direction. Which tools would be the best to use for this case? Thanks again.

A: this should get you started
Option Explicit

Sub parseONIX()

    Dim URL As String

    URL = "http://btsoep.appspot.com/rest/book/9789082516425"
 '  URL = "https://www.w3schools.com/xml/plant_catalog.xml"

    Dim XMLPage As New MSXML2.XMLHTTP60
    XMLPage.Open "GET", URL, False
    XMLPage.send

    Dim XMLDoc As New MSXML2.DOMDocument
    XMLDoc.LoadXML XMLPage.responseText

    Debug.Print XMLDoc.ChildNodes(0).BaseName
    Debug.Print XMLDoc.ChildNodes(1).BaseName
    Debug.Print XMLDoc.ChildNodes(1).ChildNodes(0).BaseName
    Debug.Print XMLDoc.ChildNodes(1).ChildNodes(1).BaseName
    Debug.Print XMLDoc.getElementsByTagName("Product").Item(0).BaseName

    Dim i As Integer

    For i = 0 To XMLDoc.getElementsByTagName("Measure").Length - 1

        Debug.Print "type: "; XMLDoc.getElementsByTagName("Measure")(i).ChildNodes(0).Text,
        Debug.Print XMLDoc.getElementsByTagName("Measure")(i).ChildNodes(1).Text,
        Debug.Print XMLDoc.getElementsByTagName("Measure")(i).ChildNodes(2).Text

    Next i

End Sub


text:
Q: Laravel large size image upload validator not work I'm using Laravel: 5.2.* with PHP Version 5.6.4 as my project and trying to validate/restrict large size(max:600kb) image(Single file) with form uploader.
While submit form with large size image(i.e. 8 MB), redirect me on home page without performing validation OR exception message. So I checked at log-viwer and found some thing exception 'Illuminate\Session\TokenMismatchException'.
I tried number of solution, some of the listed below
- Small file get uploaded but not large file in Laravel
- File validation failing on larger files
- L4.0, (CSRF) TokenMismatchException when uploading large files (I know this is for L4)
Further forms, route, request and all other stuffs are working fine with small size so I think not an issue with code. Also I changed php.ini as per require and restart the apache but getting hard luck.
Current php.ini
upload_max_filesize = 1G
post_max_size = 2G

Loaded Configuration File(php.ini path)
/etc/php5/apache2/php.ini

My problem is why large size image not work as small size for my project? Please help me.
P.S. I appreciate your help/assistance.
UPDATE (2016/12/22)
I have reviewed and found the question similar like me but answer still not work for me. Any Idea! Please help!

A: can you please check after commenting
\App\Http\Middleware\VerifyCsrfToken::class,
in kernel.php in Http folder. If thats the issue you can try the below solution
Add {!! csrf_token() !!} within your form to generate a CSRF token. And pass it as a hidden field
You can try this as in laravel there is a middleware for csrf token.
Hope this works.


text:
Q: what is different between using Variable and not in Mariadb? I just want to get some hint. Is there a type issue?
issue case.
SET @ids = '4094,8562,11144,3017,5815,11121,1957,4095,8563,11145,3018,5816,8527,11122,1959,4096,8564,3020,5817,8528,11123,1961,4097,8571,3021,6020,8535,11128,1962,5181,8572,3581,6021';

this @ids value is actually collected by GROUP_CONCAT() from the subquery;
        SELECT
            ifnull(sum(case when a.student IS NOT NULL then total END), 0)
        from
            tb_class a
        WHERE
            a.id IN (@ids)
            and a.date >= '2023-02-01'  AND a.DATE <= '2023-02-02'

==> 0
correct case2.
SELECT
    ifnull(sum(case when a.student IS NOT NULL then total END), 0)
from
    tb_class a
WHERE
    a.id IN (4094,8562,11144,3017,5815,11121,1957,4095,8563,11145,3018,5816,8527,11122,1959,4096,8564,3020,5817,8528,11123,1961,4097,8571,3021,6020,8535,11128,1962,5181,8572,3581,6021)
    and a.date >= '2023-02-01'  AND a.DATE <= '2023-02-02'

==> 54

A: I got answer from googling. use function FIND_IN_SET()
        SELECT
            ifnull(sum(case when a.student IS NOT NULL then total END), 0)
        from
            tb_class a
        WHERE
            FIND_IN_SET(a.id, @ids)
            and a.date >= '2023-02-01'  AND a.DATE <= '2023-02-02'

A: Variables store single values, not lists.    Your @ids is just a string that happens to have a comma separated list of numbers.  The IN operator only compares against an explicit list; what you are doing is no different than a.id = @ids (which will actually be true, with a warning, for the first number in the list if id is a numeric type, since the string will be converted to a number and the trailing non-numeric portion discarded).
Sometimes you do want to work with a string containing a list of ids such as this, for instance if you have a query that reads many rows that you want to use to produce a small list of ids to update, without the update locking those all the rows read.  Then you can use dynamic sql:
SET @ids = '4094,8562,...';
SET @sql = concat('select * from a where a.id in (',@ids,')');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;

Or, in mariadb since 10.2,
EXECUTE IMMEDIATE concat('select * from a where a.id in (',@ids,')');

Another alternative is to use FIND_IN_SET, as shown in another answer, but that will not use an index to look up ids, so may be inefficient.


text:
Q: Why would Visual Studio 2010 (Intellisense) stop generating an interface pointer? I had working code that implemented a wrapper and interface along the lines of:
public class wrapper : wrapperInterface {
    ...
}

Intellisense was generating a wrapperInterfacePtr so that in a C++ header I had a valid statement of:
wrapper::wrapperInterfacePtr m_wrapper;

I was mucking around trying to add some Delegate functionality so I could pass a C++ callback into the C# (I failed), and at some point during the mucking around the auto-generated wrapperInterfacePtr became undefined.  Even after I returned all the code to (what appears) to be its original state, Intellisense is not generating wrapperInterfacePtr.
Any thoughts on how what I could have done, or how to kick-start Intellisense?

A: Ok, I got it to work again.  I can't give the definitive reason it failed, but I have an idea.  The new c# managed code is on top of a huge library of existing C++ unmanaged code. I build the managed code using VS and then use an in-house tool to build everything else.  The in-house build tool doesn't do a clean unless you really, really force the issue.  (It would take days.)  When I did a build-clean on the dlls that interfaced with the managed code, that fixed the problem.


text:
Q: Wait a few ajax finished, but the ajax function is dynamically called I want to wait a few ajax finished.
I have checked some pages and get the ideas of
$.when ().done(funciton(){})....
However in my case is little bit complex.
ajax is dynamically generated and, it is the method of the Class.
class TestClass{
    constructor(){}
    myAjax = function(id){
        $.ajax({
            url:  myajax,
            type: 'POST',dataType: 'json',
            data: {"id" : id},
            success: function(data) {
                console.log("byId loaded:"+ id);
            }
        });
    }
}
testclass = new TestClass();
var myIds = [1,3,5,7];
for (var i in myIds) {
    testclass.myAjax(myIds[i]); // I want to wait every ajax is finished.
}

I have tried like this using $.when() but in vain (compile error)
$.when(
for (var i in myIds) {
    testclass.callGraph(myIds[i]); .

).done(function(){
    console.log("load finished");
}

A: Try this
class TestClass{
    constructor(){}
    myAjax = function(id){
        return $.ajax({
            url:  myajax,
            type: 'POST',dataType: 'json',
            data: {"id" : id},
            success: function(data) {
                console.log("byId loaded:"+ id);
            }
        });
    }
}
testclass = new TestClass();
var promises = [];
var myIds = [1,3,5,7];
for (var i in myIds) {
    promises.push(testclass.myAjax(myIds[i])); // I want to wait every ajax is finished.
}

$.when(promises).then(function(values){
   console.log('all ajax request completed');
});