text:
Q: iOS: Rendering UITableView into PDF I have written pdfGenerator class to render whole UITableView to generate PDF.
Usage:
[pdfGenerator createPDFFromTableview:self.tableView];

Class Methods:
- (void)createPDFFromTableview:(UITableView *)tableview {
    [tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self renderTableView:tableview];

    int rows = [tableview numberOfRowsInSection:0];
    int numberofRowsInView = 17;
    for (int i = 0; i < rows/numberofRowsInView; i++) {
        [tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(i+1)*numberofRowsInView inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
        [self renderTableView:tableview];
    }
}

- (void)renderTableView:(UITableView*)tableview {
    UIGraphicsBeginImageContext(tableview.frame.size);
    [tableview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *tableviewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIGraphicsBeginPDFPage();
    [tableviewImage drawInRect:tableview.frame];
}

This code scrolls tableview correctly but it create PDF only for first page and rest of pages are coming blank! I have no idea why it is happening while it should take current uitableview snapshot as is and render but it seems to do this only for first page. Can someone point out what could be wrong here? Is there any better way doing what I am trying to achieve?
[EDIT]
Following gives the same result;
int totalRows = [tableview numberOfRowsInSection:0];
int totalVisibleRows = 17;
for (int i = 0; i < ceil((float)totalRows/totalVisibleRows); i++) {
    [tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:i * totalVisibleRows inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

    [pdfGenerator renderTableView:tableview indexPathStart:[NSIndexPath indexPathForRow:i * totalVisibleRows inSection:0] indexPathEnd:[[tableview indexPathsForVisibleRows] lastObject]];
}

- (void)renderTableView:(UITableView*)tableview indexPathStart:(NSIndexPath *)startingIndexPath indexPathEnd:(NSIndexPath *)endIndexPath {
    CGRect rectToDraw = CGRectUnion([tableview rectForRowAtIndexPath:startingIndexPath], [tableview rectForRowAtIndexPath:endIndexPath]);

    NSLog(@"%@", NSStringFromCGRect(rectToDraw));

    UIGraphicsBeginImageContext(rectToDraw.size);
    [tableview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *tableviewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIGraphicsBeginPDFPage();
    [tableviewImage drawInRect:rectToDraw];
}

Output rectToDraw:
{{0, 0}, {768, 720}}
{{0, 680}, {768, 720}}
{{0, 1360}, {768, 720}}
{{0, 2040}, {768, 360}}

A: I end-up rendering the view which is holding tableview after scrolling tableview programmatically. Rendering tableview doesn't seem to be working after scroll!

A: Your graphics context is initialized with the frame of the UITableView, so it'll always look at the 'first page'. The graphics context for the following 'pages' would need the context offset of the internal UIScrollView of your UITableView. Barring any trickery to access the UIScrollView directly, I suggest you use the [UITableView rectForRowAtIndexPath:] method to get the CGRects of the first and last row you want to draw in the step (i.e. page) and CGRectUnion them to get a rect which will include both (and by that all the rows inbetween).
Edit (as requested in comments):
You'd basically replace the rendering message in your loop with something like that
[self renderTableView:tableview
       indexPathStart:[NSIndexPath indexPathForRow:row inSection:0]
         indexPathEnd:[[tableview indexPathsForVisibleRows] lastObject]];

And your rendering method would then look like:
- (void)renderTableView:(UITableView*)tableview indexPathStart:(NSIndexPath *)startingIndexPath indexPathEnd:(NSIndexPath *)endIndexPath{
    CGRect rectToDraw = CGRectUnion([tableview rectForRowAtIndexPath:startingIndexPath], [tableview rectForRowAtIndexPath:endIndexPath]);
    NSLog(@"%@", NSStringFromCGRect(rectToDraw));
   //...
}

As to your question about the indexPaths. The indexPath.row will not be always 0-16. They will be 0-16, 17-34, 35-51, etc. This also reflects on your context, i.e. you want to draw the rect for the relevant indexPath rectangle, as this is the 'place' where the layer backing the UITableView has the backing store for the currently rendered graphics. Not knowing your PDF drawing routine, you might need to check your drawing rect there too.


text:
Q: filter in ForEach based on id from another API SwiftUI This is the struct having id and image url :
struct SampleImageLink:Codable{
    let success:Bool
    let message:String
    let linkResponse:[LinkResponse]

    enum CodingKeys: String, CodingKey{

        case success = "IsSuccess"
        case message = "Message"
        case linkResponse = "ResponseData"
    }
}

struct LinkResponse:Codable,Identifiable{

    var id:Int
    let fileName:String

    //fileName is the link for image url and id is unique id associated with url

    enum CodingKeys: String, CodingKey{

        case id = "Id"
        case fileName = "FileName"
    }

}

Given below is the json response from another API
{
    "IsSuccess": true,
    "Message": "Data Returned",
    "ResponseData": [
        {
            "TestId": 681,
            "TestName": "Acidity Check Profile",
            "Type": "Package",
            "MRP": 0.0,
            "NetAmount": 0.0,
            "TestListForPackage": [
                {
                    "TestId": 274,
                    "TestName": "Sugar (Glucose) Fasting",
                    "TestCode": null,
                    "Type": null,
                    "MRP": 0.0,
                    "NetAmount": 0.0,
                    "TestPackageGroupId": null,
                    "MetabolitesList": [
                        {
                            "MetaboliteId": 820,
                            "MetaboliteName": "Glucose (Fasting)",
                            "TestName": null
                        }
                    ],
                    "TurnAroundTime": 4,
                    "TurnAroundTimeString": ""
                },
                {
                    "TestId": 1096,
                    "TestName": "Serum Electrolyte Profile",
                    "TestCode": null,
                    "Type": null,
                    "MRP": 0.0,
                    "NetAmount": 0.0,
                    "TestPackageGroupId": null,
                    "MetabolitesList": [
                        {
                            "MetaboliteId": 1117,
                            "MetaboliteName": "Chloride",
                            "TestName": null
                        },
                        {
                            "MetaboliteId": 1116,
                            "MetaboliteName": "Potassium",
                            "TestName": null
                        },
                        {
                            "MetaboliteId": 1115,
                            "MetaboliteName": "Sodium",
                            "TestName": null
                        }
                    ],
                    "TurnAroundTime": 4,
                    "TurnAroundTimeString": ""
                },
              ],
            "SampleTypeList": [
                {
                    "TestSampleTypeId": "51",
                    "SampleName": "Fluoride Plasma - F",
                    "PackageId": 681,
                    "PackageName": null

                },
                {
                    "TestSampleTypeId": "55",
                    "SampleName": "EDTA Whole Blood",
                    "PackageId": 681,
                    "PackageName": null

                },
                {
                    "TestSampleTypeId": "50",
                    "SampleName": "Serum",
                    "PackageId": 681,
                    "PackageName": null

                }
            ]
        }
    ]
}

Below is the struct for above json.
struct PriceDetailResponse:Codable{
let success:Bool
let message:String
let response:[DetailResponse]

enum CodingKeys: String, CodingKey{

    case success = "IsSuccess"
    case message = "Message"
    case response = "ResponseData"
}}

struct DetailResponse:Codable, Identifiable{

    var id: Int{testId}
    let testId:Int
    //define items
    let testPackage:[TestListPackage]
    let sampleType:[SampleList]

    enum CodingKeys: String, CodingKey{

        case testId = "TestId"
       //define items
        case testPackage = "TestListForPackage"
        case sampleType = "SampleTypeList"
    }
}

struct TestListPackage:Codable{

    //define all items
    let metabolite : [Metabolites]

    enum CodingKeys: String, CodingKey{

        case metabolite = "MetabolitesList"

    }
}

struct Metabolites:Codable{
    //define items
}

struct SampleList:Codable, Identifiable{
    var id:Int{packageId}

    let testSampleTypeId : String
    let sampleName : String
    let packageId : Int
    let packageName : String?

    enum CodingKeys: String, CodingKey{

        case testSampleTypeId = "TestSampleTypeId"
        case sampleName = "SampleName"
        case packageId = "PackageId"
        case packageName = "PackageName"

    }
}

All is working fine. I have also displayed images using UIImage and Asyncimage. However, the requirement is image should be displayed if
Id from SampleImageLink struct == TestSampleTypeId of SampleList struct

I have created a view to display images, now need to filter the ids so that only the above matching id images should display
for eg:
ForEach(imgModel.link.filter{$0.id == 51}){img in
                        ImageLoader(urlString: img.fileName)
                   }
//imgModel is the ImageViewModel object.

is working fine. But how to iterate over SampleList and match with id of image What is the way to do it (id in SampleImageLink is int whereas in SampleList, testSampleTypeId is string).

A: One approach could be to cast testSampleTypeId to an Int while decoding. This way you can compare to it in the ForEach loop:
struct SampleList:Codable, Identifiable{
    var id:Int{packageId}

    let testSampleTypeId : Int
    let sampleName : String
    let packageId : Int
    let packageName : String?

    enum CodingKeys: String, CodingKey{

        case testSampleTypeId = "TestSampleTypeId"
        case sampleName = "SampleName"
        case packageId = "PackageId"
        case packageName = "PackageName"

    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        sampleName = try container.decode(String.self, forKey: .sampleName)
        packageId = try container.decode(Int.self, forKey: .packageId)
        packageName = try container.decodeIfPresent(String.self, forKey: .packageName)
        // decode to a String, cast it to an Int and check if successfull; else throw error
        guard let testSampleTypeId = Int(try container.decode(String.self, forKey: .testSampleTypeId)) else{
            throw DecodingError.dataCorrupted(.init(codingPath: [CodingKeys.testSampleTypeId], debugDescription: "TestSampleTypeId could not be casted to type Int"))
        }

        self.testSampleTypeId = testSampleTypeId
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mac OS X pstopdf utility defaults to Letter page size I am using the a2ps utility from Homebrew to pretty print code, generating .ps files, and then the Mac OS X utility pstopdf (used by Preview.app) to convert these to .pdf format. But whatever page size is specified in the PostScript, the generated PDF files have a Letter page size of 11 x 8.5 inches.
For example
a2ps --medium=A4 -P file myfile.py

or
a2ps --medium=A3 -P file myfile.py

generate PostScript files with the correct page dimensions (A4 and A3 respectively) but when converted to PDF by pstopdf the resulting PDF is Letter size with the output truncated at the right/ bottom edge of the page.
I can't find any mention anywhere of how to specify what default page size pstopdf uses.  Opening the PostScript files in Preview.app uses pstopdf in the back end so I get the same result.

A: If I remove all page size information from a PostScript file, then Preview renders it on a Letter page, even though my default Paper size in CUPS is A4.
There are no user-accessible options or preferences that I can discern. It's certainly undocumented, if it exists.
You may be better off trying to explicitly define the page size in a2ps.
Alternative PDF creators, like GhostScript, offer greater control over the output.


text:
Q: How to do all includes in source file? Is it possible to write all includes in the source file?
Let's say we have to write a module called sum (sum.h/sum.c) that provides sum functions for all numeric types.
All function declarations are done in sum.h file as follows:
uint16_t sum(uint16_t a, uint16_t b); // uint16 sum function
in this case I have to include <stdint.h> in sum.h.
Is it possible, for any version of the C standard, to do this include in the source file sum.c?

A:
Is it possible, for any version of the c standard, to do this include in the source file sum.c .

It is possible in all versions of the C standard to include the standard header in the source file. In fact, doing so is arguably recommended.
However, if you were asking if you could avoid including the header in sum.h while still relying on the typedef (and without forcing the code including sum.h to include the standard header before including sum.h: bad design!), no there's no C standard version where that's possible.

A: Either is fine as far as the C standard goes, as long as each inclusion is done before a feature from the included header is used.
Apart from that, there are two schools of coding style:

*

*Either include all headers used by a module from the .h file, in order to document that modules file dependencies to the user.
Generally it's a good thing to tell the user of your code which headers that are required for the program to build. There's few things more frustrating than including some 3rd party lib in your code, then get "mysterious linker error: 1" and from there you have no idea why - at best the problem points somewhere inside the included lib.
Also, the header file itself might require access to various types or constants in the included files.

*Or alternatively include all headers used from the .c file, to hide the file dependencies.
There are scenarios when you are making a library and you only wish the user to interact with a single header file, hiding the internal file structure of the lib away from them, similar to private encapsulation. You might not want to expose information about which private headers your code are using to the caller - particularly if you are linking your code into a single lib binary (or DLL etc).
Which of these styles to use is fairly subjective and as indicated above, you might  use one style over the other depending on the requirements of the specific project.


text:
Q: I Want to Launch Visual Studio on D Drive Unlike what most people are going through to get Visual Studio off of their system drive, I was able to put Visual Studio on my D drive, mostly by accident.
I ended up doing this because I had installed Windows 10 on a shiny, brand new solid state drive, making my old C drive my new D drive.
The problem is that I can't find where to launch Visual Studio because that the actual application is deeply hidden inside numerous files and such. Even a start menu search given nothing helpful.
I'd either like to find and delete every single file associated with Visual Studio so that I could reinstall it, or find the actual application and launch it from the D drive.


text:
Q: HTML5 Banner Ad: Clicktag without URL We recently built an HTML5 banner ad for a client and they came back to us asking why we did not add clicktag to the banner.
We were not provided a URL so so we did not add a clicktag.
Is it possible to add a clicktag without having a URL?
I added this to my link tag, but when I use DoubleClick's validator, it still says the clicktag is missing.
<a href="javascript:void(0);" onclick="window.open(clickTag);">

Here's what I added to remove the error, but this implies that I need a URL to add the clicktag. Please advise.
<script type="text/javascript">
    // Change the value of this string to your URL
    var clickTag = "https://www.google.com/";
    </script>

A: You can use "#" tag in URL to skip the error.
var clickTag = "#";


text:
Q: Bootstrap toggle footer i try to make footer columns to be hidden on mobile platforms, and when press on title to open. Is there any way to make this with bootstrap without add any javascript?
My Code is:

Company

Login

About us

Why buy from us

Shipping & Returns

Secure Shopping

My account

Sign In

View Cart

A: You might add the hidden-xs and hidden-sm classes to the footer, so it won't show up on screens narrower than 963px.

A: If by Bootstrap alone, you mean CSS alone i can give you a solution that i kind of used a while ago
https://jsfiddle.net/arunzo/ybgayvL8/
Adding tabindex to the h4 tags with some css did it, But this could be insufficient for crossbrowser dependancy and stuff , use with caution.

Company

Login

About us

Why buy from us

Shipping & Returns

Secure Shopping

My account

Sign In

View Cart

and the css (you might want to put this inside your media query and five-three is for idenntification sakes consider adding a more semantic class name):
    @media screen and (max-width: 768px) {
    .five-three ul {
        display:none;
    }
    .five-three h4:focus + ul {
        display:block;
    }
    }

A: you can use media queries (in css) to hide your columns with a new rule you define.
here an exemple :
html :

Something

Another thing

css (new stylesheet):
@media screen and (max-width: 768px) {
   /*I take max-width: 768px because of bootstrap : sm is for 768px too*/
  .hide {
    display: none !important; /*You don't need !important if you load this stylesheet after you main one*/
  }
}


text:
Q: How can I separate a multi-page table (e.g. using longtable) by columns? I have a table with a lot of columns (about Model-Statistics). I already tried to use a (rotated) longtable, but I failed because I need to duplicate the first column and not the first row as a "header".
For example I would need to have the Columnes "Variables, Model 1, Model 2" on one page and "Variables, Model 3 & Model 4" on a another page.
If that is not possible, maybe someone knows if it is possible to label two separate tables as one (for the table index) (e.g. label Table 1 & Table 2 both as "Table 1")?
Edit: I am using the APA7-Man-class


text:
Q: What is an output file in python I'm starting to work on problems for google's Code Jam. However I there seams to be a problem with my submission. Whenever I submit I am told "Your output should start with 'Case #1: '". My output a print statement starts with ""Case #%s: %s"%(y + 1, p)" which says Case #1: ext... when I run my code.
I looked into it and it said "Your output should start with 'Case #1: ': If you get this message, make sure you did not upload the source file in place of the output file, and that you're outputting case numbers properly. The first line of the output file should always start with "Case #1:", followed by a space or the end of the line."
So what is an output file and how would I incorporate it into my code?
Extra info: This is my code I'm saving it as GoogleCode1.py and submitting that file. I wrote it in the IDLE.
import string
firstimput = raw_input ("cases ")
for y in range(int(first)):
    nextimput = raw_input ("imput ")
    firstlist = string.split(nextimput)
    firstlist.reverse()
    p = ""
    for x in range(len(firstlist)):
        p = p +firstlist[x] + " "
    p = p [:-1]
    print "Case #%s: %s"%(y + 1, p)

A: Run the script in a shell, and redirect the output.
python GoogleCode1.py > GoogleCode1.out

A: I/O redirection aside, the other way to do this would be to read from and write to various files. Lookup file handling in python
input_file = open('/path/to/input_file')
output_file = open('/path/to/output_file', 'w')
for line in input_file:
    answer = myFunction(line)
    output_file.write("Case #x: "+str(answer))
input_file.close()
output_file.close()

Cheers

A: Make sure you're submitting a file containing what your code outputs --  don't submit the code itself during a practice round.


text:
Q: Find and Revoke User in GCP Project We have no of GCP projects (Ex: 50 projects) under an organization. We want to revoke one of the user access, but not sure what are all the projects he has the access. So we need to identify that user access list and then revoke the same.
As a 1st step I tried the following command to fetch user and roles details. But it gives all the users info. I couldn't find the parameter for the specific user.
gcloud projects get-iam-policy "project-id"
Can anyone help me in this scenario.

A: As @John Hanley mentioned in comments, using Cloud Identity Platform can be the best workaround in this situation. Besides there are some other ways in revoking access of the user.
This following steps will be an efficient and secure way to revoke a user's access:
1.In the Google Cloud Platform console, go to the IAM permissions page.
2.Select the project you want to remove an account from.
3.Click the checkbox next to the row containing the account you want removed from the member list, then click Remove. Alternatively, click the trash      can icon next to the account you want to remove.
This documentation has detailed instructions of revoking a user account from GCP and to get the roles assigned to the user refer to this documentation.


text:
Q: Does MySQL compress query responses? I am currently trying to optimise some DB queries that get run a lot, the queries are run by using a SELECT query against a view, this view does a lot of joins. I thought I might be able to speed things up by caching the results of the view into a table and selecting from the table instead of the view.
Let's say I have 2 tables
People:

PersonId
Name

1
Anne

2
Brian

3
Charlie

4
Doug

CustomerPeople:

CustomerId
PersonId

1
1

1
2

1
3

1
4

2
1

2
2

and I have a view that joins the two tables to give a list of people, by name, belonging to the customer:

CustomerId
PersonName

1
Anne

1
Brian

1
Charlie

1
Doug

2
Anne

2
Brian

When I query the view, I look at the Duration/Fetch and it is 0.10 sec/4.00 sec
I decide to cache the view data into a table and create a new table:
CustomerNamedPeople

CustomerId
PersonName

1
Anne

1
Brian

1
Charlie

1
Doug

2
Anne

2
Brian

Which contains the exact same data, however now when I query the table, I look at the Duration/Fetch and it is 0.05 sec/6.00 sec
My understanding is the Duration is the time it takes MySQL engine to run the query, and Fetch is the time it takes the data to be returned to the client (over the network). Unsurprisingly the Duration was faster, and took only 50% of the time, which makes sense, there is no longer a join occurring, however the Fetch took 150% of the time, and is slower.
My question here is: Does MySQL do some sort of response stream compression, since it knows that Anne and Brian are repeated, it can send them only once and have the client "decompress" the data?
The reason I ask is because I am doing something similar but with 1,000,000 rows returned, the data in the two responses is identical, but the view Fetch takes 20 seconds, and the table Fetch is 60 seconds, most of the PersonNames are repeated more than once, so I am wondering if perhaps there is some sort of compression occurring in the response, should I not expect MySQL to take the same time to Fetch two sets of identical data?


text:
Q: Phantom equals sign in aligned equation When typing out long equations, I like to split everything up into separate lines and start each one off with an equals sign. How do I hide the first equals sign while keeping the layout exactly the same? I tried wrapping it with \phantom, but that oddly decreases the horizontal offset of the first line:

Here's the source for the above picture:
\documentclass[preview]{standalone}

\usepackage{amsmath}

\begin{document}
    \begin{align*}
        &\phantom{=} x^2 - 1 \\
        &= (x - 1) (x + 1) \\           &= 7
    \end{align*}
\end{document}

Moving the ampersands to the other side of the equals signs sort of works, but it makes the equals signs too close to the equations:

A: Rather ugly, but if you like...
\documentclass{article}
\usepackage{amsmath}

\begin{document}
    \begin{align*}
        {}& x^2 - 1 \\
        ={} &(x - 1) (x + 1) \\
        ={} &7
    \end{align*}
\end{document}

A: Your first attempt almost had it: you just need to write \phantom{{}={}} instead of \phantom{=}.
In the picture below, I've inserted Xs at the start of each line to help ascertain visually that the alignment is working.

\documentclass[preview]{standalone}
\usepackage{amsmath}
\begin{document}
    \begin{align*}
        &\phantom{{}={}} x^2 - 1 \\
        &= (x - 1) (x + 1) \\
        &= 7
    \end{align*}
\end{document}


text:
Q: How can I use Javascript to "click" a button that has no ID? I'm trying to click a button without ID. Already tried document.querySelectorAll and document.getElementsByClassName with no success.
The button code:
<input name="1X" type="2X" class="3X" style="width:160px;" value="4X" data-role="5X" role="5X" aria-disabled="false" tabindex="0">

A: Any element in the document can be selected using CSS selector syntax via:

*

*document.querySelector('css selector') (returns the first matching element)

*document.querySelectorAll('css selector') (returns all matching elements).

To actually click the button, just call click() on the element, like so:
var button1X = document.querySelector('input[name="1X"]');
button1X.click();

For more details on querySelector/All: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

A: You can use element name:
document.getElementsByName( '1X' )[0] or document.querySelector( '[name="1X"]' )
Or any attribute:
document.querySelector( '[data-role="5X"]' )
getElementsByClassName returns HTMLCollection, not single element. You can get access to single element in array-style:
document.getElementsByClassName( '3X' )[0]
The same thing is with getElementsByName
And make sure that your attribute values (class, name, etc.) begin with a letter, not a digit


text:
Q: python list.sort() vs. list.sort(key=itemgetter(0)) I'm a python noob, but I'm using python to solve problems on leetcode.
I solved one on leetcode (merge overlapping intervals). I have the following code:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if len(intervals) < 2: return intervals
        intervals.sort(key=itemgetter(0))
        merged = [intervals[0]]
        for interval in intervals[1:]:
            if merged[-1][1] >= interval[0]: merged[-1][1] = max(merged[-1][1],interval[1])
            else: merged.append(interval)
        return merged

I noticed that if I replace intervals.sort(key=itemgetter(0))
with intervals.sort() I get noticably worse performance (~80ms vs. ~110ms respectively)
Isn't sort() technically the same as sort(key=itemgetter(0))? Shouldn't they have identical runtime?
Unless, is leetcode just being inconsistent with recoding the exact runtime?

A: Your main question has been already answered.

LeetCode's performance measurements are not accurate at all. You can just ignore their benchmark data as you solve problems.
class Solution:
    def merge(self, intervals):
        merged = []
        for interval in sorted(intervals, key=lambda x: x[0]):
            if merged and interval[0] <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], interval[1])
            else:
                merged.append(interval)
        return merged

class Solution:
    def merge(self, intervals):
        merged = []
        for interval in sorted(intervals):
            if merged and interval[0] <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], interval[1])
            else:
                merged.append(interval)
        return merged

References

*

*For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.

A: intervals.sort(key=itemgetter(0)) is different from intervals.sort().
intervals.sort(key=itemgetter(0)) only compare the first items of two intervals, but intervals.sort() compare the second when the first are same. So intervals.sort(key=itemgetter(0)) may has more intervals look the same to sort, or just do less compare when compare intervals. It maybe one reason the first one run faster.
An other possible reason is optmization. Also Python is interpreted language, the interpreter may generate biniry code when running, and do some optmization. Which one will get better performance is dependent on the interpreter.
But empirically, in most online judges, the diffrence about 30ms is just measurement error.
Try again you may get a different result.


text:
Q: Java regex help I'm trying to write a regular expression for Java's String.matches(regex) method to match a file extension. I tried .*.ext but this doesn't match files ending in .ext just ext
I then tried .*\.ext and this worked in a regular expression tester but in Eclipse I am getting an invalid escape sequence error.
Can anyone help me with this?
Thanks

A: Here's a test program that shows you the regex to use:
public class Demo {
    public static void main(String[] args) {
        String re = "^.*\\.ext$";
        String [] strings = new String[] {
            "file.ext", ".ext",
            "file.text", "file.ext2",
            "ext"
        };
        for (String str : strings) {
            System.out.println (str + " matches('" + re + "') is " +
                (str.matches (re) ? "true" : "false"));
        }
    }
}

and here's the output (slightly edited for "beauty"):
file.ext   matches('^.*\.ext$') is true
.ext       matches('^.*\.ext$') is true
file.text  matches('^.*\.ext$') is false
file.ext2  matches('^.*\.ext$') is false
ext        matches('^.*\.ext$') is false

But you don't really need that, a simple
str.endsWith (".ext")

will do just as well for this particular job.
If you need the comparison to be case insensitive (.EXT, .eXt, ...) for Windows, you can use:
str.toLowerCase().endsWith(".ext")

A: In eclipse (java), the regex String need to be "escaped":
".*\\.ext"

A: For such a simple scenario, why don't you just use String.endsWith?

A: Matches a dot followed by zero or more non-dots and end of string:
\.[^.]*$

Note that if that's in a Java string literal, you need to escape the backslash:
Pattern p = Pattern.compile("\\.[^.]*$");


text:
Q: BottomSheetDialogFragment does the enter animation again on `onStart`. How to halt it? Everytime when the BottomSheetDialogFragment passes through the onStart lifecycle point, the enter window animation occurs again, as can be seen in the gif below.

What can be done to stop it from happening? I thought that it would only happen once, when the bottom action sheet was opened.

The code is as simple as that:
MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val bottomSheet = CustomBottomSheetFragment()
        bottomSheet.show(supportFragmentManager, null)
    }
}

CustomBottomSheetFragment.kt
class CustomBottomSheetFragment : BottomSheetDialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = FrameLayout(requireContext())
        view.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            800
        )

        view.setBackgroundColor(Color.CYAN)

        return view
    }

}

Obs.: "Don't keep activities" option is not enabled :)


text:
Q: Maven deploy jar with dependencies to repo I can deploy a jar by using the following in my pom.xml and running mvn deploy:
    <distributionManagement>
    <repository>
        <id>releases</id>
        <url>http://${host}:8081/nexus/content/repositories/releases</url>
    </repository>
    <snapshotRepository>
        <id>snapshots</id>
        <name>Internal Snapshots</name>
        <url>http://${host}:8081/nexus/content/repositories/snapshots</url>
    </snapshotRepository>
</distributionManagement>

And I can build an executable jar-with-dependencies using the following:
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <id>create-executable-jar</id>
                    <phase>deploy</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                        <archive>
                            <manifest>
                                <mainClass>my.company.app.Main</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Problem is I don't know how to stitch these together to deploy the executable jar to my Maven repo.  I don't really know if this is accomplished by a new plugin or by adding a goal or other step to the existing assembly plugin.

A: In order to build a (so-called) Über JAR and deploy it using maven, you could also use the shade plugin. The following code is taken from their website but I've made one or two projects using this feature.
 <project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.0</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>true</shadedArtifactAttached>
              <shadedClassifierName>jackofall</shadedClassifierName> <!-- Any name that makes sense -->
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

In this configuration you get the Über JAR as one deployment besides the normal JAR. The user of your JAR can then decide to pull the all-in-one package or the JAR with dependencies based on the classifier.
I'll usually use the shade plugin to build Über JARs (or modify the JAR in a way) and use the assembly plugin to build things like installation packages (containing the JAR and possibly other things). I am unsure what the intended goals of the single plugins are however.

A: The following worked.  I'm going to leave this question open a bit because I'm not positive this is best practice, but working is something.
Problems I notice are that I made up the ID name and I don't know if this is usual practice and that I have to hard code the jar name; it isn't inferred from anything else.
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<executions>
    <execution>
        <id>deploy-executable</id>
        <goals>
            <goal>deploy-file</goal>
        </goals>
        <configuration>
            <file>target/Monitoring-Client-1.0-SNAPSHOT-jar-with-dependencies.jar</file>
        </configuration>
    </execution>
</executions>
</plugin>

A: If you bind the assembly to the packaging phase, it will install in your repository both the "regular" jar and the with-dependencies jar when you do a build:
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <archive>
                <manifest>
                    <mainClass>my.company.app.Main</mainClass>
                </manifest>
            </archive>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
        <executions>
            <execution>
                <id>make-assembly</id> <!-- this is used for inheritance merges -->
                <phase>package</phase> <!--  bind to the packaging phase -->
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

Then simply run mvn clean install deploy to upload both jars to your repository.

A: Essentially my difficulty doing this revealed the fact that my pom.xml was way off the rails already.  Everything would have snapped into place on its own.  I was formerly doing:

*

*Save all the dependencies into a lib folder

*Build a jar with a classpath slurping up that lib folder

*Use the assembly plugin to make another deployable jar

I think there were several reasons this sort of made sense along the way, especially when my libraries were not well-factored from my applications.
However by deleting 1 and 2 all that is needed is the distributionManagement section and the deploy phase works automagically.  So all in all this is an amazing case of literally adding functionality by deleting large swathes of code.

A: First you shouldn't do the creation of the ueber jar in the deploy phase it's better to do this in the package phase. Furthermore the created jar file is usually automatically attached to your artifact and will be transfered to the remote repository (in your case Nexus). You can check this if you simply try to do a mvn install and take a look at the output if the created jar is installed into the local repository.
To deploy the results into nexus you need to call mvn deploy.


text:
Q: How to align dropdown list and img button? Hi i have following (View)html code and css produced this result, how do i align it?
Result

View

@Html.DropDownListFor(model => model.tintFactorType , slFactorType, new { @class = "divfloatleft rulestextbox5" })

@Html.TextBoxFor(model => model.decFactorValue, new { @class = "divfloatleft rulestextbox6" })

@Html.TextBoxFor(model => model.decMaxBonus, new { @class = "divfloatleft rulestextbox7" })

@Html.TextBoxFor(model => model.nvarMsg , new { @class = "divfloatleft rulestextbox8" })

@Html.TextBoxFor(model => model.varVCode  , new { @class = "divfloatleft rulestextbox9" })

css
.rulestextbox5 {
    min-width: 125px !important;
    width:125px !important;
    height:30px !important;
    margin-right:6px;
    top:30px;
}

.rulestextbox6 {
    min-width: 80px !important;
    width:80px !important;
    height:20px !important;
    margin-right:6px;
}

.rulestextbox7 {
    min-width: 89px !important;
    width:89px !important;
    height:20px !important;
    margin-right:6px;
}

.rulestextbox8 {
    min-width: 72px !important;
    width:72px !important;
    height:20px !important;
    margin-right:6px;
}

.rulestextbox9 {
    min-width: 70px !important;
    width:70px !important;
    height:20px !important;
    margin-right:6px;
}

.removeimg {
     cursor:pointer;
    width: 19px !important;
    height: 18px !important;
    background: transparent url("images/basicsetup/remove.png") no-repeat center center !important;
}

A: It is a good idea to put all of them in a table with 5 columns and 1 row.
No need to use a seperate div for each component unless you need it. I put one component as an example the rest should be done the same way.

           @Html.DropDownListFor(model => model.tintFactorType , slFactorType, new { @class = "divfloatleft rulestextbox5" })

If you need to use class or ID just add it to them using span tag, since you need to make them disappear.

A: Remember to check with a dev tool the css that may be affecting your combobox and div besides the CSS you showed us.
position: relative;
top: 0px;

A: Just add display:block for .divfloatleft
CSS:
.divfloatleft {
 display:inline-block;
 float:left;
}


text:
Q: parSapply error. Function works without Parallel I have a working function but when running on AWS EC2 it only uses a single core and I want to convert to parallel
Original problem solved (without Parallel) at: apply - test multiple conditions before moving rows
I have installed the Intel MKL on the AWS EC2 server and that still runs using only a single core. I have tried to edit the code as below.
PipSize <- 0.00886

myfun <- function(x, df = EURUSD, Limit = PipSize, StopLoss = PipSize) {

  highComp <- which(df$High - df$Open[x] > Limit)
  highCompMin <- if(length(highComp) == 0) 0 else min(highComp)
  lowComp <- which(df$Open[x] - df$Low > StopLoss)
  lowCompMin <- if(length(lowComp) == 0) 0 else min(lowComp)

  if(highCompMin == 0 & lowCompMin == 0) {
    result <<- c(Limit = NA, Open = df$Open[x])
  } else if (highCompMin <= lowCompMin) {
    result <<- c(Limit = 1, Open = df$Open[x])
  } else {
    result <<- c(Limit= 0, Open = df$Open[x])
  }

  return(result)

}

t(sapply(1:10, function(x) myfun(x, df = EURUSD, Limit = PipSize, StopLoss = PipSize)))

Additional Parallel code that returns error
library("parallel")
library("doParallel")
n.cores <- detectCores()
cl <- makeCluster(n.cores, type="FORK")
clusterExport(cl, "myfun")
parSapply(cl, 1:10, myfun)

stopCluster(clust)

Error:
Error in checkForRemoteErrors(val) :
  8 nodes produced errors; first error: can only subtract from "POSIXt" objects

Head of EURUSD:
                  Date    Open    High     Low   Close
1  2016-01-03 17:00:00 1.08701 1.08713 1.08701 1.08713
2  2016-01-03 17:01:00 1.08712 1.08712 1.08712 1.08712
3  2016-01-03 17:02:00 1.08708 1.08722 1.08708 1.08722
4  2016-01-03 17:03:00 1.08717 1.08723 1.08717 1.08723
5  2016-01-03 17:04:00 1.08718 1.08718 1.08711 1.08711
6  2016-01-03 17:05:00 1.08703 1.08716 1.08701 1.08712
7  2016-01-03 17:06:00 1.08721 1.08721 1.08710 1.08710
8  2016-01-03 17:07:00 1.08712 1.08715 1.08712 1.08712
9  2016-01-03 17:08:00 1.08711 1.08720 1.08711 1.08713
10 2016-01-03 17:09:00 1.08716 1.08723 1.08708 1.08708

Intended outcome:
If (High-Open > limit) then return 1, if (Open - Low > StopLoss) return 0. If neither then compare the same Open price to the High and Low of the next period. When either 1 or 0 is returned then increment Open by + 1 and repeat the process.

A: I am unsure what the cause of the problem was, but I fiddled with the code and it now works and thought it may benefit others.
library("parallel")
library("doParallel")

n.cores <- detectCores()
cl <- makeCluster(n.cores, type="FORK")
clusterExport(cl, "myfun")
t(parSapply(cl, i:j, function(x) myfun(x, df = EURUSD2, Limit = k, StopLoss = k)))
stopCluster(cl)

I added the arguments to the myfun part of parSapply as well as changing the stopCluster argument.


text:
Q: Can't get ip2long() to work I'm trying to compare some IP addresses that are stored as strings. I read about ip2long() to convert the string to an integer so I'm playing around with it to see if it would do what I want. So, initially, I'm just trying to see what the converted IP looks like. I wrote the following code to look at that but nothing is being converted. I don't see what I'm doing wrong. Here is the code:
<?php
foreach($form->data[vicondb] as $video_net_key)
{
    if ($video_net_key['ipaddress'] != null)
    {
        echo "The IP address is " . $video_net_key['ipaddress'];
        $iplong = ip2long($video_net_key['ipaddress']);
        echo " --- The ip long conversion is " . $iplong . "
";
    }

} // End foreach($form->data[vicondb] as $video_net_key)

echo "End of both foreach statements
";
?>

Here is a sample of the result:

The IP address is 172.26.0.10 --- The ip long conversion is
The IP address is 172.26.0.31 --- The ip long conversion is
The IP address is 172.26.0.32 --- The ip long conversion is
The IP address is 172.26.0.33 --- The ip long conversion is

Here is a sample of the var_dump() for IP and converted to integer:
string(12) "172.26.0.10 "
bool(false)
string(12) "172.26.0.31 "
bool(false)
string(12) "172.26.0.32 "
bool(false)

A: It could be something similar like this
"Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address." From ip2long php.net article
This should work:
echo " --- The ip long conversion is " . sprintf("%u", ip2long($video_net_key['ipaddress'])) . "
";

A: You need to trim the IP as it seems to have a trailing space and is not valid:
$iplong = ip2long(trim($video_net_key['ipaddress']));


text:
Q: How to replace the duplicated values in a string by a specific character? How can I change the value of the duplicated character in a string?
if they are duplicated I want to have a specific value for that else if they are not, I also want to put a specific value for that too.
Scenario 1:
Input: hello
Output: ..??.
Scenario 2:
Input: elephant
Output: ?.?....
$str = "elephant";

$arr= str_split($str);

    for($i = 0; $i < count($arr); $i++) {
     for($j = $i + 1; $j < count($arr); $j++) {
        if($arr[$i] == $arr[$j]){

       }
     }
    }

I really don't know on how will I change the value of it then implode them again.

A: If you don't care about speed that much try this:

<?php

function transform($str) {
    $arr= str_split($str);
    $counted = array_count_values($arr);

    foreach($counted as $letter => $times) {
      if($times == 1) {
          $str = str_replace($letter, ".", $str);
      }else {
          $str = str_replace($letter, "?", $str);
      }
    }
    return $str;
}

var_dump(transform("elephant")); // string(8) "?.?....."
var_dump(transform("hello"));    // string(5) "..??."

array_count_values will store the amount of time each value is present in the array, so for "elephant" it looks like this:
array(7) {
  ["e"]=>
  int(2)
  ["l"]=>
  int(1)
  ["p"]=>
  int(1)
  ["h"]=>
  int(1)
  ["a"]=>
  int(1)
  ["n"]=>
  int(1)
  ["t"]=>
  int(1)
}

So then it's as easy as iterating over this array, and calling str_replace with '.' if the counted value is 1, and '?' otherwise.
It can be improved to be more performable, but that's not the point of this question.

A: try this:
$str = "hello";
$arr = str_split($str);
$duplicates = array_unique(array_diff_assoc($arr,array_unique($arr)));
for($i = 0; $i < strlen($str); $i++) {
   if(in_array($str[$i], $duplicates)) {
      $str[$i] = '?';
   } else {
      $str[$i] = '.';
   }
}
echo $str;


text:
Q: Is there a way to pass the object of two different class in one variable in different conditions I have two classes for language that I want to use at run-time in different conditions.
I want to get both the class's objects in one single variable, as per the condition. However, I am getting an error.
var constantCL = LanguageEnglish()
if languageType == Constants.LoginParameters.LANGUAGE_CODE_ENGLISH {
    constantCL = LanguageEnglish()
} else {
    constantCL = LanguageHindi()
}

Getting this error on constantCL = LanguageHindi() in my else:

Cannot assign value of type 'LanguageHindi' to type 'LanguageEnglish'

Screenshot of error:

A: This is an expected behavior since your language is an actual class, instead of something a bit more flexible.
Possible solutions:
Use a superclass for your languages, e.g.
class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()

Use a protocol instead, and implement it in your language classes (almost the same as above, difference is in implementation and declaration):
class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()

Or maybe use an enum to represent your languages, or a similar more elegant construct if it suits your needs:
enum Language {
    case english
    case hindi

    // Other useful stuff
}

var constantCL: Language = .english
constantCL = .hindi


text:
Q: Why is declaration and definition defined this way in Effective C++? In Effective C++ (3rd Ed.), Item 2 (Prefer const, enum and inline to #define), the code segment for class-specific constants read:
class GamePlayer {
private:
    static const int NumTurns = 5;    // constant declaration
    int scores[NumTurns];             // use of constant
    ...
};

The book then says (in my own words) that static const int NumTurns = 5; is not a definition, which is normally required by C++ for class members unless it is a static integral constant whose address is never used. If the above is not true for the constant or if the compiler insists on a definition for any reason, the definition should be provided in the implementation file as follows:
const int GamePlayer::NumTurns;    // definition of NumTurns; see
                                   // below for why no value is given

According to the book (also in my own words), no value is given in the definition because it's already given in the declaration.
This is confusing what I thought I already know about the definitions of declaration and definition (and I double-checked on Google before asking this question):

*

*Why is static const int NumTurns = 5 not a definition? Is NumTurns not initialized to a value of 5 here, and is it not that when a declaration and a definition occurs together, it is called an initialization?

*Why do static integral constants not require a definition?

*Why is the second code snippet considered to be a definition when no value is defined, yet the declaration inside the class which contains the value is still not one (essentially going back to my first question)?

*Isn't initialization a definition? Why is the "only one definition" rule not violated here?

It's possible I'm just confusing myself here at this point, so can someone kindly re-educate me from scratch: Why are those two lines of code declarations and definitions and not the other, and are there any instances of initialization there? Is initialization also a definition?
Credit: Code snippets are directly quoted from the book.
Edit: With additional reference to What is the difference between a definition and a declaration?

*

*A declaration introduces the identifier and type

*A definition instantiates and implements

So, yeah...that doesn't seem to be what's going on here.
Edit 2: I consider it is possible that compilers may optimize a static integral constant by not storing it in-memory and just substituting it inline in the code. But if NumTurns address is used, why doesn't the declaration change into a declaration+definition automatically since the instantiation is already there?
Edit 3:
(This edit has less to do with the original question, but is still outstanding from it. I place it here so that I don't need to copy-paste into the comments for each answer below. Please answer me for this in the comments. Thanks!)
Thanks for the answers. My head is much clearer now, but the last question from Edit 2 still remains: If the compiler detects conditions in the program where a definition is needed (eg. &NumTurns is used in the program), why doesn't it just automatically reinterpret static const int NumTurns = 5; as a declaration & definition instead of declaration-only? It has all the syntax a definition anywhere else in a program would have.
I come from a Java background in school, and have not needed to make separate definitions like these for static members in the manner above. I know C++ is different, but I want to know why the above is like this. A static integral member being substituted inline if the address is never used sounds more like an optimization to me rather than a fundamental feature, so why is it I need to work around it (providing a separate statement as the definition when the conditions aren't met even though the original statement's syntax is sufficient) rather than the other way round (compiler treating the original statement as a definition when it is needed to have one since syntax is sufficient)?

A: One of the consequences of the one-definition rule is that a static member of a class can only have one definition.   However, if multiple compilation units define it,  there would be one definition for every compilation unit within a program.   The net effect is that the declaration cannot be a definition without breaking the one-definition rule.   In practice, linkers are not typically smart enough to resolve such multiple definitions.
The reason static integral constants do not require a definition is that it is not necessary.   If the value is initialised within the class definition, the compiler can just substitute the initialised value whenever it is used.  Practically, this means there is no need for that value to actually occupy a memory location in the program (as long as no code computes the address of that constant, in which case a definition would be needed).
Declaration, definition, initialisation are actually separate (albeit related) concepts.   A declaration tells the compiler something exists.   A definition is a type of declaration that causes that something to exist (so code with visibility of other declarations can refer to it) - for example, allocates memory for it.   Initialisation is the act of giving a value.   This distinction actually occurs in other parts of the language.  For example;
#include <iostream>
int main()
{
     int x;   //  declaration and definition of x

     std::cout << x << '\n';    // undefined behaviour as x is uninitialised

     x = 42;   // since x is not yet initialised, this assignment has an effect of initialising it

     std::cout << x << '\n';    // OK as x is now initialised
}

In practice, an initialisation can be part of a declaration, but is not required to be.
Edited to respond to "Edit 3" in the original question:
C++ has a separate compilation model.  Java's model relies on capability (smarter linker, run time linking) that C++'s model does not. In C++, if one compilation unit sees a declaration but no definition, the compiler simply assumes the definition is in another compilation unit. Typically (with a lot of build chains) the linker later detects if a necessary definition does not exist, so the linking stage fails.   Conversely, if every compilation unit that needed a definition to exist actually created one, the compiler would break the "one definition rule", and a typical dumb linker - which among other things is not smart enough to collapse something defined repeatedly into a single definition - would complain about a multiply-defined symbol.

A:
Why is static const NumTurns = 5 not a definition? Is NumTurns not initialized to a value of 5 here, and is it not that when a declaration and a definition occurs together, it is called an initialization?

That's the wrong question. A declaration is where the compiler is notified that a type/variable/function/whatever exists, and what it is. A definition is where the compiler is instructed to actually allocate storage to keep said entity.
Since the member is "defined" inside the class' declaration (i.e. - no instance of the class is created at that point), then this is a declaration.
The equal sign you rely on in order to call this a definition is merely a default value for the struct member, not an initialization.

Why do static integral constants not require a definition?

You kinda answered that one yourself. It is because the compiler can avoid allocating any storage to them, and simply drop them into the code where used.

Why is the second code snippet considered to be a definition when no value is defined, yet the declaration inside the class which contains the value is still not one (essentially going back to my first question)?

As I said before, that's because the second code allocates storage for the variable.

Isn't initialization a definition? Why is the "only one definition" rule not violated here?

Because initialization is not definition.

If the compiler detects conditions in the program where a definition is needed (eg. &NumTurns is used in the program), why doesn't it just automatically reinterpret static const int NumTurns = 5; as a declaration & definition instead of declaration-only?

Because a definition allocates the storage. More specifically, because if the compiler did this, then there would be multiple storage allocations in different compilation units. This is bad, because, during linking, the linker needs to have only one. The linker sees several definitions of the same variable with the same scope, and does not know it has the same value. All it does know is that it cannot merge them all into a single location.
In order to avoid that problem, it makes you do the definition manually. You define it inside a cpp file (i.e. - not in the header), thus resolving the allocation to one specific file which the linker can stomach.

A: Disclaimer: I am not a standard guru.
I suggest you read the following two :
http://www.stroustrup.com/bs_faq2.html#in-class
and:
What is the difference between a definition and a declaration?

Why is static const int NumTurns = 5 not a definition? Is NumTurns not
  initialized to a value of 5 here, and is it not that when a
  declaration and a definition occurs together, it is called an
  initialization?

In high level, definition (as opposed to declaration) instantiates or implements the entity (variable, class, function). In case of variables, definition makes the variable be allocated on the program memory. In case of functions - definition gives instructions that can be compiled to assembly instructions.*
The line of code
static const int NumTurns = 5;

does not make NumTurns be allocated in the program memory by default, so it's only declaration. In order to make (the only) instance of NumTurns in the program memory you will have to provide the needed definition:
const int MyClass::NumTurns;

Bjarne quote:

You can take the address of a static member if (and only if) it has an
  out-of-class definition:

class AE {
    // ...
public:
    static const int c6 = 7;
    static const int c7 = 31;
};

const int AE::c7;   // definition

int f()
{
    const int* p1 = &AE::c6;    // error: c6 not an lvalue
    const int* p2 = &AE::c7;    // ok
    // ...
}

Why do static integral constants not require a definition?

They do if you want to take their addresses.

Isn't initialization a definition?

No. initialization is the act of setting initial values in some entity (primitive,object).
void someFunc (){
  int x; //x is declared, but not initialized
  int y = 0; //y is declared+ initialized.
}

Why is the "only one definition" rule not violated here?

Why would it ? You still have one NumTurns in the entire code. The symbol MyClas::NumTurns appears only once. The definition only makes the variable appear on the program memory. ODR rule specify that any symbol may be declared only once.
EDIT:
The question basically boils down to "Why can't the compiler decide on its own?"
I am not a member of the comitee, so I can't give fully legit answer.
My smart guess is that letting the compiler decide things is not the C++ philosophy.
when you let the compiler decide , e.g. where to declare a static integral const,
I, as a developer, may raise the following issues:
1)  what happens If my code is a headers-only library?
where should my compiler declare the variable? in the first cpp file it encounters?
in the file which containes main ?
2) if the compiler decides where to declare the variable , does I have any any guarantee
that this variable will be declared alongside with other static variables (which I have manually declared), thus keeping
the cache locality tight?
there are more and more questions raised as soon as we approve the mindset of "let the compielr go wild"
I think this is a fundamental difference between Java and C++.
Java: let the JVM do its hueristics.
C++: let the developer do his profiling.
eventually, in C++ , the compiler checks that everything makes sence and turn the code into binary,
not do the job instead of the developer.
*or bytecode, if you use managed C++ (boo...)


text:
Q: Wx.Media running in Windows but error in Linux First time i create video player with Wx.Media in windows, its fine. The code is working. When i try to running in Linux. Wx.Media doesn't run.
The give me information like this.
File "/usr/lib/python2.6/site-packages/wx-2.8-gtk2-unicode/wx/media.py", line 96,
in __init__ _media.MediaCtrl_swiginit(self,_media.new_MediaCtrl(*args, **kwargs))
 NotImplementedError


text:
Q: Why do conditionals inside of an event listener not work? When I have the conditionals inside of an event listener inside of a function, they don't seem to work properly [I commented them in]. In fact they don't work at all, but when I delete the conditionals everything works (except it works incorrectly because I need the conditionals) I'm a lot more familiar with Java if that helps in the explanation.
var board = document.getElementById("checkersBoard");
var isRedHighlighted = false;
var isBlackHighlighted = false;
var lastClick;
board.addEventListener("click", function(e)
{

    //alert(e.target.src);

    if(isBlackHighlighted || isRedHighlighted)
    {
        if(isBlackHighlighted)
        {
            e.target.src= "Directory/BlackPiece.png";
            lastClick.src = "Directory/BlankSpace.png";
            isBlackHighlighted = false;
        }
        if(isRedHighlighted)
        {
            e.target.src= "Directory/RedPiece.png";
            lastClick.src = "Directory/BlankSpace.png";
            isRedHighlighted = false;
        }

    }

    else
    {
        if (e.target.src == "Directory/BlackPiece.png") // why does this not work
        {
            e.target.src = "Directory/BlackPieceH.png"
            lastClick = e.target;
            isBlackHighlighted = true;
        }

        if (e.target.src == "Directory/RedPiece.png")  // why does this not work
        {
            e.target.src = "Directory/RedPieceH.png"
            lastClick = e.target;
            isRedHighlighted = true;
        }

    }
});

A: Judging by the strings you're comparing against, such as: "Directory/BlackPiece.png", it seems that you're intending to compare the variable(s) against the value of the src attribute (e.target.getAttribute('src')), rather than the src property (e.target.src).
This would yield a comparison such as, for example:
e.target.getAttribute('src') = "Directory/BlackPiece.png";

The difference between the two is that the src attribute looks at the attribute-value found within, and retrieves the value from, the specified attribute.
Whereas the src property resolves to an absolute URL, which would give a value similar to: http://www.example.com/Directory/BlackPiece.png.
References:

*

*Element.getAttribute.

*HTMLImageElement.src.


text:
Q: Remove the unwanted commented code copied from word using php
Possible Duplicate:
PHP to clean-up pasted Microsoft input

Need to remove the code in comments
[if gte mso 9]><xml> <w:WordDocument>  ..... --> [endif] -->

from my db field, when copying text from word and saving this unwanted code is coming.In Ie the source after this was not displaying as it causes display problems

A: If thats the exact string you would like to clean then you can use something like this
 $clean_string = preg_replace("/(\[if.+?\[endif\]\s{0,}-->)/","",$dirty_string);

Example here
http://ideone.com/cf0MG
Updated ideone link
http://ideone.com/08L6L

A: try this:
$clean_string = preg_replace("/(\[if\s.*?\].*?\[endif\]\s*-->/)","",$dirty_string);

A: Take a look at the paste plugin:

[paste_remove_styles] If true, removes all style information when pasting, regardless of browser type. Pasting from Word 2000 will cause tinyMCE to error. Default is false.


text:
Q: Find value in Jade array I want to populate a html form using data passed through the variable 'object'. The form has some checkbox inputs. I thought I could perhaps check if a certain value exists in data.array, then add 'checked' to the box if it does. However, I have no idea if something like this is possible (without using mixins at least, as I can't get them to work in-line), or if there is an easier way to populate the checkboxes.
Checkbox item:
input.form-control(type="checkbox" value="item1" name="items")

Mixin:
mixin inArray(array, value)
    - for (var i = 0; i < array.length; i++)
            if array[i] === value
                    | checked

Attempted:
input.form-control(type="checkbox" value="item1" name="items" #[+inArray(object.items, 'item1')])

HTML result:
<input type="checkbox" value="item1" name="items" #[+inarray(object.items="" item1')]="" class="form-control">

A: You could use Array.includes() method in conjunction with boolean attribute to check only checkboxes that contain a specific value:
input.form-control(type="checkbox" value="item1" checked=object.items.includes('item1'))


text:
Q: Question about inequality and logarithms Let's say we have an inequality:
$x < y$
does this hold true?
$\log x < \log y$
and if so, how can I prove it?

A: Hint: $f(x)=\log_a (x)\Rightarrow f'(x)=\frac{1}{\ln (a) x}$

A: Let $\log_{B}{x}=a$ and $\log_{B}{y}=b$ for $B>0$. Then $ x=B^{a} $ and $ y=B^{b} $. So we can write $$x<y\Rightarrow B^{a}<B^{b}.$$
If $0<B\leq 1$, then
$$\begin{eqnarray}
B^{a}<B^{b} & \Rightarrow & a>b \\ & \Rightarrow & \log_{B}{x}>\log_{B}{y}
\end{eqnarray}
$$but otherwise (say $B>1$),
$$\begin{eqnarray}
B^{a}<B^{b} & \Rightarrow & a<b \\ & \Rightarrow & \log_{B}{x}<\log_{B}{y}
\end{eqnarray}$$


text:
Q: Unknown error while parsing Json data from url while parsing below code, I am getting unknown BaseException as ' search-results' or 'citedby-count' for some of the queries which are perfectly similar to other queries.
Thanks in advance.
            params = get_connection_parameters(title)
            r=requests.get(params[0],headers=params[1],timeout=60)
            response = r.content
            data = json.loads(response)

            try:
                c_data = data['search-results']['entry'][0]['citedby-count']
                value = row.strip("\n")+','+str(c_data)
                output.write("\n"+value)
            except BaseException as b:
                print(b)

json data to be parsed:
{"search-results":{
    "opensearch:totalResults": "1",
    "opensearch:startIndex": "0",
    "opensearch:itemsPerPage": "1",
    "opensearch:Query": {
        "@role": "request",
        "@searchTerms": "TITLE(daime, a novel image analysis program for microbial ecology and biofilm research)",
        "@startPage": "0"
    },
    "link": [
        {
            "@_fa": "true",
            "@ref": "self",

        },
        {
            "@_fa": "true",
            "@ref": "first",

        }
    ],
    "entry": [
        {
            "@_fa": "true",
            "prism:url": "https://api.elsevier.com/content/abstract/scopus_id/33644868597",
            "eid": "2-s2.0-33644868597",
            "dc:title": "daime, a novel image analysis program for microbial ecology and biofilm research",
            "citedby-count": "298"
        }
    ]
}

}


text:
Q: How to check that new app.js file is available without refreshing page? I have SPA created with ReactJS and I need to check if new SPA version is released when current session is opened.
I mean if user open SPA with app.js?v=x and when we create the new release, a user should be informed about a release and will be asked to refresh the page.
What is the best way to do this?
Thanks !


text:
Q: How do I update the FileVault 2 recovery key stored in iCloud? It's been a long saga getting to the point where I am comfortable that my new Macbook Pro has FileVault 2 enabled properly on Yosemite.
I ran into the "Encryption paused - connect power adapter" problem several times. Had to do a hard-disk erase and full re-install twice, and spent hours online with Apple support.
Eventually, encryption completed and it told me "A recovery key has been set" ... but never told me what the key was!
Today, I disabled encryption, rebooted, and re-enabled encryption - with the same result.
Eventually, I used fdesetup changerecovery --personal to create a new recovery key, which I was able to validate with fdesetup validaterecovery.
I now have that key stored in a very safe place (nowhere near my MBP).
But I originally requested, via the GUI, that the key also be stored in iCloud. Now I suspect that the key they have is not the key which will work to decrypt my drive at last resort.
I've spent hours googling, and browsing Apple's support pages, but nowhere can I find out how to update the recovery key stored in my iCloud account.
Any advice greatly appreciated

A: According to Apple's [documentation on Filevault 2] (https://support.apple.com/en-us/HT4790) (emphasis added by me)

Changing your recovery key
In the Security & Privacy system preference, under the FileVault tab, click "Turn Off FileVault" to disable FileVault. After FileVault is off, FileVault will begin to decrypt your drive. Once decryption is complete, you can click the "Turn On FileVault" button. Doing this allows you to enable unlock-capable users. You're also provided with a new recovery key and have the option of sending this new key to Apple. The old key sent to Apple will not be able to unlock your newly-encrypted disk. If you need to retrieve your recovery key from Apple, only the new one will be retrieved based on the Serial Number and Record Number displayed in the login window.

I think that this might be your answer.

A: I don't know how to solve the iCloud issue, but I'd recommend instead that you use an excellent encryption tool like GPG or TrueCrypt (7.1a only!!) to encrypt a text file that has your FileVault Recovery Key and then you can upload that file to iCloud file storage or any Cloud service you like -- then it's super secure AND you don't have to jump through Apple verification steps or talk to support.

A: If you choose to "Create a recovery key and do not use my icloud account" it means that the key stored in icloud can no longer decrypt your disk. Only the key you made (and wrote down, took a screenshot of, or took a picture of with your camera), will allow you to decrypt. If you chose to store the key with apple as well then you would get prompted to answer three security questions which you would need to be able to answer to decrypt your disk.
Did you get those prompts? If not, you are the sole holder of a decryption key.


text:
Q: JQuery hidden element input issue traversing I have a problem I just can't figure out. I have a set of DIV's which are display: none; by default:

Pivot

        <input class="small" value="030-" disabled />
        <input class="input" id="pi" maxlength="6" />

Position 1

        <input class="small" value="031-" disabled />
        <input class="input" id="p1" maxlength="6" />

Position 2

        <input class="small" value="031-" disabled />
        <input class="input" id="p2" maxlength="6" />

Position 3

        <input class="small" value="031-" disabled />
        <input class="input" id="p3" maxlength="6" />

Position 4

        <input class="small" value="031-" disabled />
        <input class="input" id="p4" maxlength="6" />

Position 5

        <input class="small" value="031-" disabled />
        <input class="input" id="p5" maxlength="6" />

Position 6

        <input class="small" value="031-" disabled />
        <input class="input" id="p6" maxlength="6" />

Then this code unhides the relevant section:
$.ajax({
    url: "getSerial.asp",
    data: { term: term },
    dataType: "json",
    success: function(data) {
        $('option:selected').append('-' + data[0].sn)
        $('#prefix').attr('disabled', true)
        var code = data[0].partno.substring(6, 12);
        len = code.length;
        $('#pivot').show(0);
        for (var i = 0; i < len; i++) {
            if (code.substr(i, 1) != "-") {
                $('#pos' + code.substr(i, 1)).show(0);
            }
        }
        $('div').find('input:enabled').first().focus();
    }
});

So that works perfectly fine.  Then what I'm trying to do is as you type in 6 characters, it automatically jumps down to the next visible input (class="input").  My code for that is very un-glamorous and works ONLY with the next logical div (pos1, pos2 etc).  The combination may be pos1,pos3,pos3 so missing out number 2 (as it is still hidden).
$(this).parent('div').parent('div').next('div').find('.input:visible').focus()

This doesn't work for the above combination.  How do I traverse successfully only to the next visible .input class?

A: Use :has() in the selector to match a DIV that contains a visible input.
$(this).parent('div').parent('div').nextAll('div:has(.input:visible)').first().find('.input:visible').focus();


text:
Q: Django Class-Based View: The view polls.views.ChoiceView didn't return an HttpResponse object. It returned None instead I am new to django and I have created a function-based view which creates choices for a question.
def create_choice(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if request.method == 'POST':
        form = ChoiceForm(request.POST)
        if form.is_valid():
            choice = form.save(commit=False)
            choice.question = question
            choice.save()
            return HttpResponseRedirect(urlresolvers.reverse('polls:detail', kwargs={'question_id':question_id}))
    else:
        form = ChoiceForm()
    context = {'form':form, 'question':question}
    return render(request, 'polls/add_choice.html', context)

then I tried converting it into a class-based view...
class ChoiceView(generic.DetailView):
    template_name = 'polls/add_choice.html'

    def get(self, request, *args, **kwargs):
        form = ChoiceForm()
        question_id = self.kwargs['pk']
        question = get_object_or_404(Question, pk=question_id)

        context = {'form':form, 'question':question}
        return render(request, 'polls/add_choice.html', context)

    def post(self, request, *args, **kwargs):
        form = QuestionForm(request.POST)
        if form.is_valid():
            choice = form.save(commit=False)
            choice.question = question
            choice.save()
            return HttpResponseRedirect(urlresolvers.reverse('polls:detail', kwargs={'question_id':question_id}))

but when I runserver add a choice I get "The view polls.views.ChoiceView didn't return an HttpResponse object. It returned None instead." What did I do wrong? why do I not get a GET data?


text:
Q: Example: Accessible category without colimits I am looking for intuitive examples of the way(s) that colimits may fail to exist in the category of (Set-valued) models for a limit/colimit sketch.
Bonus points if the sketch and/or the colimit diagram is finite.

A: *

*The category Hil of Hilbert spaces, considered as a full subcategory of Ban is $\aleph_1$-accessible but not locally presentable, in fact it is self dual.

*The category Lin of linear orders and strictly increasing maps is finitely accessible.

*The category of Sets and one-to-one functions is finitely accessible and not locally presentable.

*The category Fld of fields is accessible but not locally presentable.
All these examples and some others can be found in Locally Presentable and Accessible Categories, 2.3.

A: Here's a general way to get an accessible category that likely will not have many colimits: let $C$ be a locally presentable category, and then let $C^{mono}$ be the category with the same objects as $C$, but just the monomorphisms of $C$ for monomorphisms. Then $C^{mono}$ is accessible. But $C^{mono}$ will typically fail to have products, for example -- it's unlikely that projection maps for a product will be monos.
In a similar vein but different direction, start with a locally presentable category, and pass to a subcategory of objects defined by some lifting property. For example, the category of injective abelian groups. For a finite example, how about the category of $p$-divisible abelian groups for a fixed prime $p$ -- to sketch this in a finite way, start with the usual sketch $S$ for abelian groups, and let $Z$ be the object of the sketch such that $Hom(Z,-) = \mathbb Z$. Then there is a map $p: Z \to Z$ given by multiplication by $p$. Put in the colimit condition saying that for $F: S \to Set$ in our category, the map $p: F(Z) \to F(Z)$ is an epimorphism -- i.e. the diagram
$\require{AMScd} \begin{CD} Z @>1>> Z\\ @V1VV @VpVV\\ Z @>p>> Z \end{CD}$
is in the colimit part of the sketch.
Another point is that an accessible category has all colimits iff it has all limits, iff it is locally presentable, iff it is the category of models for a limit sketch. So any category sketched by a (limit,colimit) sketch which actually uses the colimit part is unlikely to have all colimits (if it does have all colimits, then there's an alternative way to sketch it without using the colimit part of the sketch).
Another class of examples is this: every small category with split idempotents is accessible. A small category is never complete / cocomplete, except maybe if it's a poset.
Another class of examples would be the category of models and elementary embeddings for any first-order theory $T$ -- this is always an accessible category, but never (co)complete except in trivial cases.


text:
Q: Heatwave calculation based on maximum temperature in R A heatwave is defined if the maximum temperature at a meteorological station is 3 °C or more than the normal temperature consecutively for 3 days or more. I have calculated the daily average (daily normal) from multiple-year daily maximum temperature data like
df <- data.frame("date"= seq(from = as.Date("1970-1-1"), to = as.Date("2000-12-31"), by = "day"),
                        "MaxT" = runif(length(seq.Date(as.Date("1970-1-1"), as.Date("2000-12-31"), "days")), 20, 40))

df$day <- format(df$date, format='%m-%d')

daily_mean <- aggregate(MaxT ~ day, data=df, FUN=mean)

Now it has to be matched with every year's daily maximum temperature and identify the dates when the maximum temperature is 3 °C or more than the normal daily temperature consecutively for 3 days or more. Those events will be considered as heatwaves. My question is how to implement it in R?

A: Here is a way using dplyr and zoo's rollapplyr.
library(dplyr)

df_out <- df %>%
           left_join(daily_mean %>% rename(mean_temp = MaxT), by = 'day') %>%
            mutate(is_heatwave = zoo::rollapplyr(MaxT > (mean_temp + 3),
              3, all,fill = NA))

some instances of heatwave :
df_out[31:50, ]

#         date     MaxT   day mean_temp is_heatwave
#31 1970-01-31 26.31675 01-31  28.31451       FALSE
#32 1970-02-01 22.05946 02-01  29.83059       FALSE
#33 1970-02-02 34.22469 02-02  29.84562       FALSE
#34 1970-02-03 33.03264 02-03  29.87919       FALSE
#35 1970-02-04 36.62357 02-04  31.50603        TRUE
#36 1970-02-05 29.82134 02-05  30.22581       FALSE
#37 1970-02-06 28.13625 02-06  29.64073       FALSE
#38 1970-02-07 29.95754 02-07  29.54277       FALSE
#39 1970-02-08 21.40026 02-08  30.96619       FALSE
#40 1970-02-09 33.10983 02-09  28.16146       FALSE
#41 1970-02-10 30.87346 02-10  29.37693       FALSE
#42 1970-02-11 31.08721 02-11  28.89930       FALSE
#43 1970-02-12 27.34925 02-12  29.27882       FALSE
#44 1970-02-13 31.88582 02-13  29.35825       FALSE
#45 1970-02-14 30.05155 02-14  28.24995       FALSE
#46 1970-02-15 35.07049 02-15  29.02716       FALSE
#47 1970-02-16 39.49029 02-16  32.75644       FALSE
#48 1970-02-17 37.41917 02-17  31.44022        TRUE
#49 1970-02-18 36.03564 02-18  29.56212        TRUE
#50 1970-02-19 36.48052 02-19  30.18766        TRUE

TRUE values are where heatwave was present. As we can see in row 33, 34 and 35 we had 3 consecutive days when MaxT was greater than mean_temp by more than 3 degrees. Similarly, we can verify for other days.

To get yearly heatwave occurrences, we can do :
df_year <- df_out %>%
             group_by(year = format(date, "%Y")) %>%
             summarise(total_heat = with(rle(is_heatwave),
                                         sum(values, na.rm = TRUE)))

and sum(df_year$total_heat) would give overall count.


text:
Q: MIPS label addressing? This is all related, and I tried to piece it all together as logically as I could, so please bear with me.
I'm really confused as to how to properly address labels. For example, in the following bit of code, "bne" translates to "00010101001001010000000000000001", and the label address of loopend is 0x00000020 (32)
.text
    la $a0, opOne
    lw $a0, 0($a0)
    la $a1, opTwo
    lw $a1, 0($a1)
    add $t0, $zero, $a0
    addi $t1, $zero, 1
    bne $t1, $a1, loopend
    addi $t1, $t1, 1
loopend:

When I move loopend up, "bne" becomes "00010101001001011111111111111011" and the address of loopend becomes 0x00000008 (8)
.text
    la $a0, opOne
    lw $a0, 0($a0)
loopend:
    la $a1, opTwo
    lw $a1, 0($a1)
    add $t0, $zero, $a0
    addi $t1, $zero, 1
    bne $t1, $a1, loopend
    addi $t1, $t1, 1

So from what I understand, in the first bit of code, loopend is after eight instructions, so its address is 4*8=32=0x00000020. In the second bit of code, loopend is after two instructions, so its address is 4*2, or 0x00000008.
What I don't understand, however, are the label addresses. Correct me if I am wrong: the label address depends on where the label is in relation to the instruction calling it. So in the first bit of code, loopend is two lines later than bne so you do not flip the signs, and its address is "0000000000000001". On the second loopend comes before bne so you flip the sign and its address becomes "1111111111111011".
I know you shift the addresses to the left 2 bits, but I'm still pretty confused. Do you only shift left if there are not two 0s at the end, like the second loopend?
My most pressing question is this: where does 0000000000000001, the address of loopend, even come from in the first bne machine language translation? I thought that address of label loopend would be 0000000000100000.

A: BNE -- Branch on not equal
 ___________________________________________________________________________
|Description: | Branches if the two registers are not equal                 |
|_____________|_____________________________________________________________|
|Operation:   | if $s != $t advance_pc (offset << 2)); else advance_pc (4); |
|_____________|_____________________________________________________________|
|Syntax:      | bne $s, $t, offset                                          |
|_____________|_____________________________________________________________|
|Encoding:    | 0001 01ss ssst tttt iiii iiii iiii iiii                     |
|_____________|_____________________________________________________________|

For the first bne the offset is 1, so 1 << 2 = 4 so you increment the program counter by four bytes. Since the word size is 32 bits the pc is incremented by one instruction
.text
    la $a0, opOne
    lw $a0, 0($a0)
    la $a1, opTwo
    lw $a1, 0($a1)
    add $t0, $zero, $a0
    addi $t1, $zero, 1
    bne $t1, $a1, loopend
    addi $t1, $t1, 1 # increment by 1 insruction
loopend:             # to here (well the next instruction)

For the second bne the offset is b1111111111111011, sign extended its -5 so -5 << 2 = -20 so you increment the program counter by - 20 bytes or decrement it by 20 bytes. Since the word size is 32 bits the pc is decremented by five instructions
.text
    la $a0, opOne
    lw $a0, 0($a0)
loopend:                  #
    la $a1, opTwo         # 5 to here
    lw $a1, 0($a1)        # 4 ^
    add $t0, $zero, $a0   # 3 |
    addi $t1, $zero, 1    # 2 |
    bne $t1, $a1, loopend # 1 |
    addi $t1, $t1, 1      # decrement by 5 instructions


text:
Q: Angular http.head on asset returns 404 I created a service that checks whether a file exists or not.
fileExists(path: string): Observable<boolean> {
    return this.http.head(path)
        .mapTo(true)
        .catch((error) => {
            console.log(error);
            return Observable.of(false);
        });
}

I have a pdf file inside:   /assets/text/text.pdf
When I open the url in a browser, the pdf is displayed but when I run the path through the service, I get a 404
HttpErrorResponse {
     headers: HttpHeaders,
     status: 404,
     statusText: "OK",
     url: "https://localhost:4200/assets/text/text.pdf",
     ok: false,
}

EDIT: When I replace head by get I get a "Unexpected token % in %PDf..." which means it found the body of the PDF
https://github.com/angular/angular-cli/issues/5170
If you have a solution for this...

A: After investigation, webpack dev server doesn't allow HEAD requests by design.
https://github.com/angular/angular-cli/issues/5170
https://github.com/webpack/webpack-dev-server/issues/924
It's possible to make a proxy but it replaces HEAD with GET which makes non sense.
Another solution is to modify the middleware to make it accept HEAD as discribed in issue 924, which is overkill.


text:
Q: In OSGi, what is the difference between type of service being tracked and type of the tracked object In OSGi the class ServiceTracker defines two type parameters:

*

*S - The type of the service being tracked.

*T - The type of the tracked object.

What is the difference between the two of them?

A: In almost all cases I use the service tracker I need to do some housekeeping related to the tracked object. When the tracked object goes away, that housekeeping info should be garbage collected.
So for example, you track WhiteboardListeners. However, you want to keep track how long they use for their callback and deny them service if they use too much time. So we create a wrapper:
public class Example {

  interface Whiteboard {
    void visit();
  }

  static class Wrapper {
    Whiteboard  whiteboard;
    AtomicLong  averageTime = new AtomicLong();

    public Wrapper(Whiteboard whiteboard) {
        this.whiteboard = whiteboard;
    }

    void visit() {
        if (averageTime.get() < 100) {
            long start = System.currentTimeMillis();
            whiteboard.visit();
            long time = System.currentTimeMillis() - start;
            averageTime.getAndUpdate(v -> (99 * v + time) / 100);
        } else
            averageTime.getAndUpdate(v -> (99 * v) / 100);
    }
  }

  ServiceTracker<Whiteboard, Wrapper> tracker;

  @Activate
  void activate(BundleContext context) {
      tracker = new ServiceTracker<Whiteboard, Wrapper>(context,
            Whiteboard.class, null) {
        @Override
        public Wrapper addingService(
                ServiceReference<Whiteboard> reference) {
            return new Wrapper(context.getService(reference));
        }

        @Override
        public void removedService(ServiceReference<Whiteboard> reference,
                Wrapper service) {
            context.ungetService(reference);
        }
    };
    tracker.open();
  }

  void visit() {
    tracker.getTracked().values().forEach(wrapper -> wrapper.visit());
  }
}

I rarely use the Service Tracker nowadays because Declarative Services does the job in most cases a lot easier. However, when I use the Service Tracker, I rarely ever have S==T.

A: The tracked object allows you to do any necessary housekeeping when the service is removed again.
As an example see the trackers in pax-jdbc. In this case we need two services. The PooledDataSourceFactoryTracker will start another tracker for the DataSourceFactory. This second tracker is the tracked object of the first tracker. When the PooledDataSourceFactory is removed again then the other DataSourceFactory tracker is also closed.
This approach allows to track more than one service or do other houskeeping on service removal without having to deal with the threading.
Be aware though that even with this approach service trackers are very difficult to use correctly. In most cases it is better to use a frameworks like declarative services from the start.

A: T allows you to track a different type than that service type S. For example, you can wrap the service S in an object of type T. For most use cases S and T are the same. But there are use cases where T != S.


text:
Q: Issue with switching the up and down glyph icons when clicked Here is the live code to play with:
http://www.bootply.com/fAR3pUSRXq
When the accordion is expanded, I do want the arrow to be pointing "UP" which  it is already. BUT when I click it to collapse the accordion, I want the arrow to be now pointing "down" BUT it still stays up.So I want the behaviour to be reverse! when accordion is open , point up !, when accordion is closed, point down.
 what is the issue?  Thanks for help.

A: You can try this:
JS:
$('.collapse').on('shown.bs.collapse', function() {
    $("span").addClass('glyphicon-chevron-up').removeClass('glyphicon-chevron-down');
  });

$('.collapse').on('hidden.bs.collapse', function() {
    $("span").addClass('glyphicon-chevron-down').removeClass('glyphicon-chevron-up');
  });

See Bootply Link


text:
Q: passport-azure-ad: Why am I getting "jwt audience is invalid"? (All IDs in the below example are made up. I've added them to illustrate the format for some of the parameters).
My tenant is at acme.co.uk, but I want the web app that I've got deployed at https://subdomain.acme2.co.uk to delegate authentication of users to Azure AD.
I registered my app as below using the new portal:
(The field names are those used on the azure portal).
App ID URL: https://acme.co.uk/11111111-2222-3333-4444-555555555555
Home page URL: https://subdomain.acme2.co.uk/api/auth/aad
Reply URLs: https://subdomain.acme2.co.uk/api/auth/aad/callback
and created a secret key that doesn't expire with the value: '111111111111111111/aaaaaaaaaaaaaaaaaaaaaaaa='
I've been following the passport-azure-ad github sample using v1 endpoint as a guide.
{
  allowHttpForRedirectUrl: false,
  clientID: 'https://acme.co.uk/11111111-2222-3333-4444-555555555555',
  clientSecret: '111111111111111111/aaaaaaaaaaaaaaaaaaaaaaaa=',
  identityMetadata: 'https://login.microsoftonline.com/acme.co.uk/.well-known/openid-configuration',
  isB2C: false,
  issuer: null,
  loggingLevel: 'info',
  passReqToCallback: false,
  redirectUrl: 'https://subdomain.acme2.co.uk/api/auth/aad/callback',
  responseMode: 'form_post',
  responseType: 'code id_token',
  skipUserProfile: true,
  useCookieInsteadOfSession: false,
  validateIssuer: true
}

When I got to 'https://subdomain.acme2.co.uk/api/auth/aad' in my browser I get redirected to MS to login, which I then do, but when the redirect back to 'https://subdomain.acme2.co.uk/api/auth/aad/callback' happens, I'm not authenticated.
Inspecting the headers from the callback POST request I see:
In _validateResponse: jwt audience is invalid. expected: https://acme.co.uk/11111111-2222-3333-4444-555555555555,spn:https://acme.co.uk/11111111-2222-3333-4444-555555555555

Any ideas what I've done wrong??? [:-|
(Aside: Debugging this is a pain, as I'm running in docker and the redirects don't seem to work properly, so I have to deploy to a real environment ATM).

A: Ok found it...
  clientID: 'https://acme.co.uk/11111111-2222-3333-4444-555555555555'
was the culprit.
That should be the app Id NOT the app Id URI. Doh. Many thanks to @Alex Blex for the guidance. This was most helpful.

A: In my instance, I was using .env and getting the clientId from there.
I solved this issue by remove the quotes around clientID in my config and .env file.


text:
Q: cannot find -lmysqlclient I'm trying to compile a C++ program and one of the classes uses . g++ is not able to find the libraries would be my guess. The command i use to compile is -
g++ c1.cpp c2.cpp c3.cpp c4.cpp -o c4 -lm -lmysqlclient

c3.cpp is the file that needs mysql.h. This works perfectly on my local machine, but refuses to run on the server with the error
cannot find -lmysqlclient

I tried finding the libmysqlclient.so files on the server using the find command, I don't think they are present there
uname -a

reveals
SunOS opteron 5.10 Generic_139556-08 i86pc i386 i86pc
user@opteron 12:26:02 ~/c++/projname/

I realize that i need to link some libraries, but where and how?
Any help would be appreciated.
Thanks.

A: Simplifying @SriHariY.S's answer-
Try installing it with sudo apt-get install libmysqlclient-dev.

A: Do you have the MySQL client libraries? Can you look for it as
find / -name "libmysqlclient.so" -type f -print 2>/dev/null

Also, you can use the -R flag on linker to hardlink the libmysqlclient as
g++ -R/usr/local/mysql/lib ....

Or, you can export the LD_LIBRARY_PATH_32 or LD_LIBRARY_PATH_64 as
export LD_LIBRARY_PATH_32=$MYSQL_HOME/lib

Urko,

A: On Ubuntu 18 I used this command to find a name of required package for fixing this error:
apt search lmysqlclient

After this I installed missing package:
sudo apt install libmariadbclient-dev-compat

A: Whatever library packages u think is not installed can be installed using sudo apt-get install. But the problem is to find the right name of the package apt-get can understand. So how to do that ?! simple
use command : sudo apt-cache search <filename>
For eg.: in this case lmysqlclient
sudo apt-cache search mysqlclient

(remember to exclude 'l' from the actual name ,ie, mysqlclient and not lmysqlclient).
This outputs:
libmysqlclient-dev - MySQL database development files

In the above -libmysqlclient-dev is the name that apt-get can recognize and solve our cannot find lmysqlclient problem
so now type: sudo apt-get install libmysqlclient-dev from interface.
After its done, try making your required file.


text:
Q: How can I show the output of <%# Container.ItemIndex + 1 %> or <% Eval('column name') %> on a stringbuilder? How can I show the output of <%# Container.ItemIndex  + 1  %> or <% Eval('column name') %> on a stringbuilder? Because I have to export the output of the DataList with the design from the Item Template of the DataList...
This is from the Page.aspx
 <asp:Label ID="Label1" runat="server" Text='<%# Container.ItemIndex  + 1  %>'></asp:Label>

<%# Eval("column name")%>

and this is on the Page.aspx.cs
 protected string ExportDatatableToHtml(DataTable dt)
    {
        StringBuilder strHTMLBuilder = new StringBuilder();
        strHTMLBuilder.Append("");
        strHTMLBuilder.Append("");
        strHTMLBuilder.Append("");
        strHTMLBuilder.Append("");
        strHTMLBuilder.Append("<bgcolor='white' >");

        strHTMLBuilder.Append("
");
        foreach (DataColumn myColumn in dt.Columns)
        {
            strHTMLBuilder.Append("");
            strHTMLBuilder.Append(myColumn.ColumnName);
            strHTMLBuilder.Append("	");

        }
        strHTMLBuilder.Append("
");

        foreach (DataRow myRow in dt.Rows)
        {

            strHTMLBuilder.Append("
");
            foreach (DataColumn myColumn in dt.Columns)
            {
                strHTMLBuilder.Append("");
                strHTMLBuilder.Append(myRow[myColumn.ColumnName].ToString());
                strHTMLBuilder.Append("	");

            }
            strHTMLBuilder.Append("
");
        }

        //Close tags.
        strHTMLBuilder.Append("
");
        strHTMLBuilder.Append("");
        strHTMLBuilder.Append("");

        string Htmltext = strHTMLBuilder.ToString();

        return Htmltext;
    }

I wonder if this is really possible... if yes, can you teach me how to do it?

A: I got the idea when Chetan commented on this question about
<%# Eval("column name")%>

in order for me to append this, I used
  foreach (DataRow myRow in dt.Rows)
            {
    string studentid= myRow["studentid"].ToString();
    strHTMLBuilder.Append(studentid);
            }

then in exchange for Container.ItemIndex + 1 on asp.net, to export to html I used this
   int i = 0;
   foreach (DataRow myRow in dt.Rows)
                {
        i++;
        strHTMLBuilder.Append(i);
                }


text:
Q: How to identify the distribution for regression models I am trying to analyze hunting harvest data with response-variable being individuals/1000 hectares and a series of explanatory variables to describe it. Response variable is continuous (fractionals), with a mean of 2.86. However, in some hunting areas, the annual harvest is zero, thus the variable includes many zeros. Ranging from 0 to 15.6 (N = 690). How do I go ahead to chose a proper probability distribution for this? I did a qqPlot (package 'Car') in R, and a simple histogram.
Further, what sort of model do you think would be most appropriate for this data? I've been thinking of GAMM's or GLMM's.

A: As your primary observations are counts, you should use an analysis method that is designed for counts and thus models observations with 0 counts directly. A Poisson generalized linear model with log link is a standard way to start.
As Kjetil B Halvorsen said in a comment, you use an offset, log(area), in your regression to account for the area corresponding to each observation. Then you can interpret your results of modeling counts in the units of individuals/1000 hectares that you desire. See this page among many others on this site.
It's possible that a simple Poisson model won't be adequate, in that the equality between variance and mean for a Poisson distribution won't adequately describe your results. A "quasi-Poisson" model, in which confidence intervals are based on other-than-Poisson variance, or a negative binomial model could be next steps in that situation.
It's not clear from your description that a mixed model ("MM" in your abbreviations) would be needed here. Whether you need to consider a "generalized additive" ("GA") model has to do with whether simple functional forms of your covariates are adequate in the linear predictor of log(counts). I'd start with simple linear modeling of covariates in a Poisson generalized linear model, as if that works it's usually easier to explain to others.


text:
Q: managing multiple values in android I am doing project on ecommerce app.
In my dashboard activity I am getting username value from login activity and mobile number from main activity.
I want to check those two values and set in text view according to incoming values.
How can I achieve?

A: You could either store them in a SQLite database or similar, or you could store them in SharedPreferences.
You can look into some more options here

A: You can use SharedPreferences Like example store value and get value entire application
//Store value
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.commit();

//getvalue
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString(Name, null);

i hope help this