text:
Q: Given iid random variables, expected number of times that a random variable is greater than all previous variables. I'm given $X_1, X_2, \dots$ iid with continuous cdfs, and let $A_1 = \Omega, A_n=\{\omega:X_n
(\omega) > X_i(\omega) \textrm{ for } i < n\}$.
I'd like to show that $\lim_{n\rightarrow \infty}{\frac{1}{\log(n)}\sum_{j=1}^{n}{1_{A_j}}} = 1$ almost surely.
This is a pretty interesting result, but I'm pretty unsure of how I might go about showing this.

A: Let me briefly sketch a proof. The first step should be to note that the $A_n$'s are independent and  $\mathsf{P}(A_n)=1/n$ for all $n$ (do you see why?). From Kolmogorov's inequality, for any $\epsilon>0$
$$\mathsf{P}\left(\max_{2^{n^2}\le k\le 2^{(n+1)^2}} \left|\sum_{j=1}^k \left(1_{A_j}-1/j\right)\right|> \epsilon n^2\right)\lesssim \frac{1}{\epsilon^2 n^2}.$$
Now we use Borel-Cantelli lemma to argue that almost surely, for $n$ large enough
$$\left|\sum_{j=1}^n \left(1_{A_j}-1/j\right)\right|\le \epsilon\log n.$$
What we just proved is
$$\forall \epsilon>0, \mathsf{P}\left(\exists n_0(\epsilon), \forall n>n_0(\epsilon), \left|\frac{1}{\log n}\sum_{j=1}^n 1_{A_j}-\frac{1}{\log n}\sum_{j=1}^n 1/j\right|\le \epsilon\right)=1.$$
As the intersection of a countable number of almost sure events is almost sure,
$$\mathsf{P}\left(\forall \epsilon\in\mathbb{Q}_+^*, \exists n_0(\epsilon), \forall n>n_0(\epsilon), \left|\frac{1}{\log n}\sum_{j=1}^n 1_{A_j}-\frac{1}{\log n}\sum_{j=1}^n 1/j\right|\le \epsilon\right)=1.$$
Now notice that if we take $n_0(\epsilon)$ large enough, from the asymptotics of the harmonic sum, it holds that for all $n>n_0(\epsilon)$, $\left|\frac{1}{\log n}\sum_{j=1}^n 1/j-1\right|\le \epsilon$. Hence:
$$\mathsf{P}\left(\forall \epsilon\in\mathbb{Q}_+^*, \exists n_0(\epsilon), \forall n>n_0(\epsilon), \left|\frac{1}{\log n}\sum_{j=1}^n 1_{A_j}-1\right|\le 2\epsilon\right)=1.$$
That's exactly the definition of almost sure convergence of $\sum_{j=1}^n 1_{A_j}/\log n$ to $1$.


text:
Q: Get AsyncFunction constructor in Typescript So I'm trying to dynamically create AsyncFunctions in a Typescript Program. MDN says that I can get the AsyncFunction constructor by
var AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;

but typescript compiles this to
var AsyncFunction = Object.getPrototypeOf(function () {
    return __awaiter(this, void 0, void 0, function* () { });
}).constructor;

The difference can be seen by simply attempting to use the constructor;
new AsyncFunction("return 1;")();

returns a Promise (what I need) when run in Firefox, but simply returns a 1when run after being passed through typescript.
How can I stop Typescript from mangling my async functions?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is "dabble in" the proper word in this case? I am writing my statement of purpose for my Ph.D. application. As you may or may not know, the candidates mainly elaborate on their research experience in the statement of purpose. My intended Ph.D. field is field_A, but I do have some experience in field_B, which I would also like to mention.
In such a case, can I say "I dabbled in field_B" and then elaborate on this experience? Will  "dabble in" here carry a negative connotation, something like "playing around"?

A: Dabble can have a negative connotation, depending on the circumstances

Take part in an activity in a casual or superficial way:
  he dabbled in writing as a young man [Oxford Dictionaries Online]

While a person may use the term in a self-deprecating way, even when they have some meaningful measure of skill, in a formal setting the term suggests that your exosure to the alternate field was trivial.
You could simply say something like

While my work has focused on field A, I also have some experience in field B.


text:
Q: Hello, I am facing problems with my code, I am attaching the code as well as the error output I am receiving the code-
def minimum(n):
    L = []
    for i in range(n):
        x = eval(input("enter number 1:"))
        y = eval(input("enter number 2:"))
        if x or y== "\n":
            print("please enter valid value")
        l = [x,y]
        L.append(l)
    print("input keyset-",L)
    for i in range(n):
        if L[i][0] < L[i][1]:
            r = L[i]
            print("FIRST","\t",r)
        elif L[i][0] == L[i][1]:
            r = L[i]
            print("ANY","\t",r)
        else:
            r = L[i]
            print("SECOND","\t",r)

print(minimum(4))

I was getting this error-
Traceback (most recent call last):
  File "c:\Users\Ban\Documents\BAANI\code s 1.py", line 22, in <module>
    print(minimum(4))
  File "c:\Users\Ban\Documents\BAANI\code s 1.py", line 5, in minimum
    y = eval(input("enter number 2:"))
  File "<string>", line 0

SyntaxError: unexpected EOF while parsing

A: I tried running your code and inputting 1, 2, etc... and it worked fine, so the issue is likely caused by your input. However, your code has some issues :

*

*In order to convert the string returned by input, you use eval. This is a really bad idea, as what eval does is interpret its argument as Python source code, and return the result. What you want to do is way simpler than that, you just want to convert a string to a number. Instead of eval(input("enter number 1:")), you should use float(input("enter number 1:")). I can't be 100% sure, but I guess that your use of eval is what causes your issue

*For (I guess) checking that the inputted values are non-empty, you use :
if x or y== "\n":
This is interpreted as "if x is true or y is a newline character". This is not at all what you want! Since x and y are outputs of eval, you don't know what their type will be, and if using the program correctly, they likely won't be strings, so the comparison to a given string is going to be False (side note: input trims the trailing \n, so when checking for emptiness of an input string, you should use if x == "": or just if not x:)

*After checking if the input is correct, even if the input is invalid, you go along and use it. You should instead use a while loop

*Finally, when iterating over L, since you only care about L[i] (and not i per se), you should use for elt in L (elt being the L[i] you used)
With all this, I would rewrite your code to this:
def minimum(n):
    L = []
    for i in range(n):
        while True:
            try:
                x = float(input("Enter number 1:"))
                y = float(input("Enter number 2:"))
            except ValueError:
                print("Please enter valid value")
            else: break

        L.append([x, y])

    print(f"Input keyset: {L}")
    for elt in L:
        if elt[0] < elt[1]: print("FIRST","\t", elt)
        elif elt[0] == elt[1]: print("ANY","\t", elt)
        else: print("SECOND","\t", elt)

minimum(4)

A: you have:
 if x or y== "\n":
       print("please enter valid value")

which always evaluates to True
if x or if y == '\n'
True or False = True --> print (enter valid value)
it'll only evaluate to False if both entries are empty, which is not what you want.
what you want to do is:
 if x =='\n' or y== "\n":
        print("please enter valid value")

also eval(input("enter number 1:")) will throw an exception when sent an empty string '', '\n' or ' ', whech might be causing the EOF error, if after removing it, you are still getting EOF, you want to consider resetting the project or the python file
I've tested the code after the fix it works fine, there's no issue with the logic.

A: def minimum(n):
    L = []
    for i in range(n):
        x = eval(input("enter number 1:"))
        y = eval(input("enter number 2:"))
        if "\n" in (x, y):
            print("please enter valid value")
        l = [x,y]
        L.append(l)
    print("input keyset-", L)
    for i in range(n):
        if L[i][0] < L[i][1]:
            r = L[i]
            print("FIRST","\t",r)
        elif L[i][0] == L[i][1]:
            r = L[i]
            print("ANY","\t",r)
        else:
            r = L[i]
            print("SECOND","\t",r)

minimum(4)

but there have more efficient way use min lib:
def minimum(n):
    L = []
    for i in range(n):
        x = eval(input("enter number 1:"))
        y = eval(input("enter number 2:"))
        if "\n" in (x, y):
            print("please enter valid value")
        L.append((x, y))
    print("input keyset-", L)
    for pair in L:
        n = min(*pair)
        print(f"the min number: {n}")

minimum(4)

UPDATE: what going on at EOL error
when you try to access user input, you wanna parsing it to int, but python cannot handle it when input is not valid.
x = input("enter number") # x is string now
n = int(x) # n is int

and when you parsing empty string x into int, you will get parsing error, for that reason, you should add error handle
x = input("enter number") # x is string now
try:
  n = int(x) # n is int
except Exception as e:
  # error
  print(str(e))
  continue

do not use eval at this case, no needed, if it is necessary, catch error is the only way to solve it.


text:
Q: UIAlert for review page I am fairly new to iPhone coding and wanted to know if someone can help me.
Have got the code ready so that when the app loads a UIAletView loads and prompts the user to review/rate the application but i have a button called "Never Rate"
I needed help to find out how to code the "never rate" button so what when it is pressed the UI Alert does not load everytime the app is loaded.
This is my code so far:
(void)viewDidLoad {

 UIAlertView *alert;
 alert = [[UIAlertView alloc] initWithTitle:@"Rate My Appication" message:@" Please Rate my Application and check out my other Apps"
           delegate: self
        cancelButtonTitle:@" Cancel "
        otherButtonTitles: @" Rate Now ", @"Check Other Apps", @" Never Rate ", nil];

 [alert show];
 [alert release];
}

(bool)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

 // Never Review Button
 if (buttonIndex == 3)
 {

 }

 // Review Button
 else if (buttonIndex == 1)
 {
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/gb/app/calculator/id389197581?mt=8"]];
 }

 // Other Apps Button
 else if (buttonIndex == 2)
 {
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/2headsolutions"]];
 }

}

A: You could store a boolean flag somewhere on disk. Then the next time, you check for neverRate == NO and display the alert accordingly.
You could store this using NSUserDefaults:
[[NSUserDefaults standardDefaults] setBool:YES forKey:@"neverRate"];

Then to retrieve it:
BOOL neverRate = [[NSUserDefaults standardDefaults] boolForKey:@"neverRate"];
if(neverRate != YES) {
  //Show alert here
}

A: This is my code so far:
- (void)viewDidLoad {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Rate My Appication"
                                                message:@" Please Rate my Application and check out my other Apps"
                                               delegate:self
                                      cancelButtonTitle:@" Cancel "
                                      otherButtonTitles: @" Rate Now ", @"Check Other Apps", @" Never Rate ", nil];

    [alert show];
    [alert release];
}

- (bool)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    // Never Review Button if (buttonIndex == 3) {

    //}

// Review Button else if (buttonIndex == 1) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/gb/app/calculator/id389197581?mt=8"]]; }

// Other Apps Button else if (buttonIndex == 2) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.com/apps/2headsolutions"]]; }

}

A: Rengers is right
Try using NSUserDefaults
Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving a BOOL
[prefs setBool:BOOL_var forKey:@"RATE_KEY"];

[prefs synchronize];

Reading
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting a BOOL
BOOL var = [prefs boolForKey:@"RATE_KEY"];

Check This link


text:
Q: macOS, "touching" OneDrive folder forces it to re-sync need your help with OneDrive folders sync process while scanning those folders.
Developing our own solution that is scanning Mac we've just faced an issue where scanning the OneDrive folder forces the service to re-sync all the files with the server.
We are using several calls to the location, scanning it, exactly these two (ObjC):
 MDItemRef item = MDItemCreate(kCFAllocatorDefault, (__bridge CFStringRef)anItemPath);
and
[[NSWorkspace sharedWorkspace] iconForFile:path]
Do you know if there any solutions, like ignore list, APIs, or any similar that won't cause files re-sync?
Thanks!


text:
Q: How IP addresses are mapped to Autonomous System Numbers? How are IP addresses mapped to Autonomous System Numbers (ASNs)? Is there a reference database for it? Then how are these Autonomous Systems geographically located?

A: There is no static mapping between IPs and AS and an AS don't have a location.
An AS is a number assigned to a company to identify them on Internet. It's used for the BGP routing protocol.
The company tell with BGP that some network IPs (let's say network Y) are reachable inside of his AS (let's say AS X). Then others companies know that to reach network Y they must talk to AS X, with this information others company routers look for the best path to reach AS X.
Nothing prevent some networks to be advertised on many AS (and this is used in some particular case).
To see a dynamic mapping of what is announced on Internet in 'real time', you can use this website. This how ATT AS information, by looking in the Prefixes IPv4 tab you will see what network they advertise. But there is no official mapping as anyone can announce anything.

A: Note: This information is kind of RIPE-centric because that's the RIR I deal with most.
The relationships between IPs (inet-num) and ASNs (aut-num) are documented in public Internet Routing Registries (IRR) using Routing Policy Specification Language (RPSL). IRRs are simply whois databases which provide additional object types (route, route-set, aut-num, as-set, etc) to store the RPSL information. IRRs are operated by all Regional Internet Registries (RIRs such as RIPE, ARIN, etc) as well as some other parties such as RADB.
RPSL can define not just which aut-num relates to which inet-num objects but also the transit and peering arrangements of a given aut-num. This information can be used to build router configurations such as with the utility RtConfig. Additionally some LIRs document their policies for accepting new peering requests and the BGP communities they make available to their peers here.
It's important to note that besides automatically configuring routers with RPSL there isn't any "magic glue" between the IRR data and what is actually happening in the wild. RPSL is a best effort practice, which should be kept up to date, but doesn't mean there's any technical barrier to announcing a route without first publicising it in RPSL.
As an example, let's see what routes are documented for the BBC website:
dan.carley@jim ~ $ whois -T route $(dig +short bbc.co.uk)
% This is the RIPE Database query service.
% The objects are in RPSL format.
%
% The RIPE Database is subject to Terms and Conditions.
% See http://www.ripe.net/db/support/db-terms-conditions.pdf

% Note: This output has been filtered.
%       To receive output for a database update, use the "-B" flag.

% Information related to '212.58.224.0/22AS2818'

route:        212.58.224.0/22
descr:        BBC
origin:       AS2818
mnt-by:       BBC-MNT
source:       RIPE # Filtered

% Information related to '212.58.224.0/20AS2818'

route:        212.58.224.0/20
descr:        BBC (EU network)
origin:       AS2818
mnt-by:       BBC-MNT
source:       RIPE # Filtered

% Information related to '212.58.224.0/19AS2818'

route:          212.58.224.0/19
descr:          BBC
origin:         AS2818
mnt-by:         BBC-MNT
source:         RIPE # Filtered

This indicates that their website will be available from three routes of increasing size (/19, /20 and /22 to the same prefix) via AS2818. Querying that ASN will then give us some additional information about their peers and policies (snipped for brevity):
dan.carley@jim ~ $ whois -T aut-num as2818
% This is the RIPE Database query service.
% The objects are in RPSL format.
%
% The RIPE Database is subject to Terms and Conditions.
% See http://www.ripe.net/db/support/db-terms-conditions.pdf

% Note: This output has been filtered.
%       To receive output for a database update, use the "-B" flag.

% Information related to 'AS2818'

aut-num:        AS2818
as-name:        BBC
descr:          BBC Internet Services, UK
import:         from AS174 action pref=100; accept AS174
import:         from AS286 action pref=100; accept AS-KQ AS-QWEST
import:         from AS553 action pref=100; accept AS-BELWUE
import:         from AS702 action pref=50; accept AS-UUNETUK
[..]
export:         to AS174 announce AS-BBC
export:         to AS286 announce AS-BBC
export:         to AS553 announce AS-BBC
export:         to AS702 announce AS-BBC
[..]

A: The RIRs publish a lot of information updated daily and offer APIs for querying that information. For example, sticking with AS2818 and RIPE:
$ curl https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS2818

{
    "status": "ok",
    "server_id": "stat-app10",
    "status_code": 200,
    "version": "1.2",
    "cached": true,
    "see_also": [],
    "time": "2018-04-12T15:29:22.144419",
    "messages": [
        [
            "info",
            "Results exclude routes with very low visibility (less than 3 RIS full-feed peers seeing)."
        ]
    ],
    "data_call_status": "supported - connecting to ursa",
    "process_time": 4,
    "build_version": "2018.4.11.320",
    "query_id": "20180412152922-853B48D2-C00D-44AD-A628-A9B8CF444B58",
    "data": {
        "resource": "2818",
        "prefixes": [
            {
                "timelines": [
                    {
                        "endtime": "2018-04-12T08:00:00",
                        "starttime": "2018-03-29T08:00:00"
                    }
                ],
                "prefix": "132.185.0.0/16"
            },
            {
                "timelines": [
                    {
                        "endtime": "2018-04-12T08:00:00",
                        "starttime": "2018-03-29T08:00:00"
                    }
                ],
                "prefix": "2001:41c1::/32"
            },
            {
                "timelines": [
                    {
                        "endtime": "2018-04-12T08:00:00",
                        "starttime": "2018-03-29T08:00:00"
                    }
                ],
                "prefix": "132.185.128.0/20"
            },
            {
                "timelines": [
                    {
                        "endtime": "2018-04-12T08:00:00",
                        "starttime": "2018-03-29T08:00:00"
                    }
                ],
                "prefix": "212.58.224.0/19"
            },
            {
                "timelines": [
                    {
                        "endtime": "2018-04-12T08:00:00",
                        "starttime": "2018-03-29T08:00:00"
                    }
                ],
                "prefix": "132.185.112.0/20"
            }
        ],
        "query_starttime": "2018-03-29T08:00:00",
        "latest_time": "2018-04-12T08:00:00",
        "query_endtime": "2018-04-12T08:00:00",
        "earliest_time": "2000-08-01T00:00:00"
    }
}

There are many other endpoints with related information on stat.ripe.net.


text:
Q: Java project to .exe file
Possible Duplicate:
How can I convert my Java program to an .exe file?
Can Maven generate exe files and mac os x apps?

I am building an application in Eclipse. Also I am using Maven to deal with my dependencies. Now I want to deliver my application to users for a testing. They are using Windows machine. I have never done this before and I am not sure how an .exe file can be built together with dependencies which reside on the Maven repository?

A: Launch4j does a good job of bundling Java applications into executables for Windows distribution.
http://launch4j.sourceforge.net/
It's what I use.

A: Use the Application Assembler Maven Plugin to build an executable.


text:
Q: How to contain variables within function when function is triggered multiple times? I'm working on a gresemonkey script.(client-side triggerd javascript)
Because you can't browse multiple pages with greasemonkey, It appends a bunch of iFrames to the DOM and every time an iFrame is opened, it shall perform a few thins to the content in that iframe:
$('.bolagsverket').load(function() {
    var orgnr = $(this).attr('id')
    var datablob = $(this).contents().find('.kungtext').text();
    console.log(datablob)
 });

When i log the datablob, it comes out with the value from the last iFrame every time, rather than the unique value of that iframe. Why?


text:
Q: Popping multiple views from the navigation controller I have an application which its rootview is a menu to 4 tableviews that the user uses to set up a search query by selecting a cell that loads another subview, so the basic structure looks like this
Root View
- Parent View (search view)
--Sub View (user selects variables here to fill search parameters of the parent view

But one of the Parent View search parameters requiers another sub view to be pushed onto the navigation stack so it would look like
Root View
- Parent View (search view)
--Sub View (user selects variables here to fill search parameters of the parent view
---Sub View (related values to the previous subview i.e. Model / sub model)

I would like to know if there is a way to pop back to the Parent View from this Sub View..
I know you can pop a single view or pop back to rootview but on this occasion I want to pop two subviews... is this possible?

A: You can add a category to UINavigationController to allow multiple controllers to be popped at once.
UINavigationController+VariablePop.h
#import <UIKit/UIKit.h>

@interface UINavigationController (VariablePop)

- (NSArray *)popViewControllers:(int)numPops animated:(BOOL)animated;

@end

UINavigationController+VariablePop.m
    #import "UINavigationController+VariablePop.h"
@implementation UINavigationController (VariablePop)

- (NSArray *)popViewControllers:(int)numPops animated:(BOOL)animated {
    NSMutableArray* returnedControllers = [NSMutableArray array];
    int indexToPopTo = self.viewControllers.count - numPops - 1;
    for(int i = indexToPopTo+1; i < self.viewControllers.count; i++) {
        UIViewController* controller = [self.viewControllers objectAtIndex:i];
        [returnedControllers addObject:controller];
    }
    UIViewController* controllerToPopTo = [self.viewControllers objectAtIndex:indexToPopTo];
    [self popToViewController:controllerToPopTo animated:YES];
    return returnedControllers;
}

@end

And then from the view controller you can:
NSArray* poppedControllers = [self.navigationController popViewControllers:2 animated:YES];

A: UINavigationViewController
popToViewController:animated:
Pops view controllers until the specified view controller is at the top of the navigation stack.
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated


text:
Q: Parsing Arraylist XML from web service using jquery (.NET Framework 2.0 - No upgrade allowed) I have gone through a lot of forum thread but still stuck before posting this.
We are still using NET Framework 2.0, not plan on upgrading.
I have created a web service returning arraylist.
` <?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.onsemi.com">
  <anyType xsi:type="xsd:string">ANNUAL</anyType>
  <anyType xsi:type="xsd:string">SEMI-ANNUAL</anyType>
  <anyType xsi:type="xsd:string">QUARTERLY</anyType>
  </ArrayOfAnyType>`

My xml parsing code is as below
    $.ajax({
    type: "POST",
    contentType: "text/xml; charset=\"utf-8\"",
    url: "Webservice url",
    dataType: "xml",
    success: function (response) {
        $(response).find("ArrayOfAnyType").each(function () {
            var data = $(this).find("anyType").text();
            alert(data);
        })
    },
    error: alert("Error")
});

I am getting the below result:
First pop-up message display "Error"
Then a second pop- message display "ANNUALSEMI-ANNUALQUARTERLY"
I want the result to "ANNUAL", "SEMI-ANNUAL", "QUARTERLY", each different pop-up.
Not sure if I have all info posted, please let me know if still lacking info.
Any positive advice is highly appreciated.
Thanks in advance.


text:
Q: Pass BST time to API using date object in Angular I am trying to pass a Javascript Date object to API in BST format. However, it always convert it to GMT when passing it to the API.
API Swagger Object:
startDate:
          type: string
          format: date-time
endDate:
          type: string
          format: date-time

Auto generated TypeScript model:
startDate?: Date;
endDate?: Date;

I am using an NgbDate to select start date and end date.
<input class="form-control" id="txtStartDate" name="txtStartDate"
                                [ngModel]="startDate" (dateSelect)="onStartDateSelect($event)"
                                ngbDatepicker #startDatePicker="ngbDatepicker" readonly
                                #txtStartDate="ngModel">

onStartDateSelect(date: NgbDate) {
    this.startDate = new Date(date.year, date.month-1, date.day);
  }

While debugging, I found this.startDate as '2021-08-31T23:00:00.000Z'. How can I change it to '2021-09-01T00:00:00.000' when passing it to API? (Is it API's responsibility to convert the GMT time to BST?)

A: I do not know NgbDate but I've used Angular Material datepicker and it returns a date as 00:00 local time. This is then stored in the Javascript Date object in UTC time so if BST is 1 hour ahead of UTC it will be stored as 23:00 on the day before.  This UTC time will be passed to APIs etc.  To correct this, I adjusted the date returned by the datepicker to be midnight UTC time before passing it on. I used the Date getTimeOffset method to do this:
        (date) => {
          return new Date(
            date.getTime() - date.getTimezoneOffset() * 60 * 1000,
          );
        }


text:
Q: How to think physically about basic "fields"  "Field" is a name for associating a value with each point in space. This value can be a scalar, vector or tensor etc. I read the wikipedia article and got that much, but then it goes it into more unfamiliar concepts.
My question is how to interpret a basic field. Lets say there is a field with momentum and energy. Does that mean, that any "object" which can interact with that field, can borrow that momentum and energy from that field and give back to it as well. Much like an electron in some (not its own) electromagnetic field, right? Now how do I extend this understanding to concepts like:

$U_\lambda$ is the radiation energy density per unit wavelength of a thermodynamic equilibrium radiation field trapped in some cavity."

Does that mean, that the "numbers" that make up the field in each point in space stay constant  with temperature or time (or both, I'm not sure.) And if there are object is that field which can interact with it, for example electrons, then they can take energy from that field or lose energy to that field. Then the author calls this field a "photon gas" without explanation. So does that mean a bag of photons in cavity is mathematically equivalent to specifying some numbers in space? Or something else.

A: I'll start here -- "So does that mean a bag of photons in cavity is mathematically equivalent to specifying some numbers in space?"
It means much more than that. First, you define a field -- in the electromagnetic case, it's a set of vectors everywhere in space. Then you allow it to be dynamic, that is you write a Lagrangian for it that leads to classical equations of motion. Then you quantize it, which leads to (1) the idea of a vacuum, that is a state of the field that contains no excitations and (2) particles -- excitations of the field that can carry momentum and energy around.
So a photon gas is much more than just a simple set of numbers everywhere. The field is dynamic. It's not in the vacuum state and so it contains particles. And finally, it is in a very precise kind of state - the photons are distributed in energy according to the Bose-Einstein distribution at a particular temperature.
How did it get into that equilibrium state? To answer that, you need to extend your field from the plain EM one to include coupling to other matter fields, say the electron. So the electron will have it's own kind of field and your combined Lagrangian will contain a term that couples the two fields together so that they can interact. This is how "objects" like electrons can borrow and lend energy to the EM field, through the coupling between the electron field (which by the way is a spinor field, and not a vector field) and the EM field.
You can have fields for all the other kinds of particles and have interaction terms for all the other known forces. So now you can have a cavity made of matter that interacts with the EM field. And through complicated dynamics that depend crucially on the Second Law of Thermodynamics, the photon gas can come into equilibrium with the matter cavity, all this mediated by the couplings in the Lagrangian.

A: Think about this: a function that maps points on a 2D space to numbers can describe the shape of terrain, but I wouldn't say that it is the terrain. In the same way, a mapping of points to objects (scalars, vectors, tensors, etc.) is the mathematical description of a field, but if you think of the field as just the mapping, you're missing out.
Fields can have various physical properties. For example, just as a particle can have a certain amount of energy, so can an electromagnetic field. The difference is, since the field is spread throughout space, so is the energy; therefore, it makes more sense to talk about the density of energy rather than the amount. Same applies for momentum, or any other physical quantity carried by the field.
Just as the field could be described by a mapping of points to vectors, so the energy density can be described by a mapping of points to numbers. Given the vector value of the field at any point, you can calculate the numeric value of the energy density at that point. But remember that these numbers (i.e. the mapping) are just a mathematical description of the energy density.
Now, you may notice that the mapping that describes the energy density ($u(x)$) satisfies the naive definition of a mathematical description of a field: it associates a number with each point in space. But physicists wouldn't normally call that mapping a "field," because in a sense, it's not really independent. Mathematically, you can calculate $u(x)$ from $A(x)$; physically, the energy "field" is completely determined by the EM field. In physics, we tend to reserve the term "field" to talk about something that can't be obtained by a simple calculation from some other field.

Does that mean, that the "numbers" that make up the field in each point in space stay constant with temperature or time (or both, I'm not sure.)

I'm not sure how you got that from the quote you listed... no, the numbers that make up the mathematical description of the EM field do not stay constant with either time or temperature. In fact, one of the things that characterizes a physical field is that it has dynamics - mathematically, this means that the numbers (or whatever) making up the field change with respect to time and space, but in a predictable manner which can be described with differential equations.
But there are things you can calculate from a field that do stay constant. For instance, you can calculate the total energy stored in the field by calculating the energy density and then integrating it over the volume of the field. You could also calculate the temperature of the field, by some mathematical procedure. In many cases, these quantities are more closely based on the manner in which the field changes than the actual values that describe it. (In fact, in some sense, it turns out that you can describe a field by the way that the numbers change, just as well as you can with the numbers themselves. Read up on the Fourier transform and momentum space if you are interested.)

A: dbrane and DZ have given Useful conventional Answers.
dbrane's characterization of the vacuum as "contains no excitations", however, is not very helpful because there is no clear Correspondence with the classical idea of no excitations, the everywhere zero classical field. Local measurements of the vacuum in general give non-zero results.
IMO (not a conventional Answer, so Useful only with care for the purposes of exams, etc.) it's more helpful to think of particles as modulations of the vacuum, which is abstractly constructed as a Poincaré invariant state over an algebra of observables. An alternative perspective is that a free field can be constructed from its Wightman functions, which are essentially correlations between the measured local values of the field when the localizations are at space-like separation [it's more usual to construct the Wightman functions from the quantum field, $W(x_1,x_2,...x_n)=\left<0\right|\hat\phi(x_1)\hat\phi(x_2)...\hat\phi(x_n)\left|0\right>$, but the other way round works too; note that, as generalized correlations, the Wightman functions are functions on the (symmetrized) space $M\oplus (M\times M)\oplus(M\times M\times M)\oplus...$, not on Minkowski space $M$ simpliciter]. The Wightman functions are not zero for the vacuum state.
Non-vacuum states have Wightman functions that are different from the vacuum state. In particular, they are not Poincaré invariant (which is why we can say that they "carry momentum and energy around"). Nonetheless, they are systematic deformations of the vacuum state, and hence of the Wightman functions, constructed by the action of the quantum field on the vacuum vector, which I choose to call modulations because I wish to emphasize the signal processing aspect of quantum field theory. [This doesn't make noncommutativity of measurements go away, but the relationship between quantum fields and classical signal processing is substantially different from the relationship between quantum mechanics and classical particle physics.] Although there is a continuum of possible modulations, there is also a discrete structure of states that can be constructed by the action of $1, 2, ...$ field operators on the vacuum vector, which we call the number of particles in the state. Unless there are superselection rules in place, we can construct (1) linear compositions of vectors and (2) linear compositions of states (superpositions and mixtures, respectively).
Note that by the vacuum state I mean a linear map from the space of operators $\omega_0:\mathcal{A}\rightarrow\mathbb{C};\omega_0(\hat A)=\left<0\right|\hat A\left|0\right>$, where I've used the vacuum vector $\left|0\right>$ to construct the vacuum state $\omega_0$. This is now a fairly universal distinction in mathematical physics, but not, I think, in Physics generally.
Now to your Question's more specific points. Interacting quantum fields defined in terms of deformed Lagrangians and Hamiltonians are only as well-defined as the degree of your acceptance of the mathematics of renormalization. From moment to moment, unitary evolution of a state preserves the Hilbert space norm (by definition), but may or may not conserve the number of particles in the state, nor even the energy and momentum if we construct an ad-hoc Hamiltonian (a thermal field in a box is an ad-hoc system, insofar as the Hamiltonian is not translation or boost invariant). Unitary evolutions are generalizations of sinusoidal motion to higher dimensional spaces, so insofar as we think of sinusoidal motion as borrowing potential energy to create kinetic energy, sure, it's "borrowing", but there are other, and I think better ways to think about such models.
From a field perspective that starts from the vacuum, a thermal state is a thermodynamic limit of mixtures of $0,1,2,...,n$ particle states (thermodynamic in the sense that $n\rightarrow\infty$), with weight for different states that is determined by the energy. The energy and the thermal state constructed using it are invariant under translations and under rotations, but not under boosts. Thermal states are special because the limit is not in the Hilbert space of bounded states. I regret that I don't have the time (I'm not sure if it's an hour, a week, or a Ph.D. thesis) to construct a field theoretic analysis of your thermal field in a box example, I'll have to leave it to you, expanding upon the principled approach I've laid out above.
Yayu, I've sent you to my papers before, so I won't do so again. I've riffed on your interestingly asked Question more than I've Answered it; I think of it as more up to you to make it Useful rather than Useful in itself. Best wishes.


text:
Q: Generic with Variable Type Arguments I want to do something like
public interface Foo<R, P...> {
    public R bar(P...) {/*misc*/}
}

to get an array of types to use in my bound implementation. Is this possible in java?
Varargs is designed to let me have any number of arguments of a given class.
I want to use it (or something similar) to have my method accept several arguments, each of which is a member of a given different class. These classes are defined when the generic is bound.
I aware there are work arounds, but is there a type-safe way to do this?

A: Since you apparently want to be able to make bar take multiple parameters of different types (something varargs are not used for), I'd suggest making it instead take a single parameter. You can then make that single parameter be a container that holds each of the individual "parameters" you want to use.
In general, it would be best to make a class for each set of parameters you want to use with this method so that you have good names for each of the objects it contains. However, you could also do something like creating a series of tuple types (such as Pair) to use as holders.
Here's an example:
public class Foo<R, P> {
  /*
   * Not sure how you intend to provide any kind of implementation
   * here since you don't know what R or P are.
   */
  public R bar(P parameters) { ... }
}

public class SomeFoo extends Foo<SomeResult, Pair<Baz, Bar>> {
  public SomeResult bar(Pair<Baz, Bar> parameters) { ... }
}

SomeFoo foo = ...
SomeResult result = foo.bar(Pair.of(baz, bar));

A: You wrote:

I want to use it (or something similar) to have my method accept several arguments, each of which is a member of a given different class.

I don't think it's possible to do this in a type-safe way without some ugly hacks, like including an instance of Class along with the object.
The problem is, that with VarArgs you're actually being passed in an Array.  But you can't have an array with different types of objects in it, they all have to be the same (or subclasses, so if you have X[] y then each element must be a subclass of X)
If your function can really deal with multiple types you could create something like a class that stores an instance of Class along with an instance of T, and the pass in a var args list of that container.
So for example you could have
class TypedInstance<T>{
   Class<T> type;
   T instance;
}

and then have a function that looks something like
public whatever(TypedInstance<? extends Object>... whatever){
  ...
  doSomethingWith(whatever[0].type, whatever[0].instance);
  ...
}

These kinds of hacks are needed because of Java's type erasure.  The generic parameter gets removed at runtime, so if you want to use it, you have to put it back.


text:
Q: UICollectionView cells only display after second call to reloadData I'm probably doing something incredibly stupid, but I can't figure out for the life of me what's going on...
What I'm trying to do is quite simple. I have a UICollectionView dependent on data I'm loading from the server. After I get and set the data from the server, I call reloadData() on the collection view. When I do so, numberOfItemsInSection is called with the correct count, but cellForItemAt never gets called unless I call reloadData() for a second time (doesn't even need a delay).
Here's the general idea (although I realize it's likely related to some race conditional elsewhere, but maybe this will be enough to start the conversation):
class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    var data = [DataModel]()

    override func viewDidLoad() {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "MyCell", bundle: nil), forCellWithReuseIdentifier: "MyCell")
        getData()
    }

    func getData() {
        someAsyncMethodToGetData() { (data) in
            // Using CloudKit so I think this is necessary, but tried it with and without
            DispatchQueue.main.async {
                self.data = data
                self.collectionView.reloadData()
                // This is the only way to get cells to render and for cellForItemAt to be called after data is loaded
                self.collectionView.reloadData()
            }
        }

    // Gets called initially AND after reloadData is called in the data completion closure. First time is 0, next time is number of DataModel objects
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    // Only gets called initially (unless I call reloadData() twice)
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = feedCollectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as? MyCell else {
            return UICollectionViewCell()
        }

        // Configure the cell with data...

        return cell
    }
}

So here are some things I've already tried:

*

*Made double sure reloadData() is being called on the main thread (added a symbolic breakpoint and called Thread.isMainThread to verify)

*Moved reloadData() into a button action to eliminate the possibility of any thread issues - still had to click the button twice to get cells to show up

*Put the updates in performBatchUpdates based on some other SO solutions I came across

*Added setNeedsLayout and setNeedsDisplay (not sure why this would be necessary in this case, but I did try it out of desperation.

Any suggestions?
Update 1
Ok, think I found the issue, but I'd like to understand the best way to solve. It appears by calling reloadData, the collection view will only reload cells already visible. I hacked the code above a bit to return 1 cell before getData() is called. When getData() then calls reloadData() that 1 cell gets updated (but if there are 10 items in the data array, it will still only [re]display the 1 cell). I suppose this makes sense, as reloadData() only reloads visible cells, but this has to be a common issue when the length of the array changes and there is still room on the screen to display. Also, why does calling reloadData() twice solve the issue and display cells that were never visible?
Here is an even simpler version of the code I have above, removing the whole "get data from a server" idea and replacing with a simple delay.

A: First make sure if the delegate and the dataSource is correctly add to collectionView.
Second make sure if the data is fill whit breakpoint or a simple print
Third add this:
    DispatchQueque.main.async{
     self.collection.reloadData()
     self.collection.collectionViewLayout.invalidateLayout()
    }

A: The thing is UICollectionViewFlowLayout isn't invalidated correctly after number of items changed. So collectionView.contentSize is still old. You need to do something like
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout()

This will tell layout to recalculate for new data source.


text:
Q: Compiled classes with resources as library project? I have to develop an Android library which needs to be packaged and distributed to Android developers. It has both Java classes and resources (icons etc).
I'm wondering about the best way of distributing such a library. As we all know many well-known libraries are distributed in different formats:

*

*ActionBAr Sherlock - ZIP or APKLIB

*Flurry - JAR

My Prerequisites:

*

*I can't distribute sources - only compiled java classes and resources are allowed

*My aim is to have integration with client project instruction as simple as possible - e.g. one line in Maven/Gradle as dependency and few lines of code how to use it within the app.

*I have to respect every build system: those using NBS, those using android-maven-plugin and those using legacy ANT.

My first idea was to distribute this library as APKLIB (Maven) and AAR (NBS) but then I realized no support for ANT.
Questions:

*

*Can APKLIB and AAR have only compiled classes and resources instead of plain Java sources?

*How to distribute a compiled android library project for ANT? As a ZIP?

*What about generating R for libraries?

Thanks for any suggestions!

A: *

*An APKLIB is only supposed to contain sources, libs and resources, not the compiled .class files. Complementary, the AAR format is "the binary distribution of an Android Library Project" and must contain classes.jar, but no sources.
Edit: However, there is a trick that you can use for an APKLIB to contain compiled classes instead of source code: Compile the source code and put it at libs/<library-name>.jar inside the APKLIB instead of the bin directory. Then replace all files in src with some dummy file.

*You can distribute a compiled Android Library Project for Ant as an AAR, but you have to keep a few things in mind when using it. Ant explicitly looks for the src directory in the extracted AAR file, but there is none, and Ant looks for classes.jar in the bin directory, but it is located at the root of the extracted AAR file. You can work around this by creating an empty src directory and copying classes.jar to bin/classes.jar. That is exactly what we do in an Ivy post-retrieve-artifact step after retrieving the AAR artifact. Edit: This has the disadvantage that ant clean will delete the bin/classes.jar, and you're probably better off with using an APKLIB with a jar packaged as part of the libs directory as described above.

*Neither APKLIB nor AAR are not supposed to come with a compiled R class, both ship with their original resources in the res directory. Additionally, an AAR has to contain an R.txt file listing all the resources (as output by aapt --output-text-symbols).


text:
Q: VB.net - Windows.Forms.Screen.AllScreens report wrong bound sizes when using any DPI scaling above 125%, anyway to fix this? I have my vb.net application (written in  VS2010 pro) setup to detect and support multi-monitor setups at various DPI scaling.
I use Screen.AllScreens.Length to get me how many monitors I have running:
Public Function getMonitorCount() As Integer
    Return Screen.AllScreens.Length
End Function

And then I loop through all the monitors to get their various info:
Public Sub getMonitorSetupFull()
    m = getMonitorCount()
    n = 0
    Do While n < m
        Monitor(n) = Windows.Forms.Screen.AllScreens(n)
        XLeft(n) = Monitor(n).Bounds.X
        YTop(n) = Monitor(n).Bounds.Y
        XRight(n) = XLeft(n) + Monitor(n).Bounds.Width
        YBottom(n) = YTop(n) + Monitor(n).Bounds.Height
        MonitorSize(n) = New Size(Monitor(n).Bounds.Width, Monitor(n).Bounds.Height)
        n = n + 1
    Loop
End Sub

I'm having an issue where Monitor(n).Bounds (aka Windows.Forms.Screen.AllScreens(n).Bounds) give me the wrong values at high DPI. For example, at 200% DPI Monitor(n).Bounds.Height gives me a value of 540 for a 1080p monitor (precisely half). At 100%/125% DPI, I get at 1080 which is correct but at 126% DPI I get 857 instead of 1080.
Is there something I can add to my code to get Windows.Forms.Screen.AllScreens(n).Bounds to detect the proper sizes at these DPI or should I just manually compensate for this eccentric behavior myself via something along the lines of if DPI > 125%, Windows.Forms.Screen.AllScreens(n).Bounds.Height = Windows.Forms.Screen.AllScreens(n).Bounds.Height * DPIratio ?
UPDATE: To confound this issue even more, I found that if I select use Windows XP DPI scaling while I'm setting the DPI, this issue doesn't occur. Nor does it occur when I'm not using Aero. I've reproduced this on other Windows 7 machines.


text:
Q: Google Apps Script - MAX EXECUTION TIME I'm on GSuite Business and i have made a Google Apps Script for read the content on a GDrive folder and write on Column A the name of the file and on Column B the GDrive Link of the file.
I have about 8800 Files on this folder and i go over the 30 minutes execution time quota.
at this time i don't have idea to solve this problem..
I past here my script...
This script are useful for see the list of images of the product for sync with my ecommerce.
function ImageDatabaseUpdate() {

  //read file on my drive foldeer -> 06 - usato fine serie
  var foldername = '06 - Usato e Fine serie';
  var folderlisting = 'Database GTLG ';

  var folders = DriveApp.getFoldersByName(foldername)
  var folder = folders.next();
  var contents = folder.getFiles();
  var contents = folder.getFiles();

  //Set file id and sheet Immagini
  var ss = SpreadsheetApp.openById("1ok2tfpLFRHE6I4ehR9lfsLwtFy1UfTdJqbi-NCqGVS0");
  var sheet = ss.getSheetByName('immagini');

  //Write heading on first sheet row
  sheet.appendRow(['name','link']);

  var file;
  var name;
  var link;
  var row;

  //start reading and writing
  while(contents.hasNext()){
    file = contents.next();
    name = file.getName();
    link = file.getUrl();
    sheet.appendRow([name, link]);
  }
}

A: Your code goes into an infinite loop because you need contents.next() to move to the next file. Since the folderIterator doesn't increment, while(contents.hasNext()) will continue forever.


text:
Q: How should ._cntr should be imported on Matplotlib (LTS) 2.2.0 In order to construct GeoJson, a package uses:
import matplotlib._cntr as cntr

While using matplotlib 2.2.0 it returns
ImportError: No module named _cntr

How it should be imported?
With previous version of Matplotlib, specially 2.1.0 it works.

A: This was a private module and should not have been used by third-party packages.
See https://github.com/matplotlib/legacycontour for an effort to package that code independently.

A: _cntr is not part of matplotlib any more. I has not been used for several versions already, and I guess it now has been removed completely.
You may of course copy a version of it from a previous release (compiled for the same system) to your matplotlib folder to continue importing it as matplotlib._cntr.


text:
Q: how to convert to json string This could be a basic question but , i'm stuck with this for some time.
i have a data
{pid: 'WEB506', session: 'WEB506_09092021_M1_S1.csv'}

how to convert this to
{
        "pid":"WEB506",
        "session":"WEB506_09092021_M1_S2.csv"
        };

regards. i used JSON.stringify and i got it as
{"pid":"WEB506","session":"WEB506_09092021_M1_S1.csv"}

but when i pass this to ajax data to call an api , the value entering req.body is
{ '{"pid":"WEB506","session":"WEB506_09092021_M1_S1.csv"}': '' }

This is my ajax call
function graphApi(){

     const apiValue = JSON.parse(localStorage.getItem('user'));

   console.log(apiValue,"apiValue");
      const f = JSON.stringify(apiValue);
      console.log(f,"ffff")
       $.ajax({
        type: "POST",
        data:  f,

        url: "http://localhost:5000/File",
        success: function (data) {
        console.log(data,"graph api");
         }

I really don't know what is happening.
regards

A: JSON.stringify()
should give you serialized string for your data.
I think the issue here is you are passing the string as the payload to the AJAX call whereas you should use the data(i.e the object) directly in req. body.
See if this helps

A: JSON.stringify() is used to stringify the objects

A: This is your Object Right
   const object = {
                  "pid":"WEB506",
                  "session":"WEB506_09092021_M1_S2.csv"
                };

Now Pass this object in the below method
const jsonObject = JSON.parse(object);
console.log(jsonObject)

Now you can dig out your PID or SESSIONS with
const pid = jsonObject.pid
const session = jsonObject.session


text:
Q: Comparing values in pandas dataframe columns, to return only species that are unique to a particular site python newbie here. Working on a project, trying to find unique species when comparing data from 3 locations. Here is the pandas dataframe I have constructed:
linktoimageofdataframe
Edit: I added a picture of the output, somehow the formatting is weird when I list it:
      index     A     B     C     D     E    F     G    H    I    J    L  \
0        0.0  10.0  14.0   1.0  15.0   5.0  0.0   6.0  0.0  0.0  2.0  0.0
1        1.0  31.0  12.0   9.0   0.0   0.0  0.0   0.0  2.0  0.0  0.0  1.0
2        2.0   5.0   4.0   6.0   5.0   5.0  9.0   5.0  6.0  5.0  7.0  0.0
Total    3.0  46.0  30.0  16.0  20.0  10.0  9.0  11.0  8.0  5.0  9.0  1.0

         M    N    O    P
0      0.0  0.0  0.0  0.0
1      0.0  0.0  1.0  1.0
2      2.0  1.0  0.0  0.0
Total  2.0  1.0  1.0  1.0

Species are represented by letters A-P. What I need to do is to somehow compare the values in the columns for each species, and return a result saying that a species is unique to a particular site or not. For example, species P is only found at the site at index 1, thus P is unique to site 1. If the species is at all three sites (e.g. A and B), then it would return nothing for those species. Same situation if a species is at two sites, but not the third one. Hopefully that makes sense. This website has been great for helping me learn about setting up dataframes and python in general, thank you for any help you can provide!


text:
Q: Weird issue while loading properties files from class path I have created this test app to explain the issue I am having.
I have two properties files with same keys and total three properties files in class path.
1.mysql.properties
2.vertica.properties
3.other.properties
I am getting following error while running the app.
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'mysql-username' in value "${mysql-username}"

Here is the code.
package com.test.demo;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@Configuration
@ComponentScan
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DemoApplication.class);
        MyController bean = applicationContext.getBean(MyController.class);
        bean.log();
    }

    @Bean
    public PropertyPlaceholderConfigurer otherProps() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setIgnoreResourceNotFound(true);

        final List<Resource> resourceList = new ArrayList<>();

        resourceList.add(getOtherResourceFile());

        ppc.setLocations(resourceList.toArray(new Resource[]{}));

        return ppc;
    }

    @Bean
    public PropertyPlaceholderConfigurer verticaProps() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setIgnoreResourceNotFound(true);
        ppc.setPlaceholderPrefix("${vertica-");

        final List<Resource> resourceList = new ArrayList<>();

        resourceList.add(getVerticaResourceFile());

        ppc.setLocations(resourceList.toArray(new Resource[]{}));

        return ppc;
    }

    @Bean
    public PropertyPlaceholderConfigurer mysqlProps() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setIgnoreResourceNotFound(true);
        ppc.setPlaceholderPrefix("${mysql-");
        final List<Resource> resourceList = new ArrayList<>();

        resourceList.add(getDatabasePropertiesFile());

        ppc.setLocations(resourceList.toArray(new Resource[]{}));

        return ppc;
    }

    private Resource getOtherResourceFile() {
        Resource resource = new ClassPathResource("other.properties");
        return resource;
    }

    private Resource getVerticaResourceFile() {
        Resource resource = new ClassPathResource("vertica.properties");
        return resource;
    }

    private Resource getDatabasePropertiesFile() {
        Resource resource = new ClassPathResource("mysql.properties");
        return resource;
    }
}

MyController.java
/*
 * MyController.java
 */
package com.test.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author
 */
@Component
public class MyController {

    @Autowired
    private MySqlProperties mySqlProperties;
    @Autowired
    private VerticaProperties verticaProperties;
    @Autowired
    private OtherProperties otherProperties;

    public String log() {
        System.out.println(mySqlProperties.getUsername());
        System.out.println(verticaProperties.getUsername());
        System.out.println(otherProperties.getKey());
        return "hello";
    }
}

MySqlProperties.java
/*
 * MySqlProperties.java
 */
package com.test.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author
 */
@Component
public class MySqlProperties {

    @Value("${mysql-username}")
    private String username;
    @Value("${mysql-password}")
    private String password;

    //getter
}

VerticaProperties.java
/*
 * VerticaProperties.java
 */
package com.test.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author
 */
@Component
public class VerticaProperties {

    @Value("${vertica-username}")
    private String username;
    @Value("${vertica-password}")
    private String password;

    //getter
}

OtherProperties.java
/*
 * OtherProperties.java
 */
package com.test.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author
 */
@Component
public class OtherProperties {

    @Value("${key}")
    private String key;
    @Value("${key1}")
    private String key1;

    //getter
}

These are the properties files.
mysql.properties
username=mysql
password=mysql

vertica.properties
username=vertica
password=vertica

other.properties
key=value
key1=value1

Weird Issue: When I remove the following code from DemoApplication.java the app works expected.
@Bean
    public PropertyPlaceholderConfigurer otherProps() {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setIgnoreResourceNotFound(true);

        final List<Resource> resourceList = new ArrayList<>();

        resourceList.add(getOtherResourceFile());

        ppc.setLocations(resourceList.toArray(new Resource[]{}));

        return ppc;
    }


text:
Q: Ensuring Matrix is symmetric (and positive-semidefinite) I am currently implementing an online estimation algorithm for a set of covariance matrices and due to numerical errors, my covariance matrices happen to be not symmetric at all times.
I currently resolve this by mirroring the upper triangular matrix onto the lower one:
    for i=1:T
       tempSigma(:, :, i) = eye(D)/sigmaT(:,:,i);
       temp = triu(tempSigma(:,:,i), 1);
       tempSigma(:, :, i) = triu(tempSigma(:, :, i));
       tempSigma(:, :, i) = tempSigma(:, :, i) + temp';
    end

Looping over every single matrix becomes very slow for large *T*s. Is there any way to speed this up in Matlab?

A: So you have an NxNxT array, where each plane of the matrix is to be considered a covariance matrix?
Learn to use MATLAB as it was designed to be used. Try to avoid explicit loops. For example, this will simply average the upper and lower triangles:
tempSigma = (tempSigma + permute(tempSigma,[2 1 3]))/2;

It is a logical way to solve the problem, arguably better than throwing away the lower triangle completely. And it runs in one line of code, with no explicit loops.


text:
Q: PHP and Python CLI programs start too slow for the first time (MacOS) I work on Mac with Python and PHP.
From some period of time (I didn't notice exactly since when) all new scripts have started to launch very slowly.
I mean, even a simple hello-world program on Python or PHP works about 5-6 seconds for the first time. After the first launch, if NOT changing anything for the second time, the program works fast. But if changing even one letter in "hello world" string it compiles as long as it did for the first time.
I do remember that is wasn't like this before. Don't know how to fix it.

A: I don't know about PHP but for python3 I think I have a solution:
The slow initial startup seems to be related to python3 being bundelnd with Xcode. After installing Xcode calling python3 resolves to /usr/bin/python3 which when called for the first time after reboot seems to check which python3 framework to use. (I'm not entirely sure what it really does though, but it seems to call Xcode-select for some reason?!?) This can take a very long time. Eventually it settles for calling a python3 framework from the Xcode installation e.g.
"/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/Current/bin/python3.9"
To circumvent this initial check I added a symlink to "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/Current/bin/python3.9" under /usr/local/bin/python3
Since one cannot edit /usr/bin because of system protection this symlink has to go to /usr/local/bin/.
Then I made sure that /usr/local/bin comes before /usr/bin in my $path variable and now a call to python3 resolves to /usr/local/bin/python3 which in turn directly resolves to the selected python3 framework from the Xcode installation.
One can use ll $(which python3) to check what gets called.
This now is again as fast as one can expect it to be.


text:
Q: Angular material design md-tab scroll content This might be a simple issue, but I'm new to this...
I am trying to have an md-tabs element that takes the entire screen, and have only the tabs' content scroll.
Here is an example on jsFiddle
Any ideas? thx!

A: Try this:

    <md-toolbar layout="row" class="md-toolbar-tools">

Welcome!

    </md-toolbar>

        <md-tabs md-stretch-tabs="always" flex>
            <md-tab label="Tab1">
                add our larger-than-life content here
            </md-tab>
            <md-tab label="Tab2">
            </md-tab>
       </md-tabs>

Adding the flex attribute to md-tabs will make the content of the inner tabs (md-tab) scrollable.

A: Try to add this style to your div element inside md-tab :
div{
  height: 100px;
  overflow-y: scroll;
}

Your container must be a fixed size.
Also, you can play with  overflow property. Read this for more information.
Thanks

A: Seems like it was a bug in 0.8.3 that is fixed now in master (commit: 74601d0)


text:
Q: Postgres SELECT WHERE IN array in Java I want to select all records form database using WHERE IN, using values form an array that I have. Is there a way to actually pass the array to the query?
I tried SELECT id FROM tag WHERE name IN "+myArray.toString()+". But, of course, it is destined to fail)
I could use preparedStatement, but number of values is always different and quite large - 5000 or so.
Or maybe I should take a different approach?

A: If you don't want to use normal concatenation to do this just use a StringBuilder, which is MUCH more efficient since it only actually creates the string when you use the toString() method.
private String ArrayToString(String[] array)
{
    StringBuilder buffer = new StringBuilder();
    buffer.append(array[0]);

    for (int i = 1; i < array.length; i++)
    {
        buffer.append(",");
        buffer.append(array[i]);
    }

    return buffer.toString();
}


text:
Q: Google Maps API Geolocation Text Search Place Details I am using google maps api geolocation to get the users location via latlng, then using this location to text search for 'golf' locations around that area. Now I would like to advance from this basic map/markers view to provide place details when the user clicks on the specific map marker. The issue is when I click marker there is no response. I feel like I am one variable off but could really use some help identifying why the details & infowindo fail to appear on click?
I also saw that google is using placeID's to return details? but was unsure if that applied to the maps API detail request.
Thank you in advance for any help.

function success(position) {

    var s = document.querySelector('#status');

    if (s.className == 'success') {
        // not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
        return;
    }

    s.innerHTML = "found you!";
    s.className = 'success';

    var mapcanvas = document.createElement('div');
    mapcanvas.id = 'mapcanvas';
    mapcanvas.style.height = '400px';
    mapcanvas.style.width = '560px';

    document.querySelector('article').appendChild(mapcanvas);

    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeControl: false,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
    var service;
    var infowindow;
    var request = {
        location: latlng,
        radius: '3200',
        query: 'golf'
    };

    infowindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);
    service.textSearch(request, callback);

    function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
                //var place = results[i];
                createMarker(results[i].geometry.location);
            }
        }
    }

function createMarker(position) {

    new google.maps.Marker({
        position: position,
        map: map
    });
 }
var request = { reference: position.reference };
    service.getDetails(request, function(details, status) {
marker.addListener(marker, 'click', function() {
    infowindow.setContent(details.name);
    infowindow.open(map, this);
  });
  });
  }
function error(msg) {
    var s = document.querySelector('#status');
    s.innerHTML = typeof msg == 'string' ? msg : "failed";
    s.className = 'fail';
}

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
} else {
    error('not supported');
}
html, body, #mapcanvas {
    height: 400px;
    width: 400px;
    margin: 0px;
    padding: 0px
}

Finding your location: checking...

A: I see two likely issues here:
var request = { reference: position.reference };
service.getDetails(request, function(details, status) {

*

*Here position is a LatLng, which doesn't have a reference attribute.  So your getDetails call fails.

*The callback function you pass to getDetails ignores the status, so you never notice any errors it reports.

Combined, this is why nothing happens.
Fix: pass the whole PlaceResult (i.e. results[i], not results[i].geometry.location) to createMarker, so you can access both the location and the Place ID.
As an aside: using reference is deprecated.  Use placeId instead.


text:
Q: Parent and child classes unexpected keyword argument I was experimenting with parent and child classes in python. I got an error that I can't seem to solve, both the error and code are posted below. If you could post a reason why this is happening and an edit of my code how to fix this it would be much appreciated.
# Classes Example
class vehicle():
    def __init__(self,name,weight,wheels,color):
        self.name = name
        self.weight = weight
        self.wheels = wheels
        self.color = color
    def __str__(self):
        return("Hi, iam a vehicle called " + self.name)
    def wow(self):
        return(self.weight/self.wheels)

class car(vehicle):

    def __init__(self,doors,quantity,mpg):
        self.doors = doors
        self.quantity = quantity
        self.mpg = mpg

    def distance(self):
        return(self.quantity/self.mpg)

# Main Program
object1 = vehicle("Audi A3",1000,4,"blue")
print(object1)
print(object1.name)
object1.name = "Audi S3"
print(object1.name)
print(object1.weight)

object2 = vehicle(name = "Claud Butler" , color = "Red" , wheels = 2, weight = 20)
print(object2)
print(object2.wow())

object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000)
print(object3.color)
print(object3.wow())
print(object3.distance())

I get the following error:
Traceback (most recent call last):
  File "H:\my documents\Computing\Class example.py", line 39, in <module>
    object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000)
TypeError: __init__() got an unexpected keyword argument 'name'

A: The error is raised in the following line:
object3 = car(name = "Burty", color = "Pink" , wheels = 3, weight = 500, doors = 3 , quantity = 10, mpg = 1000)

There, you are calling the car constructor with (amongst others) a name parameter. Now, if you look at the define constructor of the car type, you see the following:
class car(vehicle):
    def __init__(self,doors,quantity,mpg):
        self.doors = doors
        self.quantity = quantity
        self.mpg = mpg

As you can see, there is no name parameter in the parameter list.
I assume that you expected the car child class to inherit all the constructor parameters from the parent vehicle class but that's not actually the case. Unless you explicitely duplicate those parameters, they won't be there. You also have to call the parent's constructor explicitely. All in all, your car constructor should look like this:
def __init__(self, name, weight, wheels, color, doors, quantity, mpg):
    # call the base type's constructor (Python 3 syntax!)
    super().__init__(name, weight, weels, color)

    self.doors = doors
    self.quantity = quantity
    self.mpg = mpg

A: The method
__init__(self,doors,quantity,mpg):

does not have an argument called name. If you want it, you should add it.


text:
Q: What are typical lengths of chat message and comment in database? I need to create a column in SQL Server database. Entries for that column will contain messages from chat. Previously such messages has been stored as comments.
My main quetion is:
What is typical text length for chat message and comment?
By the way:
What would happen if I used varchar(max)? How would it impact database size and performance? Is better to use powers of 2 or powers of 10 (e.g. 128 instead of 100) while considering text lengths?

A: Short answer - it doesn't matter.
From MSDN:

The storage size is the actual length of the data entered + 2 bytes.

So VARCHAR(10) and VARCHAR(10000) will consume the same amount of data if the values don't exceed 10 characters.

A: Using VARCHAR(MAX) has a disadvantage: you can not define an index over this column.
Generally, your application should impose a maximum length for a chat message. How big that limit is depends very much on what the application is used for. But anything more than 1000 byte is probably less a legitimate message but an attempt to disrupt your service.
If your maximum value is a power of 2, or a power of ten or any other value has no influence on the performance as long as the row fits in one (8KB) page.

A: Definitely use N/VARCHAR(MAX), it can grow to be 2GB (if I remember correctly). It will grow as required though, so it is very efficient with regards to space unless you are only storing very small amounts of data.


text:
Q: Hibernate: Many to many mapping exception I am stuck up with mapping exception. I have many to many relationship between Employee and Role. Here is the code.
Role class
@Entity
@Table(name = "role", catalog = "app")
public class Role implements java.io.Serializable {

@GeneratedValue(strategy = IDENTITY)

@Column(name = "roleId", unique = true, nullable = false)
private Integer roleId;

@Column(name = "title", nullable = false, length = 50)
private String title;

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
private Set<Employee> employees = new HashSet<Employee>(0);

public Role() {
}

public Role(String title) {
    this.title = title;
}

public Role(String title, Set<Employee> employees) {
    this.title = title;
    this.employees = employees;
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public String getTitle() {
    return this.title;
}

public void setTitle(String title) {
    this.title = title;
}

public Set<Employee> getEmployees() {
    return this.employees;
}

public void setEmployees(Set<Employee> employees) {
    this.employees = employees;
}

}

and Employee class
@Entity
@Table(name = "employee", catalog = "app", uniqueConstraints =       @UniqueConstraint(columnNames = "email"))
public class Employee implements java.io.Serializable {

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "empId", unique = true, nullable = false)
private Integer empId;

@Column(name = "name", nullable = false, length = 100)
private String name;

@Column(name = "email", unique = true, nullable = false, length = 50)
private String email;

@Column(name = "phone", nullable = false, length = 11)
private String phone;

@Column(name = "ip", nullable = false, length = 20)
private String ip;

@Column(name = "password", nullable = false, length = 200)
private String password;

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "employee_role", catalog = "app", joinColumns = {
        @JoinColumn(name = "empId", nullable = false, updatable = false) }, inverseJoinColumns = {
                @JoinColumn(name = "roleId", nullable = false, updatable = false) })
private Set<Role> roles = new HashSet<Role>(0);

public Employee() {
}

public Integer getEmpId() {
    return this.empId;
}

public void setEmpId(Integer empId) {
    this.empId = empId;
}

public City getCity() {
    return this.city;
}

public void setCity(City city) {
    this.city = city;
}

public Posts getPosts() {
    return this.posts;
}

public void setPosts(Posts posts) {
    this.posts = posts;
}

public Teams getTeams() {
    return this.teams;
}

public void setTeams(Teams teams) {
    this.teams = teams;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return this.email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhone() {
    return this.phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getIp() {
    return this.ip;
}

public void setIp(String ip) {
    this.ip = ip;
}

public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

public Set<Role> getRoles() {
    return this.roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

}

Here is the exception. Please also explain the exception
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: org.company.app.models.Role.employees in org.company.app.models.Employee.roles
what is wrong?

A: It looks you miss @Id anotation for Role class
@Id
@Column(name = "roleId", unique = true, nullable = false)
private Integer roleId;


text:
Q: Windows Live with e-mail through Azure Access Control Service I am trying to allow users to sign in to the ASP.NET MVC web site with their Google, Facebook, and Windows Live accounts.  I am currently using the Azure App Fabric ACS, which made it almost too easy. The catch is I need the e-mail address.  Google and Facebook provide the e-mail as a claim, but Windows Live doesn't.  From the LiveConnect site it seems like this is easily possible using the wl.basic (to get the user's name) and wl.emails (to get the user's email address) scopes, but I haven't been able to influence the ACS in order to obtain this information.  I also tried implementing the OAuth2 web server flow to get it from my site after the user has signed in.  I was able to get the information I needed, but I became stuck in an infinite loop of signing on because the FedAuth cookies were removed when I redirected to https://oauth.live.com/authorize to start the flow.  Has anybody been able to get this to work (on the server side)?  Should I just scrap the ACS altogether and provide a custom page with uses the custom code from each provider to enable sign in?
I retrofitted a previous demo (blog engine ala smarx) with the code so that I wouldn't have to expose anything proprietary.  In my web.config FedUtil has inserted the following:
<httpModules>
  <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  <add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>

I removed the deny all users
But I have a particular action method (post of a new blog) that forces users to be authorized
    [Authorize]
    public ActionResult New()
    {
        var principal = Thread.CurrentPrincipal as IClaimsPrincipal;
        if (principal == null)
            return new HttpStatusCodeResult(403);

        // if this is a Windows Live User we have more work to do
        string redirectUrl = CheckForWindowsLiveUser(principal);
        if (redirectUrl != null)
        {
            return Redirect(redirectUrl);
        }

Inside the New request the first time the cookies (FedAuth and FedAuth1) have been filled in.  After the redirect comes back they are gone.  I haven't done anything to the session provider (maybe I should).

A: In my case, the issue was caused by an incorrect configuration of the domain names between ACS, the Windows Live application, and the URL I was using to access the site.  In development, I was using a single host name, localhost, for all of my redirections.  However, Windows Live application API settings do not allow the localhost domain and so I used a host entry to work around it, myapp.localhost.  The cookies were correctly being set on the ACS logon redirect (localhost) and, also correctly, not being sent on the authorization redirect (myapp.localhost) because the domains were different.
Incorrect
Development URI: http://localhost/app

ACS Redirect URI: http://localhost/app/sso

Windows Live Connect Authorization Redirect URI: http://myapp.localhost/app/sso/authorizations

Correct
Development URI: http://myapp.localhost/app

ACS Redirect URI: http://myapp.localhost/app/sso

Windows Live Connect Authorization Redirect URI: http://myapp.localhost/app/sso/authorizations

A: I think you're on the right track with oauth2 and live connect and it should be possible to solve your infinite loop issue. Where in your site's code are you performing your redirect to oauth.live.com/authorize? I think at the very least, it must happen after the user completes a full conventional sign-in to LiveID via ACS.
Take a look at this blog post for context
If your site is making the oauth.live.com/authorize call before step 5, before WIF has the chance to establish a session, then you'll get this infinite loop.
However, if you wait until step 6, then your FedAuth cookie should be written and the user has a session established. You should be able to make a further redirect to oauth.live.com/authorize to collect the user's email without risk of an infinite loop. The user will be prompted by live connect about releasing emails the first time, but this should be seamless. The other advantage is at step 6 you have the ACS token available in HttpContext.User.Current, you can make use of the IdentityProvider claim that ACS issues, since you only need to make this further oauth redirect when IdentityProvider == LiveID.


text:
Q: 'JavaPackage' object is not callable when doing "ssc = StreamingContext(sc, 1)" I currently have Spark spark-2.4.7-bin-hadoop2.7 and Kafka kafka_2.11-2.4.1.
I'm trying to connect to an Apache Broker to process the data that is stored in a topic.
I am running the following code:
import os
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.4.7 pyspark-shell'

from pyspark import SparkContext
from pyspark.streaming import StreamingContext

sc = SparkContext("local[2]", "testtopic")
ssc = StreamingContext(sc, 2)

and I am getting the following error

Traceback (most recent call last):   File "", line 1, in
   File
"/home/bupry_dev/development/spark_home/spark-2.4.7-bin-hadoop2.7/python/pyspark/streaming/context.py",
line 61, in init
self._jssc = jssc or self._initialize_context(self._sc, batchDuration)   File
"/home/bupry_dev/development/spark_home/spark-2.4.7-bin-hadoop2.7/python/pyspark/streaming/context.py",
line 64, in _initialize_context
self._ensure_initialized()   File "/home/bupry_dev/development/spark_home/spark-2.4.7-bin-hadoop2.7/python/pyspark/streaming/context.py",
line 88, in _ensure_initialized
SparkContext._active_spark_context, CloudPickleSerializer(), gw)   File
"/home/bupry_dev/development/spark_home/spark-2.4.7-bin-hadoop2.7/python/pyspark/streaming/util.py",
line 106, in init
self.gateway.jvm.PythonDStream.registerSerializer(self) TypeError: 'JavaPackage' object is not callable

I have tried with several --jars and --packages, with different versions and I'm not sure what I am doing wrong. In every post they say you have to match the pre-built version (which is 2.11) of Spark with you Kafka and that is what I'm doing.


text:
Q: Questions about Mountain Lion breaking programming tools OS X Mountain Lion was released a short while ago and as a result many people who upgraded are experiencing problems with their programming tools (see osx-mountain-lion).
What's the policy regarding these questions? On-topic? Off-topic? Migrate to Superuser or AskDifferent?

A: Surely this depends. Developer tools are not on topic on Superuser or AskDifferent so should stay here as noted in the SO FAQ.

software tools commonly used by programmers

Ones that re just running applications could be on topic for AskDifferent. I also would think that most are more on topic for Ask Different rather than Superuser - I think things get migrated more to Superuser because it is one of the 5 sites that show on the off topic dialog.
But it depends :) for example this gatekeeper question starts by asking what is happeing and that really should be answered on AskDifferent but then asks about how to sign the code which is development an on topic on SO.
I am not certain where installing/building software should go as it is code related but not writing code.
Oh a general comment to those upgrading ASSUME THINGS WILL BREAK so either set up on a spare machine to test or wait for reports from others before upgrading if you have to have things working for an urgent deliverable. (If people did that many of the questions would not arise)


text:
Q: Nodemon for development environment I wanted to know how to use nodemon, and push it to a git repo, and have other developers on the project be able to use nodemon without having to run the command npm install -g nodemon. Ideally, I would like all developers on the project to be able to just run npm start and nodemon is called whether or not it's installed globally. I've already run npm install --save-dev nodemon, and I'm mostly curious if there is a way to get nodemon to be run from within node_modules, in my start command in the scripts section of the package.json file.

A: If you install it locally, i.e. without the -g flag, it's available in ./node_modules/.bin/nodemon.  So just configure that path in your npm start script.
For example:
"start" : "./node_modules/.bin/nodemon app.js"


text:
Q: MSMQ - Cannot see public queues I'm new to MSMQ. I started in a Win 2008 domain controller VM, installed all features under Message Queuing category.
In Computer Management, Services and Applicatoins, Message Queing, I do see Outgoing, Private and System queues, but cannot see Public queues.
Why is that? Again, is a domain controller VM, so AD is installed, up & running.
If I go through Visual Studio's Server Explorer, I do see Public queues, but when I click refresh, I get "A workgroup installation computer does not support the operation." But I clearly see that the machine is joined to a domain - it's actually the DC!
Ideas appreciated, thanks in advance!
UPDATE: it was because of permissions were not propertly assigned during MSMQ feature setup,

A: This may be because MSMQ is using the workgroup instead of AD.
To fix this, open RegEdit and go to the following location:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters

and change the Workgroup field from 1 to 0


text:
Q: Double Curtain Reveal Effect of Footer I'd like to build a footer, which reveals when the bottom of page is reached, kinda like this:
https://www.thecssninja.com/css/reveal-effect
So far so good, I have that.
What I want to add now is an additional information within the footer, which gets revealed, when the other part of the footer is shown completely.
One could say, that I have two fixed footer parts. After the whole page is scrolled it will reveal the first part. And then this first part must somehow change from fixed to normal positioning allowing it to scroll up further to reveal a second footer part (fixed) underneath.
Does somebody know any examples (can include JS stuff) or does anyone have a trick for this?
Thanks for all the help.
Cheers


text:
Q: Does $\exp(\ln(I+A))=I+A$ when $\|A\|<1$? For matrices, I know certain equalities like $e^{A+B}=e^Ae^B$ aren't always true. I'm curious, do $\exp$ and $\ln$ serve as inverses?
I saw earlier that if $\|A\|<1$, then $\ln(I+A)$ converges. My question is, does
$$
\exp(\ln(I+A))=I+A
$$
when $\|A\|<1$? Certainly $\exp(\ln(I+A))$ converge since $\ln(I+A)$ converges and $\exp(\cdot)$ converges for all matrices, but do we necessarily get the original matrix back?

A: Yes, you do get the original matrix back. One way to see this is to recall that it is true for the reals and these are analytic functions (the one with log suitably restricted).
So you can develop both $\exp(x)$ and $\ln(1+x)$ into powerseries (the former converges everywhere and the latter for $|x|<1$).
But now you could consider these powerseries as formal powerseries, say denoting them by $E(X)$ and $L(X)$, respectively.
Then you can check (or rather it also follows) from the result for the reals that $E(L(X)) =1+X$ as formal powerseries.
So it also holds when you plug in a matrix (such that the series converge).
Note: you recalled the exponential identity that does not always hold, and one might now think my argument is bogus as it would also show the former, but it is not as it does not show it, since  while it is true that $\exp(X+Y)=\exp(X)\exp(Y)$ as formal powerseries the variablex $X,Y$ are assumed to commute. So, you need this too for the matrices. And if it is true that $AB=BA$ then infact $\exp(A+B)=\exp(A)\exp(B)$.

A: Another more analytical approach than quid's fine answer is the following:
In the unit ball of $\text{Mat}_n(\mathbb{C})$ the diagonalizable matrices (that are in the ball) are dense. It is trivial to verify the equation
$$\exp(\log(1+A))=1+A$$
holds for $A$ in the unit ball, and diagonalizable. Then, you can use the fact that both $X\mapsto \exp(\log(1+X))$ and $X\mapsto 1+X$ are continuos functions from the unit ball to $\text{Mat}_n(\mathbb{C})$. Since the latter space is metrizable (Hausdorff) and the diagonalizable matrices are dense, it follows that $X\mapsto \exp(\log(1+X))$ and $X\mapsto 1+X$ must agree on the unit ball.


text:
Q: Mac keyboard shortcut to strip special characters and search selected text in youtube Often I will look at a podcasts tracklist and identify the songs I would like to download. My process looks something like this:

*

*Go to tracklist page

*Select a song name (which on the occassion has underscores / hyphens instead of spaces)

*Switch to my YouTube tab

*Paste the text

*Remove any special characters such as underscores and/or hyphens

*Search

I would like to create a keyboard shortcut that would take my selected text, strip out any special characters (mostly concerned about hyphens and underscores), and create a YouTube search for it in a new tab. I am on Mac OS X 10.6 and use FireFox for the most part. Any ideas?

A: Greasemonkey might be able to help you out here, or you may like to use this bookmarklet:
javascript:void(window.open("http://www.youtube.com/results?aq=f&oq=&search_query="+window.getSelection().toString().replace(/\W+/g,'+')));


text:
Q: How to check which version of Java is installed before a user tries to run an application? If a user double-clicks on an executable JAR file, is it possible to check what version of Java that he or she has installed, and then display an appropriate message in a window that says that he or she needs to have X version of Java to run the application?
I am creating an application that requires Java 7, and if a user does not have that version installed, I would like to display a message that says that he or she needs to download and install it.
Of course, the user can type java -version, but it would be nice to display the version in a window for those who don't know how to check what version is installed. Is it possible to do so?
Or should I run some type of script to check before launching the application?

A: Check the System.getProperty("java.version")
You'll need to do some parsing, but this should give you a jumping of point

A: You can get the java version by using
System.getProperty("java.version")
See the documentation (http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html)


text:
Q: Jquery/JS script to handle multiple selection on my JSP Page On my JSP Page have select field like this, Need to write a script- SCript should be like sending value from front end as per user selection. If selected is ALL US than all 4 entries should be selected, If all NJ than all inside NJ Should be selected and sent back to database in sql query.
<select multiple="multiple" class="form-control" id="SelectRegion" name="SelectRegion">
<option value="0" selected="selected">All(US)</option>
<option value="00001">All (NJ) </option>
<option value="123">Ship -1008 (NJ - 123) </option>
<option value="234">Ship -4120 (NJ - 234) </option>
<option value="00040">All (CA) </option>
<option value="345">Ship -1008 (CA - 345) </option>
<option value="567">Ship -4120 (CA - 567) </option>
</select>

A: If you're going to hardcode the specific values you want selected, then you can just set the values of your select tag directly using jQuery like so:
if ($("#SelectRegion").val() == 0) {
    $("#SelectRegion").val(["123", "234", "345", "567"]);
}

Otherwise, you can add a class name to the elements for US and NJ and have some jQuery trigger whatever event you would like to select them dynamically:
if ($("#SelectRegion").val() == 0) {
    $('.US').prop("selected", true);
}

If you don't necessarily need the selection reflected on the front end and just need the corresponding values, then you can again use class names to iterate through the values:
if ($("#SelectRegion").val() == 0) {
  $(".US").each(function() {
      // do something
  });
}


text:
Q: django-form-designer admin URLs not going through I'm setting up a website using django-cms and wanted to use philomat's django-form-designer I downloaded it and followed the steps as laid out in the readme, but when I go to the admin, I can see there's a category for the app, but none of the two links go through...they give 404's.
What could I be missing?  The app is exactly what I want and would be glad if someone has insight on this problem.

A: Seems I managed to solve the issue....the instructions say you can skip adding form_designer to INSTALLED_APPS, but adding it solved my problem.  Hope this helps someone in future


text:
Q: How do you force a java swt program to "move itself to the foreground"? Currently with swt, I sometimes want a program to arbitrarily come to the foreground (like an alarm clock might).
Typically the following works (jruby):
@shell.setMinimized(false)
@shell.forceActive

This brings the shell to the front if it was minimized.
Creating a new shell at any time also brings the (new shell) to the front.
So far so good, however, if the shell is not minimized, the above code just flashes (blinks) the app's icon in the taskbar.  Well actually the first time you run it, it brings it to the front.  After that, it just blinks in the taskbar.  That's windows.  On Linux it appears to only blink in the taskbar (ubuntu default).
Does anybody know of a cross platform way of getting the app to come to the front, in swt?
It seems that no incantation of forceActive setActive setMinimized(false) setFocus forceFocus and setVisible can accomplish this thing.
I'm pretty sure it is possible (at least in windows), as the E Text Editor does it.  Well, that's not swt, but at least some other apps have been known to do it.
I'm thinking maybe this is swt bug 192036?
Many thanks.
Related:

*

*How to bring a window to the front?

*Opening a Shell

*Keep window in foreground (even if it loses focus)

*Bug 244597 - Cannot activate shell programatically on gtk

*Need to bring application to foreground on Windows

*How to bring a window to the front? this swing example might be some type of clue, too...

A: http://github.com/rdp/redcar/commit/d7dfeb8e77f13e5596b11df3027da236f23c83f0
shows how I did it in windows, anyway (using ffi).
A couple of helpful tricks "may" be
add a 'sleep 0.1' after the BringToFront.SetForegroundWindow(wanted)
call (hopefully this one isn't actually necessary).
add a shell.set_active after you have brought the window to the foreground.  For some reason forceActive doesn't call setActive.
NB that setActive does a user32.dll BringWindowToTop call, and needs to be done before you detach thread input.
Note also that it appears if you can do you calls in the right order you may not need to use the thread input hack at all (?)
http://betterlogic.com/roger/?p=2950
(contains several good hints on how to actually do this right)
On Linux, forceActive does work--but only until you move to another few windows,, then it blinks in the taskbar after that (only). Guessing swt bug. [1]
Also related:
How to bring a window to the front?
http://github.com/jarmo/win32screenshot/blob/master/lib/win32/screenshot/bitmap_maker.rb#L110 "set_foreground" which seems to work with both xp and windows 7
[1] Need to bring application to foreground on Windows and https://bugs.eclipse.org/bugs/show_bug.cgi?id=303710

A: This worked for me on Windows 7 and Ubuntu:
private void bringToFront(final Shell shell) {
    shell.getDisplay().asyncExec(new Runnable() {
        public void run() {
            shell.forceActive();
        }
    });
}

A: This is actually a feature of Windows, which can be enabled via the Tweak UI power toy (at least for Windows XP).  When enabled the O/S deliberately prevents a window from forcing itself to be the focused window to stop it "stealing focus".  As such, the action to grab focus is changed to just flashing the taskbar icon - since the O/S is deliberately converting the action at the user's request, there will be nothing you can do about it (and this is a good thing).
This was (probably) done because so many applications abused the bring-to-front API and the behavior both annoyed users and caused them to input into the wrong application.

A: Bug 192036 - Shell.forceActive doesn't raise a window above all other windows
@rogerdpack's query on Eclipse bug tracker was answered with the following dirty workaround doing what we need.
public void forceActive(Shell shell) {
    int hFrom = OS.GetForegroundWindow();

    if (hFrom <= 0) {
      OS.SetForegroundWindow(shell.handle);
      return;
    }

    if (shell.handle == hFrom) {
      return;
    }

    int pid = OS.GetWindowThreadProcessId(hFrom, null);
    int _threadid = OS.GetWindowThreadProcessId(shell.handle, null);

    if (_threadid == pid) {
      OS.SetForegroundWindow(shell.handle);
      return;
    }

    if (pid > 0) {
      if ( !OS.AttachThreadInput(_threadid, pid, true)) {
        return;
      }
      OS.SetForegroundWindow(shell.handle);
      OS.AttachThreadInput(_threadid, pid, false);
    }

    OS.BringWindowToTop(shell.handle);
    OS.UpdateWindow(shell.handle);
    OS.SetActiveWindow(shell.handle);
  }

A: private static void onTop(Shell shell) {
        int s = -1;
        Shell[] shells = display.getShells();
        for (int i = 0; i < shells.length; ++i) {
            if (!shells[i].equals(shell)) {
                shells[i].setEnabled(false);
                shells[i].update();
            } else {
                s = i;
            }
        }
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        for (int i = 0; i < shells.length; ++i) {
            if (i != s) {
                shells[i].setEnabled(true);
                shells[i].update();
            }
        }
    }

A: There is a way to make it work with what you initially tried. You actually need to call shell.setMinimized(false) and after that shell.setActive() to restore the previous state of the shell. However, that only works if the shell was truely in the minimized state. So here is my final solution, which artificially minimizes the shell if it was not minimized already. The cost is a quick animation if the minimization has to be done.
shell.getDisplay().syncExec(new Runnable() {

    @Override
    public void run() {
        if (!shell.getMinimized())
        {
            shell.setMinimized(true);
        }
        shell.setMinimized(false);
        shell.setActive();
    }
});