text:
Q: Match Dataframes Excluding Last Non-NA Value and disregarding order I have two dataframes:
Partner<-c("Alpha","Beta","Zeta")
COL1<-c("A","C","M")
COL2<-c("B","D","K")
COL3<-c("C","F",NA)
COL4<-c("D",NA,NA)
df1<-data.frame(Partner,COL1,COL2,COL3,COL4)

lift<-c(9,10,11,12,12,23,12,24)
RULE1<-c("B","B","D","A","C","K","M","K")
RULE2<-c("A","A","C","B","A","M","T","M")
RULE3<-c("G","D","M","C" ,"M", "E",NA,NA)
RULE4<-c(NA,NA,"K","D" ,NA, NA,NA,NA)

df2<-data.frame(lift,RULE1,RULE2,RULE3,RULE4)

df1
Partner    COL1    COL2    COL3    COL4
Alpha         A       B       C       D
Beta          C       D       F      NA
Zeta          M       K      NA      NA

df2
lift    RULE1    RULE2     RULE3    RULE4
   9        B        A         G       NA
  10        B        A         D       NA
  11        D        C         M        K
  12        A        B         C        D
  12        C        A         M       NA
  23        K        M         E       NA
  12        M        T        NA       NA
  24        K        M        NA       NA

This is a market basket analysis. df1 is the customer/partner that bought each of the items listed: A, B, C...etc.
df2 are the recommendations associated with the items bought in the past.
The last value in each of the df2 rows represent the recommendation. So the preceding values in each row from the last non-NA value are the "baskets".
So for example in the first row of df2, it is stating: If B and A are bought together, recommend G.
I want to be able to figure out if each partner from df1 bought ALL the values in each row excluding the final value since that is the recommendation. Then add that recommendation to the end of each row of the new dataframe.
For example:
For partner: Alpha, would it be good to recommend value G from the first row? Answer would be yes because they bought all the values from that row in df2 (A and B).
For partner: Beta, it would not be good to recommend value G because not all of the values from the first row of df2 are found in the Beta row.
Final Output:
Partner    COL1    COL2    COL3    COL4    lift   RULE1    RULE2    RULE3    RULE4   Does Last Non-NA Value Exist in Row?
Alpha         A       B       C       D       9       B        A        G       NA                                    No
Alpha         A       B       C       D      10       B        A        D       NA                                   Yes
Alpha         A       B       C       D      12       A        B        C        D                                   Yes
Alpha         A       B       C       D      12       C        A        M       NA                                    No
Zeta          M       K      NA      NA      23       K        M        E       NA                                    No
Zeta          M       K      NA      NA      12       M        T       NA       NA                                    No
Zeta          M       K      NA      NA      24       K        M       NA       NA                                   Yes

Written out results for clarity:
df3
row1    outputs "No" because G is not found in Alpha Partner and all values before G show up in Alpha Partner (B,A)
row2    outputs "Yes" because D is found in Alpha Partner and all values before D show up in Alpha Partner (B,A)
row3    outputs "Yes" because D is found in Alpha Partner and all values before D show up in Alpha Partner (A,B,C)
row4    outputs "No"  because M is not found in Alpha Partner and all values before M show up in Alpha Partner (C,A)
row5    outputs "No"  because E is not found in Zeta Partner and all values before E show up in Zeta Partner (K,M)
row6    outputs "No"  because T is not found in Zeta Partner and all values before T show up in Zeta Partner (M)
row7    outputs "Yes"  because M is found in Zeta Partner and all values before M show up in Zeta Partner (K)
I think that has to be a join or a match of some kind but can't figure out how to do it.
This would be extremely helpful if someone can help me out with this.
Thanks.
This was the attempt:
df1<-cbind(df1_id=1:nrow(df1),df1)
df2 <- cbind(df2_id=1:nrow(df2),df2)
d11  <- df1 %>% gather(Col, Value,starts_with("C"))           #Long
d11 <- d11 %>% na.omit() %>%group_by(df1_id) %>% slice(-n()) #remove last non NA
d22  <- df2 %>%  gather(Rule, Value,starts_with("R"))
res <- inner_join(d11,d22)
rm(d22)
rm(d11)
final<-cbind(df1[res$df1_id,],df2[res$df2_id,])
final$Exist <- apply(final, 1, FUN = function(x)
c("No", "Yes")[(anyDuplicated(x[!is.na(x) & x != "" ])!=0) +1])

But this didn't work because it didn't take all of the values into account, only if one of them matched...not all.

A: This is quite tricky because the purchases of n customers have to be compared to a set of m rules. Besides this, there are two points which add to the complexity:

*

*The last non-NA RULE column in df2 is semantically different from the others. Unfortunately, the given data structure doesn't reflect this. So, df2 is missing an explicite recommended column.

*Finally, it has to be determined whether a partner already has purchased the recommended item.
The approach below relies on melt(), dcast() and join operations of the data.table package for performance reasons. However, in order to avoid creation of cartesian crossproduct of n * m rows, a loop is used.
EDIT The dcast() has been moved out of the lapply() function.
Prepare data for n:m join
library(data.table)
# convert to data.table and add row numbers
# here, a copy is used insteasd of setDT() in order to rename the data.tables
purchases <- as.data.table(df1)[, rnp := seq_len(.N)]
rules <- as.data.table(df2)[, rnr := seq_len(.N)]

# prepare purchases for joins
lp <- melt(purchases, id.vars = c("rnp", "Partner"), na.rm = TRUE)
wp <- dcast(lp, rnp ~ value, drop = FALSE)
wp
#   rnp  A  B  C  D  F  K  M
#1:   1  A  B  C  D NA NA NA
#2:   2 NA NA  C  D  F NA NA
#3:   3 NA NA NA NA NA  K  M

# prepare rules
lr <- melt(rules, id.vars = c("rnr", "lift"), na.rm = TRUE)
# identify last column of each rule which becomes the recommendation
rn_of_last_col <- lr[, last(.I), by = rnr][, V1]
# reshape from long to wide without recommendation
wr <- dcast(lr[-rn_of_last_col], rnr ~ value)
# add column with recommendations (kind of cbind, no join)
wr[, recommended := lr[rn_of_last_col, value]]
wr
#   rnr  A  B  C  D  K  M recommended
#1:   1  A  B NA NA NA NA           G
#2:   2  A  B NA NA NA NA           D
#3:   3 NA NA  C  D NA  M           K
#4:   4  A  B  C NA NA NA           D
#5:   5  A NA  C NA NA NA           M
#6:   6 NA NA NA NA  K  M           E
#7:   7 NA NA NA NA NA  M           T
#8:   8 NA NA NA NA  K NA           M

Combine rules and purchases
combi <- rbindlist(
  # implied loop over rules to find matching purchases for each rule
  lapply(seq_len(nrow(rules)), function(i) {
    # get col names except last col which is the recommendation
    cols <- lr[rnr == i, value[-.N]]
    # join single rule with all partners on relevant cols for this rule
    wp[wr[i, .SD, .SDcols = c(cols, "rnr", "recommended")], on = cols, nomatch = 0]
  })
)
# check if recommendation was purchased already
combi[, already_purchased := Reduce(`|`, lapply(.SD, function(x) x == recommended)),
      .SDcols = -c("rnp", "rnr", "recommended")]
# clean up already purchased
combi[is.na(already_purchased), already_purchased := FALSE
      ][, already_purchased := ifelse(already_purchased, "Yes", "No")]
combi
#   rnp  A  B  C  D  F  K  M rnr recommended already_purchased
#1:   1  A  B  C  D NA NA NA   1           G                No
#2:   1  A  B  C  D NA NA NA   2           D               Yes
#3:   1  A  B  C  D NA NA NA   4           D               Yes
#4:   1  A  B  C  D NA NA NA   5           M                No
#5:   3 NA NA NA NA NA  K  M   6           E                No
#6:   3 NA NA NA NA NA  K  M   7           T                No
#7:   3 NA NA NA NA NA  K  M   8           M               Yes

In creating combi, the trick is to join only on those columns which are included in each rule. This is why the join needs to be done for each rule separately.
Essentially, we are done now. However, it doesn't look like the desired output.
Final joins
tmp_rules <- rules[combi[, .(rnp, rnr, recommended, already_purchased)], on = "rnr"]
tmp_purch <- purchases[combi[, .(rnp, rnr)], on = "rnp"]
result <- tmp_purch[tmp_rules, on = c("rnp", "rnr")]
result[, (c("rnp", "rnr")) := NULL]
result
#   Partner COL1 COL2 COL3 COL4 lift RULE1 RULE2 RULE3 RULE4 recommend already_purchased
#1:   Alpha    A    B    C    D    9     B     A     G    NA         G                No
#2:   Alpha    A    B    C    D   10     B     A     D    NA         D               Yes
#3:   Alpha    A    B    C    D   12     A     B     C     D         D               Yes
#4:   Alpha    A    B    C    D   12     C     A     M    NA         M                No
#5:    Zeta    M    K   NA   NA   23     K     M     E    NA         E                No
#6:    Zeta    M    K   NA   NA   12     M     T    NA    NA         T                No
#7:    Zeta    M    K   NA   NA   24     K     M    NA    NA         M               Yes


text:
Q: installing pg_repack fails with pgut/pgut.h:13:10: fatal error: c.h: No such file or directory In am installing pg_repack with
"sudo pgxn install pg_repack" and it end
INFO: best version: pg_repack 1.4.7
INFO: saving /tmp/tmp7qn9rttz/pg_repack-1.4.7.zip
INFO: unpacking: /tmp/tmp7qn9rttz/pg_repack-1.4.7.zip
INFO: building extension
make[1]: Entering directory '/tmp/tmp7qn9rttz/pg_repack-1.4.7/bin'
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -Wno-stringop-truncation -g -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fno-omit-frame-pointer -I/usr/include/postgresql -DREPACK_VERSION=1.4.7 -I. -I./ -I/usr/include/postgresql/9.6/server -I/usr/include/postgresql/internal -Wdate-time -D_FORTIFY_SOURCE=2 -D_GNU_SOURCE -I/usr/include/libxml2  -I/usr/include/mit-krb5  -c -o pg_repack.o pg_repack.c
In file included from pgut/pgut-fe.h:13,
                 from pg_repack.c:25:
pgut/pgut.h:13:10: fatal error: c.h: No such file or directory
   13 | #include "c.h"
      |          ^~~~~
compilation terminated.
make[1]: *** [<builtin>: pg_repack.o] Error 1
make[1]: Leaving directory '/tmp/tmp7qn9rttz/pg_repack-1.4.7/bin'
make: *** [Makefile:35: all] Error 2
ERROR: command returned 2: make PG_CONFIG=/usr/bin/pg_config all

Even downloading the pg_repack source and build with make has the same error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is this sentence grammatical, "Power measure going to watts"? It sounds like the lecturer is saying

Power measure going to watts.

Is this sentence grammatical?

A: It sounds like "Power's measured in Watts" to me, which is grammatical. The copula "is" has been reduced to just "'s"; the full sentence is "Power is measured in Watts".


text:
Q: SharePoint : best way to insert a list item with formated hyperlink? I have the following code:
web.AllowUnsafeUpdates = true;
SPList list = web.Lists[this.ListName];
SPListItem item = list.Items.Add();
item["linktoAttachment"] = this.SiteAddress +  file.Url;

My question is how can I have friendly link text...
like in a classic hyperlink you have
friendly link here

Thanks

A: YOur LinkToAttachment field Should of Type Url, then you can use the following:
item["linktoAttachment"] = string.Format("{0},{1}", this.SiteAddress +  file.Url, "friendly link here");

Another option is:
SPListItem newLink = list.Items.Add();
SPFieldUrlValue value = new SPFieldUrlValue();
value.Description = "friendly link here";
value.Url = this.SiteAddress +  file.Url;
newLink["linktoAttachment"] = value;


text:
Q: Create Standalone Bokeh Document with js Trying to rewrite Bokeh example as standalone document but not sure how I can add widgets to the html file.
With "file_html" I can create an html string but what should I do if I also want to save and add widgets like Sliders, Buttons etc. ?
from bokeh.models.widgets import *
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature

def bkapp():
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    html = file_html(plot, CDN, "myplot")
    with open('my-plot.html','w') as file:
        file.write(html)

A: file_html only accepts a single object, but there is no reason that object can't be a layout:
from bokeh.layouts import column

html = file_html(column(slider, plot), CDN, "myplot")


text:
Q: How to Integrate multi-step contact form into flipbox using wordpress? I have a WordPress website using ElementorPro. I would like to integrate a form similar to this one
https://www.fluenthome.com/build/
The form seems to be enclosed in flip-box and on-click next, with flip animation, it goes to the next step and at the end, it gets user's info and send an email.
I google many times and read a lot of forums and questions but couldn't get the way I do that. I'm not a back-end developer so I'm looking forward to some kind of plugin or way that can help me to achieve the desired form.

A: You wouldn't be able to achieve something similar with Elementor's Form widget and the Flipbox widget. The closest thing would be to try to implement a multistep form which can be achieved with plugins like: https://wordpress.org/plugins/multi-step-form/
Otherwise, to get what you're looking for you would have to hire a developer to develop it from scratch.


text:
Q: JSON in MySQL : get data from an object within a range of keys What I have:

*

*A mysql table, say table1

*table1 contains two columns viz. id and data

*id is int but the twist is data is JSON type and its keys are comparable

*the table1 contains only one row (for the sake of this question)
table1

id
data

1
{'1': 'content1', '2': 'content2',    '3':'content3',.......,'10000':'content10000' }

What I want to have:
I want a query such that it returns me key-value pairs within a range of keys, say, 100 to 200.
What I'm getting on searching on internet:
Everywhere I got only the answers where one can get rows which have the values within a range, but here the case is I want values of keys within a range.

A: Possible realization:
WITH RECURSIVE cte AS ( SELECT @from num
                        UNION ALL
                        SELECT num+1 FROM cte WHERE num < @till )
SELECT CONCAT('key', num) `key`,
       JSON_EXTRACT(test.val, CONCAT('$.key', num)) `value`
FROM test
CROSS JOIN cte
HAVING `value` IS NOT NULL;

fiddle


text: Q: Hide some text from shared users in GoogleDocs Is there any possibility to hide some part of Google Doc form users that also have access to this doc. For example owner of doc just mark some text as sensitive and other users that don't have enought permissions can't see that. Maybe write some subscripts? Or maybe there is some custom solution in web. I need sth like CVS with revision history and commenting changes + hiding some sensitive text from other readers of document.


text:
Q: replace the string "Microsoft" with "W3Schools Test$'" I would like to replace the string "Microsoft" with "W3Schools Test$".
Please note that there is single quotes after the dollar sign.
It is not working with my below code. You can see demo-one is working perfectly, but in case of demo-two its not working well.

function myFunction() {
    var str_one = document.getElementById("demo-one").innerHTML;
    var res_one = str_one.replace("Microsoft", "W3Schools Test$");
    document.getElementById("demo-one").innerHTML = res_one;

    var str_two = document.getElementById("demo-two").innerHTML;
    var res_two = str_two.replace("Microsoft", "W3Schools Test$'");
    document.getElementById("demo-two").innerHTML = res_two;
}

Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:

Visit Microsoft!

Visit Microsoft!

<button onclick="myFunction()">Try it</button>

Here is the output of the above code.
Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:
Visit W3Schools Test$!
Visit W3Schools Test!!
Third line should show as Visit W3Schools Test$' but it showing as Visit W3Schools Test!!
Please help me to get out from this problem.
Thanks in advance.

A: In the context of replace , $' is use to inserts the portion of the string that follows the matched substring.
To insert $ using the string#replace, use $$.

function myFunction() {
    var str_one = document.getElementById("demo-one").innerHTML;
    var res_one = str_one.replace("Microsoft", "W3Schools Test$");
    document.getElementById("demo-one").innerHTML = res_one;

    var str_two = document.getElementById("demo-two").innerHTML;
    var res_two = str_two.replace("Microsoft", "W3Schools Test$$'");
    console.log(res_two);
    document.getElementById("demo-two").innerHTML = res_two;
}

Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:

Visit Microsoft!

Visit Microsoft!

<button onclick="myFunction()">Try it</button>

A:

function myFunction() {
        var str_one = document.getElementById("demo-one").innerHTML;
        var res_one = str_one.replace("Microsoft", "W3Schools Test$$'");
        document.getElementById("demo-one").innerHTML = res_one;

        var str_two = document.getElementById("demo-two").innerHTML;
        var res_two = str_two.replace("Microsoft", "W3Schools Test$$'");
        document.getElementById("demo-two").innerHTML = res_two;
    }

Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:

Visit Microsoft!

Visit Microsoft!

<button onclick="myFunction()">Try it</button>


text:
Q: Ways of Dependency Injection Can the Factory Patterns (Factory Method,Simple Factory Method and Abstract Factory) or Service Locator Pattern way of fetching the dependency be called Dependency Injection.
My understanding is with this way of instantiating dependency, the high level class still have to know about about the Factory or Service locator.Dependency Injection means the dependency is pushed and not pulled unlike Factory type and the best way to do it is using Inversion of Control containers like NInject,Unity,CastleWindsor etc. Please share your views.

A: Dependency Injection and Service Locator are two opposing ways to program to interfaces, but Dependency Injection solves most problems and challenges far better than the Service Locator anti-pattern.
Abstract Factories can be injected into services that need them, so can be combined with both approaches. They are perpendicular to the discussion, not a variation of Service Locator.

A: No, they can't.
Dependency injection is a pattern that implements IoC or inversion of control. It implies, that classes should not be tightly coupled to each other and should not know about where to fetch their dependency.
Inversion of control principle is often expressed as "Don't call us, we'll call you" - in this case the classes, managed by IoC container shouldn't know anything about their dependencies and how to fetch them. Factory patterns and service locator implies, that the using class actually knows about the way to fetch that dependency.
UPDATE
Let me also cite Martin Fowler:

The fundamental choice is between Service Locator and Dependency
  Injection. The first point is that both implementations provide the
  fundamental decoupling that's missing in the naive example - in both
  cases application code is independent of the concrete implementation
  of the service interface. The important difference between the two
  patterns is about how that implementation is provided to the
  application class. With service locator the application class asks for
  it explicitly by a message to the locator. With injection there is no
  explicit request, the service appears in the application class - hence
  the inversion of control.

http://martinfowler.com/articles/injection.html


text:
Q: KindError in Google App Engine I defined a simple class in GAE for keeping user profiles data like this:
class User(db.Model):
    email = db.EmailProperty()
    role = db.StringProperty(default=roles.USER)
    first_name = db.StringProperty()
    last_name = db.StringProperty()
...

I use memcache to keep session information. memcache data looks like this { 'key': 'agpjYW5kaXJhdGVzcgoLEgRVc2VyGCMM'}. I get session_id value from the cookie. When I try to get user info linked to that cookie like this:
session_id = request['session_id']
data = memcache.get(session_id)
user = User.get(data['key'])

I get KindError exception:
KindError: Kind 'User' is not a subclass of kind 'User'

I know this user exists, memcache exists. User class is defined only once in my project. Why this error occurs and how can I make it work?
UPDATE: I tried to use db.get() instead of User.get() and it worked. So, what's the problem there can be?

A: Model.get() does check whether the supplied key is of the correct kind, as defined in the documentation. If not of the correct kind it will throw a KindError.
db.get() does not do any type checking and therefore will succeed with the supplied value if it exists in the data store, but will not necessarily return a User entity.
So you need to check whether the key in your memcache is actually of the User kind. Are you sure it's not overwritten with the key of a different model at some point?

A: The App Engine framework defines a class called 'User' as part of the Users API. In addition, you have your own class by the same name. When the exception occurs, you're trying to use one, but getting the other.
To avoid this, rename your model. You should also be careful how you import modules in Python. Instead of:
from google.appengine.api.users import User

or worse:
from google.appengine.api.users import *

you should use:
from google.appengine.api import users

And then refer to users.User, which is unambiguous.

A: The problem, it seems to me, is more subtle than that. I was getting the error with this call to Model.get() (I'm retrieving a top-level singleton object, always there):
datastore = GDSDatastore.get(gds.Key.from_path(*path))

so I investigated with this code:
datastore = gds.get(gds.Key.from_path(*path))
if not(datastore is None or isinstance(datastore, GDSDatastore)):
    logger.error("KindError isinstance(GDSDatastore)=%s class=%s" % (isinstance(datastore, GDSDatastore), datastore.__class__.__name__))
    raise gds.KindError('Kind %r is not a GDSDatastore instance' %
                    (datastore.kind()))

The vast majority of the time I get no error, but today I got this interesting log:
KindError isinstance(GDSDatastore)=False class=GDSDatastore

Now, that strikes me as rather peculiar.
(Note: GDSDatastore is defined locally: class GDSDatastore(gds.Model))


text:
Q: gitignore to only track 2 directories with it's contents I want to setup my .gitignore file to only keep track of 2 directories along with all files inside of them (with some exceptions like vendor). We do a lot of development for cPanel hosts and find it difficult with all other cPanel directories in the user directory to also want to be added to the local repo.
We have 2 directories we want to track
public_html
synergy
And want to exclude:
synergy/vendor (composer)
synergy/logs/* (only the files within this directory, not the directory)
public_html/uploads/*
I have tried the following (got it from another stackoverflow question) but this seems to exclude all subdirectories.
# Ignore everything
*

# But not these files...
!.gitignore
!synergy
!synergy/
!synergy/*
!public_html
!public_html/
!public_html/*

# Further specific excludes:
synergy/vendor
synergy/vendor/*
synergy/logs/*
/public_html/uploads/
/public_html/uploads/*

A: Use /** to select all subdirectories
*
!.gitignore

!a
!b
!a/**
!b/**


text:
Q: Using cmake to copy files to multiple dependent target binary folders I have a project system (multiple users) in cmake that use ctest to run regression tests. One of the libraries in the project have data files that are required by the library, like plugins and config files. I then have X other executable targets (ctests) that depend on this library. I have been trying to setup the library CMakeLists.txt to copy files to the binary output directory of each target that use the library. I have tried add_custom_command and file to copy the files. I can get the files copied to any directory once. But it is still the library that decide where the files are copied to. How can I turn this around and define generic "data" files as part of the library target (or custom target) so that these files are copied along with the library binary itself to the dependent target binary directories?
lib/CMakeLists.txt
add_library(mylib ${mylib_sources})

file (COPY datafile DESTINATION $<TARGET_FILE_DIR,mylib>)

app2/CMakeLists.txt
add_executable(app1 ${app1_sources})
target_link_libraries(app2 mylib)

add_test(NAME app1_test COMMAND app1)

app2/CMakeLists.txt
add_executable(app2 ${app2_sources})
target_link_libraries(app2 mylib)

add_test(NAME app2_test COMMAND app2)

Now that I run ctest it will execute app1 and app2. Both of these are statically linked with the mylib library. But datafile is not copied to the app1/app2 binary directories. I don't want to do the copy in each appX (can be 100s) and there can be multiple libraries with data files. So I would like to add datafiles in the library CMakeLists that get copied to all binary directories that use it.


text:
Q: WPF event unsubscribe leak in DataTemplate (XAML) on NET Framework Imagine a UserControl with a ListBox having a CheckBox in a DataTemplate. The ItemsSource for the ListBox is some global list. The CheckBox has Checked/Unchecked events attached to it.
<ListBox ItemsSource="{Binding Source={x:Static a:MainWindow.Source}}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type a:Data}">
            <CheckBox Content="{Binding Path=Name}"
                      Checked="ToggleButton_OnChecked"
                      Unchecked="ToggleButton_OnUnchecked"
                      IsChecked="{Binding Path=IsEnabled}"
                      Padding="10"
                      VerticalContentAlignment="Center"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I am logging loaded/unloaded/checked/unchecked events in the main window's log.
    private void ToggleButton_OnChecked(object sender, RoutedEventArgs e)
    {
        Log("Checked");
    }

    private void ToggleButton_OnUnchecked(object sender, RoutedEventArgs e)
    {
        Log("Unchecked");
    }

    private void UserControl1_OnLoaded(object sender, RoutedEventArgs e)
    {
        Log("Loaded");
    }

    private void UserControl1_OnUnloaded(object sender, RoutedEventArgs e)
    {
        Log("Unloaded");
    }

The main window features a dynamic list of UserControl1 instances (starting with just one). There are add/remove buttons that allow me to add more instances.
<UniformGrid Rows="2">
    <DockPanel>
        <Button DockPanel.Dock="Top" Click="Add">Add</Button>
        <Button DockPanel.Dock="Top" Click="Remove">Remove</Button>
        <ListBox x:Name="ListBox">
            <local:UserControl1 />
        </ListBox>
    </DockPanel>

    <ListBox ItemsSource="{Binding ElementName=This,Path=Log}" FontFamily="Courier New"/>
</UniformGrid>

The window's codebehind:
    private void Add(object sender, RoutedEventArgs e)
    {
        ListBox.Items.Add(new UserControl1());
    }

    private void Remove(object sender, RoutedEventArgs e)
    {
        if (ListBox.Items.Count == 0) return;
        ListBox.Items.RemoveAt(0);
    }

When I run the app there is just one UserControl1 instance. If I add one more and then immediately remove one of them, then click the one and only checkbox on the screen, I see two "Checked" events logged. If I now uncheck it, there are two "Unchecked" events (even though "Unloaded" event was previously clearly logged. The hex numbers on the left show the output of a GetHashCode() which clearly shows the events were handled by distinct UserControl1 instances.

So even though one of UserControl1 gets unloaded, the events don't seem to get unsubscribed automatically. I have tried upgrading to NET Framework 4.8 to no avail. I see the same behavior. If I add 10 new controls and remove them immediately, I will observe 10 "Checked" or "Unchecked" events.
I have tried searching for a similar problem but could not find it. Is there something I am missing or did I just encounter a bug? Looking for workarounds.
Full source code is available on GitHub. https://github.com/wpfwannabe/datacontext-event-leak

A: In the MVVM pattern, the view is bind to the view model and doesn't survive it when the garbage collection do it's job.
In the example you provided, the view model is a static object and by definition can't be garbage collected, so the view can't neither be garbage collected.
There is no automatic unbinding since you can reuse an instance of an user control (it can be Loaded and UnLoaded multiple times).
The simplest¹ way to fix this memory leak is to do the unbinding on unload :
Wpf
// First give the ListBox a name
<ListBox x:Name="ListBox" ItemsSource="{Binding Source={x:Static a:MainWindow.Source}}">

Code behind
private void UserControl1_OnUnloaded(object sender, RoutedEventArgs e)
{
    Log("Unloaded");
    ListBox.ItemsSource = null;
}

1: The proper way is to wrap the static list in a dedicated list view model, make the view model disposable (to unbind the wrapper from the static list on dispose), dispose the view model on remove.


text:
Q: server side code mixed with client side code - best practices Inside a given php script, I have the following:
<script>

    function showMember() {

           return $.ajax({ //Perform an asynchronous HTTP (Ajax) request.

                type: 'get',

                //A string containing the URL to which the request is sent.
                url: '<?php echo $this->createUrl('member'); ?>',
    ...

This works, if I place this  inside the php file.
But this seems not to be a good way for organizing things, and I would wish to place all this code, on a separate .js file.
What is the proper way for dealing with those scenarios ?

A: We use two approaches to make data created at server-side accessible to the client-side:
1) 'data transfer' object, filled by server-side scripts. For example:
PHP:
<?php
  $data = [
    'urls' => [
      'createSomething' => $this->createUrl($from, $something),
      // ...
    ],
    'labels' => [
      'createSomething' => $this->cms($labelName),
      // ..
    ],
  ]
?>
<script>
  var dto = <?= json_encode($data) ?>;
</script>

JS:
$.ajax(dto.urls.createSomething, {}, function() {
  alert(dto.labels.createSomethingSuccess);
}

2) dataset attributes, again, filled by the server. For example:
PHP:
<button data-target-url="<?= $this->createUrl($from, $something) ?>"
     >Something</button>

JS:
$('button[data-target-url]').click(function() {
  var targetUrl = $(this).data('targetUrl');
  $.post(targetUrl...);
}

The second approach, to me, appears to be most useful when there's some UI-related set of attributes still calculated at server-side - for example, plugin settings.

A: It is best to split your php and javascript code. What you can generate is a base url so javascript can generate it's own urls. Generate those variables with php in your html.
Example in your html and php
<html>
<head>
  <script>
  var BASE_URL = <?=$baseUrl?>;
  </script>
  <script src="external.js"></script>
</head>
<body>
</body>
</html>

Then you can use the variable BASE_URL in your external.js
function showMember() {

       return $.ajax({ //Perform an asynchronous HTTP (Ajax) request.

            type: 'get',

            //A string containing the URL to which the request is sent.
            url: BASE_URL + "member",

This is a simple scenario that a lot of websites use. Generate global script variables in body before including external scripts.

A: You can call a javascript function and send url as function parameter.
showMember(<?php echo $this->createUrl('member'); ?>);

In js catch and use it .
function showMember(posturl) {
return $.ajax({ //Perform an asynchronous HTTP (Ajax) request.

                type: 'get',

                //A string containing the URL to which the request is sent.
                url: posturl,


text:
Q: Extracting coefficients with all information from gls output in R I need to get the coefficients along with their SEs, t-values and p-values from gls output in R.
library(nlme)
fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary,
       correlation = corAR1(form = ~ 1 | Mare))

summary(fm1)
Generalized least squares fit by REML
  Model: follicles ~ sin(2 * pi * Time) + cos(2 * pi * Time)
  Data: Ovary
   AIC      BIC    logLik
  1571.455 1590.056 -780.7273

Correlation Structure: AR(1)
 Formula: ~1 | Mare
 Parameter estimate(s):
  Phi
0.7532079

Coefficients:
                   Value Std.Error   t-value p-value
(Intercept)        12.216398 0.6646437 18.380373  0.0000
sin(2 * pi * Time) -2.774712 0.6450478 -4.301561  0.0000
cos(2 * pi * Time) -0.899605 0.6975383 -1.289685  0.1981

 Correlation:
               (Intr) s(*p*T
sin(2 * pi * Time)  0.000
cos(2 * pi * Time) -0.294  0.000

Standardized residuals:
        Min          Q1         Med          Q3         Max
-2.41180365 -0.75405234 -0.02923628  0.63156880  3.16247697

Residual standard error: 4.616172
Degrees of freedom: 308 total; 305 residual

I'd highly appreciate if someone help me to figure out this. Thanks in advance.

A: Assuming that you want the values above for some kind of table, a solution is relatively simple.
sumfm1 <- summary(fm1)

sumfm1$tTable

                       Value Std.Error   t-value      p-value
(Intercept)        12.2163982 0.6646437 18.380373 2.618737e-51
sin(2 * pi * Time) -2.7747122 0.6450478 -4.301561 2.286284e-05
cos(2 * pi * Time) -0.8996047 0.6975383 -1.289685 1.981371e-01

More generally, if you call the str() function on any R object, you can normally (with a bit of trial and error) figure out how to extract the results you need.
EDIT: if you need it to go into a sweave file, then call xtable on the object above, and all should be good.

A: try this:
> cs <- as.data.frame(summary(fm1)$tTable)
> cs
                        Value Std.Error   t-value      p-value
(Intercept)        12.2163982 0.6646437 18.380373 2.618737e-51
sin(2 * pi * Time) -2.7747122 0.6450478 -4.301561 2.286284e-05
cos(2 * pi * Time) -0.8996047 0.6975383 -1.289685 1.981371e-01
> cs$t
[1] 18.380373 -4.301561 -1.289685
> cs$p
[1] 2.618737e-51 2.286284e-05 1.981371e-01


text:
Q: Deciding which package manager was used to install a Python package I want to remove a Python package, let's say Satchmo. But I don't remember which tool I used to install it.
I can think of the following ways:

*

*Downloading source

*

*distutils

*distribute

*SetupTools

*Python package managers

*

*EasyInstall

*PyPM

*pip

*apt-get

Is there a way to determine how it was installed? I think I need this information to safely and properly remove them.

A: Each installation tool may keep a separate index of which packages it knows about/has installed. All Python cares about is that the files are in place. So basically, if you think it may have been installed with a certain tool, you'll have to ask the tool.
For apt/dpkg, you can check if the package appears in the dpkg -l listing. I do not know whether pip's index is as easily accessible, but you could simply try running pip uninstall package-name, it should complain if it didn't install the package. I don't know about PyPM, but if you installed from source or with easy_install, you'll simply have to track down and remove the files, the package isn't listed anywhere.


text:
Q: Prevent domain user making changes on desktop I have a problem with desktop icons for domain users. I have about 150 domain PC's with the same config (programs, icons, same hardware, OS - win 10, etc). The problem is that users are saving some files on the desktop and it is a bit messy after some time. How to stop it?
I was thinking about using Public Desktop folder, but if I join the computer to a domain, it is creating a new folder for that user. Using roaming profiles (mandatory, without ability to change anything) instead won't work, because they are using the same domain user. I was looking for some GPO that would prevent the user from making changes to a certain folder, but can't find anything.

A: Please have a look at the following articles:
Prevent user to save in desktop

Workaround this would be - set user for roaming profile and redirect the desktop folder in network share. Once you redirect desktop folder to network share this will create \server\share\deskto\username and remove the right permission there. That will prevent user to save item in desktop.

Solution by Madal
VBScript to prevent users from saving files to the desktop - source
Hope this helps.


text:
Q: Convergence of semi-telescopic series $\sum\limits_{k=1}^\infty\frac{1}{k(k+1)(k+2)}$
Does the following series converge? If it does, determine the appropriate limit.
$$\sum\limits_{k=1}^\infty\left(\frac{1}{2k}-\frac{1}{k+1}+\frac{1}{2(k+2)}\right)$$

The only thing i noticed so far is the occurence od the telescopic series via a transformation:
$$\frac{1}{2k}-\frac{1}{k+1}+\frac{1}{2(k+2)}=\frac{1}{k(k+1)(k+2)}$$
The ratio test delivers the result $k/(k+3)$ which renders it unhelpful, so I have to try something else. Now I have been thinking about finding an explicit expression for the partial sums
$$\sum\limits_{k=1}^N\left(\frac{1}{k(k+1)(k+2)}\right)$$
however I neither know, how do so nor do I know whether it suffices to show, that the partial sums will converge for $N\to\infty$ to conclude that the whole series will have a limit.
I need help on how to determine the the explicit expression of the partial sums and would like to know some good suggestions on what to do else.

A: You're making it harder than necessary: for each $k\in\Bbb Z^+$ you have
$$\frac1{k(k+1)(k+2)}<\frac1{k^3}\;;$$
Now just use the ordinary comparison test.
I'm assuming that you've already shown that $\sum_{k\ge 1}\frac1{k^p}$ converges for all $p>1$. If not, note that
$$\sum_{k\ge 1}\frac1{k^p}\ge\int_1^\infty\frac{dx}{x^p}\;,$$
which diverges for $p>1$.
Added: In view of the comments, I'll suggest another approach, a variation on partial fractions. In order to get something that might telescope, you want ideally two terms with denominators that are offset by $1$, so try this decomposition:
$$\frac1{k(k+1)(k+2)}=\frac{A}{k(k+1)}+\frac{B}{(k+1)(k+2)}\;;$$
clearly $B=-A$ and $A=\frac12$, so $$\frac1{k(k+1)(k+2)}=\frac12\left(\frac1{k(k+1)}-\frac1{(k+1)(k+2)}\right)\;,$$ and your partial sum is
$$\frac12\sum_{k=1}^N\left(\frac1{k(k+1)}-\frac1{(k+1)(k+2)}\right)\;.$$

A: Hint: $\dfrac{1}{k(k+1)(k+2)}=\dfrac{1}{2}\left(\dfrac{1}{k(k+1)}-\dfrac{1}{(k+1)(k+2)}\right).$ Now use the method of differences to find an explicit expression for the partial sums.

A: You can bound each term from above by $k^{-3}$.  Do you know that sum converges?  If not, you can bound that from above by the integral of $x^{-3}$

A: You may write it in the form $x_k=a_{k+2}-2a_{k+1}+a_k$ (you're almost there).  Thus, if you write out the partial sums
$$x_1+ \cdots + \cdots + x_n$$
cancelling out the corresponding intermediate terms, you will see that since $a_n \to 0$, the sum clearly converges.
You're almost there.


text:
Q: Generic Include on ObjectQuery doesn't actually include anything Today I tried to modify my existing generic GetAll method to work with eager includes.
I have Lazy loading enabled, but I want to do eager loading for some specific caching optimizations.
  public IQueryable<T> GetAll<T>(List<string> eagerIncludeList) where T : EntityObject, new()
    {
        var entitySet = String.Format("[{0}]", FetchEntitySetName<T>());
        ObjectQuery<T> q = this.db.CreateQuery<T>(entitySet);

        foreach (string x in eagerIncludeList) {
            q.Include(x);
        }
        return q;
    }

The above code doesn't work (not eager loaded at least) , calling it with e.g.
DB.GetAll<PageConfig>(new List<string>() {"Containers"})

does not load the related Containers for my PageConfigs,
BUT
When hard coding the include, it does work, so i'm sure the name "Containers" is correct
var example = db.PageConfigSet.Include("Containers").ToList();

this gives example.First().Containers.IsLoaded = true;
Any ideas on why the generic code that uses CreateQuery doesn't work, but the one that uses the hard coded ObjectSet does?

A: q.Include(x) returns a new ObjectQuery<T> that includes that table.
You aren't doing anything with the return value.


text:
Q: Print string without single quotes & brackets After installing countryinfo and import CountryInfo, I have tried to print
currency = country.currencies()
print(currency)

and the result is ['CAD']. I am interested in CAD without quotes & brackets.

A: It sounds like country.currencies() returns a list, which is why you see ['CAD']. In order to access the first (and only) element in the list, which is a string, you can use currency[0]. To print it, you can use print(currency[0]), which will give the desired output.
I would strongly suggest reading about lists, what you can put inside of them, and most importantly, how you can access elements in them.

A: You need to get element of the list by doing this:
print(currency[0])

A: According to the countryinfo documentation, the .countries() function returns an array of strings:
# coding=utf-8
from countryinfo import CountryInfo

country = CountryInfo('Singapore')
country.currencies()
# returns array of strings, currencies
# ['SGD']

You just need to print a specific entry from an array, in your case it would be:
print(currency[0]).


text:
Q: Optimize tables used more than once: make dataframe persistent or save as parquet I heard Spark SQL is lazy: whenver a result table is referred, Spark recalculates the table :(
For example,
WITH tab0 AS (
   -- some complicated SQL that generates a table
   -- with size of Giga bytes or Tera bytes
),

tab1 AS (
   -- use tab0
),

tab2 AS (
   -- use tab0
),

...

tabn AS (
   -- use tab0
),

select * from tab1
join tab2 on ...
...
join tabn on ...
...

Spark could recalculate tab0 N times.
To avoid this, it is possible to save tab0 as a temp table. I found two solutions.
1) save tab0 into parquet, then load it into a temp view
https://community.hortonworks.com/articles/21303/write-read-parquet-file-in-spark.html
How does createOrReplaceTempView work in Spark?
2) make tab0 persistent
https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html#rdd-persistence
Which one is better in terms of query speed?

A: If you have enough memory to hold the data, using dataFrame.cache() will be faster than writing to disk as Parquet and using a TempView to access it. The TempView will potentially go to disk N times.
If you don't have enough memory, I'd benchmark and see if there's a difference between persisting with the MEMORY_AND_DISK storage level and between writing to Parquet. It's hard for me to imagine that the disk format that Spark uses would be less efficient than Parquet (because why not just use Parquet in that case?), but I've learned to be careful with my assumptions when optimizing Spark code.


text:
Q: QueryBuilder and BasicDBObjectBuilder usage in MongoDB 3.3.0 above PART 1
Following up solutions to Querying Mongo Collection using QueryBuilder in Mongo 3.3.0
, I tried implementing the suggested methods to implement collection.find(). But was stuck with different parameters been passed a BasicDBObjectBuilder to the same as follows -
BasicDBObjectBuilder queryBuilder = BasicDBObjectBuilder.start();

query.getParams().entrySet().stream().forEach(entry -> queryBuilder.add(entry.getKey(), entry.getValue()));

BasicDBObjectBuilder outputQuery = BasicDBObjectBuilder.start();
outputQuery.add(nameKey, 1);

This doesn't compile :
FindIterable<TDocType> tDocTypeList = collection.find(queryBuilder.get(), outputQuery.get());

This also won't compile :
FindIterable<TDocType> tDocTypeList = collection.find((Bson)queryBuilder.get(), (Bson)outputQuery.get());

And this won't compile either :
org.bson.Document queryBuilder = new org.bson.Document();

query.getParams().entrySet().stream().forEach(entry -> queryBuilder.put(entry.getKey(), entry.getValue()));

org.bson.Document outputQuery = new org.bson.Document();
outputQuery.put(nameKey, 1);

FindIterable<TDocType> tDocTypeList = collection.find(queryBuilder, outputQuery);

Question - How do I specify a projection for the results required out of find() from collections?

PART 2
At one end I can simply replace mongo 3.0.4 java driver's code  -
DBObject dbObject = collection.findOne(new QueryBuilder().put(ids).is(id).get())

to
Bson filter = Filters.eq(ids, id);
TDocType doc = collection.find(filter).first();

Now if we have an implementation where we build query through an iteration as in the sample code -
for(Map.Entry<String, Object> entry : query.getParams().entrySet()) {
    // this is where its building the query
    if(some condition) {
        queryBuilder.put(entry.getKey()).is(entry.getValue());
    }
    if(some other condition) {
        queryBuilder.put(entry.getKey()).in(query.getValues());
    }
}

Question - Is there a way to implement such appending query Filters
  with current mongo 3.3.0+ as well?

A: The second argument of find method is result type. Try as below.
FindIterable<TDocType> tDocTypeList = dbCollection.find(filter, TDocType.class);

Update for projection
FindIterable<TDocType> tDocTypeList = dbCollection.find(filter, TDocType.class).projection(outputQuery);

Update for appending filters
List<Bson> filters = new ArrayList<>();
for (Map.Entry<String, Object> entry : query.getParams().entrySet()) {
        // this is where its building the query
   if (some condition){
       filters.add(Filters.eq(entry.getKey(), entry.getValue()));
   }
   if (some other condition){
       filters.add(Filters.in(entry.getKey(), query.getValues()));
   }
}
FindIterable<TDocType> docType = dbCollection.find(Filters.and(filters));


text:
Q: How do I increase the font size in Ubuntu 18.04 LTS for a HDPI / 4K display? I have a Dell XPS 15-9560 laptop with 15.6" 4K Ultra HD (3840 x 2160) IGZO IPS 350-nits Touch-screen, and NVIDIA GeForce GTX1050 4GB GDDR5.
It's having 4K resolution. Right from the grub screen to Ubuntu, it's having very very small fonts. Is there any way i can increase the fonts size?
This is a real nice laptop - real MacBook Pro killer..getting very popular...and i can see a lot of folks will be having the same issue.
Edit 1
I messed up my current installation of ubuntu desktop 18.04 LTS and have to reinstall it all over again.
Just tried this one now:
Adding nouveau.modeset=0 to the boot parameters was much better workaround for smaller fonts and i am having much better resolution now.
It's much better solution than others as of now.
Seems to ubuntu18.04 LTS is not as stable and much more complex issues with Nvidia graphics card than the previous versions.

A: You may use (UNITY) Tweaks to adjust font size along with other UI elements. Install it using:
sudo apt install unity-tweak-tool

The settings I'm using for scaling on a 1920x1080 monitor are 1.38 times. You would probably want 2.00 or higher:

The Text scaling factor scales both fonts and UI elements like title bars, menus, etc.

Here's a GIF showing changing scaling from 1.38 to 1.00 and then to 2.00:

In the .gif above scaling starts at 1.38 on a 1920x1080 monitor. Then it is changed to 1 and everything gets tiny, which is normal. Then it is changed to 2 which is ideal for the visually challenged. Once again the icons have fixed pixel size and the font shrinking or expanding under the icon gives the illusion their size is changing.

There are others tweak tools that may be of interest in 18.04 LTS:
$ apt list | grep tweak
gajim-rostertweaks/bionic,bionic 1.0.0-3 all
gnome-tweak-tool/bionic,bionic 3.28.1-1 all
gnome-tweaks/bionic,bionic 3.28.1-1 all
mate-tweak/bionic,bionic 18.04.16-1 all
mousetweaks/bionic,bionic,now 3.12.0-4 amd64 [installed]
tweak/bionic 3.02-2 amd64
unity-tweak-tool/bionic,bionic,now 0.0.7ubuntu4 all [installed]

A: This helped me when I upgraded from 16.04 lts to 18.04 lts:

*

*open system settings

*select universal access

*turn on large text

A: You don't need to install third-party tools if you using Unity.
Just go: Unity control center -> Displays -> Scale for menu and title bars
Now you can scale everything to a readable size:

A: You may use (GNOME) Tweaks to adjust font sizes of various elements. First install Tweaks by running
sudo apt install gnome-tweaks

(or sudo apt install gnome-tweak-tool).
Then launch Tweaks and go to the Fonts section, you'll get the options to change font sizes.

A: Some people suggest to just scale everything up going to Settings > Displays:

run_scaled
As you may notice scaling up may work for decorations and almost all apps. But some apps will still look tiny. For example, MySQL Workbench have this bug since 2009.
To scale per-application windows on Xorg for HiDPIs (as Arch Wiki state) you can use run_scaled.
Install it:
sudo apt install xpra  # tool to detach/reattach running X programs
curl "https://raw.githubusercontent.com/kaueraal/run_scaled/master/run_scaled" > ~/.local/bin/
chmod +x ~/.local/bin/run_scaled

Then
run_scaled someapp

By default will scale by a factor of 2 but you can use --scale option.

A: Not sure if this will help, but in XUbuntu:

*

*Lower Left corner button (where the big K is)

*Applications > Settings > System Settings > Font


text:
Q: F# - type must be defined above where it is used I have an F# file with the types MyUIImagePickerControllerDelegate and NewListing defined:
[<Register ("MyUIImagePickerControllerDelegate")>]
type MyUIImagePickerControllerDelegate() as x =
   inherit UIImagePickerControllerDelegate ()

let mutable parentView : UIViewController = null

member this.GetSelectedImage
    with get() = selectedImage
    and set(value) = selectedImage <- value

member this.GetParentView
    with get() = parentView
    and set(value) = (
        parentView <- value
    )

override x.FinishedPickingImage(controller : UIImagePickerController, image : UIImage, dict : NSDictionary) =
    let chosenImage = image
    (parentView :?> NewListing).GetIm1.Image <- chosenImage
    parentView.DismissModalViewController(true)

[<Register ("NewListing")>]
type NewListing (handle:IntPtr) as this =
    inherit UIViewController (handle)

    override x.ViewDidLoad () =
        base.ViewDidLoad ()

        let del = new MyUIImagePickerControllerDelegate()
        del.GetParentView <- x

The problem is these two lines:
(parentView :?> NewListing).GetIm1.Image <- chosenImage

and:
let del = new MyUIImagePickerControllerDelegate()

as you can see I am using the NewListing inside the MyUIImagePickerControllerDelegate and the MyUIImagePickerControllerDelegate inside NewListing. Due to F# requiring all types used later on in the file to be defined above the place where they are used, this code will never work...how can I get around this issue?

A: recursive types:
type Foo = ...

and Bar = ...

so
[<Register ("MyUIImagePickerControllerDelegate")>]
type MyUIImagePickerControllerDelegate() as x = ...

and [<Register ("NewListing")>]
    NewListing (handle:IntPtr) as this = ...


text:
Q: static_assert doesn't fire on MSVC The below example code fires the "testing" assert with gcc and clang, but not MSVC. Only when the line marked comment this out is commented out does it fire. With GCC and clang it fires both with and without that line. Is that expected?
#include <type_traits>

template <bool B>
constexpr void issue_error()
{
    static_assert(B, "testing");
};

int main()
{
    issue_error<false>();
    static_assert(std::is_same_v<int,char>,"!!"); // comment this out
}


text:
Q: AppDomain.CurrentDomain.BaseDirectory returns unit test project root location instead of source project In my application project i have used AppDomain.CurrentDomain.BaseDirectory to get the file path. When i include the unit test in my project, the AppDomain.CurrentDomain.BaseDirectory returns unit test project directory instead of my source project while debugg. Can you please let me know how to resolve this issue?
Thanks.

A: That's the expected behaviour.
You could consider copying the required files to the unit test directory.
In Visual Studio 2010, look at "Deployment" under "Test Settings".

A: Default setting point to bin\debug folder in Visual studio 2010 test projects. But if you enable deployment option of Edit test settings, AppDomain.CurrentDomain.BaseDirectory points to the TestResults\Out folder. I have added unit test project first, later with additional projects.
Joe, can you provide link from MSDN to support your expected behaviour answer?
I would suggest to read this answer for referring to the location where your assembly resides.
https://stackoverflow.com/a/8670008/2611808


text:
Q: Would a project with Angular-Java-MySQL be called a 4-tier application-architecture? Or if it were 3 tier, would Angular be considered as a client layer or
presentation layer?
I'd like to understand more of these off-base (That's what I believe until I get enlightened) terminology of 'n-tier'.
Any info would be of great help.

A: *

*Angular -> Presentation Tier

*Java    -> Middle Tier

*MySQL   -> Data Tier

Yor application is based on a n-tier architecture. You can find a good explanation in here


text:
Q: How to run a Shiny docker container on Alpine Linux? I have Alpine Linux 2.6 64-bit installed with the latest version of docker. I pulled the rocker/shiny container to test Shiny. All is well but when I try to run the temporary container via:
docker run --rm -p 3838:3838 rocker/shiny

I get nothing. I verified the container exists via docker images. What am I missing?

A: Your container might be running in the background, you can use
docker ps

If you start the container with
--name shiny, you can give the running container a name. If you'd want to "log in" to the container you could start a shell inside of it by running something like:
docker exec -ti shiny /bin/sh

If you want to log into a running container which is not named explicitly you can also check out the name of your container by checking the output of
docker ps


text:
Q: Does Visual Studio Emulator for Android allow creating directories Tried to create directory as following:
File dir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
dir.mkdirs()

dir.mkdirs() always returns false for Visual Studio Emulator for Android.  The app with the above code works fine with Android devices.
I also tried several other directories (e.g. a directory under the existing directory Download), and all have the same result.
Does Visual Studio Emulator for Android allow creating any directory at all?

A: Yes. I was able to get it to work by having these permissions setup in the manifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

I also hit the ">>" icon in the emulator and setup the SD card to point to a folder on my dev machine.


text:
Q: Are the winter map files still accessible? Maybe some of you guys remember the winter map from league of legends that was released in 2012 or 2011 (and earlier, but that was an older model). Now I remember searching for special files when it was somehow easier to view the content of the game (around 2011) and I also found some Icons of Items that already didn't exist anymore at this point like zhonyas ring or the blue pill.
Now since there are (or were) files of things that don't exist anymore, I thought about whether the new or old winter/halloween maps are still in the game files or not. And if they are, how could you activate them as the default map?

A: This map has not been updated in some time. So even if the files did still exist in the downloaded content on your machine, and you were able to activate it somehow, most likely it would cause errors during play.
Many walls, brushes, etc are different between the last released winter map and the current season map. I'm not sure exactly how league servers would deal with this, but most likely you'd be clipping inside walls as your computer would fight against the server to determine what is correct. At best you will have issues navigating the map and determining bushes, etc; at worst you won't be able to play at all until you revert the change.
That being said, I'm not familiar with a method to change the default map, and Riot (at the present time) does not support such modification of your client. AND the map would only be available for you if you were able to get it to work, not your teammates or opponents.


text:
Q: Bitbucket Server : Merge check - Minimum successful builds not enabling merge even after the condition is satisfied I have configured Bitbucket Server to work with Jenkins by enabling a Webhook in Bitbucket with the Jenkins URL and the event being - Pull request approved. So I want a build on Jenkins to be triggered when a pull request is approved by the named reviewer.
The Jenkins job is configured to be triggered remotely using a token and that token is specified in the Bitbucket Webhook along with the Jenkins URL. This is working as expected. The Jenkins job is triggered automatically as soon as the pull request is approved by the reviewer.
But, I have also configured a merge check for the project . The merge check is enabled for minimum successful builds and the number of builds to be successful is configured to be 1. So, I expect the merge button to be enabled as the reviewer has approved the pull request and the Jenkins build has run (also success). But unfortunately, the merge button is not enabled even after all this. I also triggered a build manually on the same commit ( was success too ) but with no success on the merge button being enabled. Please help me out. Thanks.

A: I had the same problem and here are the steps of how I fixed it.

*

*Use Bitbucket and not Git as the source code management. But, Bitbucket seems to be only avaiable when creating a Multibranch Pipeline.

*Now, that you use Bitbucket, install plugin Bitbucket Branch Source Plugin

*Bitbucket appears to get the result of the build from Bitbucket Branch Source plugin
The plugin requires some configuration, this webpage helped me a lot.

A: We had the same problem, if in your case you have at least one failed build before the succesfull one, then you will not be able to merge until you push a new code to the PR branch. This answer comes after discussing it with Bitbucket's support team.


text:
Q: Help building patched android framework I am new to Android platform development. I have just succeded building Cyanogenmod 7 sources after applying a patch, which adds extra jars to the system (fit into /system/framework directory).
After flashing the device and checking that the new custom jars are there, and decompiling (extracting classes.dex and running dex2jar) just to verify that the needed classes are there, I see my test program crashing due to ClassNotFound exceptions.
Since the compiled custom java sources seem ok, have I missed something in the building process so my applications can use these new framework classes?
UPDATE:
I realized that framework jars are included inside an environment variable called BOOTCLASSPATH, which is defined in init.rc. I modified it to include the new jars from SEEK project (smartcardapi.jar and org.simalliance.openmobileapi.jar). I rebuilt the image and flashed my phone.
The device now does not start. I have read something here about class optimizations that are run against BOOTCLASSPATH classes. The advice is not to mess with BOOTCLASSPATH.
But what can I do so my applications can use the extended API classes defined in the new jars?


text:
Q: How to handle read notifications in mobile app backend I'm wrapping up the development of a mobile app (ionic, but irrelevant), backed by a backend developed in Ruby on Rails 5, irrelevant again since this is more of a theoretical question/issue.
The thing here is, given the fact that users in the mobile application can log in or not (they've got a bunch of functionalities, and maybe half of those can be accessed by not logged in users), how should I handle the storage of the notification itself and the read state? Note: with notification I'm not referring to a push notification, but to the "message" that stays in a side menu inside the app (I've got push delivery covered).
The main issue here is: I want to be able to track the read notifications to prevent them from being marked as unread in case the user reinstalls the app (imagine 50 unread notifications just because you reinstalled).
I began with a model as follows for storing the notifications in the backend:

*

*id

*user_id

*push_notification_id (reference to the push notification id, irrelevant)

*read: Boolean

*content: Text

With this model, I'd insert a row for every user that needs to be notified, and track with a boolean column whether it was read or not. The issue is, only registered users could have notifications.
A second option is the removal of the user_id reference and the "read" attribute server-side, and assume I'm always gonna notify everyone, not some users. But now, I need a way to track which notifications were read. I could do that locally in the mobile app storing some ids in the local storage, but then again those would be deleted in case of reinstall.
A third option I've thought of, is to implement the second option with an "expiry" column server-side, which indicates when a notification should stop being "unread" by default in case of a new app install. This is the best I've got so far, but I'm not really convinced.
I know I'm asking for a lot of things here, but I am just looking for a good implementation model someone has made before, since I've been unable to find anything googling, and I'm sure this is a heavily repeated design pattern.
Thank you!

A: We used similar approach like you with some changes:

*

*for the problem with registered/unregistered user, you can change the user_id for some device uid so the user does not need to be logged in to track the read

*instead of cumulating the info about read in one table, we had a table of unread notifications and in moment of chnage, we moved the read ones to new table -> the table will not get huge and the operations on it (like counting) will remain fast (depends on users count, but think for future!)

*plus some features likes storing date_insert and running a monthly job to clear entries older than a year

A: Before you send a notification to user, generate a hash, place it into your Notification table and in the notification body. On mobile side, when user opens the push notification - you need to send a request to the server with that hash and notification-type (if you want). Server gets the hash and finds out which user and notes that the notification was read, and you can set your flag (isRead) to true,

A: You might find this example from the folks at unow.com useful.
https://github.com/universitynow/message_center/tree/ce3ed6e17b4e650eae53e031ea764012ce6cbf4b/lib/concerns/models
The "item" model should give you some ideas for how to hand read status for one more more recipients.


text:
Q: Permission Denied Creating Subscription on group root drive - Permissions set per docs I'm trying to do the following:
            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create(APP_ID)
                .WithTenantId(AzureConfiguration.TenantId)
                .WithClientSecret(APP_SECRET)
                .Build();

            var authProvider = new ClientCredentialProvider(confidentialClientApplication);
            var client = new GraphServiceClient(GRAPH_URL, authProvider);

            subscription = await client.Subscriptions.Request().AddAsync(new Subscription
                    {
                        ChangeType = "updated",
                        NotificationUrl = notificationUrl,
                        Resource = $"/groups/{CONTENT_GROUP_ID}/drive/root",
                        ExpirationDateTime = DateTimeOffset.UtcNow.AddMinutes(SubscriptionLength),
                        ClientState = Guid.NewGuid().ToString()
                    });

Content group is a valid group.  The application has Files.ReadWrite.All and Group.ReadWrite.All at the application level, and the Grant Admin for button has been clicked.
This used to work with HTTPClient and REST with login like this:
var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{AzureConfiguration.TenantId}");

        var creds = new ClientCredential(APP_ID, APP_SECRET);

        var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

and then calling it like this: with a helper function that just posts the json:
var result = await Post<Subscription, Subscription>(client, $"{GRAPH_URL}/subscriptions", new Subscription
                {
                    ChangeType = "updated",
                    NotificationUrl = $"{apiUrl}/v1/SharepointNotifications/Notify",
                    Resource = $"/groups/{CONTENT_GROUP_ID}/drive/root",
                    ExpirationDateTime = DateTimeOffset.UtcNow.AddMinutes(SubscriptionLength),
                    ClientState = Guid.NewGuid().ToString()
                });

(This code used to work but failed at this refresh of the subscription.)
I'm at a loss as to what's different and causing it not to work.  How do I get this going?


text:
Q: Path counts in a graph via enumerating independent sets of a graphic matroid If I have a simple graph $G$, and what to count the number of simple paths between two distinct vertices, can the paths be seen as independent sets of a matroid?
Perhaps yes, because the edge space of the graph and the cycles form a matroid (the cycle matroid), but the union of two paths (overlapping or otherwise) forms a series of loops, at least 1. Also, there is the notion of the paths spanning the union of paths, if we think of this as a vector space over $\text{GF}(2)$ (so paths as elements of a basis are either scaled by 0 or 1, i.e. exist of don't exist, and addition means the two paths become the respective union, and multiplication is set up properly i.e. considering the edges as part of vector space).
I do not think this matroid is the path matroid or gammoid. But, crucially, though you may be able to construct a matroid like this, is there a theory of enumerating the independent sets, for example, when the graph is random, in order to get some probabilities for path counts in e.g. continuum percolation?

A: The set of all "partial simple paths" between two vertices is a simplicial complex. More precisely, if $v,w$ are vertices of the graph $G$ then the set of all simple paths between $v$ and $w$ is a subgraph $G(v,w)$ that can be directed so that $v$ is the unique source and $w$ the unique sink. This directed graph is acyclic so it is the Hasse diagram of a partially-ordered set $P = P(G;v,w)$. Now take the chain complex $\Delta = \Delta(G;v,w)$ of this poset.
The independent sets of a matroid form a pure simplicial complex, that is, a simplicial complex all of whose facets have the same cardiniality.
Since $P$ is a bounded poset, $\Delta$ is pure if and only if $P=P(G;v,w)$ is graded if and only if every simple path in $G$ from $v$ to $w$ has the same length. It is easy to construct graphs and select vertices such that $\Delta$ is not pure and hence not a matroid. For example let $G$ be any odd cycle and $v,w$ be arbitrary distinct vertices.
For an example of a triple $D = (G,v,w)$ such that $\Delta(D)$ is pure but still not a matroid take $G = T_{m,n}$ to be the tadpole graph with $m$ even and $m \ge 4$ and take $v,w$ to be the two vertices at distance $m/2+n$. Then $\Delta(D)$ is pure because its two facets both have size $m/2+n$ but it is not a matroid because these facets don't satisfy the matroid basis exchange axiom.
EDIT: The "partial simple paths" in the graph $G(v,w)$ are the chains in the poset $P = P(G;v,w)$. The chain complex of $P$ is also known as the order complex which is a main topic of Wachs' wonderful lecture notes. See page six of those notes for the definition for a full accounting. In short, a "partial simple path" turns out to be a collection of edges in $G(v,w)$ that can be completed to a (directed) path from $v$ to $w$.


text:
Q: Vertical alignment of text on multiple lines I use
\begin{itemize}
  \item \makebox[2.5cm][l]{some text} some very long text. some very long text. some very long text. some very long text.
\end{itemize}

to produce

The problem is that I want the second line of the item to be aligned with the second part of the item. So "some text" acts somehow like the item bullet. So I kind of want \makebox{} to also work in 'the vertical direction', such that no text is placed below this.

A: There are serveral solutions for such a thing, here are two. First using labeling environment of scrextend or any KOMA-Script class, second using a environment derived from description using enumitem:
\documentclass{article}
\renewcommand{\familydefault}{\sfdefault}% you are using a sans serif font

% use package scrextend to have the labeling environment of KOMA-Script
\usepackage{scrextend}
\setkomafont{labelinglabel}{$\triangleright$\enskip}% ugly hack to have a
                                % triangle before the item

% use package enumitem to have an extended description environment
\usepackage{enumitem}
\newcommand*{\descriptionlabelwith}[2]{\hspace\labelsep
  \normalfont#1\enskip #2}
\newlist{itemdesc}{description}{1}% currently only one level is definded
\setlist*[itemdesc,1]{font=\normalfont,format=\descriptionlabelwith{$\triangleright$},leftmargin=27mm,labelwidth=*}

\begin{document}
\begin{labeling}{\hspace{2.5cm}}
\item[some text] some very long text. some very long text. some very long text. some very long text.
\end{labeling}

\begin{itemdesc}
\item[some text] some very long text. some very long text. some very long text. some very long text.
\end{itemdesc}

\end{document}


text:
Q: Visual Studio 2010 C# Grid Format I want to create a sudoku game in visual studio 2010 c# windows form application. How to create a grid to look like this one?
http://m.imgur.com/Xz2GgzP

A: Here's a simple way to create a 10x10 grid. Create a pictureBox control with 501,501 in size. Name it Grid. On the Paint event of the control, add the following code.
private void Grid_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    int i = 0;
    int j = 0;
    for (i = 0; i <= 10; i++) {
        for (j = 0; j <= 10; j++) {
            e.Graphics.DrawLine(Pens.Black, i * 50, 0, i * 50, 500);
            e.Graphics.DrawLine(Pens.Black, 0, j * 50, 500, j * 50);
        }
    }
}

I hope this could start up your project.


text:
Q: How to pass value to date parameter in apex method from LWC JS? Please provide a proper way to call this method from LWC passing date parameter.
public with sharing class ApexClass {
    @AuraEnabled(cacheable = true)
    public Date string apexMethod(Date z) {
        return z;
    }
}

We got date type in aura component for this situation. Any such way in LWC?

A: Hi i have used following code -
APEX Class -
  @AuraEnabled(cacheable=true)
    public static Date getDate(Date dt)
    {
        System.Debug('dt '+dt);
        return dt;

    }

and JS Code -
@wire(getDate,{dt:"2019-12-31"})
   date({data})
  { if(data){
      console.log("Data"+JSON.stringify(data));
  }
}

or
 @wire(getDate,{dt:new Date("2019-12-31")})
    date({data})
   { if(data){
       console.log("Data"+JSON.stringify(data));
   }

    }

And for My understanding, the date parameter accepts in YYYY-MM-DD format.

A: The first thing is your apex method return value is wrong. Your method expect a string value to return but you are returning a date value.
The correct code is:-
@AuraEnabled(cacheable = true)
public static string apexMethod(Date z) {
    return String.valueOf(z);
}

Now, to call it from LWC, You can pass a date object value as parameter from JavaScript code:-
import { LightningElement } from 'lwc';
import apexMethod from '@salesforce/apex/ContactController.apexMethod';

export default class CurrencyInputField extends LightningElement {
     handleChange() {
        var d = new Date();
        apexMethod({ z: d })
            .then(result => {
                JSON.stringify('result ' + result);
            })
            .catch(error => {
                JSON.stringify('error ' + error);
            });
    }
}

Learn more about how to create a date instance in JavaScript here:-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
and calling an apex method in LWC here:-
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.apex


text:
Q: Can I run heroku run rake db:migrate after using taps and heroku db:push? I accidentally deleted my production database on heroku cedar stack several months ago.  I tried to recreate the db via heroku run rake db:migrate, but something was wrong with my migrations and it failed.  I then installed taps and did a heroku db:push and all was right with the world.
Can I now use heroku run rake db:migrate after running local migrations to update the production database, or am I forever tied to taps and heroku db:push?
Perhaps a better way to ask this question:  will heroku run rake db:migrate go through all of my migrations (and likely fail), or will it only go through migrations that have occurred since the last heroku db:push?

A: Take a look at the schema_migrations table in your database. This is what Rails uses to determine which migrations to run. It has a single column containing each migration version Rails has applied to your application. For example, I have the following file in db/migrate:

*

*20110415064108_create_users.rb
20110415064108 is listed as a row in my schema_migrations table. The same goes for every other migration file in db/migrate that existed since I last ran rake db:migrate.
Assuming taps (which I know nothing about) pushed this schema_migraions table in its entirety to production, you should be able to create new migrations and run them with rake db:migrate in production without trouble (only those newly created migrations will be applied, since their version #s are the only ones missing from the production schema_migrations table).


text:
Q: fread isnt reading an updated value despite the file has been changed by another program There are two programs that are working with my special file at the same time. They have a common beginning:
    #define TASK_POSITION 0x0100

    #include <stdio.h>
    #include <stdlib.h>
    #include <inttypes.h>

    int main() {

        FILE * control_file;
        unsigned int task_code;
        fpos_t task_position;

        control_file = fopen("/home/anonymous/.control", "r+");
        fseek(control_file, TASK_POSITION, SEEK_SET);
        fgetpos(control_file, &task_position);

But later they have a very different code

*

*1st program could change a value at TASK_POSITION offset of this file:
    /* ... lots of code there ... */

    task_code = 0xFEEDFACE;

    fsetpos(control_file, &task_position);
    fwrite(&task_code, 4, 1, control_file);
      fflush(control_file);
        sleep(1);

    fclose(control_file);
    return 0;
}

*2nd program is repeatedly freading a value at the same offset of this file:
    for (;;) {
        fsetpos(control_file, &task_position);
        fread(&task_code, 4, 1, control_file);
        if (task_code == 0xFEEDFACE) {
            /* ... Do something awesome! ... */
        }
        else { // remove after debugging
          fprintf(stdout, "not hungry yet :P 0x%08x value has been read... \n");
          fflush(stdout);
        }
        sleep(60);
    }

    // just in case
    fclose(control_file);
    return 0;
}

By default, there is 0x12345678 value stored at TASK_POSITION offset.
Here is a problem:
after the 1st program has been launched and completed its' work, I could see in a hex editor that a special file has been changed successfully. However: for some unknown to me reason, fread of 2nd program keeps reading the same old value - 0x12345678 !
Although I found a temporary workaround by fclosing/fopening this file during the each iteration of 2nd program's infinite cycle (between the fread checks) it does not look like the best possible solution! Please tell: how to force fread to actually re-read a new value from a file, instead of just returning a previously read value (from its' cache??) ?

A: C's standard I/O functions are typically buffered.  To disable buffering, you can do:
setvbuf(control_file, NULL, _IONBUF, 0);

immediately after you open the file, before you perform any I/O on it.


text:
Q: Writing function as infinite Fourier sum with sine kernel
Let $f\in L^2(\mathbb{R})$ be such that $\hat{f}$ is supported on $[-\pi,\pi]$. Also, $f$ is continuous and goes to $0$ at $\pm \infty$. Let $K(y)=\dfrac{1}{\pi y}\sin(\pi y)$. Show that $f(x)=\sum_{n=-\infty}^\infty f(n)K(x-n)$ for every $x$.

This looks like a Fourier sum of some sort, but it's rather strange that the index $n$ goes from $-\infty$ to $\infty$. How do we approach it?

A: Disclaimer: I do all the computation below without any care for the factors $2\pi$. No one shall ever do that, it's bad. But the ideas are there and I don't have a lot of time.
We set $BL^2 := \{f \in L^2 (\mathbb R) \mid \hat f = 0 \text{ almost everywhere on }\mathbb R \setminus [-\pi,\pi]\}$
First observe that $f\in BL^2 \Rightarrow f\in L^2(\mathbb R) \Rightarrow \hat f \in L^2(\mathbb R)$
{$\hat f(\mathbb R)$ has bounded support and $\hat f \in L^2(\mathbb R)$} $\Rightarrow \hat f \in L^1(\mathbb R)$
For $ f\in BL^2$, taking the inverse Fourier transform $\mathcal F^{-1}:L^2(\mathbb R)\to L^2(\mathbb R)$ of $\hat f$ then gives a continuous function, hence $f$ has a unique continuous version, which we still denote by $f$.
(In fact this version is even an holomorphic function.)
It thus makes sense to consider $f(n)$. (This was not obvious as $f$ was a priori only considered to be an element of $L^2(\mathbb R)$.)
Now we write $\hat f |_{[-\pi,\pi]}\in L^2([-\pi,\pi])$ as a Fourier series:
$$\hat f (\xi)=\sum_{n\in\mathbb Z} c_n(\hat f) e^{in\xi}$$
with
$$c_n(\hat f) = \frac{1}{2\pi}\int_{[-\pi,\pi]}\hat f (\xi) e^{-in\xi}d\xi= \frac{1}{2\pi}\int_{\mathbb R}\hat f (\xi) e^{-in\xi}d\xi=\mathcal F^{-1} \hat f (n) = f(n)$$
with $(c_n(\hat f))_{n\in \mathbb Z}=(f(n))_{n\in \mathbb Z} \in \ell^2(\mathbb Z)$.
We thus get the formula
$$\hat f (\xi)=\sum_{n\in\mathbb Z} f(n) e^{in\xi}$$
as an equality in $L^2([-\pi,\pi])$, but then
$$\hat f (\xi)=\sum_{n\in\mathbb Z} f(n) e^{in\xi}1_{[-\pi,\pi]}(\xi)$$
where the series converges in $L^2(\mathbb R)$. We can thus take the inverse Fourier transform of both sides and obtain the equality
$$f (x)=\sum_{n\in\mathbb Z} f(n) \mathcal F^{-1}\big(e^{in\xi}\big|_{[-\pi,\pi]}\big)(x)=\sum_{n\in\mathbb Z} f(n) K(x-n)\qquad (*)$$
in $L^2(\mathbb R)$.
Now as a last remark we observe that for $u\in BL^2$, $\|u\|_\infty\leq \frac{1}{\sqrt{2\pi}}\|u\|_2$ as
\begin{align}
|u(x)|&=|\frac{1}{2\pi}\int_{\mathbb R}\hat u (\xi)e^{-i\pi x\xi}d\xi|\\
& = |\frac{1}{2\pi}\int_{[-\pi,\pi]}\hat u (\xi)e^{-i\pi x\xi}d\xi|\\
(Cauchy-Schwarz)\qquad & \leq \frac{1}{\sqrt{2\pi}} (\int_{[-\pi,\pi]} |\hat u (\xi)|^2d\xi)^{1/2}\\
& = \frac{1}{\sqrt{2\pi}}(\int_{\mathbb R} |\hat u (\xi)|^2d\xi)^{1/2}\\
(Plancherel)\qquad& = \frac{1}{\sqrt{2\pi}}\|u\|_2 \,.
\end{align}
Thus in $BL^2$ the convergence in $L^2$ implies the convergence in $\|\|_\infty$ and the formula $(*)$ is not only valid almost everywhere but for all $x$ in $\mathbb R$.
For more details see Willem, Analyse harmonique réelle, 1995. Section 6.3.

A: Theoram 2.6 in
http://math.uchicago.edu/~may/REU2012/REUPapers/Cuddy.pdf
gives proof.
index going from −∞ to +∞ is equalent to convolution


text:
Q: Is there a way to configure openapi-generator to use jakarta package during generation I've recently upgraded my project to use spring-boot 3.0.0. So I don't have javax.* modules in the project anymore. But the open-API generator keeps trying to import javax modules. Especially, it uses javax.annotation.Generated and @Generated annotation which is not present in the project anymore. Is there a way to reconfigure it somehow?

A: Yes, you can use useSpringBoot3: "true" in your configoptions of the generator.
Example in gradle:
        configOptions = [
            useSpringBoot3: "true"
        ]

A: I used the following as well, in my config.json file:
    configOptions = [
        useSpringBoot3: "true"
    ]

I heard other places that it should be default on newer versions of openapi generator - but in my case it was not and I had to force it this way which worked.


text:
Q: Socket.io - unable to access 'this' object I'm writing a game in NodeJS with Socket.io. I have a Player class with a method move(), which gets called when the player.move event is triggered. This then tries to access the current object properties.
This should work fine, however when move() is called it creates an error since the variable this.location cannot be accessed. Is there a way to access this variable in any way? Thank you.
This is my code:
main.js
var io = require('socket.io')(8080);
var Player = require('./Player');

// All players
var players = {};

io.on('connection', function(socket) {

    // Add a new player
    players[socket.id] = new Player(socket);

    // Remove user from the game
    socket.on('disconnect', function() {
        players[socket.id].__unbind();
    });
});

Player.js
/**
 * Player class
 * @param socket
 * @constructor
 */
function Player(socket) {
    this.socket = socket;
    this.location = {x : 0, y : 0};
    this.__bind();
}

/**
 * Move a player
 * @param {int} x
 * @param {int} y
 */
Player.prototype.move = function(x, y) {
    this.location.x = x;
    this.location.y = y;
};

/**
 * Add event listeners
 * @private
 */
Player.prototype.__bind = function() {
    this.socket.on('player.move', this.move);
};

/**
 * Remove event listeners
 * @private
 */
Player.prototype.__unbind = function() {
    this.socket.removeListener('player.move', this.move);
};

// Exports
module.exports = Player;

Generated error:
TypeError: Cannot set property 'x' of undefined
    at Socket.Player.move ...(stack trace here)

A: You have to bind the function calls to the Player object in order to not loose the context when it's called:
this.socket.on('player.move', this.move.bind(this)); //Add binding here.

You will have to bind all method calls you want to perform outside the Player context.


text:
Q: Load custom UIView from xib programmatically I have created a custom UIView in MySample.xib. I have added the class MyView to the File Owner of xib.
MyView.swift
class MyView: UIView {

    @IBOutlet var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    func setup() {
        NSBundle.mainBundle().loadNibNamed("MySample", owner: self, options: nil)
        self.addSubview(self.view)
    }
}

I am now loading this MyView from MyController file like this:
MyController.swift
class MyController: UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)

        view.addSubview(MyView())

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Now to display this view, I am using to following code from another controller's UIButton:
presentViewController(MyController(), animated: true, completion: nil)

This does display the view on screen. But the problem is, it doesn't accept any user interaction. In my custom view, I have a UITableView which does display the data but it doesn't scroll or get tapped due to lack of user interaction.
Any idea what I am doing wrong?

A: There are some unnecessary things in your example.
I am still not sure what are you trying to do, but if you want to add a custom view from xib to your view controller then:

*

*Create a view in a xib file , you don't need to override init , and you can't init view from xib using the default init UIView() , so please remove init method from your MyView class.

*In your xib make sure that your view that you see in the IB is of the class type you want to use (i guess MyView class).

*In your view controller init the view like this:
class MyController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Get all views in the xib
        let allViewsInXibArray = NSBundle.mainBundle().loadNibNamed("MySample", owner: self, options: nil)

        //If you only have one view in the xib and you set it's class to MyView class
        let myView = allViewsInXibArray.first as! MyView

        //Set wanted position and size (frame)
        myView.frame = self.view.bounds

        //Add the view
        self.view.addSubview(myView)

        //TODO: set wanted constraints.
    }
}

A: You don't have to re-instantiate this twice
already if you using the design pattern.
It's so simple. Just write:
class MyController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    //Get all views in the xib
    let view = MyView()
    self.view.addSubview(myView)

    //TODO: set wanted constraints.
}}

And It will work.

A: Instead of linking xib File's Owner class to MyView, I have to change the class of root view in xib to MyView. Then based on @Oleg Sherman code, it works perfectly with small changes of adding MyView() as owner to get all it's events, otherwise it will throw an error this class is not key value coding-compliant for the key ****.:
let allViewsInXibArray = NSBundle.mainBundle().loadNibNamed("MySample", owner: MyView(), options: nil)

Using File's Owner class to MyView is only required when you have to use the xib in Storyboard.
Not sure if there is a workaround to use File's Owner class to MyView when programmatically loading xib from custom controller like in my original question.


text:
Q: Android Studio: Where do I have to put assets and res? Where do I have to put the folders assets and res to? In assets/gfx, there are some .png images, and in res/layout and /values, there are some .xml files.

A: The assets and res folders should be in the same level as your java folder:


text:
Q: Comparing two different folders with Regex in C# I want to compare if one file is in two different folders.
var reg = new Regex(@"TC__\d{3,4}_8exp$");
var reg1 = new Regex(@"TC_\d{3,4}$");

var FileNames_List_Jetzt_Dateien = Directory.GetFiles(@"PATH2", "*.html")
           .Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path)))
           .Select(Folder_Jetzt_Dateien =>
               Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien));

From this one I am getting list :
TC__6493_8exp
TC__6494_8exp
TC__6495_8exp...

From this one:
var TEST_FÄLLE = Directory.GetFiles(@"PATH2", "*.exp")
          .Where(path => reg1.IsMatch(Path.GetFileNameWithoutExtension(path)))
          .Select(Folder_Jetzt_Dateien =>
              Path.GetFileNameWithoutExtension(Folder_Jetzt_Dateien));

I am getting list:
TC_6493
TC_6494
TC_6495...

For me the TC__6493_8exp is the same with TC_6493. How to use Intersect for these two lists with the same elements?

A: You can write custom comparer and pass it to Intersect method
using System.Collections.Generic;

class FileComparer : IEqualityComparer<string>
{
    const string ext = "_exp8";

    public bool Equals(string left, string right)
    {
        if (left.EndsWith(ext) && !right.EndsWith(ext))
        {
            return StripExt(left) == right;
        }
        else if (right.EndsWith(ext))
        {
            return left == StripExt(right);
        }

        return left == right;
    }

    private static string StripExt(string s)
        => s.Substring(0, s.Length - ext.Length);

    public int GetHashCode(string s)
    {
        if (s.EndsWith(ext))
        {
            return StripExt(s).GetHashCode();
        }
        else
        {
            return s.GetHashCode();
        }
    }
}

using System;
using System.Linq;

var files1 = new string[] { "1", "2", "3" };
var files2 = new string[] { "1_ext", "2_exp8", "3_exp8" };

var a = files1.Intersect(files2, new FileComparer());

var res = string.Join(", ", a);
Console.WriteLine(res);

A: Here is a way to write the custom comparer with a regex:
public static Regex rx = new Regex(@"^(TC_)_?(\d+).*", RegexOptions.Compiled);
public class FilePathComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return rx.Replace(x, "$1$2") == rx.Replace(y, "$1$2");
    }
    public int GetHashCode(string s)
    {
        return rx.Replace(s,"$1$2").GetHashCode();
    }
}

In the code later, just use
var intersected = FileNames_List_Jetzt_Dateien.Intersect(TEST_FÄLLE, new FilePathComparer());

See the C# demo and the regex demo.
The ^(TC_)_?(\d+).* regex matches

*

*^ - start of string

*(TC_) - Group 1 ($1): TC_

*_? - an optional underscore

*(\d+) - Group 2 ($2): one or more digits

*.* - the rest of the string.


text:
Q: The convert between YCbCr and RGB on python I want to write some image processing code on python.
A = imread('Example.bmp');
B  = ycbcr2rgb(rgb2ycbcr(A));
psnr(A,B)
%= 52.7283

However , when I try to do the same thing on python
the psnr is lower then the result of matlab.
from PIL import Image
import numpy
from skimage.measure import compare_psnr

A = Image.open('Example.bmp')
B = A.convert('YCbCr').convert('RGB')
compare_psnr(numpy.asarray(A),numpy.asarray(B))
# = 44.7441927214

There is no any problem of the psnr function on both python/matlab , I am sure that they are the same, beacuse i have tried to output the image and measure them on both python/matlab.
The problem is , why a got a lower psnr when i do convert on Python ?


text:
Q: Custom exception with Guava Preconditions It's very simple question, I often use com.google.common.base.Preconditions in my projects to validate arguments and parameters, for example:
Preconditions.checkNotNull(parameter, "message");
Preconditions.checkArgument(parameter > 0, "message");
this code may produce IllegalArgumentException or NPE. But very often I need throw own exception.
How can I do it by this library? Or maybe you can advise another one?
thank you in advance!
UPDATE: I understand, that I can to create own simple utility class, but I'm interested to find ready-made solutions. Please, let me know, if somebody know it's possible.

A: If you want to throw your own exception, just create your own class with similar methods to the ones in Preconditions. Each of those methods is extremely simple - adding some sort of "plug-in" ability to allow the exception class to be specified would really be overkill compared with writing your own.
You could always use the source of Preconditions as a starting point.

A: That's the solution I finally came to. It does exactly what I wanted.  Might be useful to anybody:
import java.lang.reflect.InvocationTargetException;

// IMPORTANT: parameter exClass must have at least no args constructor and constructor with String param
public class Precondition {

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass) throws T {
    checkArgument(expression, exClass, null);
}

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (!expression) {
        generateException(exClass, errorMessage, args);
    }
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass) throws T {
    checkNotNull(reference, exClass, null);
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (reference == null) {
        generateException(exClass, errorMessage, args);
    }
}

private static <T extends Exception> void generateException(Class<T> exClass, String errorMessage, Object... args) throws T {
    try {
        if (errorMessage == null) {
            throw exClass.newInstance();
        } else {
            throw exClass.getDeclaredConstructor(String.class, Object[].class).newInstance(errorMessage, args);
        }
    } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

}

A: You can use valid4j with hamcrest-matchers instead (found on Maven Central as org.valid4j:valid4j)
For input validation throwing custom exceptions:
import static org.valid4j.Validation.*;

validate(argument, isValid(), otherwiseThrowing(InvalidException.class));

For preconditions and postconditions (i.e. assertions):
import static org.valid4j.Assertive.*;

require(argument, notNullValue());
...
ensure(result, isValid());

Links:

*

*http://www.valid4j.org/

*https://github.com/helsing/valid4j

A: You could always make something like that for you own (I don't know why the guys from guava did not add it yet):
public static void check(final boolean expression, RuntimeException exceptionToThrow) {
    if (!expression) {
        throw checkNotNull(exceptionToThrow);
    }
}

public static void check(final boolean expression, Supplier<? extends RuntimeException> exceptionToThrowSupplier) {
    if (!expression) {
        throw checkNotNull(exceptionToThrowSupplier).get();
    }
}

A: The Exception types are hard coded into the Preconditions class. You will need to implement your own exception and your own checking function. You could always do it in a static class of your own similar to how Preconditions works.


text:
Q: Image Alignment HTML CSS I want to bring the delete and edit buttons on one line and the text on next line.
Unable to figure it out.

    <%= comment.author.username%>
    10 days ago

      <a id="myImg" href="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/edit">

      <form class="delete-form" action="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/?_method=DELETE" method="POST">
        <input width="10" height="10" type="image" src="https://cdn2.iconfinder.com/data/icons/25-free-ui-icons/40/trash_bin-128.png"></input>
      </form>
      <%=comment.text%>

A:

                <%= comment.author.username%>
                10 days ago

                 <a id="myImg" href="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/edit">

                    <form class="delete-form" action="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/?_method=DELETE" method="POST">
                       <input width="10" height="10" type="image" src = "https://cdn2.iconfinder.com/data/icons/25-free-ui-icons/40/trash_bin-128.png"></input>
                    </form>

                        <%=comment.text%>

A:

    Username
    10 days ago

      <form class="delete-form" action="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/?_method=DELETE" method="POST">
        <a id="myImg" href="/campgrounds/<%=campground._id%>/comments/<%= comment._id%>/edit">

        <input width="10" height="10" type="image" src="https://cdn2.iconfinder.com/data/icons/25-free-ui-icons/40/trash_bin-128.png"></input>
      </form>
      Comment text


text:
Q: How to prove? $0<\left(n^2-1\right)^n(n+1)$$
\displaystyle 0<\left(n^2-1\right)^n(n+1)<n^{2n+1}
$$

How does one prove this inequality for $n>1\in \mathbb{N}$ ?

A: The LHS is immediate since all the terms are positive.
The RHS follows from AM-GM. We have
$$ (n^2-1)^n (n^2+n) < \left( \frac{n \times (n^2 -1) +1 \times  (n^2+n)}{n+1} \right) ^{n+1} =  (n^2)^{n+1}. $$
We have strict inequality since not all the terms are equal.
Cancel 1 factor of $n$ from both sides.

A: $(n^2-1)^n\cdot (n+1) = (n-1)^n\cdot (n+1)^{n+1} < n^{2n+1} \iff \left(1-\dfrac{1}{n}\right)^n\cdot \left(1+\dfrac{1}{n}\right)^{n+1} < 1 \iff n\cdot ln\left(1-\dfrac{1}{n}\right) + (n+1)\cdot ln\left(1 + \dfrac{1}{n}\right) < 0 \iff \dfrac{ln(1-\dfrac{1}{n})}{\dfrac{1}{n}} + ln(1 + \dfrac{1}{n}) + \dfrac{ln(1 + \dfrac{1}{n})}{\dfrac{1}{n}} < 0$.
Let $x = \dfrac{1}{n}$, then $0 < x < 1$, and the inequality to be proven is:
$\dfrac{ln(1-x^2)}{x} + ln(1 + x) < 0 \iff \dfrac{ln(1-x^2) + xln(1+x)}{x} < 0$. To complete the proof, we show: $f(x) < 0$ with $f(x) = ln(1-x^2) + xln(1+x)$ on $(0,1)$. Thus:
$f'(x) = -\dfrac{2x}{1-x^2} + ln(1+x) + \dfrac{x}{1+x} = ln(1+x) - \dfrac{x}{1-x} = g(x)$. Observe that if $f'(x) < 0$, then $f(x) < f(0) = 0$, and we're done. So we need to show again that: $f'(x) = g(x) < 0$ on $(0,1)$.
To get this, differentiate $g$ and have:
$g'(x) = \left(ln(1+x) + 1 + \dfrac{1}{x-1}\right)' = \dfrac{1}{1+x} - \dfrac{1}{(1-x)^2} =\dfrac{x(x-3)}{(1+x)(1-x)^2} < 0$. Thus: $g(x) < g(0) = 0$, and we're done.