Python 3.6 fails to build in QEMU with "failed to get random numbers to initialize Python"

Question: I'm trying to build Python using qemu on Linux. Python 2.7 worked great, no problems, standard build process. Python 3.6, same build process is throwing an error like this:
<code>./Programs/_freeze_importlib \
    ./Lib/importlib/_bootstrap.py Python/importlib.h
Fatal Python error: failed to get random numbers to initialize Python
</code>
So I'm thinking this is due to qemu not having /dev/random or /dev/urandom? So either I figure out how to add random to the qemu, or convince Python 3.6 to not require it?
Edit: I'm trying to use PYTHONHASHSEED to get around this, but from what I can tell it has no effect - I can set crazy values like PYTHONHASHSEED=Jeff (which should generate a different error), but no difference. So now I'm thinking its the qemu and environment variables that I am not understanding.
Comment: Here's the line in question: https://hg.python.org/cpython/file/tip/Python/random.c#l583
Comment: Thanks for that! I should have mentioned I tried to use PYTHONHASHSEED to get around this - but I'm thinking I must not have used it correctly. I'm going to experiment with that.
Answer: Ok - the real answer is to fix the QEMU - which turned out to be easy:
<code>mknod -m 444 /dev/random c 1 8
mknod -m 444 /dev/urandom c 1 9
</code>
Python3.6 is building now - thanks for watching!


SQLite define output field separator on a single line command

Question: I need to use a single command line to fetch a set of records from a database.
If I do this:
$ sqlite3 con.db "SELECT name,cell,email FROM contacts"

I get output with a separator "|", where the output looks like this:
firstname.lastname@example.com
email@example.com
firstname.lastname@example.com

Is there a way (in single command line format like specified above) to change the output field separator to something else, like ";;;" or something else or more unique. This is because the output occasionally get the character "|" inside the records, and it causes issues.
My desired result is:
Alison;;;+12345678;;;firstname.lastname@example.com
Ben;;;+23456789;;;email@example.com
Steve;;;+34567890;;;firstname.lastname@example.com

Or any other unique separator, which is not likely to be found inside the values.
(The command is executed on a Linux machine)
Thank you.
Answer: The -separator option does what you want:
sqlite3 -separator ';;;' con.db "SELECT ..."

The only way to format the output so that you are guaranteed to not get the separator in the values is to quote all strings:
sqlite3 con.db "SELECT quote(name), quote(cell), quote(email) FROM contacts"

However, this would require you to parse the output according to the SQL syntax rules.
Comment: Thanks, exactly what I needed! The first option did the trick nicely.
Comment: Thank you, the SELECT quote(blah) helped me!


How to Unblock UI Thread manually

Question: Hi i have a project in Xamarin.Android Visual Studio that copy some images to sdcard , for reasons i need to make stop in loop without main UI blocked, i already tested some solutions in Async/await but that not really works.
here is my code need to wait for do somethings like show progress bar and etc..
void ExportBitmapAsPNG(Bitmap bitmap, string filename)
        {
            var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
            var filePath = System.IO.Path.Combine(sdCardPath + dirPath + "/images", filename);
            var stream = new FileStream(filePath, FileMode.Create);
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
            stream.Close();
            progressBar.IncrementProgressBy(5);
            txtLoading.Text = "Loop Loading : " + progressBar.Progress.ToString();
            RunOnUiThread(() => Thread.Sleep(1000));
            Console.WriteLine("Image {0} Created", filename);

        }

what should i do for that ? thank you
Answer: Your bitmap.Compress could be causing some of the freezing as well as your sleep.  I would try something like this
async Task ExportBitmapAsPNG(Bitmap bitmap, string filename)
 {
        var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
        var filePath = System.IO.Path.Combine(sdCardPath + dirPath + "/images", filename);
        var stream = new FileStream(filePath, FileMode.Create);
        await bitmap.CompressAsync(Bitmap.CompressFormat.Png, 100, stream);
        stream.Close();
        progressBar.IncrementProgressBy(5);
        txtLoading.Text = "Loop Loading : " + progressBar.Progress.ToString();
        await Task.Delay(1000);
        Console.WriteLine("Image {0} Created", filename);

    }

How to Unblock UI Thread manually


vbscript for WQL WMI with or operator

Question:
i am querying for event viewer log using vbscript.

When I try ot use OR operator @ Where Logfile='System' Or 'Application' it gives info but drops TYPE condition and i found my results with information type data.
How do i combine this two queries so that I don't have to write
extra code.

Set colLoggedEvents = objWMIService.ExecQuery _
        ("Select * from Win32_NTLogEvent Where Logfile = 'Application'  AND Type <> 'Information' AND TimeGenerated >  ' " & dteDate & "' ")
Set colLoggedEvents = objWMIService.ExecQuery _
            ("Select * from Win32_NTLogEvent Where Logfile = 'System'  AND Type <> 'Information' AND TimeGenerated >  ' " & dteDate & "' ")
regards : msinfo
Answer: You can use parentheses for an inner comparison.

Select * from Win32_NTLogEvent Where ( Logfile = 'System' Or Logfile = 'Application' ) AND Type <> 'Information' AND TimeGenerated >  '" & dteDate & "'
Comment: Thanks! It opened my eyes, I was putting parentheses before Where keyword in actual code. :-)

vbscript for WQL WMI with or operator


removing list elements while traversing the list has unintended effect

Question: Here is the simple example
>>> list=[(1,2),(3,4),(5,6)]
>>> for i in list:
...     print(i)
...     list.remove(i)
...
(1, 2)
(5, 6)
>>> list
[(3, 4)]
>>>

My intention was to print and element and remove it but it seems that the next element gets removed though that is also not true as unprinted element got restored after loop.
Can you explain this behaviour ?
Is this a bug or my method is incorrect ?
Is it possible to do in-place removal without using another copy of list ?
Thanks.
Comment: Yeah . My aim was to understand this behaviour .
Comment: Sure, I thought that was covered somewhere in the [duplicate link](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating), perhaps its not. It does address some of your other concerns though.
Comment: See [this answer](https://stackoverflow.com/a/6260097/5014455) in the linked duplicate
Comment: "Is it possible to do in-place removal without using another copy of list ?" yes it is, but it is error prone and inefficient.
Answer: l =[(1,2),(3,4),(5,6)]

for i, v in enumerate(l):
    print (v)
    l[i] = ""

print ([x for x in l if x])

Output:
(1, 2)
(3, 4)
(5, 6)
[]

Briefly, if you remove a list element while you are iterating through, you change the index range. So you remove (1,2), then you skip (3,4) cause it is now at the index of removed element (1,2). So second iteration third element (5,6).
So no it is not a bug, and your method is certainly not correct for your needs!
Use enumerate, in my example, or alternatively:
for i in range(len(l)):
    print (l[i])
    l[i] = ""

print ([x for x in l if x])

In fact, you should never remove an element/index in list while iterating through. You can set the value at index to nothing "" then remove the empty elements.
Comment: I definitely agree ```In fact, you should never remove an element/index in list while iterating through.```, but once in a while, I somewhat have to do that but with great caution.
Comment: to Synthase , that was a nice explanation for behaviour . 'enumerate' solution  replaces list element with empty string but list length is still same and list is not empty at the end . An empty list return 'not list' as true. Also, alternatively solution gave error 'TypeError: 'list' object cannot be interpreted as an integer'
Comment: Yes sorry I corrected for the alternative solution. Range(len(l)) and not range(l)!


How to get access from inner module (library) to application what include the module?

Question: I am developing an android library(SDK).
Each user (a partner) who will use this library should include it like a dependency in a gradle and initialize it with String partnerId in his code.
My library has Service what starts by different device events like ACTION_BOOT_COMPLETED etc.
This Service has to have String partnerId for correctly working.
The issue:
A play market user, who downloaded partner's application (which includes my library), install it but does not start the application by himself. This means that partner's code does not set String partnerId yet, and when a Service will start by some device event it will not has String partnerId.
How can I solve the issue? Any suggestions. Thanks in advance.
Answer: I would have them set their partnerId in the Manifest.xml, perhaps as a meta-data entry. You can then access it via the getPackageManager().getApplicationInfo() call in your Service.


"Essential C++"ch3.9 use "back_inserter(ivec2)" replace the "ivec2.begin()" can't compile

Question: This example copy from the book:
#include "stdafx.h"
#include<functional>
#include<iostream>
#include <vector>
#include <algorithm>
#include<iterator>

using namespace std;

template<typename input_iterator_tag, typename output_iterator_tag,
typename elem_type, typename comp>
output_iterator_tag
filter(input_iterator_tag first, output_iterator_tag last,
output_iterator_tag at, const elem_type &val, comp pred)
{
    while ((first = find_if(first, last, bind2nd(pred, val))) != last)
    {
        cout << "found value: " << *first << endl;
        *at++ = *first++;
    }
    return at;
 }

 int _tmain(int argc, _TCHAR* argv[])
{
const int elem_size = 8;
int ia[elem_size] = { 12, 8, 43, 0, 6, 21, 3, 7 };
vector<int>ivec(ia, ia + elem_size);

int ia2[elem_size];
vector<int>ivec2(elem_size);

cout << "filtering integer array for values less than 8\n";
filter(ia, ia + elem_size, ia2, elem_size, less<int>());
cout << "filtering integer vector for value greater than 8\n";
filter(ivec.begin(), ivec.end(), ivec2.begin(), elem_size, greater<int>  ());//it's work ok
filter(ivec.begin(), ivec.end(), back_inserter(ivec2), elem_size, greater<int>());//compile error,no instance of function template "filter" matches

system("pause");
return 0;
}

Why i use "back_inserter(ivec2)" replace " ivec2.begin()" as the book said, but it can't compile in the visual studio;
   IntelliSense: no instance of function template "filter" matches the argument list argument types are: (std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>, std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>, std::back_insert_iterator<std::vector<int, std::allocator<int>>>, const int, std::greater<int>)

anyone can help me correct it and why?
Answer: Looks like a typo in the function declaration. The second parameter (last) should be a input_iterator_tag not an output_iterator_tag, as it should match the first iterator since it is compared directly to first.
template<typename input_iterator_tag, typename output_iterator_tag,
typename elem_type, typename comp>
output_iterator_tag
filter(input_iterator_tag first, input_iterator_tag last,
output_iterator_tag at, const elem_type &val, comp pred)

Note: The reason it worked for your first case was that the both input and output types were the same.
Comment: That's also a terrible way to name a template parameter.
Comment: Thank you very much.any advice for name template parameter?

“Essential C++”ch3.9 use "back_inserter(ivec2)" replace the "ivec2.begin()" can't compile


Loop through two arrays and check if key value in items of the first array are present in the second [JavaScript]

Question: I am trying to loop a array of objects and compare it with another array and check of the key value is present in the array which is to be compared. Here I am not going to check for the array length too.
Example
Array1 is the array which needs to be compared to array 2
[{name:'Linus',id:1},{name:'Anthony',id:2},{name:'Carl',id:3}]

Array 2
[{name:'Linus',id:1},{name:'Anthony',id:2},{name:'Beth',id:3},{name:'Kyle',id:4}]

I am trying to validate if all the id values in array 1 are present in array 2 and if not present then I expect a boolean value and get the best solution in terms of performance.
Answer: array1.every(item1 => array2.some(item2 => item1.id === item2.id))

Comment: Thanks for the quick solution.Gave a idea of how it can be done.Thanks <3
Answer:

const arr1 = [{
  name: 'Linus',
  id: 1
}, {
  name: 'Anthony',
  id: 2
}, {
  name: 'Carl',
  id: 3
}];

const arr2 = [{
  name: 'Linus',
  id: 1
}, {
  name: 'Anthony',
  id: 2
}, {
  name: 'Beth',
  id: 3
}, {
  name: 'Kyle',
  id: 4
}]

let compareTwoArrayOfObjects = (
  first_array_of_objects,
  second_array_of_objects
) => {
  return (
    first_array_of_objects.length === second_array_of_objects.length &&
    first_array_of_objects.every((element_1) =>
      second_array_of_objects.some(
        (element_2) =>
        element_1.id === element_2.id
      )
    )
  );
};

console.log(compareTwoArrayOfObjects(arr1, arr2));

You can do it with this method to compare each object's element and check their id value
Comment: The OP never specifies that the length of the arrays would necessarily be equal. The first array could have more items than needed.
Comment: then both arrays would no longer be equal, I'm pretty sure thats what the OP actually needs. Makes no sense having an array where a bunch of users share the same id, compare with a short array with only 3 users and return true becuz they are all present in both
Comment: Except for  the check for the length of array.The solution is fine.Thanks <3
Answer: Pretty easy using the .findIndex() in a loop and filter depending upon your needs.

const array1 = [{
  name: 'Linus',
  id: 1
}, {
  name: 'Anthony',
  id: 2
}, {
  name: 'Carl',
  id: 3
}];

const array2 = [{
  name: 'Linus',
  id: 1
}, {
  name: 'Anthony',
  id: 2
}, {
  name: 'Beth',
  id: 3
}, {
  name: 'Kyle',
  id: 4
}];

array1.forEach((a1) => {
  const idx = array2.findIndex((x) => {
    return x.id === a1.id
  });
  console.log(idx);
});
// idx set to -1 if it is not found
array2.forEach((a2) => {
  const idx = array1.findIndex((x) => {
    return x.id === a2.id
  });
  console.log(idx);
});

let matches = array2.filter((a) => {
  return array1.findIndex((x) => {
    return x.id === a.id
  }) > -1;
});
console.log(matches);

let nomatches = array2.filter((a) => {
  return array1.findIndex((x) => {
    return x.id === a.id
  }) == -1;
});
console.log(nomatches);
Comment: I dont think its good in terms of performance


Change form action and verb on button click using jQuery

Question: I have a form that has a main submit button that needs to use POST and a specific action, but I also have a couple of buttons that need to submit the form using GET and to different actions.
The only way I could see to do this was to intercept the submit using a jQuery .click() event and passing the form vars using something like this:
<code>$('#btnClick').click(function (event) {

    event.preventDefault;

    input = $(':input');
    window.location.href = '/action/?' + input;

    return false;
})
</code>
This makes a messy querystring and exposes some hidden fields that contain lengthy data. What is the best way of using jQuery to intercept form submission and resending using GET?
Btw, I am targeting different MVC GET Controller Actions with a couple of buttons while the main button uses POST to the Controller Action of the current view.
EDIT
Though I haven't tried it yet, Mike provided an idea I hadn't thought of. I could do something like:
<code>$("form").attr("action", "/action");
$("form").attr("method", "post");
</code>
or
<code>$("form").attr("action", "/action");
$("form").attr("method", "get");
</code>
but the latter will still expose some vars that are messy, mainly hidden fields. Is there a way of excluding the hidden fields without manually manipulating the querystring?
Comment: I'm going to say handle the submit event and use ajax. Without ajax you could probably change it. Never tried it though.
Comment: I guess I've never used Ajax while redirecting to another page. Is this what you are saying?
Comment: No I was saying if you using ajax you can intercept what they are doing in the submit event. If not you can probably just change the form method attribute on the form itself. That's what I would try first. I do so much ajax these days...
Comment: The form has a button that submits using POST and a couple of others that submit using GET.
Comment: To intercept form submission you handle the submit event in jquery. To cancel entirely just return false. You MIGHT be able to do something like $("form").attr("method", "post").
Answer: It'd probably be best to disable the fields you don't want so they aren't submitting, and the form can work like normal otherwise. So if for example, by default you have the form submitting via POST, but you have another button <code>#search</code> which does a GET but you want to exclude some elements:
<code>$('#search').click(function (event) {
    event.preventDefault;
    $(this)
        .parents("form")
            .find("input.excludeOnSearch")
                .prop("disabled", true)
            .end()
            .attr("method", "GET")
            .submit();
})
</code>
Comment: I like this. Nice solution to prevent unwanted fields from being submitted. Thank you.
Answer: See here: http://jsbin.com/cakov/1/edit?html,js,output
<code>$("form").on("submit", function(e) {
  var method = $("form").attr("method");
  if(method === "POST") {
    $("form").attr("method", "GET");
  } else {
    $("form").attr("method", "POST");
  }

  alert($("form").attr("method"));

  return false;
});
</code>
This code effectively acts a toggle and changes the http method to, in this case, the opposite of what it was. The final return statement cancels the submit of the form.
I think this is what you are asking?
Comment: Mike, you definitely provided me with a better option and dyagmin expanded on it. I think his answer will work the way I'm needing. Wish I could mark both of your answers as correct. ;)


AWS Lambda Function : {"message":"Internal Server Error"

Question: Im trying to run the United States Postal Service's Web Tools, for converting ZIP Codes into State and City. I created an AWS Lambda function inside the AWS Amplify.
But the Lambda function is always giving me the return message {"message":"Internal Server Error"}
Here is my Lambda FUnction Code.
const axios = require("axios");

const BASE_URI =
  "http://production.shippingapis.com/ShippingAPITest.dll?API=CityStateLookup&XML=";
const config = {
  headers: {
    "Content-Type": "text/xml",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Methods": "GET",
  },
  method: "get",
};
exports.handler = async function (event, context, callback) {
  // The zipcode is sent by the frontend application.
  // This is where we use it.
  const zipcode = event.queryStringParameters.zipcode;

  // The xml variable is the string we are going to send to the
  // USPS to request the information
  const xml = `<CityStateLookupRequest USERID="400000000"><ZipCode ID="0"><Zip5>${zipcode}</Zip5></ZipCode></CityStateLookupRequest>`;
  try {
    // Using syntactic sugar (async/await) we send a fetch request
    // with all the required information to the USPS.
    const response = await axios(`${BASE_URI}${xml}`, config);
    // We first check if we got a good response. response.ok is
    // saying "hey backend API, did we receive a good response?"
    if (!response.ok) {
      // If we did get a good response we store the response
      // object in the variable
      return { statusCode: response.status, body: response };
    }
    // Format the response as text because the USPS response is
    // not JSON but XML
    const data = await response.text();
    // Return the response to the frontend where it will be used.
    return {
      statusCode: 200,
      body: data,
    };
    // Error checking is very important because if we don't get a
    // response this is what we will use to troubleshoot problems
  } catch (err) {
    console.log("Error: ", err);
    return {
      statusCode: 500,
      body: JSON.stringify({ msg: err.message }),
    };
  }
};

The axios is working fine I think.
Any help would be appreciated as I'm trying to solve this for days now.
Comment: Did you check the function logs in cloudwatch?
Comment: "errorType": "Error",
    "errorMessage": "Unable to stringify response body",
Answer: By default Lambda functions does not have outbound access to internet.
You can add a Nat Gateway to your VPC but it's not cheap.


How to Validate the String and it's Value in excel through Java?

Question: Am new to Java and I have challenge in validating the excel file.Please help me.
I want to validate that 'Hyderabad' is the location Name and '1' is the location ID from excel(pls screenshot below)through JAVA .Am able to read all the cell values.But I want to verify whether Location Name is Hyderabad or not(Similarly , the location ID).Please suggest me here.

<code>if (fileType.equalsIgnoreCase("Excel")) {
            Workbook wb = new XSSFWorkbook(f);

            for (int i = 0; i < wb.getNumberOfSheets(); i++) {

                System.out.println("Sheet name: " + wb.getSheetName(i));
                Sheet sh=wb.getSheetAt(i);

                if (wb.getSheetName(i).matches("A|B|C|D"))
                {
                    int rowCount = sh.getLastRowNum() - sh.getFirstRowNum();

                    for (int j = 0; j < rowCount + 1; j++) {

                        Row row = sh.getRow(j);

                        for (int k = 0; k < row.getLastCellNum(); k++) {

                            System.out.print(row.getCell(k).getStringCellValue() + "|| ");

                        }
                }
            }

        }
</code>
Comment: if(row.getCell(k).getStringCellValue().equals("Hyderabad")) sop("pass")
Comment: Thanks for your comment.But I think, this statement will check if the string Hyderabad exists in the given sheet or not. I wanted Location Name == Hyderabad to be validated. Hope it is clear.
Comment: What gave you idea that "equals" means "contained somewhere"?
Answer: if (fileType.equalsIgnoreCase("Excel")) {
            Workbook wb = new XSSFWorkbook(f);
<code>        for (int i = 0; i < wb.getNumberOfSheets(); i++) {

            System.out.println("Sheet name: " + wb.getSheetName(i));
            Sheet sh=wb.getSheetAt(i);

            if (wb.getSheetName(i).matches("A|B|C|D"))
            {
                int rowCount = sh.getLastRowNum() - sh.getFirstRowNum();

                for (int j = 0; j < rowCount + 1; j++) {

                    Row row = sh.getRow(j);

                    if(row.getCell(0).getStringCellValue().contains("Location Name")){
                    {
                        if(row.getCell(1).getStringCellValue().equalsIgnoreCase("Hydrabad")){
                            System.out.print("Location name is matches with Hydrabad");
                        }
                        else{
                            System.out.print("Location name isn't matches with Hydrabad");
                        }
                    }

                    if(row.getCell(0).getStringCellValue().contains("Location ID")){
                    {
                        if(row.getCell(1).getStringCellValue().equalsIgnoreCase("1")){
                            System.out.print("Location id matches");
                        }
                        else{
                            System.out.print("Location id mismatches");
                        }
                    }
            }

    }
</code>
Comment: Thank you for detailed code. But it's partially resolved. Able to match with Location Name. Failed to match the location ID.Please see if you can modify it.
Comment: you can try with contains instead of equalsIgnoreCase for location id
Comment: Okay...Btwn, am still wondering, who downvoted this question. :( Hope it's not a weird question.


Angular tour of heroes, How is the ID added in the addHero method?

Question: in Agular's tour of hero official tutorial (https://angular.io/tutorial/toh-pt6)
when calling the addHero method, only the hero's name property is passed, but somehow a new hero object with id property is created.
I may be missing something, but where did the id property come from?
Comment: stuck at the same place... upvoted.
Answer: This angular application uses angular-in-memory-web-api package that intercepts all http requests and hides some features under the hood:
<code>protected post(...): ResponseOptions {
  const item = this.clone(this.getJsonBody(req));

  if (item.id == undefined) {
    try {
      item.id = id || this.genId(collection, collectionName);
                      ^^^^^^^^^^^^^
                     generate id
</code>
https://github.com/angular/in-memory-web-api/blob/25c6a217986695de619feed35851332636769a05/src/in-mem/backend.service.ts#L590-L592


Limit cart to only use 1 coupon - woocommerce

Question: how can I limit my coupon so a customer won't be able to use multiple coupon on the same checkout?
I'm using WP Woocommerce 4.2.2
Comment: what have you tried so far? can you show some code where you are having the problem?
Comment: I have the problem fx. when a customer uses 3 coupons of 40% of the basket (each) - then the items will be 'free'.
Comment: Check out the [Woocommerce documentation on usage restriction](http://docs.woothemes.com/document/coupon-management/#section-3)
Comment: Thank you @Harben - i've been struggling with this for quite a while now :)
Answer: You can do this by activating the option Individual use only, at the coupon editing form. This will block the use of additional coupons.
For more information check the official documentation.
Comment: Anyway to do this using PHP code rather than the setting?
Comment: https://stackoverflow.com/a/53251149/8391466
Answer: The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):
<code>add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
function one_applied_coupon_only( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // For more than 1 applied coupons only
    if (  sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
        // Remove the first applied coupon keeping only the last appield coupon
        $cart->remove_coupon( reset($coupons) );
    }
}
</code>
Code goes in function.php file of your active child theme (active theme). Tested and works.


define if two planes are parallel

Question: I am trying to develop a function to determine if 2 planes are parallel or not.
I have their equations :
P1 : a1.x + b1.y + c1.z + d1 = 0
P2 : a2.x + b2.y + c2.z + d1 = 0

I check :
a1=0 & a2=0 => parallel
b1=0 & b2=0 => parallel
c1=0 & c2=0 => parallel

else, if a1/a2 = b1/b2 = c1/c2 => parallel

I have some big doubts about it, because I read on courses that none of parameters may be equal to 0, but if I have a plane on $(x,y)$, with $z=10$, the equation may be :
$z-10 = 0$, so $a, b =0$, right?
How could I check parallelism, taking in account each particular case?
After thinking, I guess it may be something like that :
(a1=0 & a2=0) => no need to check equality
(b1=0 & b2=0) => no need to check equality
(c1=0 & c2=0) => no need to check equality

if (a1=0 & a2!=0) or (a1!=0 & a2=0) => not parallel
if (b1=0 & b2!=0) or (b1!=0 & b2=0) => not parallel
if (c1=0 & c2!=0) or (c1!=0 & c2=0) => not parallel

Where != means different
Then check if a1/a2 = b1/b2 = c1/c2 (if I need to check)
Aside : How can I insert here some mathematical signs, I cannot find?
Comment: To avoid worrying about zero, you could check whether $(a1.b2=a2.b1) and (a1.c2=a2.c1) and (b1.c2=b2.c1)$
Comment: In fact, I just found a better course, that is giving the definition. In fact, I can have 1a=0, or b1=0, or c1=0, but never 3 of thm = 0, right?
Comment: Yes, check for that too
Comment: You should check mathjax - where we write math within `$...$` for typing out math signs.
Math Meta Stackexchange has a mathjax tutorial, search for it
Comment: @Empty thanks that helped. if you write as answer, I could accept it, or may I accept `jp bouchon`'s answer, as it is good explained too, don't know what may be the correct way.
Comment: @Siegfried.V Empy2's comment and jp bouchon's answer give the same condition.
Comment: Your test suggest that the planes $x=1$ and $y=2$ are parallel
Comment: @Apass.Jack that's why I askd. Empy answerd first. Never mind I accepted it. And Hagen von Eitzen I know, that's why I asked, I saw something was wrong.
Answer: If a plane $P$ has $ax+by+cz+d=0$ as cartesian equation —with $(a,b,c)\ne(0,0,0)$—, then the vector $\left(\begin{smallmatrix}
a\\ b\\ c
\end{smallmatrix}\right)$
is orthogonal to $P$.
Now two planes $P_1$ and $P_2$ are parallel iff $\left(\begin{smallmatrix}
a_1\\ b_1\\ c_1
\end{smallmatrix}\right)$
and
$\left(\begin{smallmatrix}
a_2\\ b_2\\ c_2
\end{smallmatrix}\right)$
are "proportional", i.e., linearly dependent, which is in turn equivalent to
$$\begin{vmatrix}
a_1&a_2\\
b_1&b_2
\end{vmatrix}
=
\begin{vmatrix}
a_1&a_2\\
c_1&c_2
\end{vmatrix}
=
\begin{vmatrix}
b_1&b_2\\
c_1&c_2
\end{vmatrix}=0.$$
That is: $a_1b_2-a_2b_1
=a_1c_2-a_2c_1
=b_1c_2-b_2c_1=0$.
Comment: you wrote `with (a,b,c)≠(0,0,0)`. Could you explain why? As I understood, a,b,c are not necessarly ≠ 0 ?
Comment: This is because the cartesian equation $0.x + 0.y + 0.z + d=0$ doesn't define a plane. According to the value of $d$, this equation defines $\emptyset$ (for $d≠0$) or $\Bbb{R}^3$ (for $d=0$). To define a plane _at least one of the coefficients_ must be ${}\neq0$. Put otherwise: the affine plane P has for _direction_ a vector space $\vec P$, which is defined as the kernel of a non-zero linear form $\ell$, and $P$ has $\ell(x,y,z)+d=0$ for equation (for some $d\in\Bbb{R}$. Such a linear form is of the type $\ell(u,v,w)=au+bv+cw$ for some $(a,b,c)\neq(0,0,0)$.
Comment: Sorry, I missunderstood the comment. I believed none of them may be equal to 0. Thanks for your answer, it helped a lot :).

define if two planes are parallel


Installing additional R Package on Azure ML

Question: I am doing the following steps to install R Hash_2.2.6.zip package on to Azure ML

Upload the .zip file as a dataset
Create a new experiment and Add "Execute R Script" to experiment
Drag and drop .zip file dataset to experiment.
Connect the Dataset in step3 to "Execute R Script" of step2
Run the experiment to install the package

However I am getting this error: zip file src/hash_2.2.6.zip not found
Just so that its very clear, I am following steps mentioned in this article: http://blogs.technet.com/b/saketbi/archive/2014/08/20/microsoft-azure-ml-amp-r-language-extensibility.aspx.
Any help in this regard is greatly appreciated.
Answer: To install a package this way, you have to create a .zip of a .zip. The outer layer of packaging will get unzipped into the src/ folder when the dataset is passed in to the module, and you'll be able to install the inner package from there.


Circle equation through 2 points

Question: Three points $(0,0) , (1,2) , (1,-2)$ are given. The circle through these 3 points is to be found. My textbook says the circle is $(x-1)(x-1)+(y-2)(y+2)+k(x-1)=0$. We can find $k$ by putting $x=y=0$. My issue is that this formula is not mentioned anywhere. The ones I am aware of are family of circle through 2 points and circle touching a line at $(x_1,\ y_1)$ on the line. What does the formula used above represent ?
Comment: In $Q.1$ they have used family of circles passing through through two points $A(x_1, y_1),B(x_2,y_2)$ which is given as $$(x-x_1)(x-x_2)+(y-y_1)(y-y_2)+\lambda(\text{eq. of}\ AB) $$
Comment: Please ask one question at a time since they are completely independent. I've flagged this question as `Needs more focus`.
Comment: Comments are not for answering questions.  This is stated very clearly in the Community Guidelines and you are reminded of this prior to writing a comment.
Comment: What have you tried?
Comment: What is the value of $m$ in part 2?
Comment: If you dont know any formula to find out the equation of circle which passes through 3 given points then try to find a formula...and use it
Comment: I have separated the quesetion @SarGe
Answer: From the given 3 points, we can always take any two of them (in this case, we take P(1, 2) and Q(1, -2) for some reason!) to construct an auxiliary circle (the green one) with PQ as diameter. Its equation is:-
$C' :(x-1)(x-1)+(y-2)(y+2)= 0$

Next, we take P and Q again to form a straight line whose equation is $L : x – 1 = 0$
L and C' form a system of lines. Its general equation for any line that passes through the intersection points is:-
$(x-1)(x-1)+(y-2)(y+2) + k(x – 1)= 0$; for some k.
Since the required circle C (the red one) will also pass through P and Q, then C is part of the system. The equation of C is then $(x-1)(x-1)+(y-2)(y+2) + k(x – 1)= 0$ for some suitable k.
We put $x = y = 0$ to find k because $(0, 0)$ is the third point of the required circle.

Circle equation through 2 points


Attaching workflow to node using rule

Question: Is there anyway I can set workflow dynamically using rule. Basically I need to setup workflow for given article only when someone flagged that article.
So can I setup some kind of rule that when an article is flagged, initialize workflow for that node and assign it to one of the workflow state?
-- Many thanks for your time.
Answer: Why not just set up a workflow that includes a default "no_workflow" state?  Use rules to automatically set all nodes to the "no_workflow" state upon creation.  Then, when a node is flagged, use rules to set it to the appropriate state.  That way, all nodes are subject to the workflow, but by default they don't move through the states until they are flagged.
Comment: But in that case a workflow tab would be still visible to the author. I don't want that tab to be shown when the article is not in the moderation state.
Comment: You could write a hook to hide the workflow tab when the node is in the "no_workflow" state.  I think that would be a lot easier to code than a rule that initializes a workflow arbitrarily when content is flagged.
Comment: Ok, I'll give a try. Thanks for your help and time.

Attaching workflow to node using rule


Para que serve o Microsoft Access?

Question: É uma pergunta idiota, eu sei.
Quase não tive contato com MS Access. Sei que é um banco de dados. Ele tem alguma coisa de especial? Alguma feature digna de nota? Como ele funciona? QuaIs demandas ele atende?
Comment: É tipo o "MS Paint", mas pra banco de dados.
Comment: Assim como toda ferramenta pode se tornar legado, eu creio que o MSAccess já é! Ele só deve "existir" ainda porque sistemas mais antigos talvez o usem, talvez ele tenha funcionalidades especificas, mas nem creio que este seja o motivo dele ainda ser usado eventualmente.
Comment: Ou seja, não perdi nada :D kthxbai
Comment: Não é uma pergunta idiota, embora possa ser negativada porque as respostas vão ser basicamente opinativas, como a minha o foi...
Comment: @epx eu acho interessante perguntas sobre coisas antigas, pq agrega conhecimento.
Comment: Kkkkk x 3 (15 caracteres de comprimento mínimo)
Answer: MS-Access é mais ou menos equivalente ao Excel e ao Word, mas para banco de dados.
Ele tem um formato próprio de banco (MDB) onde dados, telas, relatórios, programas, etc. ficam juntos. Mas ele também pode ser cliente de qualquer servidor de banco de dados via ODBC. Ou pode-se separar o banco num MDB e a aplicação noutro MDB.
Foi uma plataforma popular, que prometia muito, nos anos 90 para desenvolvimento de sistemas inteiros, pois é programável usando Visual Basic (que também é um fator de popularidade do Excel). Havia um pouco aquela ilusão na época que pequenos negócios poderiam desenvolver seus próprios sistemas sem o auxílio de um desenvolvedor profissional.
É uma ferramenta poderosa porém o Excel prevaleceu como ferramenta de administração de pequenos negócios, visto que também é scriptável e também pode ler bancos de dados, há inclusive um forte mercado secundário de planilhas e plugins Excel. O Excel também tem uma interface intuitiva (planilha eletrônica todo mundo conhece, bancos de dados nem tanto) e a curva de aprendizado é mais linear - em Access é fácil fazer coisas básicas, mas na hora que precisa de algo um pouquinho mais complexo, a coisa engrossa bem rápido.
Fora isso, a complexidade dos sistemas aumentou muito desde então - nos anos 90 um pequeno negócio tinha um computador, no máximo um punhado ligado via rede local, hoje em dia quando se fala "sistema" já se pressupõe acesso via Web, acesso remoto, alta disponibilidade, etc. etc. por menor que seja o negócio, então aquela ilusão de "faça-você-mesmo" ou de contratar o sobrinho para fazer sistema no fim-de-semana já não existe.
Comment: Fiz o que pediu, se quiser que eu expanda mais para outra direção, peço avisar.
Comment: Deu um feeling já do que era o MS Access... +1 e provavelmente vou aceitar. Só acho que faltou incluir um segundo parágrafo detalhando melhor a primeira frase da resposta.
Comment: vou aceitar mas não deixe de notar meu comentário logo acima. E obrigado pela resposta :)

Para que serve o Microsoft Access?


If $Df \equiv 0$, prove that $f$ is constant.

Question: Let $V$ and $W$ be finite-dimensional vector spaces, $U$ a connected open set in
$V$ , and $f : U \rightarrow W$ a differentiable function. If $Df \equiv 0$, prove that $f$ is constant.
If $a\not=b$, the line passing through $a$ and $b$ must contain a point $c$ where the derivative of the restriction $g$ of $f$ to that line parametrised by length along that line is $g'(c)=\frac{g(a)-g(c)}{a-b}$. If $D(f)=0$ everywhere, then $\displaystyle g'(c)$ is always $0$.
For any point $c$ in an open set, points $a$ and $b$ can be chosen in an arbitrarily small neighbourhood of  $c$ with the line between then passing through $c$, and since differentiable functions must be continuous, $g(a)=g(b)$ and hence $f(a)=f(b)$ everywhere in $V$. qed
I am trying to make sense of this proof, but I don't understand this line: derivative of the restriction $g$ of $f$ to that line parametrised by length along that line is $g'(c)=\frac{g(a)-g(c)}{a-b}$.
I understand that $g'(c)=\frac{g(a)-g(c)}{a-b}$ is from the MVT, but is $g$ of $f$ meaning the composition $g\circ f$? and what is meant by the restriction, also parametrized by length?
Answer: Here is another approach based on the same idea:
Pick $u_0 \in U$ and let $A = \{ u \in U | f(u) = f(u_0) \}$. Since $f$ is continuous,
$A$ is closed.
If $u \in A$, then $B(u,\epsilon) \subset U$ for some $\epsilon>0$ since $U$
is open. The main point here being that the ball is convex and contains all straight lines from $u$ to any point in the ball.
Choose $u' \in B(u,\epsilon)$ and let $p(t) = u+t(u'-u)$.
Now suppose $f(u) \neq f(u')$, then we can find a linear $g$ such that
$g(f(u)) \neq g(f(u'))$.
Define the function $\phi = g \circ f \circ p$ and note that
$D \phi(t) = g(Df(p(t)) (u'-u)) = g(0) = 0$, from which we get
$g(f(u)) = g(f(u'))$,
which is a contradiction. Hence $f(u) = f(u')$, and so $u' \in A$. Hence $B(u,\epsilon) \subset A$ and so we see that
$A$ is open.
Since $U$ is connected, it follows that $A=U$.
Comment: Thanks very much @copper.hat !
Comment: Hi, if you have time I have a few questions about your answer. 1. If $u \in A$, then $B(u,\epsilon) \subset A$ for some $\epsilon>0$ since $U$ is open. Why is this true at this point in the proof? $U$ is open means that we can find an open ball around any point of $U$, but why is the ball necessarily contained in $A$? Wouldn't the fact that we can find an open ball around any point of $A$ immediately imply that $A$ is open, which is what the bulk of the proof I have linked is about?
Comment: 2. Hence $f(u)=f(u')$, and so we see that $A$ is open. Why does this imply that $A$ is open? Doesn't this just imply that the point we started with is in $A$, which is what we assumed right at the beginning?
Comment: @GreenCoffee248 I had a typo, the $\subset A$ in the first comment should have been $\subset U$. I have rewritten the proof slightly, hopefully it is a little easier to follow.
Answer: Let a, b in $U \in R^n$, the line segment between a and b is a + t(b - a)/||b-a||, where $0\le t \le 1$.
Consider function $g(t) = f( a+ t (b -a)/||b-a||)$, we have g(0) = f(a), g(1) = f(b). There exists $t^*$, such that
$$\frac{g(1)-g(0)}{1 -0} = g'(t^*) = Df(a + t^*(b-a)/||b-a||)\dot (b - a)/||b-a|| = 0$$
Hence g(1) = g(0).
If you look at g(t), we used the line segement fron a to b, and a and b must be in the same open ball in U.
The final conclusion is from the compactness of path in U. For any two point x, y in U, you can have path from x and y. The path is compact.  And you can have a finte number of small open ball to cover the path, so it is the constant along the path.


Where to get samples of various PDF versions?

Question: I need sample PDFs of various versions (say 1.3 - 1.7) for testing purposes. Is there a place where I can download such samples?
Thanks!
Comment: I think the versions are somewhat 'incremental' so for example 1.4 is just a subset of 1.5. So If a PDF 1.5 doesn't have the "special features" of the 1.5 version vs the 1.4, then it will work even on an interpreter that only reads 1.4. As of the examples, I don't see where you can get them.
Comment: I'm testing a JVue customization and it behaves differently for 1.4 and 1.5
Comment: I ended up creating the samples myself using this PDF printer tool: http://www.bullzip.com/products/pdf/info.php. It supports version 1.1 through 1.5 and the A-1b preservation version
Answer: Most Adobe applications give you the option to select PDF version in their export. I have InDesign CS 5 now and it has 1.3-1.7.


How to denote that vector must have one non-zero entry.

Question: How to denote a vector of integers that contains one and only one non-zero entries.
Answer: Well, it is relatively common to let $e_i$ denote a unit vector that has $1$ in the $i$th position and $0$ everywhere else.  So with that notation, you can simply say that the intended vector is of the form $n e_i$ for some $i$, where $n \in \mathbb{Z}$.


What is the complex partial fraction decomposition of $\frac{1}{z^2 - z + 1}$

Question: I need this result to compute a residue. I haven't been successful so far.
What I have tried:
I have tried decomposing $\frac{1}{z^2 - z + 1} = \frac{A + Bi}{z - \omega} + \frac{C + Di}{z + \omega}$ where $\omega$ is the cube root of unity. I didn't get anything from this method.
Answer: By the quadratic formula the zeroes of $z^2-z+1$ are $\frac12(1\pm i\sqrt3)$, the two non-real cube roots of $1$. Let $\omega=\frac12(1+ i\sqrt3)$; the other root is $\overline\omega$, the complex conjugate of $\omega$. Then $z^2-z+1=$  $(z-\omega)(z-\overline\omega)$.
Now just set up the usual partial fractions computation:
$$\frac1{z^2-z+1}=\frac{u}{z-\omega}+\frac{v}{z-\overline\omega}\;,$$ so $u(z-\overline\omega)+v(z-\omega)=1$, and you have the system $$\left\{\begin{align*}&u+v=0\\&u\overline\omega+v\omega=-1\;.\end{align*}\right.$$ That ought to be pretty straightforward to solve.
Comment: +1 If it doesn't feel like cheating, you can also find the values of $u$ and $v$ by using l'Hospital's rule:
$$ u=\lim_{z\to\omega}\frac{z-\omega}{z^2-z+1}=\lim_{z\to\omega}\frac1{2z-1}\ldots$$
Comment: @Jyrki: Neat. I don't think that I've seen anyone do that before.
Answer: Hint 1 Given that the degree of the polynomial is $2$, it is fundamental that
$$z^2-z+1=(z-\alpha)(z-\beta)$$
Hint 2
$$\left\{\begin{align*}
&\alpha\beta=1\\
&\alpha+\beta=1
\end{align*}\right.$$
(Why?)
Hint 3
$$\frac{1}{(z-\alpha)(z-\beta)}= \frac{A}{(z-\alpha)}+\frac{B}{(z-\beta)}$$
for some $A$ and $B$.
Answer: An alternate starting point:
$$
1-z+z^2 = \frac{z^3+1}{z+1}.
$$


Run a function periodically in background mode in react native

Question: I want to make an api call to backend when the app is in background (closed) mode in react native.
Basically, the function should check for internet connection and then get some data from async storage , then make an api call to sync the data with the db.
I'm not familiar with native code.
Can anyone help me with how this can be achieved ? Any suggestions is appreciated.
Answer: There is no way to make API calls in the background for iOS devices as Apple Policy restrict developer to run tasks in background iOS.
So, If you are looking to make API calls in the background for Android devices.
Then you can use the below dependency to run API calls in the background.
React Native Background Fetch


A number theory puzzle

Question: I recently came across the following number theoretic puzzle. Suppose I've infinitely many cards, each with a natural number written on it. Given any $n\in \mathbb N$, the number of cards which have a divisor of $n$ written is exactly equal to $n$. I need to show that every natural number appears on at least one card. Any ideas on how to proceed?
Comment: Why is $n=1$ a problem? For $n=1$, since 1 is the only divisor of 1, we can conclude that 1 appears on (at least) 1 card. What's the problem?
Comment: Suppose $n=1$. 1 is the only divisor, so 1 appears on exactly 1 card. Please ignore the bracketed at least in my previous comment. 1 appears on exactly 1 card. For any other $n$, say $n=10$, note that 10 has the divisors 1,2,5 and 10. So, 1,2,5 and 10 together appear on 10 cards. For a prime $n$, say $n=5$, there are 2 divisors and 1 appears on exactly 1 card. So 5 (and actually, any prime $p$) appears on 4 ($p-1)$ cards. Now what?
Comment: I deleted my comment (because I didn't initially understand the question), but it still stands ($n = 1$ is always going to be a problem)...it must be removed, yes?
Comment: I'm trying to understand your constraint.  Given _any_ $n$, say $n = 1$, then the number of cards which have a divisor of $n$, say $n = 1$ (which will be every natural number), will be equal to $n$ (which would be $n = 1$ in this case).
Comment: Here's an example, let's say our set is $\{1,2\}$.  Let $n = 1$.  The number of cards which have divisors of $1$ are _both_ $1$ _and_ $2$ which means the number of cards which have divisor equal to $n = 1$ is $2 \neq 1$.  What am I missing here (I'm sure it's something).
Answer: You're looking for a function $f:\mathbb{N}\to\mathbb{N}$ such that $\sum_{d\mid n} f(d) = n$ for all $n$.
The key is that this determines $f(n)$ if you know $f(1), f(2), \ldots ,f(n-1)$ already.  So if you can find any $g$ that does the job, then $f=g$ follows from induction.  How to find such a function?
Hint #1: In a cyclic group with $n$ elements, how many elements of order $d$ are there?
Hint #2: How many $n$-th roots of unity are there?  How many of those are primitive $d$-th roots of unity?
Comment: Doesn't the totient function fit the bill?
Comment: Stated as in the first line, one can directly appeal to the Mobius Inversion formula to find $f(d)$. (Though that feels a bit like using a crane to crush a fly.)
Comment: Yes, definitely :D.
Comment: Got it, thanks. This $was$ easy, it seems. Just needed to prove the uniqueness part.
Comment: @Semiclassical You can, but how to show that the result is always positive?
Comment: It's more complicated than I realized, yes. Reading Wikipedia's page on the totient function, it looks like one can show that $f(n)=\sum_{d|n}\mu(n)n/d$ (the form obtained via Mobius) is equivalent to $\prod_{p|n}(1-p^{-1})$ which is Euler's product formula. Not exactly a trivial route!
Comment: @Semiclassical Ah yes.  I was going to suggest Dirichlet generating functions if we're looking for serious overkill.
Answer: I came up with the following formulae, not sure if they are entirely correct:
If i and p (here p is a prime and i is any integer) are coprime then #(ip) = (p-1).#i
Else, #(ip) = p.#i
Where, #k represents the number of cards with number k written on them.
For example, #(1) = 1, #(2) = 1 (in general for a prime q, #q = q-1)
Now assume that k is the smallest of the numbers that are absent on the cards. Basically we assume that for all i < k, #i>0. Now, there are three options for k:
1. k is a prime, in which case, #k = k-1 > 0; or
2. k is of the form, k = ip (p is a prime) where:
         2a. i and p are coprime. Then, #k = (p-1).#i > 0; or
         2b. p divides i. Then, #k = p.#i > 0; or
3. k= 1, where obviously #k = 1 > 0
Since in each case we have a contradiction, our assumption was invalid which means all integers are present at least once.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your answer.

A number theory puzzle


Cezaro mean convergence implies regular convergence outside of a rare set

Question: I have a bounded sequence of non-negative real numbers ($0 \leq a_i < C$), which Cezaro mean converges to $0$:
$$
  \lim_{n \to \infty} \frac{1}{n} \sum_{i=1}^{n - 1} a_i = 0
$$
How do I proof that $\exists J \subset \mathbb{N}$ such that
$$
  \lim_{i \to \infty, \ i \not\in J} a_i = 0
$$
and $J$ is rare, namely
$$
  \lim_{n \to \infty} \frac{|\{ k \ | \ k \in J, 0 \leq k < n \}|}{n} = 0
$$
My attempts to prove by contradiction turned out to be non rigorous. I suspect something from measure theory should be involved, but have no solid ideas.
Answer: Similar question was answered there.
It's possible to construct $J$, which has required properties from the original sequence $a_i$. Firstly:
$$
  I^k = \{i \ \big| \ i \in \mathbb{N}, \ a_i \geq \frac{1}{k} \}, \quad I_n^k  = I^k \ \cap \ [1;n) = \{i \ \big| \ i \in \mathbb{N}, \ i < n, \ a_i \geq \frac{1}{k} \}
$$
For fixed $k$:
$$
    \frac{|I^k_n|}{n} = \frac{k}{n} \cdot
    \sum_{i=1}^{n - 1} \left\{\begin{aligned}
        0, \quad \text{if} \; a_i < \frac{1}{k} \\
        \frac{1}{k}, \quad \text{if} \; a_i \geq \frac{1}{k}
    \end{aligned}\right\}
\leq k \cdot \frac{1}{n} \sum_{i=1}^{n - 1} a_i \underset{n \to \infty}{ \longrightarrow} 0
$$
It implies that $\frac{|I^k_n|}{n} \to 0$, ie for any $\varepsilon > 0$ exist $n_\varepsilon$, such that $\forall n \geq n_\varepsilon$ satisfies $\frac{|I^k_n|}{n}<\varepsilon$. For $k = 1, 2, ...$ choose $\varepsilon = \frac{1}{k}$ and denote $n_{\varepsilon}$ as $n_k$, $n_0 = 1$. $n \geq n_k \ \Rightarrow \ \frac{ | I^{k}_n  | }{n} < \frac{1}{k}$. $n_k$ may be choosen as nondecreasing. It is not bounded (or $a_i$ already has ordinary convergence). Then $J = \bigcup_{k = 0}^\infty \Big( I^{k+1} \ \cap \ [n_k; n_{k+1}) \Big)$ has the required properties. $a_i$ approaches zero outside of the set, because for any $\varepsilon > 0$ exists $m = n_{ \lceil1/\varepsilon\rceil}$ and all of the sequence members with indicies $i \geq m$ which are greater than $\varepsilon$ already lie in $J$.
$$
    J_n = J \cap [1; n) = \bigcup_{i = 0}^\infty \Big( I^{i} \ \cap \ [1;n) \ \cap \ [n_i; n_{i+1} \Big) =
    \bigcup_{i = 0}^{k(n)} \Big( I^{i}_n \cap [n_i; n_{i+1}) \Big) \subset I^{k(n)}_n
$$
$$
    \frac{|J_n|}{n} \leq \frac{|I_n^{k(n)}|}{n} \leq \frac{1}{k(n)}
$$
$k(n)$ increases to infinity with $n \to \infty$, then $\frac{|J_n|}{n} \to 0$.


How is it $\nabla.(\nabla u_2 \times \nabla u_3)=0$?

Question:
I think
Since $\nabla u_2 \times \nabla u_3=\dfrac{\vec{e_1}}{h_2h_3} ,$ then $ \nabla\cdot(\nabla u_2 \times \nabla u_3)=\dfrac{1}{h_1} \dfrac{\partial}{\partial u_1}\bigg(\dfrac{1}{h_1h_2} \bigg)$
but
How is it $\nabla\cdot(\nabla u_2 \times \nabla u_3)=0$ ?
Answer: Using the definition
$$
\nabla \cdot (A_1\mathbf{e}_1) = \frac{1}{h_1h_2h_3}\frac{\partial}{\partial u_1}(A_1h_2h_3)
$$
we can see that $A_1 = \frac{1}{h_2h_3}$
$$
\nabla \cdot (\frac{1}{h_2h_3} \mathbf{e}_1)  = \frac{1}{h_1h_2h_3}\frac{\partial}{\partial u_1}(\frac{1}{h_2h_3} \times h_2h_3)=\frac{1}{h_1h_2h_3}\frac{\partial}{\partial u_1} 1 = 0
$$
Comment: That is what I want to prove not a definition?
Comment: yes, but you are meant to use the definitions in the original question - plus you wrote down $\nabla \cdot (\nabla u_2 \times \nabla u_3)$ wrong compared with the definition at the start. Unless you want to prove $\nabla \cdot (A_1\mathbf{e_1})$?
Comment: we know only $\nabla u_2 \times \nabla u_3=\dfrac{\vec{e_1}}{h_2h_3}$
Comment: but you can see from definition (a) how  $\nabla u_2 \times \nabla u_3 = \frac{1}{h_2h_3}\mathbf{e_1} = A_1  \mathbf{e_1}$ should be treated.
Answer: This is a standard vector calculus identity:
$$
\nabla\cdot(\nabla f \times \nabla g) = (\nabla\times\nabla f)g - (\nabla\times\nabla g)f = 0.
$$
Answer: Here's a graphical derivation of the identity $\nabla\cdot(\nabla f\times \nabla g)=0$, following the notation in the fun paper Boosting Vector Calculus with the Graphical Notation.
In the following, the left-hand side represents $\nabla\cdot(\nabla f\times \nabla g)$, and to get the right-hand side we apply the product rule for the outer bubble.

We need the following identity:

This is a bubble swap (a change in the order of the variables of differentiation) followed by swapping the inputs of the cross product, which negates the expression.  Since this is saying the left-hand side diagram is negative of itself, it's equal to zero.
Going back to the original diagrams, we can see in the sum that the first term has this diagram with $h=f$ and the second has it with $h=g$, so both terms are zero. Therefore $\nabla\cdot(\nabla f\times \nabla g)=0$.

By the way, the first diagram with $h$ represents the following vector:
$$\sum_{i,j} \frac{\partial^2 h}{\partial u_i\, \partial u_j}(\mathbf{e}_i\times \mathbf{e}_j)$$
where $h$ is a function of $(u_1,u_2,u_3)$.  The graphical proof is that
$$\sum_{i,j} \frac{\partial^2 h}{\partial u_i\, \partial u_j}(\mathbf{e}_i\times \mathbf{e}_j) = - \sum_{i,j} \frac{\partial^2 h}{\partial u_j\, \partial u_i}(\mathbf{e}_j\times \mathbf{e}_i).$$
Answer: Using Levi—Civita symbol $\varepsilon^{ijk}$ (and assuming $\partial_i(\partial_jf) =\partial_j(\partial_if)$ and $\partial_i(\partial_jg) =\partial_j(\partial_ig)$) one can get
$$
\nabla\cdot(\nabla f \times \nabla g) = \varepsilon^{ijk}\partial_i (\partial_jf \partial_k g) = \underbrace{\varepsilon^{ijk}\partial_i(\partial_jf)\partial_kg}_0 + \underbrace{\varepsilon^{ijk}\partial_jf\partial_i(\partial_kg)}_0 = 0.
$$

PS. I used here the following trick (and the property $\varepsilon^{ijk} = -\varepsilon^{jik}$)
$$
\varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g =
\tfrac12 \varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g
+\tfrac12 \varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g =
\tfrac12 \varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g
+\tfrac12 \varepsilon^{jik}\partial_j(\partial_if)\partial_k g =
\tfrac12 \varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g
-\tfrac12 \varepsilon^{ijk}\partial_i(\partial_jf)\partial_k g = 0.
$$
Same with the term $\varepsilon^{ijk}\partial_jf\partial_i(\partial_kg)$.


Como coloco o valor de uma variavel em uma declaração de outra variavel?

Question: NomeDoProduto1 = str(input("Qual o seu primeiro produto? "))
NomeDoProduto2 = str(input("Qual o seu segundo produto? "))
NomeDoProduto3 = str(input("Qual o seu terceiro produto? "))
PrecoProduto1 = float(input("Digite o preço do")) print(NomeDoProduto1)

No código acima quero que na linha 4 que no print apareça a mensagem digite o preço do:(e aqui apareça o nome do primeiro produto). Tipo se na linha 1 eu disse que o nome do meu produto é açúcar então quero q na linha 4 apareça (digite o preço do açúcar).
desconsidere a linha 2 e 3 que e do meu código. estava tentando fazer assim porem da erro de sintaxe. sei que é um erro básico tbm.
Answer: Você pode fazer isso de múltiplas formas.
1) Concatenando as strings
Como você percebeu pode apenas concatenar as strings:
PrecoProduto1 = float(input("Digite o preço do:" + NomeDoProduto1))

2) Múltiplas chamadas de print sem quebra de linha
Você pode fazer chamadas diferentes à função print, mas definir que você não deseja adicionar a quebra de linha no final, que é adicionado por padrão no Python.
print('Digite o preço do: ', end='')
print(NomeDoProduto1, end='')
PrecoProduto1 = float(input())

Não recomendo... prefira a opção 3 sempre.
3) Interpolação de valores
A partir da versão 3.6 do Python existem as f-strings que permitem você fazer a interpolação de strings:
PrecoProduto1 = float(input(f"Digite o preço do {NomeDoProduto1}: "))

Perceba o prefixo f na string (por isso o nome f-string).
Mais informações:

https://pt.stackoverflow.com/a/264722/5878
O que utilizar para formatar uma string, % ou format?
Como concatenar multiplas Strings em Python?
Qual é a melhor forma de concatenar strings em Python?
Answer: Não sei se devo responder minhas perguntas, porem pesquisando aqui vi que é só colocar um "+" depois de fechar aspas e o nome da variável. tipo:
PrecoProduto1 = float(input("Digite o preço do:" + NomeDoProduto1))


How to use function NSLayoutConstraint.constraintsWithVisualFormat on Swift?

Question: I'm trying Swift and using layout format.
The IDE I'm using is Xcode6-Beta2.
<code>    var viewDictionary:Dictionary = ["myButton": myButton]

    var constraintFormat1:AnyObject[]! =
            NSLayoutConstraint.constraintsWithVisualFormat("H:|-[myButton]-|",
        options : NSLayoutFormatOptions(0),
         metrics: nil,
           views: viewDictionary)
</code>
But I got error message below.
<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unable to parse constraint format:
Unable to interpret '|' character, because the related view doesn't have a superview
H:|-[myButton]
              ^'
</code>
Doesn't it work on swift? Or I write wrong format pattern?
Comment: I think the error is quite clear... if `myButton` does in fact have a superview, try adding it to the `viewDictionary`
Comment: Are you adding the constraints to myButton or the superview of myButton?
Comment: I intend to add constraints to myButton.
Answer: The "|" (vertical bar) character refers to the superview of the view(s) you're declaring as inside of it (directly or indirectly) in this case "myButton". When you call .constraintsWithVisualFormat, it tries to implicitly find the superview of your button so it can create constraints between that view and your button. However, as your button has not yet been added to a view, it fails.
Comment: I should have written  self.addSubview(myButton) before adapt constraints.
Comment: I had had written self.addSubview(myButton) after constraints that does not work. Thanx!!
Answer: I had same problem, I checked in details , I was not adding subview to my superview , so it was complaining for
<code>" Unable to interpret '|' character, because the related view doesn't have a superview
H:|-[yourSubView]"
</code>
Make sure you called addSubview(youSubview) too.


How to add file extensions while creating a field (type file) through the module installer.yaml?

Question: I need to add 4 fields to an existing content type in Drupal 8 website, 2 of them is text another 2 is file type, I have a multisite setup and have 30 country-specific sites so I need to add for every locale site, Now I have created a module and created installer file, right now I am able to create the fields but I am unable to add the file extension to the file type field. can anyone please help with this?
I have followed this below documentation to create the filed.
https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type
Comment: Why can't you just add the fields in the interface, and then export configuration?
Answer: Really, that's a task for the Features module. And even if you decide against fully using Features in the end, you could at least use it locally to export your content type and fields and see in the resulting installer files how the allowed file extensions needs to be defined in your own module then. As Features exports its config into ready-made modules. But going for fully using Features also will enable you to constantly sync certain config (content types, fields, image styles etc.) pretty easily across all your multisite instances.

Take one of your multisite instances where you have the content type like you want it to be on all other sites.
Go through Features' UI and create a features module from it (that's called "package", usually that goes under /modules/features/my_package).
Activate the resulting package (module) on all other instances.

Leaving the Features module and your package module activated on all instances now allows you to sync all following changes to your content type by a certain set of commands:
# In the site_foo instance export changes into its package module.
drush -y features:export my_package -l site_foo

# In the site_bar instance import the changes.
drush -y features:import:all --bundle my_bundle -l site_bar

# In the end export config as usual.
drush -y config:export -l site_foo
drush -y config:export -l site_bar

To have a file field install sample yaml:
langcode: en
status: true
dependencies:
  config:
    - field.storage.paragraph.field_dlbox_files
    - paragraphs.paragraphs_type.dlbox
  module:
    - file
id: paragraph.dlbox.field_dlbox_files
field_name: field_dlbox_files
entity_type: paragraph
bundle: dlbox
label: Files
description: ''
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings:
  file_directory: paragraphs/dlboxfiles
  file_extensions: 'pdf doc docx'
  max_filesize: ''
  description_field: true
  handler: 'default:file'
  handler_settings: {  }
field_type: file


Como minificar o CSS/Javascript automaticamente no ASP.NET MVC5

Question: Utilizo o Visual studio 2017, minha aplicação roda em ASP.NET MVC5 (Razor), existe um modo de minificar todos os arquivos que eu escolher no momento do "publish" ?
Answer: Tem o Bundle do framework. Dentro do seu folder App_Start crie uma classe BundleConfig.cs e adicione:
public static void RegisterBundles(BundleCollection bundles)
{
    //para javascript, você pode fazer vários includes para o mesmo arquivo "scripts"
    bundles.Add(new ScriptBundle("~/bundles/scripts").Include("~/seuJs.js"));
    //para Css
    bundles.Add(new StyleBundle("~/Content/css").Include("~/seuCss.css"));

    //EnableOptimizations força a minificação mesmo em desenvolvimento, serve para fazer teste se esta minificado corretamente.
    //BundleTable.EnableOptimizations = true;
}

Depois é apenas registrar ele no seu Application_Start:
BundleConfig.RegisterBundles(BundleTable.Bundles);

No seu .cshtml é necessário mandar renderizar o javascript ou css:

    @Styles.Render("~/Content/css")

   @Scripts.Render("~/bundles/scripts")

Comment: Certinho ! obrigado


MYSQL Counting matching results across multiple tables

Question: I have the following tables
Business
    +-------------+--------------+------+-----+---------+----------------+
    | Field       | Type         | Null | Key | Default | Extra          |
    +-------------+--------------+------+-----+---------+----------------+
    | b_id        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
    | b_name      | varchar(255) | NO   |     | NULL    |                |
    +-------------+--------------+------+-----+---------+----------------+

Locations
    +-------------+--------------+------+-----+---------+----------------+
    | Field       | Type         | Null | Key | Default | Extra          |
    +-------------+--------------+------+-----+---------+----------------+
    | l_id        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
    | l_name      | varchar(255) | NO   |     | NULL    |                |
    | b_id        | big(20)      | NO   |     | NULL    |                |
    +-------------+--------------+------+-----+---------+----------------+

Jobs
    +-------------+--------------+------+-----+---------+----------------+
    | Field       | Type         | Null | Key | Default | Extra          |
    +-------------+--------------+------+-----+---------+----------------+
    | j_id        | bigint(20)   | NO   | PRI | NULL    | auto_increment |
    | j_name      | varchar(255) | NO   |     | NULL    |                |
    | b_id        | bigint(20)   | NO   |     | NULL    |                |
    | l_id        | bigint(20)   | NO   |     | NULL    |                |
    +-------------+--------------+------+-----+---------+----------------+

People
    +-------------+---------------+------+-----+---------+----------------+
    | Field       | Type          | Null | Key | Default | Extra          |
    +-------------+---------------+------+-----+---------+----------------+
    | u_id        | bigint(20)    | NO   | PRI | NULL    | auto_increment |
    | salutation  | varchar(10)   | NO   |     | NULL    |                |
    | first_name  | varchar(25)   | NO   |     | NULL    |                |
    | last_name   | varchar(25)   | NO   |     | NULL    |                |
    +-------------+---------------+------+-----+---------+----------------+

People's Jobs
    +-------------+------------+------+-----+---------+----------------+
    | Field       | Type       | Null | Key | Default | Extra          |
    +-------------+------------+------+-----+---------+----------------+
    | pj_id       | bigint(20) | NO   | PRI | NULL    | auto_increment |
    | u_id        | bigint(20) | NO   |     | NULL    |                |
    | j_id        | bigint(20) | NO   |     | NULL    |                |
    | l_id        | bigint(20) | NO   | MUL | NULL    |                |
    +-------------+------------+------+-----+---------+----------------+

I need to produce a table that shows
    +----------+-------------------------+------------+------------+------------+
    | b_id     | b_name                  | Locations  | Jobs       | People     |
    +----------+-------------------------+------------+------------+------------+
    |       21 | Widgets Inc             |          0 |          x |          0 |
    |       24 | Prince Privates         |          0 |          0 |          0 |
    |       23 | Halon plc               |          x |          0 |          0 |
    |       18 | Stinky Hotels           |          x |          x |          x |
    |       20 | Pylon Catering Corps    |          x |          x |          x |
    |       22 | Skytrain Biscuits       |          0 |          0 |          0 |
    +----------+-------------------------+------------+------------+------------+

I can achieve a correct count of matching locations for each business with:
SELECT b.b_id,
       b.b_name,
       count(l.l_id) AS locations
FROM business AS b
LEFT JOIN locations AS l ON b.b_id=l.b_id
GROUP BY b.b_id
ORDER BY b_name

If I extend it to include a count of the jobs at each business and then the count of people at each business it all goes pear shaped.
I know that the following is inherently wrong with regards to getting the count of people (as people can hold more than 1 job). I don't know if I need to use sub selects or COALESCE?
SELECT b.b_id,
       b.b_name,
       count(l.l_id) AS locations,
       count(j.j_id) AS jobs,
       count(p.u_id) AS people
FROM business AS b
LEFT JOIN locations AS l ON b.b_id=l.b_id
LEFT JOIN job AS j ON b.b_id=j.b_id
LEFT JOIN people_jobs AS p ON l.l_id=p.l_id
GROUP BY b.b_id
ORDER BY b_name

Answer: I think you can do a quick-and-dirty fix of your query by using count(distinct):
SELECT b.b_id, b.b_name,
       count(distinct l.l_id) AS locations,
       count(distinct j.j_id) AS jobs,
       count(distinct p.u_id) AS people
FROM business b LEFT JOIN
     locations l
     ON b.b_id = l.b_id LEFT JOIN
     job j
     ON b.b_id = j.b_id LEFT JOIN
     people_jobs p
     ON l.l_id = p.l_id
GROUP BY b.b_id
ORDER BY b_name ;

It is also possible that the problem is simply that the join to people_jobs needs more conditions:
     people_jobs p
     ON l.l_id = p.l_id and j.j_id = p.j_id

And maybe a condition on u.
Your problem is that you are trying to do aggregation across multiple dimensions and getting a cartesian product for each business.  An alternative that is sometimes necessary is to do the counts in subqueries.
Comment: Thank you for the reply. Adding distinct to the count() does seem to provide correct results. I am just checking this over now.
Comment: Yes, simply adding distinct to the counts does return correct results. Awesome. Thank you.
Answer: This query should do what you need:
SELECT
  b.b_id,
  b.b_name,
  (SELECT COALESCE(COUNT(l_id         ),0) FROM locations WHERE b_id=b.b_id) AS locations,
  (SELECT COALESCE(COUNT(j_id         ),0) FROM jobs      WHERE b_id=b.b_id) AS jobs,
  (SELECT COALESCE(COUNT(DISTINCT u_id),0)
     FROM jobs        j
     JOIN people_jobs pj ON pj.j_id=j.j_id
     WHERE j.b_id=b.b_id
  ) AS people
FROM business as b
ORDER BY b_name

You don't need the GROUP BY if you use subSELECTs, as the outer query will return 1 row per b_id, no more.
If instead you do JOIN the 4 tables at the main query level, like you were doing, you have two difficulties:

number of rows increases (avoidable with GROUP BY)
a simple COUNT does not work properly (avoidable with COUNT(DISTINCT
...))

(as shown in Gordon's answer)
Comment: Thank you Frazz, so would this be more efficient that what Gordon proposes?
Comment: I wouldn't be so sure. With subSELECTs you can only calculate 1 column per subSELECT. In this case the JOIN on jobs is executed twice within 2 distinct subselects. With Gordon's solution it is only joined once. But engines do cache and optimize, and indexes do have their importance. So I cannot really tell. You should try both on a significantly populated and indexed DB to understand and be sure of which is more efficient.
Comment: Thank you Frazz. At this moment I will accept Gordon's reply as it offers the path of least resistance. But, I do appreciate your reply.
Comment: His is a good answer. I posted mine not for the reputation, but because it is different. Efficiency depends a lot on the engine. I have used firebird for many years, and it was really good with subselects (i.e. it would not have executed that JOIN twice). But I am not sure about MySQL.
Answer: You can try This Query:-
SELECT b.b_id,b.b_name,count(l.l_id) AS locations,count(j.j_id) AS jobs,count(p.u_id) AS people
FROM business as b LEFT JOIN locations as l ON b.b_id=l.b_id
LEFT JOIN job as j ON b.b_id=j.b_id
LEFT JOIN people_jobs as p ON l.l_id=p.l_id
GROUP BY b.b_id, b.b_name
ORDER BY b_name

I hope this will work for you.
Comment: The COUNT without DISTINCT will not produce the desired output on that JOIN.


Normal Operators on Hilbert Spaces

Question: Let $H$ be a Hilbert space. An operator $T\in L(H)$ is said to be normal if $TT^*=T^*T$, where $T^*$ is the adjoint operator. I have to prove that $T$ is normal if and only if $||Tx||=||T^*x||$, for any $x\in H$.
I was able to solve it in the case when $H$ is complex, using the property $$Tx\cdot x=0,\forall x\in H\Longrightarrow T=0.$$ But this is not true in $\mathbb{R}^2$, for example. The rotation of $\pi/2$ would be a counterexample.
My question is: is this still true when $H$ is a real Hilbert space? Maybe there is another simple way of proving it, but I have not been able to figure that out.
Thank you!
Comment: Why is a rotation in $\mathbb{R}^2$ a counterexample? If $T$ is the matrix representing that rotation, $T^*T=I=TT^*$, and $\|Tx\|=\|x\|=\|T^*x\|$.
Comment: Oh no no no I meant that the rotation is a counterexample to the property right above it! $Tx\cdot x=0$ implies $T=0$! Sorry if I was not clear
Answer: Suppose that $H$ is a real Hilbert space $TT^*=T^*T$, $\langle T(x),T(x)\rangle=\langle T^*T(x),x\rangle=\langle TT^*(x),x\rangle=\langle T^*(x),T^*(x)\rangle$.
On the other hand, suppose that $\|T(x)\|^2=\|T^*(x)\|^2$. You have
$2\langle x,y\rangle =\|x+y\|^2-\|x\|^2-\|y\|^2$. This implies that for every $x,y\in H$,
$\|T(x)+T(y)\|^2-\|T(x)\|^2-\|T(y)\|^2=\|T^*(x)+T^*(y)\|-\|T^*(x)\|-\|T^*(y)\|$
$=2\langle T(x),T(y)\rangle=2\langle T^*(x),T^*(y)\rangle$. We deduce that $\langle T^*T(x),y\rangle=\langle TT^*(x),y\rangle$ for every $y\in H$ and henceforth $T^*T=TT^*$.

Normal Operators on Hilbert Spaces


ROC vs Precision-recall curves on imbalanced dataset

Question: I just finished reading this discussion. They argue that PR AUC is better than ROC AUC on imbalanced dataset.
For example, we have 10 samples in test dataset. 9 samples are positive and 1 is negative. We have a terrible model which predicts everything positive. Thus, we will have a metric that TP = 9, FP = 1, TN = 0, FN = 0.
Then, Precision = 0.9, Recall = 1.0. The precision and recall are both very high, but we have a poor classifier.
On the other hand, TPR = TP/(TP+FN) = 1.0, FPR = FP/(FP+TN) = 1.0. Because the FPR is very high, we can identify that this is not a good classifier.
Clearly, ROC is better than PR on imbalanced datasets. Can somebody explain why PR is better?
Comment: Precision, recall, sensitivity, and specificity are improper discontinuous arbitrary information-losing accuracy scores and should not be used.  They can be especially problematic under imbalance.  The $c$-index (concordance probability; AUROC) works fine under extreme balance.  Better: use a proper accuracy scoring rule related to log-likelihood or the Brier score.
Comment: @DavidMWPowers, why not turn that into an official answer? That seems like a very informative response to me.
Comment: Precision and Recall both ignore False Negatives. The usual justification for using PR tradeoff (curves or F-score) is that the number of Negatives and False Negatives is huge relative to TP and FP. So TNR->1 and FPR->0 (sum to 1 with same |Negs| denominator). So PR in this case does reflect (amplify or zoom in on) the trade off TP vs FP, but this is *not* meaningful and what is relevant is an increase in the Youden J index (Informedness=TPR-FPR=TPR+TNR-1=Sensitivity+Specificity-1) which corresponds to twice the area between the triangular single operating point curve and the ROC chance line.
Comment: Your example is artificial, so perhaps you do not realize that it is fundamentally flawed and so probably muddies the clarity of the question. In real life, the minority class is almost always the positive class, not the majority class (we seek to explain exceptions). So, you cannot have 9 positives and 1 negative; you would have 1 positive and 9 negatives. If you reframe the question with that adjustment, then it should be clearer why ROC is not so helpful with your example scenario: TP = 0, FP = 9, TN = 9, FN = 1. Then Precision = 0 and Recall = 0. Clearly a horrible performance.
Answer: First, the claim on the Kaggle post is bogus. The paper they reference, "The Relationship Between Precision-Recall and ROC Curves", never claims that PR AUC is better than ROC AUC. They simply compare their properties, without judging their value.
ROC curves can sometimes be misleading in some very imbalanced applications. A ROC curve can still look pretty good (ie better than random) while misclassifying most or all of the minority class.
In contrast, PR curves are specifically tailored for the detection of rare events and are pretty useful in those scenarios. They will show that your classifier has a low performance if it is misclassifying most or all of the minority class. But they don't translate well to more balanced cases, or cases where negatives are rare.
In addition, because they are sensitive to the baseline probability of positive events, they don't generalize well and only apply to the specific dataset they were built on, or to datastets with the exact same balance. This means it is generally difficult to compare PR curves from different studies, limiting their usefulness.
As always, it is important to understand the tools that are available to you and select the right one for the right application. I suggest reading the question ROC vs precision-and-recall curves  here on CV.
Comment: @skan you should ask this as a new question.
Comment: What if we have used weights or a cost matrix to compensate the imbalance? Will it be still be preferred to use the AUC PR?
Or using weights or a cost matrix it's enough and then we can use the AUC ROC curve or even the Accuracy as a metric to optimize our model?
Answer: Your example is definitely correct.
However, I think in the context of Kaggle competition / real life application, a skewed dataset usually means a dataset with much less positive samples than negative samples. Only in this case, PR AUC is more "meaningful" than ROC AUC.
Consider a detector with TP=9, FN=1, TN=900, FP=90, where there are 10 positive and 990 negative sample. TPR=0.9, FPR=0.1 which indicates a good ROC score, however Precision=0.1 which indicates a bad PR score.
Answer: You're half way there.
Usually when I do imbalanced models, heck, even balanced models, I look at PR for ALL my classes.
In your example, yes, your positive class has P = 0.9 and R = 1.0. But what you should look at are ALL your classes. So for your negative class, your P = 0 and your R = 0. And you usually don't just look at PR scores individually. You want to look at F1-score (F1 macro or F1 micro, depending on your problem) that is a harmonic average of your PR scores for both class 1 and class 0. Your class 1 PR score is super good, but combine that with your class 0 PR score, your F1-score will be TERRIBLE, which is the correct conclusion for your scenario.
TL,DR: Look at PR scores for ALL your classes, and combine them with a metric like F1-score to have a realistic conclusion about your model performance. The F1-score for your scenario will be TERRIBLE, which is the correct conclusion for your scenario.
Answer: Using ROC can miss the low precision where FP > TP because ROC only look at TPR and FPR. I think what we need to ask is:

Will FP > TP happen with your data and the model.
Does FP > TP matter for your business problem.

If the answer is yes for both, then ROC only is not fit for use.

If the problem is identifying shoplifters and FP will alarm the police. Almost all the shop customers are honest, then catching more honest customers as shoplifters than real ones will cause angry customers and police. Then looking at only ROC will not be a good idea to measure the model.
If the problem is identifying potentially fatal food for toddlers, FP > TP may not be a big issue because there will be so many safe food (TN) as long as TPR is really high. Then ROC will be fit for use to measure the model.
FP: False Positive
TP: True Positive
FPR: False Positive Rate
TPR: True Positive Rate

Suppose I am running a risky loan business where majority of the customers are risky. If I evaluate the business performance with ROC only, I think the performance is good because TPR is high and FPR is low, although actually the business is losing money because of FP > TP. By looking at PR, it will tell the low precision and I will understand the business performance is bad as I am looking money.


htacess hide the redirect from browser

Question: I've tried all suggestions here and else where but I can't hide the redirect from a .htacess rewrite rule. My full .htaccess is:
RewriteEngine On    # Turn on the rewriting engine
RewriteBase         /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^classes/(.+)?$ index.php [L]

#shop
RewriteRule         ^shop/(sector1|sector2|sector3|sector4)/([A-Za-z0-9-]+) shop?site=$1&category=$2 [NC]
RewriteRule         ^shop/(sector1|sector2|sector3|sector4)/$                   shop?site=$1 [NC,L]

Mose of the advice I've gotten is to remove [r=301] but I've never had that flag there. No matter what I try example.com/shop/sector1 always displays as example.com/shop?site=sector1 any help appreciated
[edit] I'm running this on localhost as a virtual host. Mac OS 7.5, Apache 2.2.26
[edit] Also from the doc root there are other .htaccess files, but none in the 'shop' folder with the above rewrite is supposed to effect.
$ find . -name .htaccess
./.htaccess
./assets/images/.htaccess
./cms/.htaccess
./cms/assets/images/.htaccess
./cms/assets/plugins/ckfinder/userfiles/.htaccess
./cms/modules/default_images/.htaccess
./sagepay/VspPHPKit/demo/.htaccess
./sagepay/VspPHPKit/lib/.htaccess
./uploads/.htaccess
./uploads/products/.htaccess

Also my directory structure is (notice that my redirect shop is an actual folder - could this be part of the issue?):
$ tree -d -L 1 ./
./
├── assets
├── classes
├── cms
├── contact
├── foo
├── news
├── page
├── products
├── sagepay
├── sample
├── search
├── services
├── shop
├── snippets
├── uploads
└── widgets

Answer: Missing trailing slash in your rewritten URI after shop is the problem since it is a real directory and Apache's mod_dir will do a 301 redirect to add trailing slash to make /shop/ and that will make final URL as: example.com/shop/?site=sector1
Also better to change order of your rules and make sure to use L flag at the end of each rule:
RewriteEngine On
RewriteBase  /

RewriteRule ^shop/(sector1|sector2|sector3|sector4)/([A-Za-z0-9-]+) shop/?site=$1&category=$2 [L,QSA,NC]
RewriteRule ^shop/(sector1|sector2|sector3|sector4)/$ shop/?site=$1 [NC,L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^classes/ index.php [L,NC]

Also I suggest you to test your rule in a separate browser.
Comment: no joy with either of those suggestions. I'm really starting to think it must something in my apache conf. Also I'm running this on localhost as a virtualhost
Comment: Do you have other rules in this .htaccess OR any other .htaccess e.g. `/shop/.htaccess`
Comment: I saw your edit, so nothing in .htaccess other than above suggested rules of mine?
Comment: nope thats it. Also everytime it rewrite the network in chrome tools shows `301 moved permanently` I've tried clearing the cache
Comment: Try updated code now. I think missing slash in rewritte URI after `shop` was the problem since it is a real directory.
Comment: your a genious ;) viola cest ca - that was the problem. Needed `shop/?x=y` instead of `shop?x=y`. I'll allow you rewrite your answer before I click the tick ;)
Answer: This might sound really dumb but it caught me out many moons ago. Given that your code looks fine to me it leads me wonder...
When I found this happening myself, it turned out that all my href attributes were actually the after-redirect address! E.g. double check that your href attributes are example.com/shop/sector1 and not example.com/shop?site=sector1.
Otherwise something else might be interfering. Do you have any other code in your htaccess? Any PHP redirecting etc?
Comment: wish it was that simple lol - same issue even when I manually type into the address bar
Comment: Ah well. It was worth a shot!

htacess hide the redirect from browser


Como fazer um subset em uma série do tipo zoo escolhendo certos anos ou meses?

Question: Eu tenho a seguinte série:
library(zoo)

zoo_serie <- zoo(1:length(seq.Date(as.Date("1991-12-01"),as.Date("1998-12-31"),'day')),seq.Date(as.Date("1991-12-01"),as.Date("1998-12-31"),'day'))

Quero fazer um subset para os anos de 1991, 1995 e 1997, como faço isso de forma ágil?
Atualmente eu crio uma série de datas e depois faço o index na série, isso não se torna viável para séries enormes.
zoo_serie[index(zoo_serie) %in% vetor_de_datas]

Queria algo como assim:
zoo_serie[year(index(zoo_serie)) %in% c(1911,1995,1997)]

Mas não funciona. Da mesma forma queria para meses específicos, essa forma ainda não consegui.
Comment: A função `year` do pacote `lubridate` faz exatamente isso. O pacote tem mais funções para extrair meses, dias e outras informações de datas.
Comment: @jorge-mendes, coloque isso como uma resposta.
Answer: Como indicado por @jorge-mendes nos comentários, o pacote lubridate tem vária funções para trabalhar facilmente com datas e faz exatamente o que deseja. Vou usar um exemplo menor que o seu para facilitar a visualização:
library(zoo)
library(lubridate)

datas <- as.Date(c("1991-03-23", "1992-05-28", "1994-03-07", "1995-11-14", "1996-07-23"))
zserie <- zoo(seq(length(datas)), datas)

anos.sel <- c(1991, 1995, 1996)

zserie[year(index(zserie)) %in% anos.sel]
#> 1991-03-23 1995-11-14 1996-07-23
#>          1          4          5

zserie[month(index(zserie)) == 3]
#> 1991-03-23 1994-03-07
#>          1          3

Pode-se também usar expressões regulares:
zserie[grep(paste(anos.sel, collapse = "|"), index(zserie))]
#> 1991-03-23 1995-11-14 1996-07-23
#>          1          4          5

zserie[grep("-03-", index(zserie))]
#> 1991-03-23 1994-03-07
#>          1          3

Comment: +1 pelo extra das expressões regulares


Is this invalid &(*_shmItr) == NULL where _shmItr is an List iterator

Question: &(*_shmItr) == NULL

this is quite noob question but, I m newbie to C++.
in GCC 3.1.2 when you check _shmItr == NULL is perfectly fine, but as GCC 4.2.2
this is an error. I did google about the error. they says dereferencing and referencing again will solve the problem. and It did. I was happy. But as I m learning more about iterator. I feel may be this is passing the error, but not valid and can give runtime problem.
What is your suggestion to me ...
I did little research and found that
_shmItr == _shmItr.end()

Also serves the same purpose and more correct. please correct me if I m wrong.
basically we are trying to check if _shmItr is holding something invalid or not. before doing any operation.
Thanks in advance.
Here is the code chunk
_shpmtItr = _shpmtList.begin();

if(_shpmtItr == NULL)
{
   eaLogMsg << setid("APP_FAILED")
            << "_shpmtItr is NULL in some::few()"
            << endl;

   return APP_FAILURE;
}

This can tell you the scenario.
static
Comment: Iterators are a different, more general concept than pointers. An iterator may be implemented as a pointer, but you should never rely on that being so.
Answer: Definately use list::end if you're checking to see if you've passed to the end of the list.  There's no guarantee that the next item after you've traversed every element in a list will be NULL.  It won't tell you if the item your pointer points to is valid.  Here's the way I'd use list::end if I were checking to see if my results were valid or not:
list<whatever>::iterator item = find( myList.begin(), myList.end(), value );
if( item != myList.end() )...

Because find returns the last item in the range you've given it to search on if no element exists.
That said, when you do &(*something) what you're doing is getting the address of the element the iterator points at which is perfectly valid code.  If you expect that the invalid items are going to be NULL then it works for your purposes.  If you don't know if they'll be NULL, that is another story.
So what code are you using?  Perhaps that could help us answer your question better.
Edit:
Looking at your code and seeing you use list::begin() and then checking it against NULL is bad unless your list is a list of pointers (or pointer like objects such as shared_ptr.)  I'd actually recommend you use list::empty to see if the list is empty rather than myList.begin() != myList.end().  The meaning of that is crystal clear and should be easier to maintain in the future.


Why use Yeoman's generators instead of Maven's archetypes?

Question: I noticed that Yeoman's generators are more focused on client-side code generation, whereas Maven's archetypes are on server-side. But I still do not fully understand why it was necessary to create Yeoman, if Maven copes well with code generation task?
I suppose, it is possible to write a Maven's archetype, for example, for Angular JS, and use it instead of analogous popular Yeoman's generator. But there is no such archetype, or at least it is much less popular.
So, please tell me why?

My guess on this occasion turned out not true.
I thought that Maven is not able to generate components inside existing projects. But this is not true. I found that an optional <allowPartial>true</allowPartial> tag makes it possible to run the archetype:generate even on existing projects.
Thus without your help, I can not answer this question quickly.
Comment: I wondered the same thing, i think its because people working on JavaScript projects didn't want to install Java & Maven just to generate code. So they decided to use a generator that would run on tools they already had installed such as node.
Comment: Believe in yourself, you can always answer your questions. You just have to be patient and do the work :)
Comment: Of course, but I meant to do it quickly :) I think that the community, among other, serves this purpose.
Comment: There is no such thing as 'it is necessary', it is determined by the use case. Both can generate projects from templates, and it's all up to the template. Check http://blog.akquinet.de/2011/02/11/mavenizing-javascript-projects/
Answer: Maven and Yeoman are both code generators using templates. It is up to template what code will be generated. Therefore both can be used to generate client-side and server-side projects.
Below points may explain why each tool is popular in one area, but not the other:
1. People are using tools that are popular inside their language ecosystem
One reason is that developers mostly use tools from ecosystem of language they are developing code in. Yeoman is code generator used mostly in client-side project, because that's where JavaScript is used most of the time. Maven is used mostly in server-side project, because that's where Java is used most of the time.
2. Tools from other environments needs that environment
Running Maven on purely JS project would demand installing Java to use it. Yeoman on the other hand can be run using Node.js. Java would be unnecessary dependency for developer. Vice versa is also true.


PHP - usando isset e GETs

Question: Boas gente,
Eu tenho estes 4 Gets para recolher, os mesmos saem de outra pagina.
O que pretendo é...
"Se apanhar($_GET) order, preço, comprador" {

    mostra valores do $_GET...

} else {

    erro.
}

Como faço isso?
Será assim?
if(isset($_GET['order'] || isset($_GET['preco'] || isset($_GET['comprador']) {

ou assim
if(isset($_GET['order'] AND isset($_GET['preco'] AND isset($_GET['comprador']) {

Comment: Precisa de todos válidos ou um só?
Comment: preciso de todos validos
Answer: O isset() não é uma função é um construct language, ele possui uma diferencial que é passar N argumentos de entrada. Dessa forma a validação é feita em todos os argumentos se um deles não for válido isset() retorna false. É o equivalente a conectar N condição com o operador E lógico (&&)
Pode deixar seu código:
if(isset($_GET['order'], $_GET['preco'], $_GET['comprador'])){
   echo 'válido';
}else{
   echo 'inválido';
}

O código abaixo é equivalmente ao primeiro.
if(isset($_GET['order']) && isset($_GET['preco']) && isset($_GET['comprador'])){

Comment: Perfeito! Acho que só para usuários iniciantes seria legal dizer algo como isso *"`isset(..,..,..)` equivalete a isto `isset(...) && isset(...) && isset(...)`"*, mas já deixo o +1
Answer: O correto seria...
if( isset($_GET['order']) && isset($_GET['preco']) && isset($_GET['comprador']) )
  echo 'os 3 existem';
else
  echo 'os 3 não existem';

Pode trocar o && por AND sem problemas.
Comment: Ok, fico muito agradecido pela ajuda. :D Obrigado...
Answer: Há uma outra forma também, é utilizar o array_diff que vai verificar exatamente os campos
<?php

$obrigatorios = ["order", "preco", "comprador"];

if (!array_diff($obrigatorios, array_keys($_GET))) {
    echo "mostra valores do GET...";
} else {
    echo "Erro";
}

Ou você pode utilizar array_diff_assoc
<?php

$obrigatorios = ["order", "preco", "comprador"];

if( !array_diff_assoc($obrigatorios, array_keys($_GET)) ) {
    echo "mostra valores do GET...";
} else {
    echo "Erro";
}

https://ideone.com/JwpTh1
Comment: @Francisco Se `$_GET` possuir **exatamente** as três chaves, a função `array_diff` retornará um *array* vazio, que é um *falsy value*, isto é, considerado falso quando tratado numa operação booleana. Como foi usado o `!`, o valor passa a ser verdadeiro.
Comment: Dito isso, essa é uma limitação nesta solução que deveria estar explícita na resposta: se houver outras chaves, o código indicará erro, mesmo se os três valores desejados existirem.
Comment: Qual das formas aqui apresentadas é a mais segura para passar dados?...
Comment: Todas elas tem o mesmo nível de segurança. O que pode ser testado é a performance de cada, mas mesmo assim, a diferença provavelmente é irrisória.
Comment: Na doc do php diz que o `array_diff` retorna um array, por que a validação funciona?
Comment: @Silva é basicamente com o @AndersonCarlosWoss mencionou, mas para contornar isso você pode utilizar o `array_diff_assoc`

PHP - usando isset e GETs


Horário de verão no Jenkins

Question: Tenho uma instância do Jenkins rodando em um Windows Server 2016 e este servidor está com o hora correta.
Tenho algumas jobs configuradas para rodar com hora especifica, porém elas estão rodando um uma hora adiantada, como se tivesse com horário de verão ainda.
Nas configurações do Jenkins tenho o seguinte:
user.timezone:America/Sao_Paulo

Alguém teve o mesmo problema e conseguiu resolver?
Answer: Jovens, resolvi o problema atualizando os timezones da JDK usando o TzUpdater.
Realmente o problema não está no Jenkins e sim na sua JDK.
Segue link:
https://www.oracle.com/technetwork/java/javase/downloads/tzupdater-download-513681.html
Faça download do TzUpdater e rode no seu servidor que tem o Jenkins:
java -jar tzupdater.jar -l

Answer: Galera, no meu caso, a solução acima não funcionou, não consegui utilizar o TzUpdate (não sei por qual motivo, provavelmente limitação do proxy da empresa), mas consegui achar outra solução para que possa ser tentada também.
Basta atualizar o java da máquina e desinstalar as versões antigas. Quando realizei este processo consegui corrigir o problema do horário errado no meu Jenkins.
Comment: Também é possível baixar o TzUpdater fora do seu proxy, coloca-ló em algum servidor (IIS por exemplo) e indica-lo caminho no parametro -l.
Comment: @BrunoWarmling Mesmo baixando por fora e tentando passar por parâmetro na minha máquina não estava conseguindo atualizar, tentei de todas as formas porém sem sucesso
Comment: Mas qual motivo de não ter funcionado?
Comment: Ele não conseguia realizar a atualização do TZUpdate, possivelmente por que meu usuário não possuí permissão de ADM da máquina...
Já a instalação do Java era feita via Portal então foi possível atualizar.

Horário de verão no Jenkins


taxonomy cck pathauto

Question: Can anyone tell me how to set the taxonomy in the following order

super Category---eg(Area)
Category--- eg(food)
sub category --- eg(fruits)

if a visitor chooses a super category area, then the fruits in that area should be shown
 And the path should be http://www.example.com/supercategory/category/subcategory/apple.php
Comment: You don't seem to be asking your question coherently.  If a vistor chooses a super category, shouldn't it show what foods (category) are available there, not what fruits (subcategory)? In any case, you need to investigate the menu() hook and all of its %wildcards.
Comment: thanks, Actually my need is exactly like for example, in ecommerce site when a visitor changes the country, the price and the products are changed. likewise, in my suituation when a visitor chooses a area, the product and prices will be changed.
Comment: i am sorry, you are right, when a visitor chooses a super category,then we should show the category and then the fruits...
Comment: I agree with jimajamma. You question is rather incoherent in it's current state. From it, I get two questions. 1. How do I set up Conditional Display of taxonomy lineage for users to select? 2. How do I set pathauto to use the taxonomy lineage in the URL structure?
Comment: also, you do not specify whether you are using D6 or D7?
Comment: You cant set path like that. You need to specify various vocabulary to gain such a path.
Answer: It seems that you're asking more than one question, but let me try and address the paths one. If you organise your taxonomy to be hierarchical then using the token [catpath-raw] will give you the path you require.

taxonomy cck pathauto