text:
Q: How to chain FilterDefinitionBuilders in Mongo.Net Driver I have a filter that I would like to add to each of my queries as a basis to any of my queries that I am going to perform on the database. This will mean that i don't have to remember to add a filter (filter.Eq("deleted", false) & filter.Eq("another query", null) on every call i make to my collection.
Using other fluent interfaces in the past i assumed that we could simply pass the builder around adding as many filters as i liked until I was actually ready to perform the query and then i would call a .Build() command and this would finally give me my FilterDefinition object.
However when I try combining the Eq() calls it simply converts to a FilterDefinition straight away rather than leaving it as a FilterDefinitionBuilder until it's time has come. This seems fairly inextensible and short sighted by the Mongo as adding a .Build() functionality would have allowed you to chain commands in a more flexible manner.
Firstly is there any reason behind the decision to do it in this manner. I want to understand why it was done like this as I know that people don't just arbitrarily make these decisions.
Secondly, has anyone managed to write any extension methods that would help me with my current predicament that they wouldn't mind sharing.
My first attempt was to include something like the following:
public static FilterDefinitionBuilder<TDocument>(this FilterDefinitionBuilder<TDocument> filter)
{
    var name = GetCollectionName<TDocument>();
    return filter.Eq("deleted", false);
}

Then i would call this to from a wrapper function that I would use instead of calling the static Builders<CosmosDocumentType>.Filter I would call a utility function that would wrap this and return a FilterDefinitionBuilder object that I can add some more filters to.
Once complete I'd like to call a .Build() method and then be presented with a rather lovely and rather functional FilterDefinition object that will get what documents I want from the collection.
Having this .Build() would also allow me to query all documents in a collection that are not deleted without having to add more filters, because at present this seems to be the only way to convert between a FilterDefinitionBuilder and a FilterDefinition.
The other alternative is writing my own Fluent wrapper around the functionality and run it through a FilterDefinitionBuilder at the end when I am satisfied that I have all of the filters in place.
If there is a way to pull the existing filters out of a FilterDefinition that might also help.

A: As I understand it, you need to decorate all your filters with a base filter. You can carry out using various approaches and I list three below.
Let's say you have the following for your base filter:
var builder = Builders<BsonDocument>.Filter;
var baseFilter = builder.Eq("deleted", false) &
                 builder.Eq("another query", BsonNull.Value);

And the following filters that you need to decorate:
var filter01 = Builders<BsonDocument>.Filter.Eq("value", 1);
var filter02 = Builders<BsonDocument>.Filter.Eq("value", 2);

Then:

*

*We can go about having a higher-order decorator function that takes a base filter and returns a function whose application on other filters will result in a filter that will be decorated with the base filter.

Its implementation is simple as follows:
public static Func<FilterDefinition<T>, FilterDefinition<T>>
  DecoratedFilter<T>(FilterDefinition<T> baseFilter) =>
    filter => baseFilter & filter;

You can now use the DecoratedFilter() function to get a function and use it on your filters as follows:
var decorate = DecoratedFilter(baseFilter);

var decoratedFilter01 = decorate(filter01);
var decoratedFilter02 = decorate(filter02);

*Another approach is for you to have an extension method itself:

public static FilterDefinition<T>
  Decorate<T>(this FilterDefinition<T> firstFilter,
              FilterDefinition<T> secondFilter) =>
    firstFilter & secondFilter;

It can be used as follows:
var decoratedFilter01 = filter01.Decorate(baseFilter);
var decoratedFilter02 = filter02.Decorate(baseFilter);

*You can hard-code the base filter based on your particular use case and can have an implementation as follows:

public static readonly FilterDefinition<BsonDocument> BaseFilter = ...

public static FilterDefinition<BsonDocument>
  WithBaseFilter(this FilterDefinition<BsonDocument> filter) =>
    BaseFilter & filter;

Then simply use it as:
var decoratedFilter01 = filter01.WithBaseFilter();
var decoratedFilter02 = filter02.WithBaseFilter();


text:
Q: Command Line Windows: How can I set a global variable within a call? I want to change a counter variable within a call function.
In my example I want to count all subfolders (= count_all) and afterwards I want to increment the count of the subfolders it successfully proceeded (= count_done).
    @echo off
    cls

    setlocal enableextensions enabledelayedexpansion
    set /a "count_all=0"
    set /a "count_done=0"

    for /d /r %%i in (.\*) do call :process_subfolders "%%i"

    if %count_all% EQU 0 (
        echo No archives found.
    ) else (
        set /a "counted=1"
        for /d /r %%i in (.\*) do call :process_subfolders "%%i"
    )

    pause
    endlocal
    goto :eof

    ::___________________________________________________________________
    :process_subfolders
    set "folder=%~nx1"

    pushd %folder%
    if exist *.rar (
        if !counted! equ 0 (
            set /a "count_all+=1"
        ) else (
            set /a "count_done+=1"
            echo !count_done!: %folder%

            rem ... do something with the rar files in this folder ...
            rem ... for testing: use ping
            ping 127.0.0.1 -n 2 > nul

            set /a "percent=!count_done!*100/!count_all!"
            title !percent!%% [!count_done!/!count_all!]
        )
    )
    popd
    exit /b

The code works but I do not understand the behaviour of setlocal enabledelayedexpansion. When I put it in the call :process_subfolders I am not able to change the variables anymore and I do not know how to return them accordingly. Somehow I could set them on the end of the call by endlocal & set "%2=whatever" (or something like this) but I still do not understand which variables are local and which are not.
What is the difference between count_all, %count_all% and !count_all! and when should I use which?

A: I would suggest using the
FOR /D command.
A small test example :
setlocal enabledelayedexpansion
set /a count_all=0
for /d /r %%i in (.\*) do (
  echo !count_all! : %%i
  set /a count_all+=1
)
echo all: %count_all%

As for the difference between the various variable substitution operators,
you are not the only one that is confused here.
The main difference is whether the substitution operator, % or !,
relates to the current or initial value of the variable.
The
EnableDelayedExpansion option
causes variables to be expanded at execution rather than at parse time.
When delayed expansion is in effect, variables can be immediately read
using !variable_name!.
Using %variable_name% will continue to show the initial value that is
expanded at the beginning of the line, which may be different for loops.
I have added to my code an echo command that demonstrates the difference.
It uses !count_all!, because using %count_all% would result in the
value as when the for command was started, which is always 0.
But %%i does not need the ! operator, because it is programmed-in
as the loop variable.
You will find a detailed explanation in the following post
(most upvoted answer):
How do SETLOCAL and ENABLEDELAYEDEXPANSION work?
This inconsistency of the two substitution operators leads to confusion
that is not always resolved by logic alone. Sometimes trial and error
is required before getting it right.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Examples how to save file from external .Net application to Sharepoint I need to save files from the existing AngularJS/.NET application to Sharepoint. Most of the examples I see online is when applications reside on Sharepoint itself. How do I save files from outside?
I've been given a user access to our organization's Sharepoint site but no application user passwords. What do I need to request from administrators of SharePoint site to be able to write the code?

A: We can use CSOM C# code to upload file to SharePoint 2010 document library. We need use an admin user and password to pass the Credentials in the .NET application server.
public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
    var fileCreationInfo = new FileCreationInformation
    {
        Content = System.IO.File.ReadAllBytes(uploadFilePath),
        Overwrite = true,
        Url = Path.GetFileName(uploadFilePath)
    };
    var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
    var uploadFile = targetFolder.Files.Add(fileCreationInfo);
    context.Load(uploadFile);
    context.ExecuteQuery();
}

Usage
var siteUrl="http://sp2010";
var username="admin";
var password="xx";
var domainName="domain1";
using (var ctx = new ClientContext(webUri))
{
    ctx.Credentials = new System.Net.NetworkCredential(username, password, domainName);
    UploadFile(ctx,"Documents/folder1",@"c:\upload\test.docx");
}

The following article for your reference.
Uploading files using Client Object Model in SharePoint 2010


text:
Q: Use gmail SMTP server for my another email, in django I have two emails, myemail@gmail.com and mymail@mydomain.com. I want to send email to users of my django app, from mymail@mydomain.com. I am using mydomain email, from my gmail account, using the add another account settings. But when I try to send email with the server as smtp.gmail.com,  I get SMTPAuthentication error. Is there any way I can use the gmail server? I cannot use smtp.mydomain.com , as there is no such host error, when I try telnet. What do I do now?

A: You can try sending an email as 'mymail@mydomain.com' after you log into google with 'myemail@gmail.com'  If your account has an alias for 'mymail@mydomain.com' it should work.  If that still fails you will need to use a service like mailchimp or sendgrid, or set up your own smtp server at smtp.mydomain.com.

A: I suggest you to use some service like mailchimp or sendgrid .


text:
Q: Search SVN File's History for Particular String This is probably basic, but I have not been with SVN for long and am wondering how to do it.
Suppose I have a line of text, say, Hello world!
I would like to search a particular file's history in my SVN repository to see when that line disappeared from there.
What is an efficient way to do that? A command line operation should work. However, something via ViewVC is also an option.
Much appreciated.


text:
Q: Adding static methods to facilitate cleaner unit tests - good practice? Say I have this class:
class MyClass {
    private String s;
    // more attributes here
    public MyClass(String s, /*more constructor params*/)  {...}

    public String myMethod(String s) {
        //complex logic here
    }
}

To unit test myMethod() I need to create the entire object (with many parameters that need constructed, etc), while the method only uses s.
Altenatelly I can add a static method:
class MyClass {
    private String s;
    // more attributes here
    public MyClass(String s, /*more constructor params*/)  {...}

    public String myMethod(String s) {
        return myStaticMethod(s);
    }

    public static myStaticMethod(String s) {
        //complex logic here
    }
}

Now I can easily test "complex logic" without the need to create the object.
someStaticMethod(String s) should have no side-effects on the class.
So I am adding an extra method just for the ease of testing.
Is this a good practice?

A: So, you've made a complex method a member of an object even though it has nothing little to do with that instance?
Yes, I agree you should use a different design. It could be a static method in that class, or factored into its own class. Or it might be a method of an object that implements a "Strategy" pattern. The right decision depends on the potential for change.

Maybe something like this:
class ComplexLogician {

  String myMethod(String a, String b) {
    /* Complex logic here. */
  }

}

class MyClass {

  private String s;

  private final ComplexLogician logic;

  /* More attributes here... */

  MyClass(String s, ComplexLogician logic, /* More parameters... */)  {...}

  String myMethod(String b) {
    return logic.myMethod(s, b);
  }

}

A: I think it would be better to not make the method static, but construct your object once in a "Before" method which will run before each test in the test class. Something like this
public class SampleTestSuite  {
    private MyClass myClass;

    @Before
    public void startUp(){
    myClass = new MyClass();//Will be called before each test method is called.

    }

    @Test
    public void testNavigationSucceeded() {
        assert...
    }

    @Test
    public void secondTest() {
        assert...
    }

    @After
    public void tearDown() {

    }

}

A: If the method can be static then it should be static regardless you need it for testing or whatever. You can switch on warnings in Eclipse for that. Eclipse gives you a warning then about non-static methods that can be static.

A: Changing your production code and expose its "guts" so that you can test it is a very bad practice. It breaks encapsulation, and if your code is not testable in the first place, that usually means it needs refactoring.
The "complex logic" that you wanted to move in a static method would certainly benefit a proper OO treatment. Make a specialist class to handle that logic, or a set of classes, inject them into your MyClass through interface, separate concerns, and your testing will be made a lot easier.
Better even, start with your tests (TDD) using a mocking framework, and that will drive a good design organically without the need for static methods or similar hacks.
Example: Let's say your MyClass needs to heavily transform one of its parameters (in your case, the String s before it can be used. So you wanted to extract that treatment into a static method? Instead of that, add to your class a dependency to, say, a StringTransformer (rename accordingly) that is an interface to the actual implementation you want. Have a method transform(String s) in the transformer, that would contain the logic you wanted. Then test your implementation using normal ways, job done. And you actually made your design better.

A: I often write parts of the functionality of a class as package protected static methods, passing in field values as required. It lets you test functionality comprehensively without splitting it out into a separate class. It can give comprehensive test coverage without adding too much complication.

A: In general, it is not good practice to expose any functionality more than what is expected from the class. This would hinder from moving away from that logic easily since other clients might have started to use the code given that the method is public. One other option is to make the function protected so that in the same package within the test hierarchy, the test cases could be written. However, I would choose to write the test case by forming a base object once and keep changing my inputs and output set in it than using these work-arounds.

A: If you only test your static method then you leave your instance method uncovered.  You could instead alter the instance method so that it can be tested.  If you post more details of a particular case here or as a new question I'm sure someone will help you to make it testable.


text:
Q: Coloring polygons (made with concaveman) in ggplot by column I'm adapting code for a map made by someone else that uses a package concaveman to generate concave hulls from points. The goal is to plot a number of different polygons in the oceans, and to color-code them by a grouping variable. The code works great to make a map of all the polygons and color-code them by identity:
library(sf)
library(concaveman)
library(data.table)
library(ggplot2)

dat <- data.table(longitude = c(-131.319783, -131.141266, -131.08165, -131.079066, -130.894966,
             -131.063783, -131.10855, -131.215533, -131.189816, -131.14565,
             -131.200866, -131.046466, -130.94055, -130.928983, -130.7513,
             -130.8406, -130.833433, -130.830666, -130.82205, -130.89, -63.3666666666667,
             -63.3666666666667, -63.1666666666667, -64.1833333333333, -63.3166666666667,
             -63.3, -63.85, -63.9333333333333, -63.9333333333333, -63.5833333333333,
             -63.5833333333333, -63.7, -63.7, -63.2833333333333, -63.5833333333333,
             -63.95, -64.1833333333333, -63.8833333333333, -63.8, -63.2166666666667,
             -5.6788, -5.4408, -5.6835, -5.424, -5.6475, -5.4371, -5.6181,
             -5.4446, -5.6753, -5.4366, -5.6746, -5.4448, -5.6642, -5.4411,
             -5.666, -5.4408, -5.624, -5.4321, -5.6806, -5.4473),
           latitude = c(52.646633, 52.589683, 52.556516, 52.559816, 52.402916, 52.5983,
             52.554216, 52.550883, 52.539166, 52.658216, 52.627966, 52.481733,
             52.486033, 52.469033, 52.469166, 52.261833, 52.292133, 52.301066,
             52.3523, 52.366966, 48.4666666666667, 48.4666666666667, 48.65,
             49.0166666666667, 48.8166666666667, 48.8166666666667, 49.1, 48.8666666666667,
             48.8666666666667, 48.8, 48.8166666666667, 48.4833333333333, 48.4833333333333,
             48.8, 48.8166666666667, 48.8833333333333, 49.05, 49.0833333333333,
             48.7166666666667, 48.6666666666667, 54.7201, 54.6033, 54.7191,
             54.5733, 54.7225, 54.5923, 54.7261, 54.6076, 54.719, 54.5978,
             54.7195, 54.6108, 54.7204, 54.6062, 54.7214, 54.5923, 54.7275,
             54.592, 54.7207, 54.6188),
           group = c(rep('NEPac',20),rep('NWAtl',20),rep('NEAtl',20))
           )

split <- split(dat, dat$group)
split.sf <- lapply(split, st_as_sf, coords = c("longitude", "latitude"))
concave <- lapply(split.sf, concaveman, concavity = 3, length_threshold = 2)
concave.binded <- do.call('rbind', concave)
concave.spdf <- as_Spatial(concave.binded)

ggplot() +
  geom_polygon(data = concave.spdf,
               aes(x = long, y = lat, group = group, fill = group, color = group))

However, I can't figure out how to fill the polygons by anything other than whatever group is. Here is my attempt:
concave.spdf$ocean <- c('P','A','A')

ggplot() +
  geom_polygon(data = concave.spdf,
               aes(x = long, y = lat, group = group, fill = ocean, color = ocean))

Which throws this error: Error in FUN(X[[i]], ...) : object 'ocean' not found
I think the issue is that split groups the polygons by identity when passed to concaveman, but if I change that, they won't plot correctly (because the points of different polygons will be merged). How do I keep the polygons plotted individually but color them by a grouping variable? (If it's possible I'd prefer to stick with concaveman for aesthetic reasons in the true plot [which is much more complicated than this reprex] -- I know that if I use a different approach to plotting the polygons this would be easier.)

A: I recommend you to use fortify function getting a data.frame. Then you can easily add any other kind of variable adding a new column:
concave.spdf2 <- fortify(concave.spdf)
concave.spdf2 <- dplyr::left_join(concave.spdf2,data.frame(id=as.character(1:3), ocean = c('P','A','A')))

ggplot() +
  geom_polygon(data = concave.spdf2,
               aes(x = long, y = lat, group = group, fill = ocean, colour = ocean))


text:
Q: Creating fishnet based on DMS Coordinates I am trying to create a random sampling map of an ocean area. To do this, I would like to create cells that are 1' x 1' in size (one minute by one minute in DMS). My map is using WGS 1984 Web Mercator as the coordinate system. Whenever I go into the Fishnet tool, it asks for cell size, but this appears to be in meters.
One minute of latitude is supposedly 6,068 feet (1.15 miles) which is about 1849.526 m and one minute of longitude is 4,800 feet or about 1463.04 m.
The issue is that this projects a straight solid grid onto the map, which when I compare it to a graticule in the layout divided into 1' ticks, these boxes do not line up. I am completely okay with having not perfectly straight boxes as I am working with a large area and am expecting curvature.
The graticule would be fine to use as a grid system but I will later be stratifying the map and need to export cell data, which is why I am trying to use Fishnet.

A: I drawn big rectangle in DMS system:

and computed small squares (see script) inside it:
W,H = 0.016666666666666666,0.016666666666666666

and this is zoom to one of the pages:

Script:
import numpy as np
inExtent = arcpy.GetParameterAsText(0)
outPages = 'in_memory/pgons'
W,H = 0.016666666666666666,0.016666666666666666
arcpy.management.CopyFeatures(inExtent, outPages) #precaution if extent is wrong
## fishnet parameters
d = arcpy.Describe(outPages)
SR = d.spatialReference
ext = d.extent
toX,toY = ext.XMax,ext.YMax
x = np.arange(ext.XMin, toX, W, dtype=float)
y = np.arange(ext.YMin, toY, H, dtype=float)
fromX,fromY = x[-1]+ W, y[-1]+ H
mg = np.meshgrid(x, y)
X = np.array([0,0,W,W])
Y = np.array([0,H,H,0])
dX,dY = (fromX - toX)/2, (fromY - toY)/2
pgons = []
for x,y in np.nditer(mg):
    arr = arcpy.Array([arcpy.Point(x,y) for x,y in zip(X+x-dX,Y+y-dY)])
    pgons.append(arcpy.Polygon(arr,SR))
arcpy.CopyFeatures_management(pgons,'Feature calss of your choice')

I used script because I have it handy, but your can create XY to line tool to create set of vertical and horizontal lines (use Excel?) and make required size squares from them.
Note: Geodetic Densify tool made no visual difference at page level.


text:
Q: Dual Boot Windows 10, 4 partition maximum I'm trying to dual boot Ubuntu with Windows 10. I shrunk my windows 10 partition to create space for Ubuntu but when I try to partition the free space I am told I can't make more than 4 partitions. I'm not sure what to do/if I can delete either one of those 2 450MB partitions?

A: If you have an older (non-UEFI) computer, its hard disk is probably formatted with a MBR partition table. The big limiting factor with this type of partition table is that it can only have 4 (maximum) partitions. Many people need more than 4, so what is done is to create 3 primary partitions, and one extended partition. The extended partition can contain more than 1 partition inside of it. Tricky way to get around the 4 partition limit, yes?
Most modern computers (UEFI) use the GPT partition tables, which allow the use of up to 128 individual partitions, eliminating the need for the extended partition trick. Also, most modern hard disk drives 2TB or larger also require the use of GPT partition tables.
So, to answer your specific question, the answer is no, don't delete any of your 4 existing partitions. You would probably loose the ability to run vendor diagnostics, or the ability to restore the OS in case of catastrophic failure.
If you post a screenshot of a gparted view of your sda drive, we can better answer on how to proceed.
update: I've looked at your gparted screenshot. And yes, sda3/4 are diag/restore partitions. If you don't mind loosing that capability, you could delete them. I'd also shrink your Windows partition USING WINDOWS DISK MANAGEMENT APPLICATION, not gparted, to make more room for Ubuntu.
Cheers, Al

A: You have two recovery partitions. I don't know what's on them, and I don't know if it would be helpful to know what's on them. Because of that, I recommend the following setup.
Since the drive is MBR, you're limited to four primary partitions. If you want more, you need an extended partition, with logical partitions under it. Since you already have four partitions, you can't create the extended partition without deleting some other partitions.
Mount the two recovery partitions (sda3 and sda4), and copy all the files off of them. Use Gparted to delete both of them and then set up your Ubuntu partition, leaving at least 1GB of free space after it. In this free space, create your extended partition and then recreate the two recovery partitions. Copy the respective files back in.
This way, you keep all your partitions and get Ubuntu. I don't know if the recovery partitions will work the way they're supposed to, but they're there if needed.


text:
Q: Mysql error with my SELECT DISTINCT query I keep running into the same error, using MySQL.
The totaal value is marked as wrong, but i have no idea what is wrong with the function at all.
My original code example
CREATE or REPLACE FUNCTION functiondave
 (p_in date)
 return date is sumMediaExpression int;

 begin;

 select distinct count(Beoordelingen) into totaal
 from media_uitingen
 where Beoordelingen like 'Positief' and DATUM like '01-07-14';

 dbms_output.put_line('Number of positive MediaExpressions op 01-07-14
 zijn : ' || sumMediaExpression);

 end;

A:
The SELECT DISTINCT statement is used to return only distinct (different) values.

Your query is wrong.
You need to write it like this:
SELECT COUNT(DISTINCT Beoordelingen) INTO totaal FROM media_uitingen (the rest of your query);
You can check this website for further information about SQL queries: https://www.w3schools.com/sql


text:
Q: How to set small widgets theme on Firefox When I switched to Firefox 57 I was able to choose a theme with small widgets. Today on Firefox 67 it looks like this.

In the addon settings it is just named the light theme.

When I create a new profile today and choose the light theme, the widgets are considerably bigger.

Does anyone know what I have to do to create a new profile with the small widgets?

A: This is not a theme; it's a separate "Density" setting under Menu → Customize.


text:
Q: My iPhone App crashes after getting push notification in some devices(especially ios_10.3.1) I have just figured out how to send push notification correctly in my app. However when it started working correctly, a new type of error has arrived. My app crashes on launch after receiving push notification. I tested on 5 devices and 2 of them crashed due to the issue(both running on iOS_10.3.1). The weird part is the other 3 devices were running on iOS 10.2 and 9.3.1. I don't really think this is something related to OS.
Apple have send a crash log like this but when i click on open in project it just opens my launch screen xib

My appDelegate class APNS service calling part->
 func registerForPushNotifications(application: UIApplication)
{

    if #available(iOS 10.0, *){
        UNUserNotificationCenter.currentNotificationCenter().delegate = self
        UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Badge, .Sound, .Alert], completionHandler: {(granted, error) in
            if (granted)
            {
                UIApplication.sharedApplication().registerForRemoteNotifications()
            }
            else{
                CommonViewController.alertViewUI("Alert", message: "Push notification is enabled")
            }
        })
    }

    else{ //If user is not on iOS 10 use the old methods we've been using
        let notificationSettings = UIUserNotificationSettings(
            forTypes: [.Badge, .Sound, .Alert], categories: nil)
        application.registerUserNotificationSettings(notificationSettings)

    }

}

My App functioning-> On launch-----------------------
A version check class to know the user version.From there its redirected to the main(Home page).
On Home page ->
  1. Load the views.
  2. Calls a link asynchronously and get the count of available notification to be displayed near alerts symbol.(I am pretty sure there is no error while calling this link or getting the notification)-------------------------
Note:
** When double tapping the iPhone home button menu the app is shown in background as a opened screen with home page open(After it crashed).
**One 10.3.1 device works properly
**If the app is reinstalled everything works fine in all.

A: If I understand you correct, your app is moving to the background and crashes when coming back to foreground.
This doesn't look like an issue with UNUserNotifications. More like the notification just triggers the crash in your app in that case. Stack shows the crash happens in your app. That means you are running on a null pointer reference somewhere when returning to the foreground.
Blind guess:
Are you listening to UIApplicationDidBecomeActiveNotification or UIApplicationWillEnterForegroundNotification?
If yes, each class that listens to those notifications needs unsubscribe before they meet the garbage collector. Good place for that is dealloc/deinit.
Since you use Swift:
deinit {
    NotificationCenter.default.removeObserver(self)
}

Objective-C ARC would look like:
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

If its not listening to notifications, then it is still a reference somewhere that get deallocated. The reason it doesn't crash right away would be then a simple Zombie. An object instance that is about to get deallocated, but didn't yet during runtime on some devices.

A: *

*This code resolve your problem::-
func registerPushNotifications() {

 if #available(iOS 10.0, *) {
    let center  = UNUserNotificationCenter.current()
    center.delegate = self
    center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
        if error == nil{
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
}
else {
    UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
    UIApplication.shared.registerForRemoteNotifications()
}
}

A: Please check that what you have written in this because this function is called on receiving push notification. Please debug this.
func  application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
}

A: For me it was setting the delegate of UNUserNotificationCenter.current() before requesting authorisation that caused the crash. This is how I fixed it. Hope its helps someone else.
func registerForPushNotifications() {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.sound, .alert, .badge]) { [weak self] granted, _ in
        print("Permission granted: \(granted)")
        guard granted else { return }
        center.delegate = self
        self?.getNotificationSettings()
    }
}

func getNotificationSettings() {
  UNUserNotificationCenter.current().getNotificationSettings { settings in
    print("Notification settings: \(settings)")
      guard settings.authorizationStatus == .authorized else { return }
      DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
      }
  }
}


text:
Q: How to remove extension association using regedit.exe? Following my post here  - Can't un-associate .css extension from Visual Stdio 2013
and the suggested solution  - Why are certain default application associations "locked"?
What do I have to do in the regedit.exe in order to remove the .css association to Visual Studio and make it associate to Notepad++ instead  ?
That what I have under -
regedit.exe -> Software -> Microsoft -> Windows -> CurrentVersion -> Explorer -> FileExts > .css

A: As describe in the attached link of @Farag - just do -
Go to -
regedit.exe -> Software -> Microsoft -> Windows -> CurrentVersion -> Explorer -> FileExts > .css

Delete the .css folder,   like this -

and then that's extension would be not associate for any program .
Now you can set its new default program by -


text:
Q: Returns [object HTMLSpanElement] <form>

        Distance:
        <input type="number" id="distance" onKeyUp="calculate();">m

        Time:
        <input type="number" id="time" onKeyUp="calculate();">s

        Speed:
        21 m/s

</form>

I am making a simple speed calculator but it isn't working. The output comes [object HTMLSpanElement]
Any help will be appreciated for I am new to javascript.

A: The variable speed in the last line is not the same as the one you set because it's in a different scope.
Try this:
var calculate = function() {
  var distance = document.getElementById("distance").value;
  var time = document.getElementById("time").value;
  var speed = distance/time;

  if (speed=="Infinity" || speed=="NaN"){
    document.getElementById("speed").innerHTML="Invalid Input";
    document.getElementById("unit").innerHTML="";
  }else{
    document.getElementById("speed").innerHTML=speed;
  }
};

A: The reason is scope:
var calculate = function() {
  var distance = document.getElementById("distance").value;
  var time = document.getElementById("time").value;
  var speed = distance/time;
}

// speed is not within the right scope anymore
// because you closed the function above!
if (speed=="Infinity" || speed=="NaN"){
  document.getElementById("speed").innerHTML="Invalid Input";
  document.getElementById("unit").innerHTML="";
}else{
  document.getElementById("speed").innerHTML=speed;
}

Because your script runs in document, the value of speed is resolved as the element .
Move the last if-statement inside the function:
var calculate = function() {
  var distance = document.getElementById("distance").value;
  var time = document.getElementById("time").value;
  var speed = distance/time;

  if (speed=="Infinity" || speed=="NaN"){
    document.getElementById("speed").innerHTML="Invalid Input";
    document.getElementById("unit").innerHTML="";
  }else{
    document.getElementById("speed").innerHTML=speed;
  }
}

A: This is a non-obvious issue. It helps with proper indentation
var calculate = function() {
  var distance = document.getElementById("distance").value;
  var time = document.getElementById("time").value;
  var speed = distance/time;
}

if (speed=="Infinity" || speed=="NaN"){
  document.getElementById("speed").innerHTML="Invalid Input";
  document.getElementById("unit").innerHTML="";
} else{
  document.getElementById("speed").innerHTML=speed;
}

The value of speed that you are assigning is not actually defined anywhere in your code. The speed from inside of calculate is not used because it is scoped within the function. The speed you are actually assigning is one that the browser automatically creates based on the id you have given to your element.
If you put the assignment within your calculate, the problem will be fixed.
var calculate = function() {
  var distance = document.getElementById("distance").value;
  var time = document.getElementById("time").value;
  var speed = distance/time;

  if (speed=="Infinity" || speed=="NaN"){
    document.getElementById("speed").innerHTML="Invalid Input";
    document.getElementById("unit").innerHTML="";
  } else{
    document.getElementById("speed").innerHTML=speed;
  }
}


text:
Q: With XSLT Can i extract the 2 first digits from a number I'm trying to extract the 2 first digits from a number.
I have this XML:
<extraccio data="01-05-2013" tipus_objecte="5">
    <objRegistral>
           <categoria id="69">2A. CATEGORIA</categoria>
            <cadastral/>
            <web>www.campingelcarlitos.com</web>
            <email>info@campingelcarlitos.com</email>
            <adreca>
                <no_normalitzada>Cra. N-II, km 658,7</no_normalitzada>
                <tipus_via id="28">Ctra</tipus_via>
                <nom_via>N-II</nom_via>
                <num>km 658,7</num>
                <bloc/>
                <escala/>
                <pis/>
                <porta/>
                **<cp>08350</cp>**
                <municipi id="893">Arenys de Mar</municipi>
                <inframunicipi/>
                <comarca id="21">Maresme</comarca>
                <provincia id="8">BARCELONA</provincia>
                <comunitat/>
                <marca_turistica>COSTA DE BARCELONA-MARESME</marca_turistica>
                <utm_x>464187</utm_x>
                <utm_y>4603963</utm_y>
                <utm_z/>
            </adreca>
            .......

I need to extract the 2 first digits from the tag <cp>..</cp>
I have this code XSLT:
The error is that i cant compare string to integer
<?xml version="1.0" encoding="UTF-8"?>

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        exclude-result-prefixes="xs"
        version="2.0">
        <xsl:template match="/">
            <campings>
                <xsl:for-each select="extraccio/objRegistral/dades_generals/adreca[substring(cp,2)= 08]">
                    <camping>
                        <nom><xsl:value-of select="municipi"/></nom>
                    </camping>
                </xsl:for-each>
            </campings>
        </xsl:template>
    </xsl:stylesheet>

A: In
<xsl:for-each select="extraccio/objRegistral/dades_generals/adreca[substring(cp,2)= 08]">

you need to express the value you are looking for as a string
...[starts-with(cp,'08')]


text:
Q: Groovy Power Print Groovy has a power assert, but I'd like a power print.  For example,
def foo = 'banna5', monkey=7, x=70
println "foo=$foo, monkey=$monkey, x/2=${x/2}"

See the repeating foo, monkey, and expression in the println line... what I want to type is this,
pprint foo, monkey, x/2

This is the output I expect (from either println or pprintln),
foo=banna5, monkey=7, x/2=35

Is there a ditty that does this already?

A: There is nothing that does what you want currently in Groovy...
The problem would be getting the names of the variables when you print out the values.
The way that powerrassert seems to do it, is via AST manipulation of the bytecode (see line 947 of the class org.codehaus.groovy.classgen.AsmClassGenerator) to decorate the assert method with several classes inside the org.codehaus.groovy.runtime.powerassert package.
So to get the results you require, something similar would have to be added to manipulate the AST in a similar way.
You could add a new feature issue to the project's JIRA, and you never know...it might make it into future versions of Groovy
But for now, I think you're stuck with your println as you have it above

A: This may or may not work for you.  it's Very Possible that it only works in scripts.
def pprint(def varClosure) {
    s=varClosure()
    print("\"$s\" = " + binding.variables[s])
}

test = 15

pprint{"test"}

I used a closure so it would pass the current context in (to get bindings).  You can iterate over the closure in various ways--for instance if you pass pprint{["test","anotherVar"]} you could use this in stead of the println:
s.each() { print("\"$it\" = ${binding.variables[s]},\t") }
println ""

That would give pretty close to the results you wanted.
If you want to do it with a groovy class the bindings hash doesn't exist.  There is a properties hash, but it only accesses object properties (not all variables available to the closure--in other words it would miss variables defined in the method and parameters).
Perhaps the closure has a hash of all properties available to it--that would be perfect.  I'll look more later.
Also there is a dump() method on object that you might enjoy.


text:
Q: Why reducer action is carying twice export const initialState = {
  ids: [],
  basket: [],
  subtotal: 0
}

const reducer = (state, action) => {

  switch (action.type) {
    case 'ADD_TO_BASKET':
      debugger
      if (state.ids.indexOf(action.item.id) !== -1) {
// if not new item increase a quantity
 console.log(state.basket.find((el) => el.id.match(action.item.id)).quantity);
        ++state.basket.find((el) => el.id.match(action.item.id)).quantity;
        state.subtotal += action.amount

      }
      if (state.ids.indexOf(action.item.id) === -1) {
//if new value push id to array and push new value to basket
        state.ids.push(action.item.id)
        state.subtotal += action.amount
        state.basket = [...state.basket, action.item]

      }
      return {
        ...state,

      }

    default:
      return state;
  }
}

I've used the debugger and where time to increase quantity it worked twice,
if I change  return { ...state  } to return state all works right only one-time increase, but UI isn't refreshing (basket counter)


text:
Q: Adjusting headline in article i have the following problem when I am adjusting my header:
\documentclass[11pt, a4paper, german]{article}
\usepackage{color}
\usepackage{amsmath, amsfonts, amsthm,}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage{mathrsfs}
\usepackage{mathtools}
\usepackage{amssymb}
\usepackage{pgfplots}
\usepackage{graphicx}
\usepackage{array}
\usepackage{scrpage2}
\ohead{\headmark}
\pagestyle{scrheadings}
\automark{section}

\usepackage{geometry}
\geometry{a4paper,left=40mm,right=30mm, top=2cm, bottom=2cm}

\begin{document}
\section{A}
\newpage

\section{BBBTest}
\end{document}

I tried fancyhdr, plain and header all ready and it doesnt work for me. It puts the headers above each other for example. Here I have the problem that it puts the header twice at the left and the right hand side.
What I want is: the page number at the bottom in the middle of the page and a header of the section or subsection at the top left-hand side with a line below the header.
I hope someone can help me.

A: Well, with class article I would prefer to use package fancyhdr. Package scrpage2 is outdated, use package scrlayer-scrpage instead! Because you are writing in german have you considered to use class scrartcl instead? And scrlayer-scrpage is designed to work optimal with any KOMA-Script class, for example scrartcl ...
Nevertheless, here is the solution for class article and scrlayer-scrpage:
You need to add option headsepline to get the wanted line under the header and you need to add command \clearscrheadfoot to get rid of all pre-definition the package scrlayer-scrpage usualy did ...
Please see the following MWE (with package blindtext to add some dummy text into the document):
\documentclass[%
  11pt,
  a4paper,
  ngerman
]{article}

\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}

\usepackage{geometry}
\geometry{a4paper,left=40mm,right=30mm, top=2cm, bottom=2cm}

\usepackage{blindtext}

\usepackage[%
  headsepline, % <======================================================
]{scrlayer-scrpage} % <=================================================
\pagestyle{scrheadings}
\clearscrheadfoot % <========================== clear all pre-definitions
\ohead{\headmark}
\cfoot{\pagemark}
\automark{section}

\begin{document}
\tableofcontents
\section{A}
\blindtext
\newpage

\section{BBBTest}
\blindtext
\end{document}

Please also note that I deleted all not needed packages for this issue! Now you get the following result:

Have you noticed the warning you should have got by compiling my MWE? It is:

Package scrlayer-scrpage Warning: \headheight to low.
(scrlayer-scrpage)                At least 13.59999pt needed,
(scrlayer-scrpage)                but only 12.0pt found.
(scrlayer-scrpage)                I'll enlarge \headheight, for further
(scrlayer-scrpage)                processing, but you should do this yourself,
(scrlayer-scrpage)                e.g., setting geometry's option
(scrlayer-scrpage)                `head=13.59999pt'.
(scrlayer-scrpage)                I'll also decrease \topmargin on input line 30.

So you should add the option head=13.6pt for geometry:
\geometry{%
  a4paper,left=40mm,right=30mm, top=2cm, bottom=2cm,
  head=13.6pt % <=======================================================
}

With the new MWE you can compile without error message or warning:
\documentclass[%
  11pt,
  a4paper,
  ngerman
]{article}

\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}

\usepackage{geometry}
\geometry{%
  a4paper,left=40mm,right=30mm, top=2cm, bottom=2cm,
  head=13.6pt % <=======================================================
}

\usepackage{blindtext}

\usepackage[%
  headsepline, % <======================================================
]{scrlayer-scrpage} % <=================================================
\pagestyle{scrheadings}
\clearscrheadfoot % <========================== clear all pre-definitions
\ohead{\headmark}
\cfoot{\pagemark}
\automark{section}

\begin{document}
\tableofcontents
\section{A}
\blindtext
\newpage

\section{BBBTest}
\blindtext
\end{document}

with the result:


text:
Q: flex 4 - layer a component on top of another? How can I change the z axis of components and put one in front of the other? The new layout property in Flex 4 has changed significantly & now not sure how to do it.

A: It works the same way that it did in Flex 3.  A components Z order is defined by the order in which they are placed as child of their parent.  The second child will be in front of the first child, and the third child will be in front of the first and second child and so on.
You can still use swapChildren and swapChildrenAt to change the Z-order of children.
The layout property's value will be an instance of a Layout class; which--in a simple form your measure() and updateDisplayList() methods.  IT does not, specifically, relate to moving one component in front of, or behind, another.
On a Flex 4 group, you can use swapElement and swapElementsAt, although I would bet if you were to examine the code you'd find that these are just layers of abstraction over swapChildren and swapChildrenAt.

A: checkout the new depth property introduced in Flex 4 e.g. see http://www.tink.ws/blog/flex-4-uicomponent-depth/

A: Maybe this help:
container's depth
you can use depth property of flex containers to define which element can overlap other elements.


text:
Q: How to use BugSense correctly with custom data? I try to implement BugSense in my Android Application, but I'm not able to see the custom data I submitted. I really can't find out where the problem is, because I get an error report but without custom data. I implemented com.bugsense.trace.ExceptionCallback to receive all unhandled exceptions in the "lastBreath" method.
Here is my example code:
@Override
public void lastBreath(Exception arg0) {
    Log.w(TAG, "executing lastBreath");
    // adding current details to crash data
    HashMap<String, String> errorDetails = new HashMap<String, String>();
    errorDetails.put("testKey", "testValue");
    errorDetails.put("testKey2", "testValue2");
    BugSenseHandler.sendExceptionMap(errorDetails, arg0);
    Log.w(TAG, "lastBreath executed");
}

This is generating an error report but I don't know where to find the custom values of "testKey" and "testKey2". I used the example code of the official site, so where is the problem? Thanks for your help.

A: I'm doing this data collection a little bit different from you. Here is how I do it:
//Call the initAndStartSession right before the setContentView of your activity (onCreate method)
BugSenseHandler.initAndStartSession(UserLogin.this, APIKEY);
//Add the values that you need to monitor
BugSenseHandler.addCrashExtraData("testKey", testKey);
BugSenseHandler.addCrashExtraData("testKey2", testKey2);

Once the error occurs, go to your BugSense errors page. (The link should look something like: https://www.bugsense.com/dashboard/project/YOUR_PROJECT_ID/errors/ ) and click on the exception link (as seen on the image bellow).

Now, once on the error page, click on the "Error Instances"

Now, if you click on the wrench Icon, you will see your "testKey" and "testKey2" available to be shown.

Hope it works!


text: Q: static text - rounded rectangle border mfc I have a static control in a dialog to show some messages in a dialog. By default it is as rectangle box. I want to make it as rounded corned rectangle to get good appearance, similar to that of a button. Any properties can be changed to make it as rounded corner rectangle


text:
Q: Implicit solution to second-order non-linear differential equation I am trying to solve the following differential equation:
$$
\frac{8}{9}y(t) - 2y(t)^2 + y(t)^3 -y''(t) =0.
$$
I think it is impossible to solve it for $y(t)$, but apparently it is possible to solve it for $t(y)$. I really do not have a clue how to solve this one. I guess I need to do some kind of transformation, but I don't really know which one. Can anyone help me?

A: Multiply the equation by $2y'$, this will transform it into
$$\frac{d}{dt}\left(\frac89y^2-\frac43y^3+\frac12y^4-y'^2\right)=0.$$
Using this first integral and separable form of the resulting 1st order ODE, we can write the implicit solution in quadratures:
$$\int\frac{dy}{\sqrt{C_1+\frac89y^2-\frac43y^3+\frac12y^4}}=\pm t+C_2.$$
The integral on the left is in principle expressible in terms of elliptic functions.

A: Assuming that $y^{\prime}(t)\neq0$ at some $t$, it follows by the continuity
of $y^{\prime}$ that this is valid for an entire interval, i.e., there exists
an interval $I$ such that $y^{\prime}(t)\neq0$ for all $t\in I$. This means
that $y^{\prime}$ has constant sign (being continuous), hence $y$ is strictly
monotone on $I$, hence $y:I\rightarrow J=y(I)$ is invertible and for
convenience denote the inverse of $y$ with $t$ (a slight abuse of notation).
In this way
$$
t\in I\overset{y}{\longmapsto}y=y(t)\in J
$$
and
$$
y\in J\overset{t}{\longmapsto}t=t(y)\in I.
$$
Now, since
$$
\left(  t\circ y\right)  (t)=t\text{  for all }t\in I
$$
it follows that
$$
\left(  t\circ y\right)  ^{\prime}(t)=1\text{  for all }t\in I
$$
meaning that
$$
y^{\prime}(t)\cdot t^{\prime}(y(t))=1
$$
or, for short,
$$
y^{\prime}(t)=\frac{1}{t^{\prime}(y)} \text{for all }t\in I\text{.}
$$
Next,
$$
\left(  y^{\prime}\cdot(t^{\prime}\circ y)\right)  ^{\prime}(t)=0
\text{for all }t\in I
$$
which leads to
$$
y^{\prime\prime}(t)\cdot t^{\prime}(y(t))+y^{\prime}(t)\cdot y^{\prime
}(t)\cdot t^{\prime\prime}(y(t))=0
$$
hence
$$
y^{\prime\prime}(t)=-\frac{\left(  y^{\prime}(t)\right)  ^{2}\cdot
t^{\prime\prime}(y)}{t^{\prime}(y)}=-\frac{t^{\prime\prime}(y)}{\left(
t^{\prime}(y)\right)  ^{3}}\text{.}
$$
Coming back to the equation
$$
\frac{8}{9}y(t)-2y(t)^{2}+y(t)^{3}-y^{\prime\prime}(t)=0
$$
and considering $y$ to be the variable and $t$ to be the function (i.e.,
$t=t(y)$), it follows that
$$
\frac{8}{9}y-2y^{2}+y^{3}=-\frac{t^{\prime\prime}(y)}{\left(  t^{\prime
}(y)\right)  ^{3}}
$$
or
$$
t^{\prime\prime}+\left(  y^{3}-2y^{2}+\frac{8}{9}y\right)  \left(  t^{\prime
}\right)  ^{3}=0.
$$
In order to solve this equation, let $u:=t^{\prime}$, hence
$$
u^{\prime}+\left(  y^{3}-2y^{2}+\frac{8}{9}y\right)  u^{3}=0
$$
which is a separable equation. Clearly $u\neq0$, since $t^{\prime}\neq0$, so
we can divide with $u^{3}$ and obtain
$$
-u^{\prime}u^{-3}=y^{3}-2y^{2}+\frac{8}{9}y
$$
which we integrate (w.r.t. $y$) and get
$$
\frac{1}{2}u^{-2}=\int\left(  y^{3}-2y^{2}+\frac{8}{9}y\right)  dy=\frac{1}
{4}y^{4}-\frac{2}{3}y^{3}+\frac{4}{9}y^{2}+C=\left(  \frac{y(3y-4)}{6}\right)
^{2}+C\text{, }C\in\mathbb{R}
$$
which leads to
$$
u=\frac{1}{\sqrt{2\left(  \dfrac{y(3y-4)}{6}\right)  ^{2}+C}}
$$
hence
$$
t(y)=\int\frac{dy}{\sqrt{2\left(  \dfrac{y(3y-4)}{6}\right)  ^{2}+C}}.
$$
In this way you can express $t$ as a function of $y$ and get an implicit form
of the solution $y$. Unfortunately, I don't know if there is a way of
computing the integral (except for $C=0$).


text:
Q: Cpython interpretter / IronPython interpretter No module named clr i'm using IronPython and i want to create some windows form,
i want to create a windows form with some button, and i want to do this in visual studio with iron python,
i'm using visual studio 2012 integrated edition,
each time i create an "ironpython windows form" project, when i want to run it, it says:

The project is currently set to use the .NET debugger for IronPython
  debugging but the project is configured to start with a CPython
  interpreter. To fix this change the debugger type in project
  properties->Debug->Launch mode

when i change debugger to Standard Python Launcher, it says:

ImportError: No module named clr

what should i do?

A: I got the same error and resolved it with these steps:
I changed the project properties
General>Interpreter to IronPython 2.7
Debug>Launch mode to IronPython(.NET) launcher
At first I didn't see IronPython as an interpreter option to select from. I added the path to IronPython installation to my Path System variable, restarted Visual Studio and it worked.

A: I understand this is an old question, but I ran into the same thing today, and did not find any satisfactory answers.
I'm working with a new install of Visual Studio 2015 - Community under Windows 8.1. After installing a bunch of additional add-ons and tool boxes, I thought it would be complete. I had an IronPython debug option in VS, but it had not been (successfully) installed!
If you're having issues with IronPython, look in C:\Program Files (x86), and verify the directory IronPython 2.7 exists.
(IronPython 2.7 is available at
http://ironpython.codeplex.com/releases/view/169382.)
Once you have verified installation was successful, setup your development environment:

*

*Create a Python project in Visual Studio

*At the bottom of the Project menu, click <project name> Properties

*On the General page, select IronPython 2.7 as your interpreter

*On the Debug page, set Launch mode to IronPython (.Net) launcher

*Finally, click on Debug Standard Library.

Using that setup, I was able to generate a blank Windows form application, and start it with/without debugging.

A: OK dudes,
i tell you how i solved the problem,
i reinstalled everything from the scratch, i used to use visual studio express, but i installed the "professional" version,
then i reinstalled everything from http://ironpython.codeplex.com/releases/view/81726
and suddenly all things worked fine in the console,
then voila, ironpython windows form project in visual studio is working now :)


text:
Q: How to get "95%CI for a Binomial Proportion" using glm in R I refer to the site Interval Estimation for a Binomial Proportion
Using glm in R, getting the "asymptotic" 95%CI.
I think binomial link doesn't have "identity", but the following program got the answer. Why?
If you know that, please give me some advice.
This example, n=10, x=2, asymptiotic 95%CI
binom.ci<-function(x,n,alpha = 0.05,link="logit"){
z<-qnorm(1-alpha/2)
family<-binomial(link=link)
fit<-summary(glm(cbind(x,n-x)~1,family=family))
est<-fit$coef[,"Estimate"]
se<-fit$coef[,"Std. Error"]
family$linkinv(est+c(-z,z)*se)
}

binom.ci(x=2,n=10,link="identity")
# [1] -0.04791801  0.44791801

A: It is possible to have an "identity" link function with binomial, but it doesn't make much sense here. We can see what's going on inside the function if we replicate the glm call with the arguments in your example.
fit <- summary(glm(cbind(2, 8) ~ 1,family = binomial("identity")))
fit
#>
#> Call:
#> glm(formula = cbind(2, 8) ~ 1, family = binomial("identity"))
#>
#> Deviance Residuals:
#> [1]  0
#>
#> Coefficients:
#>             Estimate Std. Error z value Pr(>|z|)
#> (Intercept)   0.2000     0.1265   1.581    0.114
#>
#> (Dispersion parameter for binomial family taken to be 1)
#>
#>     Null deviance: 0  on 0  degrees of freedom
#> Residual deviance: 0  on 0  degrees of freedom
#> AIC: 4.3947
#>
#> Number of Fisher Scoring iterations: 2

The "identity" link means that the intercept is to be interpreted directly as a probability, but the problem is that taken literally, that means our 95% confidence interval includes a negative probability, which doesn't make any sense. We really need to use a logit link here to get the correct answer.
So yes, we can use binomial(link = "identity") here without it throwing an error, but it does not give us the classical 95% confidence interval for a binomial proportion.


text:
Q: White Space Issue For some reason I can not see how to delete this large gap in between my title and the details. I inspected different areas and cant see any padding being added.  I marked out the area in red that I would like to remove. The only tricky part is that I would like to delete this spacing without it affecting the page once you click on "heavy duty mechanic"
I apologize for the easy question but have tried and cant seem to get it but must be over looking something.
http://jobspark.ca/job-listings/

A: It seems that the problem relies on a margin being added to all the headings:
h1, h2, h3, h4, h5, h6 {margin: 0 0 24px}

adding a margin to the bottom of your title (as well as your subtitles, etc).
By removing that value (24px) you affect the page when you click on "heavy duty mechanic". Maybe you could try removing the margin bottom on the h1 and adding a margin a top to the subtitle in "heavy duty mechanic" ("About this opportunity").

A: The .article-meta rule includes margin-top:24px, is this maybe what's causing it?
Additionaly, the h1 rule specifies a margin-bottom:24px.

A: Your "footer" element has 24px margin-top. This is the structure of your HTML:
<header>
(space because the header is 45px)
<div class="body">
(space because the footer has margin-top: 24px)
<footer>

On the page produced by clicking "Heavy Duty", the footer and it's margin-top spacing is still there, it's just after that long chunk of text in your "body" div. In the link you gave, your body is empty, so you're seeing that margin-top space right below your header. You're going to need to add CSS/Javascript for specifically this page if you want to overwrite the margin-top. If you're using Chrome, right click your element, click Inspect Element, and on the right click Computed Style and you'll see the margin-top

A: Change the margin-bottom of h1 and margin-top of footer. Instead of removing one's margin I would say, reduce both to half, maybe?
article h1 {
    margin-bottom: 12px;
}

article footer {
    margin-top: 12px;
}


text:
Q: Xcode UI testing can't be used to dismiss KeyChain access dialog My application requires access to the KeyChain when first started. Therefore, whenever new build is launched, a system dialog pops up asking permissions from the user for my application to access the KeyChain. This, however, blocks UI testing completely - the XCUIApplication's launch call is synchronous, so there is no way to dismiss this dialog programmatically.
How can I workaround this problem?


text:
Q: Limpar campo com Jquery Tenho um formulário onde através do modal Bootstrap, ele faz o upload automaticamente. Está funcionando corretamente, o problema é que ele não está limpando o campo. Vejam:
<form method="post" id="form-upload" novalidate enctype="multipart/form-data">
    Formato permitido: JPG, JPEG e PNG
Tamanho da imagem: 1170 x 300

          <button class="btn btn-primary waves-effect waves-light">Foto</button>

      <input type="file" id="fotoCapa" name="FotoCapa"/>
      <input type="text" class="md-form-control md-form-file">

</form>

A: Para limpar apenas o <input="file">, sem precisar resetar todo o forumlário, você pode utilizar o método wrap(), adicionando um novo formulário para esse elemento, resetar só ele e e depois utilizar o unwrap() para remover o formulário adicionado.

$(function(){
    $('#fotoCapa').change(function(e) {
      e.preventDefault();
      var formData = new FormData();
      formData.append('FotoCapa', $('#fotoCapa').prop('files')[0]);

      // Código que iria no success do seu post ajax
      $('#fotoCapa').wrap('<form>').closest('form')[0].reset();
      $('#fotoCapa').unwrap();

      console.clear();
      console.log(formData.get('FotoCapa').name)

   });
});
@import 'https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'

<form method="post" id="form-upload" novalidate enctype="multipart/form-data">
    Formato permitido: JPG, JPEG e PNG
Tamanho da imagem: 1170 x 300

          <button class="btn btn-primary waves-effect waves-light">Foto</button>

      <input type="file" id="fotoCapa" name="FotoCapa"/>
      <input type="text" class="md-form-control md-form-file">

</form>


text:
Q: Existence of periodic orbit of the ODE system $\dot{r}=r-r^3 \cos^2(\theta),\,\dot{\theta}= 1$
Consider the system of ODEs (in polar coordinates):
  $$\dot{r}=r-r^3 \cos^2(\theta)$$
  $$\dot{\theta}= 1$$

If we take $r_1 = \frac{1}{4}$ then $\dot{r}> 0$, and if we take $r_2 = \frac{3}{2}$ then $\dot{r}<0$, so $S:=\{r\in \mathbb{R}:r_1 \le r\le r_2\}$ should be a positively invariant set. Thus there should be a periodic orbit in $S$. But either I'm mistaken or not, and if not then what does the orbit look like?

A: Since $\theta' = 1$, we may as well treat $\theta$ as the independent variable. Changing (dependent) variables to $u := r^{-2}$ and rearranging gives
$$u' + 2 u = 2 \cos^2 \theta,$$
which is a linear, first-order ODE and can hence be solved by elementary techniques (including two integrations). The involved integrals can be evaluated in closed form and this leads to the solutions
$$u = \tfrac{1}{4}(2 + \sin 2 \theta + \cos 2 \theta + C e^{-2 \theta}) .$$
So, $u$ (and thus $r$) is periodic iff $C = 0$. Substituting shows that this holds only for the initial condition $u(0) = \tfrac{3}{4}$, or equivalently, $r(0) = u(0)^{-1 / 2} = \frac{2}{\sqrt{3}}$, which agrees with Semiclassical's comment.
This plot shows indicates the behavior for the three qualitative types of solutions; the blue plot is the unique periodic solution.

This plot was generated using the following Maple code:
dsolve(diff(r(theta), theta) = r(theta) - (r(theta)^3) * cos(theta)^2, r(theta));
op(2, %[2]);
[seq(eval(op(2, %), _C1 = C), C in {-3, 0, 3})];
plots:-polarplot(%, axiscoordinates = polar, coordinateview=[0..2, (-2 * Pi)..(2 * Pi)]);


text:
Q: C++ stringstream parsing I am trying to read valid a user input from command prompt:
for example, valid user input is in following format:
getData <>
<> - any string type value
on Command Prompt:
e.g getData name   => Correct (only one parameter entered after getData as expected)
e.g getData name ID => InCorrect (more than one parameter entered after getData)
e.g getData          => InCorrect  (due to no parameter entered after getData)
How do I check for number of parameters? my code logic is as follow:
string cmd_input;

getline(cin, cmd_input)

stringstream ss(cmd_input);

string input;
string parameter;

 ss >> input; //getData
 ss >> parameter; //name

How do I go about valid/invalid checking? I don't want to run it through loop till EOF stream and count the number of parameter. I read up on peek() and not sure how it fits here. Also, I don't want to use vectors to store parameter.
Thanks!

A: You can check the state of the stream itself after you retrieve input. If the retrieval succeeded, it will be true. You want it to return true after two retrievals, but be false on the third.
if (!(ss >> input1) || input1 != "getData") { //... error : unexpected cmd
}
if (!(ss >> input2)) { //... error: no param
}
if (ss >> input3) { //... error: too many params
}
//... okay

A: With the constraint of not using loops and not even std::vector, it could look the following way:
std::string line, command, arg1, arg2, arg3;

if (std::getline(std::cin, line)) {

    std::istringstream is(line);
    if (is >> command) {
        std::string word;
        if (is >> arg1) {
            ...
            if (is >> arg2) {
                ...
                if (is >> arg3) {
                     ...
                }
            }
        }
    } // end of is >> command
}

Yet if you change your mind and decide to use std::vector, it could look like this:
std::string line, command;
std::vector<std::string> arguments;

if (std::getline(std::cin, line)) {

    std::istringstream is(line);
    if (is >> command) {
        std::string word;
        while (is >> word)
            arguments.push_back(word);
    }
}

A: ss >> input;
if( ss.eof() )
    //no parameter code
else
{
    ss >> param;
    if( !ss.eof() )
         // too many param code
    else
         // good input
}

A: Here is a simple test program reading commands. If the command is getData one argument is extracted and, if this is successful, any trailing whitespace is skipped. At this point the stream parsing the line is expected to have reached its end, i.e., eof() needs to be set:
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    for (std::string line; std::getline(std::cin, line); ) {
        std::istringstream in(line);
        std::string command, name;
        if (in >> command) {
            if (command == "getData" && in >> name && (in >> std::ws).eof()) {
                std::cout << "getData: read one argument: '" << name << '\n';
            }
            else {
                std::cout << "wrong format on line '" << line << "'\n";
            }
        }
    }
}


text:
Q: Google Maps - Click Marker Open InfoWindow and Draw Route Is it possible to both open and infowindow and draw the route between a 'home' marker and the marker clicked?
What I've got is multiple markers on a map with a 'home' marker.  I'd like to have the route drawn on the map from this 'home' marker to the marker clicked.

A: What you want is an event listener on your markers for the click event.  Within that, use the DirectionsService to draw your route.


text:
Q: How to provide internationalization / localization in such a way, that a Property List can be updated any time in the future? I'm looking for a way of how to provide more localizations for my app after it has been released, without the need that Apple has to approve every little change in my localization files. i.e. my app may first ship only in english, but a week later I may add czech, french and spanish as well.
So generally, what would you suggest? As far as I know, for every language there is a subdirectory in Xcode which contains a special strings plist. But that plist is not going to be stored in documents dir, and the standard implementation would always look only at these files on the private directory that can't be changed, right? Is there any practical / easy way to achieve this flexibility or should I just forget it and hard-code my whole app?

A: I have an application that downloads localized strings from a server. It creates a DownloadedBundle/[lang].lproj directory in application's cache directory and saves the downloaded Localizable.strings file there. Then it creates a NSBundle using the DownloadedBundle directory as the path, and loads the resources from that bundle.
Some code snippets, omitting the actual downloading part:
// Returns the path of the downloaded bundle:
- (NSString*) downloadedBundlePath {
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* path = [paths objectAtIndex:0];
    return [path stringByAppendingPathComponent:@"DownloadedBundle"];
}

// Returns the downloaded bundle:
- (NSBundle*) downloadedBundle {
    if (downloadedBundle == nil) {
        downloadedBundle = [[NSBundle bundleWithPath:self.downloadedBundlePath] retain];
    }
    return downloadedBundle;
}

// Returns a string from the downloaded bundle:
- (NSString*) localizedStringForKey:(NSString*)key {
    return [self.downloadedBundle localizedStringForKey:key value:nil table:nil];
}

// Saves the downloaded strings file in the bundle:
- (void) saveDownloadedFile:(NSString*)downloadedFilePath inLanguage:(NSString*)language {
    NSFileManager* fileManager = [[NSFileManager alloc] init];
    NSError* error = nil;
    NSString* lprojPath = [[self downloadedBundlePath]
                           stringByAppendingPathComponent:[language stringByAppendingString:@".lproj"]];
    if (![fileManager createDirectoryAtPath:lprojPath withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"Failed to create a directory at %@: %@", lprojPath, error);
        return;
    }

    // Move the downloaded file to be the new strings file:
    NSString* stringsFilePath = [lprojPath stringByAppendingPathComponent:@"Localizable.strings"];
    if ([fileManager fileExistsAtPath:stringsFilePath]) {
        if (![fileManager removeItemAtPath:stringsFilePath error:&error]) {
            NSLog(@"Failed to remove the old strings file at %@: %@", stringsFilePath, error);
            return;
        }
    }
    if (![fileManager moveItemAtPath:downloadedFilePath toPath:stringsFilePath error:&error]) {
        NSLog(@"Failed to move the new strings file from %@ to %@: %@", moveItemAtPath:downloadedFilePath, stringsFilePath, error);
        return;
    }
}

Disclaimer: This code is a simplified version of what I actually have and not tested in this form. But hopefully it gives some idea.

A: Why do you want to have a dynamically updated localization strings? If the only concern is to add more localizations, you should be ok with updating your application and re-submitting it to appstore. As the process takes time, you wouldn't do that say every 3-5 days when you finush up new localizations, but rather wrap them all in one update.
As a side-effect, your application will get to the updated list and float on top for a while.

A: You are right, you can't change items that are stored in your Resources folder (your bundle).  You could store your localizations in your documents folder, but then you would have to change how that folder is accessed instead of the one folder in your bundle.  It is not clear to me whether this can be trivial.

A: you could also store the data remotely.


text:
Q: How to pivot table correctly with tidyverse? I´m using tidyverse to extract two different datasets from NOAA:
library(tidyverse)
library(fpp3)

SOI <- read_table("https://psl.noaa.gov/data/correlation/soi.data",
       skip = 1,
       n_max = 74,
       col_names = FALSE) %>%
set_names(c('year', month.abb)) %>%
pivot_longer(-year,
           names_to = 'month',
           values_to = 'SOI')

SOI <- SOI %>%
mutate(
year = substr(year, 0, 4), # Preserve only the fourth last digits
YearMonth = paste(year," ",month),
YearMonth = yearmonth(YearMonth)
     )

# SOI <- SOI %>%
# filter(SOI != -99.99)

SOI <- data.frame(SOI$YearMonth, SOI$SOI) %>%
rename(
 YearMonth = "SOI.YearMonth",
 SOI = "SOI.SOI"
 ) %>%
 as_tsibble()

 glimpse(SOI)

And the output is:
  Rows: 778
  Columns: 2
  $ YearMonth <mth> 1951 jan, 1951 fev, 1951 mar, 1951 abr, 1951 mai, 1951 jun, ~
  $ SOI       <dbl> 1.5, -0.2, -0.5, -1.1, 0.3, -1.7, -0.4, -1.8, -1.6, -1.3, -1~

In the same logic I tryed to do the same with ONI dataset:
ONI <- read_table("https://psl.noaa.gov/data/correlation/oni.data",
       skip = 1,
       n_max = 73,
       col_names = FALSE) %>%
set_names(c('year', month.abb)) %>%
pivot_longer(-year,
           names_to = 'month',
           values_to = 'ONI')

 ONI <- as.data.frame(ONI)

 ONI <- ONI %>%
  mutate(
   year = substr(year, 0, 4) #, # Preserve only the fourth last digits
#YearMonth = paste(year," ",month),
#YearMonth = yearmonth(YearMonth)
)

ONI <- ONI %>%
  filter(ONI != -99.90)

glimpse(ONI)

And the result is:
Rows: 788
Columns: 3
$ year  <chr> "1950", "1950", "1950", "1950", "1950", "1950", "1950", "1950", ~
$ month <chr> "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "~
$ ONI   <dbl> -1.34, -1.16, -1.18, -1.07, -0.85, -0.54, -0.42, -0.39, -0.44, -~

By inspecting the first register (as expected to be Jan 1948 for SOI and Jan 1950 for ONI) I see that the wrong pivoted values are in my time series object.
The first value expected to be for Jan 1948 (in https://psl.noaa.gov/data/correlation/soi.data) SOI was -99.99 and for ONI (https://psl.noaa.gov/data/correlation/oni.data) have to -1.53 for Jan 1950.
How can I fix it ?


text:
Q: KiCAD: Error Type (13) - Track crossing In the routing phase, how do you avoid track crossing error?
It seems I can't connect some pads without track crossing. Looks like I am missing some techniques.
Can anyone please help?

A: Basically all non-trivial layouts will have mathematically guaranteed track crossings, if restricting yourself to a 2D plane. The trick is to not restrict yourself to a 2D plane ;)
Technique 1: Multi-layered PCB.
If track A needs to pass to the other side of track B, make it go through a via (an electrically conductive hole in the PCB) to the bottom PCB side, continue there for a bit, and come back up again through a second via on the other side of B. More sophisticated designs even utilize four, six, eight or more layers to make routing possible.
Technique 2: Jumpers.
Often you can get away with using parts (resistors/caps/ICs) as bridges. If the part is wide enough, you can make a trace go in between its pads and thus cross the path. If you do not have a part to route under, available where you need it, you can add so-called jumpers (think 0 ohm SMD resistors, or just pieces of wire for through-hole) to jump over existing traces. This solves the track crossing problem without utilizing extra PCB layers, and thus can save costs or time in PCB manufacturing.
Other tricks are for example connecting ICs not outward, but having traces go under the ICs body and continue from there. This can help disentangle the buses leaving thin-pitch ICs.


text:
Q: Static import in javafx application returns 'null ' with standard javafx:run command but works in debug mode and in artefact I recently ported a non-maven javafx application built in IntelliJ to a Maven application in VSCode (JDK14), partly to upgrade my code and partly to get more experience working with VSCode.
My Main class declares a static import:
public class Main extends Application {

static Stage theMainStage;
final Class<?> cls = this.getClass();
final ClassLoader cLoader = cls.getClassLoader();

public static void main(String[] args) {

    Application.launch(Main.class, (java.lang.String[]) null);
}

@Override
public void start(Stage PrimaryStage) {
    /*
    handle to the primary stage use as reference for other
    parts of application*/
    theMainStage = PrimaryStage;  //more code here..................

The main stage is reloaded by a call to the MainReloader class elsewhere in the program:
 //at head of class:
import static WeightingMachine.Main.theMainStage;

public void Load() throws IOException {
    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        BorderPane bp = fxmlLoader.load(getClass().getClassLoader().getResource("UI_HE2.fxml").openStream());
        chordController cC = fxmlLoader.getController();
        cC.setSingleEditState(se);
        cC.setInsertModeState(ins);

        //clear coordinate fields if in single edit mode:
        if ((se) || (ins)) {
            Collection<Node> collNodes = cC.chGridPane.getChildren();
            for (Node n : collNodes) {
                if (n.getId() != null && n.getId().contains("Num")) {
                    ((TextField) n).clear();
                }
            }
        }

        //set GUIto fit screen (need this to ensure interface is scrollable:
        Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
        Scene scene = new Scene(bp, screenBounds.getWidth(), screenBounds.getHeight());
        scene.getStylesheets().addAll(getClass().getClassLoader().getResource("style.css").toExternalForm());
        theMainStage.setScene(scene);
        theMainStage.show();

    } catch (IllegalStateException ise) {
        Alert locAlert = new Alert(Alert.AlertType.ERROR);
        locAlert.setHeaderText("No resource found!");
        locAlert.setContentText("The program was unable to locate an FXML resource. " +
                "Try restarting the program and logging in to the database required.");
    }
}

The pox.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>HE.groupID</groupId>
  <artifactId>HE-archetypeID</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>HE-archetypeID</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>14</maven.compiler.source>
    <javafx.version>14.0.1</javafx.version>
  </properties>

    <dependencies>
      <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-api</artifactId>
          <version>5.4.2</version>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.junit.jupiter</groupId>
          <artifactId>junit-jupiter-engine</artifactId>
          <version>5.4.2</version>
          <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.21.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-junit-jupiter</artifactId>
      <version>2.23.0</version>
      <scope>test</scope>
  </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-math3</artifactId>
      <version>3.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.openjfx</groupId>
      <artifactId>javafx-controls</artifactId>
      <version>15-ea+5</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>15-ea+5</version>
    </dependency>
    <dependency>
      <groupId>org.ops4j.base</groupId>
      <artifactId>ops4j-base-io</artifactId>
      <version>1.5.1</version>
    </dependency>
    <!-- Logging dependencies -->
    <!-- first include logging api: -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>2.0.0-alpha1</version>
  </dependency>
  <!-- Choose ONE! logging provider: -->
  <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.3.0-alpha5</version>
  </dependency>
  </dependencies>
  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <!-- Include plugin so generated artifact can identify main class -->
        <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>14</source>
                        <target>14</target>
                    </configuration>
                </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
          <configuration>
              <archive>
                  <index>true</index>
                  <manifest>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>lib/</classpathPrefix>
                    <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
                    <mainClass>WeightingMachine.Main</mainClass>
                  </manifest>
              </archive>
          </configuration>
      </plugin>
      <!-- Include a helper plugin to assist with source management and
        build config: Note the structure of this!-->
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>build-helper-maven-plugin</artifactId>
          <version>3.1.0</version>
          <executions>
              <execution>
                  <phase>generate-sources</phase>
                  <goals>
                      <goal>add-source</goal>
                  </goals>
                  <configuration>
                     <!-- Include paths to source pacakges: -->
                      <sources>
                          <source>src/main/java/Login</source>
                          <source>src/main/java/Convolution</source>
                          <source>src/main/java/WeightingMachine</source>
                      </sources>
                  </configuration>
              </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>3.1.2</version>
          <executions>
            <execution>
              <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
                <goal>copy-dependencies</goal>
              </goals>
              <configuration>
                <outputDirectory>${project.build.directory}</outputDirectory>
                <overWriteReleases>false</overWriteReleases>
                <overWriteSnapshots>false</overWriteSnapshots>
                <overWriteIfNewer>true</overWriteIfNewer>
              </configuration>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <!-- This, together with the Maven-jar-pluin is responsible for building an artifact
          Make sure the main class in stated
          the mojo to generate the artifcat is: mvn compile assembly:single -->
          <artifactId>maven-assembly-plugin</artifactId>
          <version>3.3.0</version>
          <configuration>
            <archive>
              <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>WeightingMachine.Main</mainClass>
              </manifest>
            </archive>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
          <executions>
            <execution>
              <id>make-assembly</id>
              <phase>package</phase> <!-- bind to the packaging phase -->
              <goals>
                <goal>single</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
          <plugin>
              <groupId>org.openjfx</groupId>
              <artifactId>javafx-maven-plugin</artifactId>
              <version>0.0.4</version>
              <configuration>
                  <mainClass>src/main/java/WeightingMachine/Main.java</mainClass>
              </configuration>
          </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

The StackTrace is as follows:

Main Stage from ChordController in initialization: null
Main Stage from ChordController before call: null
Main Stage from ChordController in initialization: null
12:42:06.382 [JavaFX Application Thread] DEBUG WeightingMachine.chordController - before MainStage
null
java.lang.NullPointerException
        at WeightingMachine.MainReloader.Load(MainReloader.java:82)
        at WeightingMachine.chordController.lambda$addPitches$9(chordController.java:530)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8885)
        at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
        at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
        at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3890)
        at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1885)
        at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2618)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
        at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
        at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
        at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
        at javafx.graphics/com.sun.glass.ui.mac.MacView.notifyMouse(MacView.java:127)
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.NullPointerException
        at WeightingMachine.chordController.lambda$addPitches$9(chordController.java:533)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Node.fireEvent(Node.java:8885)
        at javafx.controls/javafx.scene.control.Button.fire(Button.java:203)
        at javafx.controls/com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:206)
        at javafx.controls/com.sun.javafx.scene.control.inputmap.InputMap.handle(InputMap.java:274)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:247)
        at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:234)
        at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
        at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
        at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
        at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
        at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
        at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3890)
        at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1885)
        at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2618)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:409)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:299)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:447)
        at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:412)
        at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:446)
        at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
        at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
        at javafx.graphics/com.sun.glass.ui.mac.MacView.notifyMouse(MacView.java:127)
Caused by: java.lang.NullPointerException
        at WeightingMachine.MainReloader.Load(MainReloader.java:82)
        at WeightingMachine.chordController.lambda$addPitches$9(chordController.java:530)
        ... 51 more

All works fine in the non-maven build in IntelliJ - without the pom obviously. Oddly, it works in the VSCode Maven build in debug mode where on stepping through 'theMainStage' is returned in the calling class as expected. Infuriatingly, The artifact built using the mvn compile assembly:single command also works OK.
In contrast, running the code in VSCode using the mvn clean javafx:run command returns 'theMainStage' as a null object within the calling class (and elsewhere in the project). There appears to be something odd happening that occurs only in the case of a standard run of the code where the static import declaration of 'theMainStage' in the Main class fails. I wonder whether anybody has any ideas what might be going on?  Thx in advance...


text:
Q: Unable to grab attribute from html tag using selenium webdriver (Java) I would like to write a selenium test to see if an HTML tag will show hidden or not.  The tag changes as follows:
Hidden state:

Shown state:

I tried to use the following code to help me pull the attribute for the test:
System.out.println(driver.findElement(By.id("gameboard")).getAttribute("style"));

Unfortunately nothing prints out. When I try to pull id its gives me the right attribute.

A: I am getting result without any error.
HTML code
<!DOCTYPE html>

<title>Test</title>

Java Selenium Code:
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HowToGetStyleValues {

    public static void main(String[] args) {
         System.setProperty("webdriver.chrome.driver", "./libs/chromedriver 4");
         WebDriver driver=new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.get("file:///Users/xxx/Downloads/testing.html");
    System.out.println(driver.findElement(By.id("gameboard")).getAttribute("style"));
    }
}

Result
display: none;