text:
Q: R list package ict.reg will not run I'm relatively new to R and trying to diagnose a problem when running "ict.reg" in the list package (developed for list experiements). When I try to run ict.reg, it returns this error message:
Error: Can't subset columns that don't exist.
x Location 2 doesn't exist.
i There are only 1 column.
Run rlang::last_error() to see where the error occurred.
In addition: Warning message:
In if (class(t) == "factor") { :
the condition has length > 1 and only the first element will be used
I've tried a few things like making sure the "treat" variable is boolean, but it still comes up with this message that I am struggling to figure out. Any help would be appreciated, thank you!
install.packages(list)

# Load package
library(list)

experimentA$treat <- ifelse(is.na (experimentA$treatmentA),FALSE, TRUE))

# Test No Design Effect Assumption:
# experiementA = dataset
# listA= list items reported by respondent
# binary = binary variable denoting whether individual received treatment or control list
# J = number of control list items

# Generate estimate of population proportion based on difference in means
diff.in.means.results<-ictreg(listA~1, data=experimentA, treat="treat", J=3,method='lm')
summary(diff.in.means.results)

A: Answer provided in case anyone runs into this error message. I encountered this error when using a tibble, i.e., data imported from an SPSS file using haven::read_sav('FILE.sav'). Once this object was converted to a standard data frame using df2 <- as.data.frame(df), then the ictreg() function from the list package worked as expected.


text:
Q: MIT Integration Bee $21$ Question:
$$\int_0^\infty {{1}\over{(1+x^{2015})({1+x^2}})}dx$$
How to solve these integrals. I have no idea.

A: Use the substitution $x\mapsto 1/x$:
\begin{align*}
I &= \int_0^\infty {{1}\over{(1+x^{2015})({1+x^2}})}dx \\
&= \int_0^\infty {{1}\over{(1+x^{-2015})({1+x^{-2}}})} \frac{1}{x^2}dx\\
&= \int_0^\infty {{x^{2015}}\over{(1+x^{2015})({1+x^{2}}})} dx
\end{align*}
Then,
\begin{align*}
2I &= \int_0^\infty {{1}\over{(1+x^{2015})({1+x^2}})}dx+\int_0^\infty {{x^{2015}}\over{(1+x^{2015})({1+x^2}})}dx\\
&=\int_0^\infty {{1+x^{2015}}\over{(1+x^{2015})({1+x^2}})}dx\\
&=\int_0^\infty \frac{1}{1+x^2}dx = \frac{\pi}{2}
\end{align*}
So $I=\pi/4$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asp.net User is in Role but [Authorize(Roles = "Admin")] returns Authorization failed So... im trying now for like 2 hours and cant get it to work.
The problem is that if i try to use role based authorization like this
[Authorize]
public ActionResult createBill() {
    return View();
}

no problem at all
but when i try to use it like this
[Authorize(Roles = "Admin")]
public ActionResult createBill() {
    return View();
}

I only get Authorization failed. in the Console
i've done this
await RoleManager.CreateAsync(new IdentityRole("Admin"));
await UserManager.AddToRoleAsync(user, "Admin");
Console.WriteLine(User.IsInRole("Admin")); <- Return true

and yes i tried relogging
this is my ConfigureServices
public void ConfigureServices(IServiceCollection services) {
    services.AddLiveReload();
    services.AddDbContext<WebinterfaceDbContext>();
    services.AddIdentity<WebinterfaceUser, IdentityRole>().AddEntityFrameworkStores<WebinterfaceDbContext>();
    services.AddRazorPages().AddRazorRuntimeCompilation();
    services.AddMvc(options => { options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); }).AddRazorRuntimeCompilation();
    services.AddAuthorization(options => { options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin")); });
    services.AddControllersWithViews();
    services.Configure<KestrelServerOptions>(options => { options.AllowSynchronousIO = true; });
}

and this is the Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseLiveReload();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();
    app.UseAuthentication();
    app.UseEndpoints(endpoints => {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

i've used the standard Template of AspNet MVC

I am using these Packages
<PackageReference Include="EntityFramework" Version="6.3.0-preview8-19405-04" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0-preview8.19405.11" />
<PackageReference Include="Westwind.AspnetCore.LiveReload" Version="0.1.5.2" />

Also netcoreapp3.0
my DbContext
public class WebinterfaceDbContext : IdentityDbContext<WebinterfaceUser> {
    public DbSet<Bill> Bills { get; set; }
    protected override void OnModelCreating(ModelBuilder builder) {
        builder.Entity<WebinterfaceUser>().Property(e => e.Servers).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<Guid>>(e));
        builder.Entity<WebinterfaceUser>().Property(e => e.ApiKeys).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<Guid>>(e));

        builder.Entity<Bill>().Property(e => e.Components).HasConversion(e => JsonConvert.SerializeObject(e), e => JsonConvert.DeserializeObject<Collection<BillComponent>>(e));

        base.OnModelCreating(builder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
        optionsBuilder.UseSqlServer("User ID=sa;Password=123456;Server=localhost;Database=Webinteface;");
    }
}

what also sucks is that the list "Bills" defiend in my Webinterface User is never filled by the Entity Framework..... i dont know anymore what to do its so frustrating to have all these issues.

btw this is my WebinterfaceUser
public class WebinterfaceUser : IdentityUser {
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string? Company { get; set; }

    public string Street { get; set; }

    public int StreetNumber { get; set; }

    public int Zip { get; set; }

    public string City { get; set; }

    public string Country { get; set; }

    public Collection<Guid> Servers { get; set; } = new Collection<Guid>();

    public Collection<Guid> ApiKeys { get; set; } = new Collection<Guid>() {Guid.NewGuid()};

    public Guid SupportApiKey { get; set; } = Guid.NewGuid();

    public Collection<Bill> Bills { get; set; } = new Collection<Bill>();

    public List<Bill> getBills() {
        return new WebinterfaceDbContext().Bills.Where(b => b.Recipient == this).ToList();
    }

    public List<Server> getOwnedServers() {
        ServerContext context = new ServerContext();
        return context.Servers.Where(s => Servers.Contains(s.Guid)).ToList();
    }

    public Server getServerByGuid(Guid guid) {
        return getOwnedServers().Find(s => s.Guid == guid);
    }
}

A: I just ran into this exact problem. It's because of some changed behavior with the authorization in dotnet core 3.0.
According to Microsoft's migration docs you have to put app.UseAuthorization() AFTER app.UseAuthentication(). Once you do that the Authorize roles should work just fine.


text:
Q: Set HTML5 doctype with XSLT How would I cleanly set the doctype of a file to HTML5 <!DOCTYPE html> via XSLT (in this case with collective.xdv)
The following, which is the best my Google foo has been able to find:
<xsl:output
    method="html"
    doctype-public="XSLT-compat"
    omit-xml-declaration="yes"
    encoding="UTF-8"
    indent="yes" />

produces:
<!DOCTYPE html PUBLIC "XSLT-compat" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

A: To use the simple HTML doctype <!DOCTYPE html>, you have to use the disable-output-escaping feature: <xsl:text disable-output-escaping="yes"><!DOCTYPE html></xsl:text>. However, disable-output-escaping is an optional feature in XSLT, so your XSLT engine or serialization pipeline might not support it.
For this reason, HTML5 provides an alternative doctype for compatibility with HTML5-unaware XSLT versions (i.e. all the currently existing versions of XSLT) and other systems that have the same problem. The alternative doctype is <!DOCTYPE html SYSTEM "about:legacy-compat">. To output this doctype, use the attribute doctype-system="about:legacy-compat" on the xsl:output element without using a doctype-public attribute at all.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" doctype-system="about:legacy-compat"/>
   ...

</xsl:stylesheet>

A: This variation of Jirka Kosek's advice, via Advanced XDV theming on Plone.org seems to work for me in collective.xdv.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output
      doctype-public="HTML"
      doctype-system=""/>
</xsl:stylesheet>

A: This is a comment, but I do not have enough karma points to put it in the correct place. Sigh.

I appreciate this is probably the correct, standards driven way to accomplish what I want (I've upvoted it as such). But the former isn't supported (my processor falls over) and the latter still results in "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" in my doctype. As @Jirka Kosek suggested, I think my XSLT processor might be broken.

No, your XSLT processor is not broken, it's just that XDV adds:
<xsl:output method="xml" indent="no" omit-xml-declaration="yes" media-type="text/html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
by default, so when you add a second <xsl:output doctype-system="about:legacy-compat"/> the previous doctype-public is not overwritten.
Note that XHTML 1.0 strict is listed as an obsolete permitted doctype string, so it is perfectly acceptable to use this doctype and still call it HTML5.

A: <xsl:output
     method="html"
     doctype-system="about:legacy-compat"
     encoding="UTF-8"
     indent="yes" />

this outputs
<!DOCTYPE html SYSTEM "about:legacy-compat">

this is modified as my fix to http://ukchill.com/technology/generating-html5-using-xslt/

A: Sorry to only provide links but this was discussed among the WHATWG group but it's been many months since I've dealt with it. Here Ian Hickson and some XML experts discuss this:
http://lists.w3.org/Archives/Public/public-html/2009Jan/0640.html
http://markmail.org/message/64aykbbsfzlbidzl
and here is the actual issue number:
http://www.w3.org/html/wg/tracker/issues/54
and here's this discussion
http://www.contentwithstyle.co.uk/content/xslt-and-html-5-problems

A: With Saxon 9.4 you can use:
<xsl:output method="html" version="5.0" encoding="UTF-8" indent="yes" />

This generates:
<!DOCTYPE HTML>

A: Use this tag

<xsl:output method="xml" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" doctype-public="XSLT-compat" indent="yes"/>

A: I think this is currently only supported by writing the doctype out as text:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" encoding="utf-8" indent="yes" />

  <xsl:template match="/">
    <xsl:text disable-output-escaping='yes'><!DOCTYPE html></xsl:text>

  </xsl:template>

</xsl:stylesheet>

This will produce the following output:
<!DOCTYPE html>

A: Use doctype-system instead of doctype-public

A: You must use XHTML 1.0 Strict as the doctype if you want XHTML output consistent with HTML5, libxml2's xml serializer has a special output mode triggered by the XHTML 1.0 doctypes that ensures output is XHTML compatible, (e.g.
 rather than
,

 rather than
). doctype-system="about:legacy-compat" does not trigger this compatibility mode
If you are happy with html output, then setting <xsl:output method="html"> should do the right thing. You can then set the doctype with <xsl:text disable-output-escaping="yes"><!DOCTYPE html></xsl:text>, though this will need plumbing in at the appropriate place as XDV does not support this yet.
In fact it seems <xsl:output method="html"/> does not really help either - this will result in
 being output as

.

A: The following code will work as a standalone template if saved as html5.xml:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="html5.xml"?>
<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"
            >
<xsl:output method="xml" encoding="utf-8" version="" indent="yes" standalone="no" media-type="text/html" omit-xml-declaration="no" doctype-system="about:legacy-compat" />

<xsl:template match="xsl:stylesheet">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="/">

      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

      <xsl:text>hi</xsl:text>

</xsl:template>

</xsl:stylesheet>

References

*

*Polyglot Markup: The Doctype

A: that's what i use to generate a compatible html5 doctype (getting saxons html5 out, otherwise doing the legacy thing)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns="http://www.w3.org/TR/REC-html40">

    <xsl:output
        method="html"
        version="5.0"
        doctype-system="about:legacy-compat"
        encoding="UTF-8"
        indent="yes" />


text:
Q: Allow only specific translations for different schemes/targets My issue is, that I have a basic set of Localizable.strings for several languages, but I don't want to allow them in all my build-targets / schemes (some of our clients want only these, others only that languages allowed).
Because the set is the same for all and will be extended with every update, I want to avoid to copy the files deeper in the folder hirarchy and maintain every target.
I use NSLocalizedStringWithDefaultValue and NSLocalizedString, but haven't found any option to give them the allowed localizations.
Thank you in advance.

A: I ended up in changing my way from using the NSLocalizedString to language specific named files (for german Localizable_de.strings, for english Localizable_en.strings and so on).
Following to
https://stackoverflow.com/a/12004482/883799
I use in my translation class
NSString *tbl = [@"Localizable_" stringByAppendingString:[MyLibrary currentLocalization]];
NSString *fname = [[NSBundle mainBundle] pathForResource:tbl ofType:@"strings"];
if(!localStrings)
    localStrings = [[NSDictionary dictionaryWithContentsOfFile:fname] retain];

NSString *value = [localStrings objectForKey:key];

where [MyLibrary currentLocalization]; is
+(NSString *)currentLocalization
{
    NSString *currentLocCode = [[NSLocale preferredLanguages] objectAtIndex:0];

    if([[AppSettings supportedLocales] containsObject:currentLocCode])
        return [currentLocCode substringToIndex:2];

    return [AppSettings defaultLocalization];
}

AppSettings is target-depending an [AppSettings supportedLocales]; is
+(NSArray *)supportedLocales
{
    return [NSArray arrayWithObjects:
    @"de",
    @"de_AT",
    @"de_BE",
    @"de_CH",
    @"de_DE",
    @"de_LI",
    @"de_LU",
     //
    @"en",
    @"en_AS",
    @"en_AU",
    @"en_BB",
    @"en_BE",
    @"en_BM",
    @"en_BS",
    @"en_BW",
    @"en_BZ",
    @"en_CA",
    @"en_FJ",
    @"en_FM",
    @"en_GB",
    @"en_GM",
    @"en_GU",
    @"en_GY",
    @"en_HK",
    @"en_IE",
    @"en_IN",
    @"en_JM",
    @"en_MH",
    @"en_MP",
    @"en_MT",
    @"en_MU",
    @"en_MW",
    @"en_NA",
    @"en_NZ",
    @"en_PG",
    @"en_PH",
    @"en_PK",
    @"en_PW",
    @"en_SB",
    @"en_SC",
    @"en_SG",
    @"en_SL",
    @"en_SZ",
    @"en_TT",
    @"en_UM",
    @"en_US",
    @"en_US_POSIX",
    @"en_VI",
    @"en_ZA",
    @"en_ZW",
    //
    @"es",
    @"es_419",
    @"es_AR",
    @"es_BO",
    @"es_CL",
    @"es_CO",
    @"es_CR",
    @"es_DO",
    @"es_EC",
    @"es_ES",
    @"es_GQ",
    @"es_GT",
    @"es_HN",
    @"es_MX",
    @"es_NI",
    @"es_PA",
    @"es_PE",
    @"es_PR",
    @"es_PY",
    @"es_SV",
    @"es_US",
    @"es_UY",
    @"es_VE",
    //
    @"fr",
    @"fr_BE",
    @"fr_BF",
    @"fr_BI",
    @"fr_BJ",
    @"fr_BL",
    @"fr_CA",
    @"fr_CD",
    @"fr_CF",
    @"fr_CG",
    @"fr_CH",
    @"fr_CI",
    @"fr_CM",
    @"fr_DJ",
    @"fr_FR",
    @"fr_GA",
    @"fr_GF",
    @"fr_GN",
    @"fr_GP",
    @"fr_GQ",
    @"fr_KM",
    @"fr_LU",
    @"fr_MC",
    @"fr_MF",
    @"fr_MG",
    @"fr_ML",
    @"fr_MQ",
    @"fr_MR",
    @"fr_NE",
    @"fr_RE",
    @"fr_RW",
    @"fr_SC",
    @"fr_SN",
    @"fr_TD",
    @"fr_TG",
    @"fr_YT",
    //
    @"it",
    @"it_CH",
    @"it_IT",
            nil];
}

but still accepting modifications to this if someone has a better solution :)


text:
Q: About checksum of TCP/IP layer Has anyone tested what will happen if checksum doesn't match?
Will the packet be ignored directly?
Suppose it's HTTP protocal at the application layer.

A: HTTP will never see the bad packet. Remember that TCP guarantees (best effort) that it will give you an error free contiguous stream of data, which is what HTTP uses.
In TCP, at some point the client will generate a NACK instead of an ACK. Depending on if selective ACK was negotiated, either the bad packet or a subset of the packets received will be retransmitted by the server (in the TCP layer, the HTTP server has no knowledge except for higher latency).
The checksum is discussed in the TCP RFC: http://www.faqs.org/rfcs/rfc793.html Section 3.1 (Page 16)
RFC1071 goes into detail about the checksum.


text:
Q: AWS - Global Accelerator not working with Network Load Balancer I have a Network Load Balancer and an Application Load Balancer, they work just fine, but as I need fixed IPs/hostnames I decided to create a Global Accelerator for each one.
Global Accelerator with Application Load Balancer works but with Network Load Balancer it doesn't respond...
Example:
ALB:
$ nc -zv <application-load-balancer>.awsglobalaccelerator.com 80
Connection to <application-load-balancer>.awsglobalaccelerator.com 80 port [tcp/*] succeeded!

NLB:
$ nc -zv <network-load-balancer>.awsglobalaccelerator.com 1883
nc: connect to <network-load-balancer>.awsglobalaccelerator.com port 1883 (tcp) failed: Connection timed out

I have changed Health Check port configuration for the NLB to 1883, and the Global Accelerator is shown as " All healthy".
And as I said, the Network Load Balancer itself works:
$ nc -zv <network-load-balancer>.elb.sa-east-1.amazonaws.com 1883
Connection to <network-load-balancer>.elb.sa-east-1.amazonaws.com 1883 port [tcp/*] succeeded!

Both load balancers are very similar (similar instances, same VPC, subnets, etc).
AWS docs say I can use Global Accelerator with both types of Load Balancers.
I don't know why the NLB Global Accelerator doesn't respond.
What am I missing?
More info:
- I'm testing in sa-east-1 region (South America)
- I need Global Accelerator because the LBs are part of terraform for deployment, so for every build the LBs hostname changes
- I could use Elastic IP's for NLB, but to do that I'd need to change my existing subnets (and as far as I know I can't use Elastic IPs for ALBs)...

A: If static ip is the only thing you need to achieve then I am not getting the point using Global accelerator and NLB together. Because both provides the features of static ip.
For static ip facility there are 2 options

*

*Use Global accelerator on top of ALB(easy configuration and high cost)

*Use NLB and forward your request to ALB(complex configuration and cost effective)
For 2nd option you can get reference from below link.
https://www.bluematador.com/blog/static-ips-for-aws-application-load-balancer


text:
Q: Hide Sharepoint 2013 web parts until linked image is clicked I have a SharePoint 2013 web part page that has 4 images and 4 webparts.  I want to hide the 4 web parts and only have them show based on click of the image above.  I.E.  Image 1 click shows WP 1, Image 2 click re-hides other wp(s) opened and only shows WP2, and so on.  See image below
Images used and 4 WP's


text:
Q: Equations describing the liquifaction of gases I would like to find out how much energy is required to liquify gases (oxygen or nitrogen, for example). What are some relevant equations?
I'm curious whether creating small quantities of dry ice or cryogenic fluids is feasible at home. If James Dewar was able to liquify hydrogen in 1898 surely it must not be that difficult!

A: This question first requires some "sorting".

*

*As long as You want to do that with nitrogen or oxygen, so called "permanent gases"
in this context, the answer is no. Linde machines are plants! The first liquefied air was
made in lab (Krakau) with simpler apparatus, but nevertheless I doubt You could tinker something like that, high pressures and precooling to rather deep temperatures are necessary.

*If You content with "not permanent" gases, then just take a flask for refill of lighters
(Butane) and open the nozzle pointing it down into a glass. some liquid and cold and boiling butane will collect.

*"dry" ice is simple too, just take a fire extinguisher filled with liquid carbon dioxide
and open the nozzle and blow into a bag made from coarse linen. Dry ice (snow) will collect in the bag.  Depending on inner construction of the gas cylinder (raiser or not)
You have to hold it upside down maybe. In general do the way prescribed for the extinguisher in use.
Edit, I forgot Your asking for "equations". Look for "Joule-Thompson-effect" (Wikipedia)
the only thing You will need, is the inversion temperature. Calculations maybe will show You the difficulty to make liquid air.
Edit/PS
If You try to tinker in this domain, please be aware that steel (and other metals)
will be very brittle at liquefied air temperatures.(Danger of explosions) Selection of materials is a very important part of cryogenics.


text:
Q: Integer Linear Programming: Sum of Products of Binary Variables Given four sets of binary variables $x_{1..N}$, $y_{1..N}$, $v_{1..N}$, and $w_{1..N}$ such that $\Sigma_{i=1}^{N} x_i = \Sigma_{i=1}^{N} y_i = \Sigma_{i=1}^{N} v_i = \Sigma_{i=1}^{N} w_i = 1$, I need to linearize the following constraint:
$\Sigma_{i=1}^{N} x_i y_i \leq \Sigma_{i=1}^{N} v_i w_i$.
All binary variables have value in $\{0, 1\}$. This constraints means that if for an $i \in \{1,.., N\}$, it holds that $x_i=y_i=1$, then for a $j \in \{1,.., N\}$, it must hold that $v_j=w_j=1$. In other words, if the dot product of vectors $\textbf{x}$ and $\textbf{y}$ is one, then the dot product of vectors $\textbf{v}$ and $\textbf{w}$ must also be 1 (based on the assumption in the first line, all vectors $\textbf{x}$, $\textbf{y}$, $\textbf{v}$, and $\textbf{w}$  are unit vectors in $R^{N}$).
1. Approach 1
I know that I can introduce for each $i$, a new variable $\alpha_i$ to mean that $\alpha_i = x_i y_i$ by the following constraints:
$\alpha_i \leq x_i$
$\alpha_i \leq y_i$
$\alpha_i \ge x_i + y_i -1$,
and, in a similar manner, introduce a new variable $\beta_i$ to mean $\beta_i = v_i w_i$, and, finally, replace the original constraint by the following:
$\Sigma_{i=1}^{N} \alpha_i \leq \Sigma_{i=1}^{N} \beta_i$.
The problem of this approach is that it considerably slows down my program implemented in cplex.
I need to use a different approach that is faster than this.
thanks
2. Approach 2
One other approach was to introduce only two new binary variables $\lambda$ and $\xi$, whose values are in $\{0, 1\}$ and restricted by the following constraints:
$\lambda \ge x_i+y_i-1   \;\;\;\;\;\;\;\;\;\;\;\; , \forall i\in \{1,...,N\}$
$\xi \ge v_i+w_i-1   \;\;\;\;\;\;\;\;\;\;\;\; , \forall i\in \{1,...,N\}$,
Accordingly, the original constraint is formulated by the following constraint:
$\lambda \leq \xi$.
This approach is extremely faster than the first approach, but it works only for one case, where for an $i \in \{1,..., N\}$, it holds that $x_i=y_i=1$, which enforces that it must hold that $v_j=w_j=1$ for a $j \in \{1, ..., N\}$. For the other case, where for no $i$, it holds that $x_i = y_i = 1$, the value of $\lambda$ is not constrained to by 0, and so it makes problem.

A: The following should do what you want, with only one set of $N$ additional binary variables $\beta_j$:
\begin{align}
x_i + y_i - 1 &\le \sum_{j=1}^N \beta_j &\text{for all $i$}\\
\beta_j &\le v_j &\text{for all $j$}\\
\beta_j &\le w_j &\text{for all $j$}
\end{align}
Alternatively, you can aggregate the last two constraints at the expense of weakening the linear programming relaxation:
\begin{align}
x_i + y_i - 1 &\le \sum_{j=1}^N \beta_j &\text{for all $i$}\\
2\beta_j &\le v_j + w_j &\text{for all $j$}
\end{align}

A: Your second approach makes no sense to me. With only two new binary variables, the best you will be able to determine is whether any product $x_i y_i = 1$, not how many such products equal 1.
In the first approach, did you give the $\alpha_i$ the domain $[0,1]$ (i.e., make them continuous variables)? I would not expect that to slow the solution very much. Those variables do not need to be declared integer-valued. It is possible that, by branching on them early, CPLEX might solve the problem faster, but my experience is that fewer integer variables is usually better.
Regarding the first approach, I believe you could omit the constraints $\alpha_i \le x_i$, $\alpha_i \le y_i$ and $\beta_i \ge v_i + w_i - 1$. This would allow the solver to set $\alpha_i = 1$ when either $x_i$ or $y_i$ was 0, and would let it set $\beta_i = 0$ when both $u_i$ and $v_i$ were 1, but the original constraint $\sum_i x_i y_i \le \sum_i u_i v_i$ would still be met: at least as many $\alpha_i$ would be 1 as the number of unit products on the left, and at most as many $\beta_i$ would be 1 as the number of unit products on the right.


text:
Q: Gromov hyperbolicity of Metric Spaces Proof of lemma 2.4
Hi, I was doing some self reading on Gromov geometry and I have difficulty accepting the proof given above for lemma 2.4. While I can understand that $(x|z)\ge \max\{(x|w),(y|z)\}$, there is no assumption imposed whatsoever on  $(y|w)$. The last line of the proof seem to suggest that $(x|z)+(y|w)\ge (y|z)+(x|w)$ 1which may not be true for the reason stated above.
Is there something wrong with the proof above or am I missing something here?


text:
Q: Statistical conclusions from incompatible measurement results I assume that the following situation is not uncommon in scientific practice:

*

*Two research groups analyse two samples.

*The reported results concern the same physical quantity at the same location and at the same time.

*The analysis methodologies are different.

*The reported results are calculated differently from the raw data that were measured.

*But: The reported results are incompatible, i.e. the sum of their bell curves has two peaks, i.e. is bi-modal.

As a specific example one may consider the atmospheric carbon dioxide concentration at the south pole

*

*directly measured from atmosphere and

*measured by an ice core.
These are for example the time series from atmospheric measurements at the south pole compared to ice core  measurements at Law Dome:

When the two samples are not identical (as in the example: one sample was gaseous, the other sample was solid) the first guess to explain the discrepancy is by the difference of the samples (1). To exclude this (for the sake of my argument/question) let me assume that the samples are identical. Discrepancies may occur nevertheless.
The next guess then to explain the discrepancy is by the difference of measurement methodologies (3) and/or calculations (4). Let me assume that both seem sound for both research groups, so both measurements may have the same a priori credibility.
For the sake of simplicity let me assume that both standard deviations are the same.
Now I am at the heart of my question:

*

*Which conclusions can be drawn from the two incompatible results (bell curves)?

*How wrong must at least one of the results be (with respect to mean and standard deviation)?

*What can be assumed to be the "true" mean and the "true" standard deviation?

Remember that two measurements (reported values) are supposed to be "incompatible" when the sum of their bell curves has two peaks, i.e. is bi-modal.
I further suppose that a measurement (a reported value) is "wrong" when the true value falls outside the two standard deviation interval of the reported mean.

A: The question is interesting. I will use a simple example to illustrate what I believe the core idea is.
Let $y_i$ denote a noisy measurement of $x$ and let each measurement have its own measurement error. In particular, let
\begin{equation}
y_i = x + \varepsilon_i
\end{equation}
where $\varepsilon_i \sim \textsf{N}(0,\sigma_i^2)$. We can re-express this as
\begin{equation}
p(y_i|x) = \textsf{N}(y_i|x,\sigma_i^2) .
\end{equation}
Suppose we have two such measurements. The likelihood of $x$ is given by
\begin{equation}
p(y_1,y_2|x) = p(y_1|x)\,p(y_2|x) = \textsf{N}(y_1|x,\sigma_1^2)\, \textsf{N}(y_2|x,\sigma_2^2) .
\end{equation}
We can re-express the likelihood of $x$ as
\begin{equation}
p(y_1,y_2|x) \propto \textsf{N}(x|m,s^2) ,
\end{equation}
where
\begin{align}
m &= s^{2}\left(\frac{y_1}{\sigma_1^2} + \frac{y_2}{\sigma_2^2}\right) \\
s^2 &= \left(\frac{1}{\sigma_1^2}+\frac{1}{\sigma_2^2}\right)^{-1} .
\end{align}
Thus, the likelihood of $x$ is unimodal regardless of how far apart the measurements are relative to their variances.
Now let us examine the likelihood of the model. Let us assume the prior for $x$ is
\begin{equation}
p(x) = \textsf{N}(x|\mu,\tau^2) .
\end{equation}
The likelihood of the model is given by
\begin{equation}
p(y_1,y_2) = \int p(y_1,y_2|x)\,p(x)\,dx = \frac{e^{-\frac{(m-\mu )^2}{2 \left(s^2+\tau
   ^2\right)}}}{\sqrt{2 \pi } \sqrt{s^2+\tau
   ^2}}
\end{equation}
In order to simplify the exposition, let us assume the measurement errors are the same: $\sigma_1 = \sigma_2 = \sigma$. We also assume $y_1 \ne y_2$. Then,
\begin{equation}
\lim_{\sigma\to 0}\ p(y_1,y_2) = 0 ,
\end{equation}
which means that in the limit the measurements are completely incompatible with the model.
A numerical illustration may prove helpful. Let $y_1 = 1$, $y_2 = -1$, $\mu = 0$, and $\tau = 1$. With these values,
\begin{equation}
p(y_1,y_2) = \frac{e^{-\frac{1}{\sigma ^2}}}{2 \pi  \sigma
   \sqrt{\sigma ^2+2}} .
\end{equation}
In this case,
\begin{equation}
p(y_1,y_2) \approx \begin{cases}
3\times 10^{-2} & \sigma = 1 \\
4\times 10^{-3} & \sigma = 1/2 \\
5\times 10^{-8} & \sigma = 1/4
\end{cases} .
\end{equation}
The likelihood of the model falls off dramatically as $\sigma$ decreases from one. The model with $\sigma = 1/4$ is roughly one million times worse than the model with $\sigma = 1$.
If one is confident that $\sigma = 1/4$ is correct, then very likely there are other assumptions of the model that are incorrect. The way to procede then is to identify those parts of the model and correct them. For example, perhaps
\begin{align}
y_i &= \xi_i + \varepsilon_i \\
\xi_i &= x + u_i ,
\end{align}
where $u_i \sim \textsf{N}(0,\omega_i^2)$.
In any event, I think it is a mistake to try to horse-out the "truth" from a model that is so completely "false."


text:
Q: Two different datasources for SearchDisplayController and TableView how can i have different datasource for SearchDisplayController and TableView on the same View?
Like Facebook app, i need the search bar to search and display data from a datasource, while the TableView shows data from another array.
How can i achieve that?

A: Setup two instance variables within your view controller. One to hold the data for your searchdisplay controller and one to hold your tableview data. In the corresponding delegate method, use the correct instance variable.


text:
Q: Why can't the particular solution have factors found in the general homogeneous equation in it? Consider the following differential equation:
$$y''-4y'+4y = g(x)$$
The general solution of the homogeneous equation is $e^{2x}(C_1+ xC_2)$.
Find the particular solution when $g(x) = e^{2x}$ and $g(x)=e^{-2x}$.
When $g(x)= e^{2x}$, why can't $y_{p_2}=Be^{2x}$ or $y_{p_2}=Bxe^{2x}$? I see that they are both part of the general homogeneous equation, but why is this a limitation?

A: It just because, by definition of the solutions of the homogeneous equation, the left-hand side is $0$ when we set $y(x)=\mathrm e^{2x}$  or  $y(x)=x\mathrm e^{2x}$. Hence the l.h.s. can't be $\mathrm e^{2x}$.
In that case you have to find a particular solution of the form; $\;Bx^2\mathrm e^{2x}$. More generally, if the r.h.s. has the form $\,p(x)\mathrm e^{2x}$, where $p(x)$ is a polynomial of degree $d$, a particular solution is $x^2q(x)\mathrm e^{2x}$, where $q(x)$ is another polynomial of degree $d$.

A: To answer your question, we must first examine the associated homogeneous DE
$$y''-4y'+4y=0$$
which has characteristic polynomial
$$p(r)=r^2-4r+4$$
$$\Rightarrow \ p(r)=(r-2)^2$$
and thus the characteristic polynomial has a root of 2 with multiplicity 2. This means our fundamental set for the homogeneous DE is
$$H=\lbrace e^{2x}, xe^{2x} \rbrace$$
Now, if you're looking for a particular solution, you cannot have any linear combinations of these, or else it's not a particular solution! We already know the general solution is of the form
$$y=y_h+y_p$$
Where $y_h$ is the solution to your associated homogeneous ($y=C_1e^{2x}+C_2xe^{2x}$), and $y_p$ a particular solution.
Thus, including elements from $H$ in the particular solution does nothing towards helping you find a particular solution! Counting elements of $H$ again when you've already included an arbitrary constant in front of them adds nothing; in essence, think of the particular solution as "the thing satisfying the DE when I make all the $C$'s$=0$"
Hopefully that explains in an intuitive way why "the limitation" exists on what can be a particular solution.

A: Consider the following differential equation:
$$y''+2y'=3+4\sin(2x)$$
What is the solution?


text:
Q: Command to check whether the current user has write permission I have to create a script to check if the current user has write permission on a file. If not, an error should appear.
I wrote this:
if [namei -m /path/to/textfile.txt | grep w]; then
  echo "message"

But I seem to get a syntax error.

A: Let's work through the issues with your code. As dessert mentioned in a comment, the first problem is the syntax of the [ command. We need to put spaces between [ and its arguments, because the shell uses spaces to separate fields, and thinks that [namei is the command you want to run.
I'm going to use a file in my home directory called file, which I know I have write permission on, in my examples. I have put your code on one line, to make it easier to test interactively. It will work in the same way as if there were a newline after then.
$ if [namei -m playground | grep w]; then echo "writeable"
No command '[namei' found, did you mean:
 Command 'namei' from package 'util-linux' (main)
[namei: command not found

Let's fix the spaces around [ and ]:
$ if [ namei -m playground | grep w ]; then echo "writeable"
>

Now I get a prompt to type something, a >. The prompt tells me that the shell is waiting for me to enter something. The simplest form of the syntax of if is
if condition; then command; fi
so the shell is waiting for the fi. If I enter it at the prompt, I get this:
$ if [ namei -m file | grep w ]; then echo "writeable"
> fi
bash: [: missing `]'
grep: ]: No such file or directory

Looks like the pipe | is causing problems here, since [ can't find its last argument, and grep thinks its last argument is ]. Since [ (or the one we're using here anyway) is a shell builtin, we should be able to get some information about it using help
$ help [
[: [ arg... ]
    Evaluate conditional expression.

    This is a synonym for the "test" builtin, but the last argument must
    be a literal `]', to match the opening `['.

We can't use a pipe in the middle of a command's arguments. In other situations, we might be able to put the commands in a subshell by enclosing them in ( ), but that is a syntax error in [ (and test).
The real problem here is that what we are trying to pass to the [ command is not something it can evaluate as true or false. If the argument you try to pass to test is a command, test does not use the exit status of that command as I think you are expecting. You can pass the output of a command to [ using command substitution, but that is not what you or your code want(s) to do.
I think what your code is trying to do is check that grep found a w in the output of namei -m somefile. We don't need the test command for that at all.
$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
    Execute commands based on conditional.

   The `if COMMANDS' list is executed.  If its exit status is zero, then the
   `then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list is
   executed in turn, and if its exit status is zero, the corresponding
   `then COMMANDS' list is executed and the if command completes.  Otherwise,
   the `else COMMANDS' list is executed, if present.  The exit status of the
   entire construct is the exit status of the last command executed, or zero
   if no condition tested true.

So if we are only interested in whether a command succeeds, we can put the command as a condition for if:
$ if namei -m file | grep w; then echo "writeable"; fi
 -rw-rw-r-- file
writeable

You can even use -q to suppress output from grep and collect only its exit status (success if a match is found):
$ if namei -m file | grep  -q w; then echo "writeable"; fi
writeable

But that's not a good way to test whether the file is writeable by you. Let's try another test file:
$ touch file_with_w
$ chmod 444 file_with_w
$ stat -c %A file_with_w
-r--r--r--
$ if namei -m file_with_w | grep  -q w; then echo "writeable"; fi
writeable

If we parse the output of namei -m for a file with a w in its name, this method will make it appear to be writeable even if it is read only for everyone.
Parsing the output of commands is sometimes the right way to get the information you want. But there is usually a better way, in the form of an option to that command, or a different command with a similar purpose.
Let's go back to test aka [ command and see if it has any useful options. You can enter help test, or for more detail read the Conditional Expressions section of the Bash manual
File operators:
...
   -w FILE        True if the file is writable by you.

Aha! the test command has exactly what we want, as mentioned in answer to Checking for a file and whether it is readable and writable
$ if [ -w file ]; then echo "writeable"; fi
writeable
$ if [ -w file_with_w ]; then echo "writeable"; fi
$

That's right :)
But you mentioned that you wanted the command to output an error message if the file is not writeable, rather than a statement that it is writeable. For that we need an else statement
$ if [ -w file_with_w ]; then echo "writeable"; else echo "not writeable"; fi
not writeable

As a script, you could write that command like this:
#!/bin/bash

if [ -w "$1" ]; then
   echo "writeable"
else
   echo "not writeable"
fi

Then you could give it execute permission (replace script with the actual filename)
chmod u+x script

and run it with the file you want to test as its argument (referenced in the script with $1):
$ ./script file
writeable
$ ./script file_with_w
not writeable

If you only want to get an error message when the file is non-writeable, and no output when it is, you can negate the test condition instead of writing an else:
$ if [ ! -w file_with_w ]; then echo "not writeable"; fi
not writeable

As Panther mentioned in a comment, you might also want to make use of the variable $USER, which should expand to the name of the user running the shell. You can thus make a more impressive error message:
$ if [ ! -w file_with_w ]; then echo "file is not writeable by $USER"; fi
file is not writeable by zanna

For simple test commands, you can also use [ and test and [[ without if, and use shell operators for the logic:
$ [ -w file_with_w ] || echo "not writeable"
not writeable

|| is the shell's logical OR. It means if the previous command failed, then execute the next command
The shell's logical AND is &&:
$ [ ! -w file_with_w ] && echo "not writeable"
not writeable

&& means if the previous command succeeded, then execute the next command
All of this works because the test command gives a helpful exit status as described in help test:
Exit Status:
Returns success if EXPR evaluates to true; fails if EXPR evaluates to
false or an invalid argument is given.


text:
Q: tow button_click_event crushing together I have tow on_click event in one activity linked to tow different buttons but what happened is when I press the first or second button the first on_click event is the one who is working!! here is the java code:
TextView user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_activity);
        user=findViewById(R.id.textView);
        Intent i = getIntent();
        String msg = i.getStringExtra(("msg"));
        user.setText("welcome"+" "+msg+" choose a category");
    }
    public void science(View v){
        Intent i = new Intent(this,science_first_activity.class);
        startActivity(i);
    }
    public  void art(View v)
    {
        Intent i = new Intent(this,art_first_activity.class);
        startActivity(i);
    }

and here is the xml:
<Button
        android:id="@+id/button_s"
        android:layout_width="258dp"
        android:layout_height="65dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="77dp"
        android:layout_marginLeft="77dp"
        android:layout_marginEnd="76dp"
        android:layout_marginRight="76dp"
        android:layout_marginBottom="437dp"
        android:onClick="science"
        android:text="science" />

<Button
        android:id="@+id/button_a"
        android:layout_width="258dp"
        android:layout_height="65dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="77dp"
        android:layout_marginLeft="77dp"
        android:layout_marginEnd="76dp"
        android:layout_marginRight="76dp"
        android:layout_marginBottom="328dp"
        android:onClick="art"
        android:text="art" />

no matter what button I click he will keep go to the science activity!

A: Start activity if view id are equal to avoid that.
 public void science(View v){

    if(view.getId==R.id.button_s){
            Intent intentS = new Intent(this,science_first_activity.class);
            startActivity(intentS );
        }}

        public  void art(View v)
        {
    if(view.getId==R.id.button_a){
            Intent intentA = new Intent(this,art_first_activity.class);
            startActivity(intentA );
        }}


text:
Q: How do some websites play video inline in iOS Safari? Pretty incredible since I thought all videos expanded to play fullscreen in regular safari. Check this out for example:
https://entertainment.theonion.com/the-onion-reviews-rogue-one-1819596116
That video plays inline and doesn't even stop when I switch Safari tabs. What's happening there? Are they using js and HTML5 canvas to render the video or something? How do they sync the sound so well?

A: Just constructing an answer based on the link @offbeatmammal posted in his comment.
Also based on new video policies for ios specifically that:

On iPhone, <video playsinline> elements will now be allowed to play inline, and will not automatically enter fullscreen mode when playback begins.
<video> elements without playsinline attributes will continue to require fullscreen mode for playback on iPhone.
When exiting fullscreen with a pinch gesture, <video> elements without playsinline will continue to play inline.

A note about the playsinline attribute:

this attribute has recently been added to the HTML specification, and WebKit has adopted this new attribute by unprefixing its legacy webkit-playsinline attribute. This legacy attribute has been supported since iPhoneOS 4.0, and accordance with our updated unprefixing policy, we're pleased to have been able to unprefix webkit-playsinline. Unfortunately, this change did not make the cut-off for iOS 10 Developer Seed 2. If you would like to experiment with this new policy with iOS Developer Seed 2, the prefixed attribute will work, but we would encourage you to transition to the unprefixed attribute when support for it is available in a future seed.

Lastly an example:
<video autoplay loop muted playsinline>
  <source src="image.mp4">
  <source src="image.webm" onerror="fallback(parentNode)">
  <img src="image.gif">
</video>

with a fall back that displays an image on video error
function fallback(video)
{
  var img = video.querySelector('img');
  if (img)
    video.parentNode.replaceChild(img, video);
}


text:
Q: error: use of undeclared identifier 'FT_Get_Var_Axis_Flags' I try to compile skia on Linux with these arguments:
cc = "clang"
cxx = "clang++"
target_os = "linux"
target_cpu = "x64"
is_debug = false
extra_cflags = [ "-I/path/to/freetype2/include/freetype" ]

But I am getting this error message
../../src/ports/SkFontHost_FreeType.cpp:1775:24: error: use of undeclared identifier 'FT_Get_Var_Axis_Flags'
        bool hidden = !FT_Get_Var_Axis_Flags(variations, i, &flags) &&
                       ^
../../src/ports/SkFontHost_FreeType.cpp:1776:32: error: use of undeclared identifier 'FT_VAR_AXIS_FLAG_HIDDEN'
                      (flags & FT_VAR_AXIS_FLAG_HIDDEN);
                               ^
2 errors generated.

I am sure the path to the include directory of freetype2 is correct. I also tried the path /path/to/freetype2/include but none of them helped.
Any idea how to solve this problem ?

A: you need to update your system freetype to 2.8.1 to use FT_Get_Var_Axis_Flags & FT_VAR_AXIS_FLAG_HIDDEN


text:
Q: Was the Skyrim Intro dialogue ever changed? Skyrim was released in 2011 and I played it when it was new.
I turned it back on recently and watched the legendary Hey you, you're finally awake opening scene. The player character is tied up on a wagon with Ulfric Stormcloak, a Stormcloak soldier named Ralof, and a horse thief named Lokir.

Lokir: Damn you Stormcloaks. Skyrim was fine until you came along. Empire was nice and lazy. If they hadn't been looking for you, I could've stolen that horse and be halfway to Hammerfell. You there. You and me - we shouldn't be here. It's these Stormcloaks the Empire wants.
Ralof: We are all brothers and sisters in binds now,

The and sisters part sticks out at me. Was it in the original script? Or is it an edit since the game came out?
It is appropriate since the player race/gender is not decided at this point. Of course if you decide you're playing a man the line then sounds strange. It would make more sense to edit the horse thief to be a woman. That way Ralof is referring to himself, the horse thief and my undetermined friend over here. . . .

A: As videos of the Skyrim intro such as this one easily prove, the dialogue on launch day was exactly as you quoted it in the question.

A: Brothers and sisters are fitting seeing that on the other carts there are female prisoners. And as Wrigglenite stated in his answer there is a video that shows it was always intended to be so.


text:
Q: Compute $\int_{-\infty}^{\infty} \frac{e^{-2ix}}{x^2 + 4}dx$ using contour integration I'm studying for an applied mathematics qualifying exam, and have the following practice problem:

Compute the integral $\int_{-\infty}^{\infty} \frac{e^{-2ix}}{x^2 + 4}dx$ using contour integration.

I'm considering a contour that is a half-circle of radius $R$ that includes a segment of the real line ($[-R, R]$) and within the path includes the pole at $2i$. Using the Cauchy integral formula I can evaluate this integral and determine that it equals $\frac{e^4\pi}{2}$.
The next step is to show that the complex part of the path of integration is negligible, and I have tried to bound $\left|\int_{Re^{i[0,\pi]}} \frac{e^{-2iz}}{z^2 + 4}dz\right|$ but it doesn't seem to work.
Help?

A: Hint. Note that along the LOWER semicircle of radius $R>0$, $z=R(\cos(t)+i\sin(t))$ with $t\in [\pi,2\pi]$  and
$$|\exp(-2iz)|=|\exp(-2iR(\cos(t)+i\sin(t))|=\exp(2R\sin(t))\leq 1.$$
Now are you able to show that the integral along the semicircle part of the path of integration is negligible?
P.S. By considering the LOWER semicircle, you will also get the correct result of the integral
$$\int\limits_{-\infty}^{+\infty}\frac{e^{-2xi}}{x^2+4}dx=-2\pi i\mbox{Res}\left(\frac{e^{-2iz}}{z^2+4},-2i\right)=
-2\pi i\cdot \frac{e^{-2i(-2i)}}{2(-2i)}=\frac{\pi e^{-4}}{2}.$$

A: $$\int\limits_{-\infty}^{+\infty}\frac{e^{-2xi}}{x^2+4}dx=\int\limits_{-\infty}^{+\infty}\frac{\cos2x-i\sin2x}{x^2+4}dx=\int\limits_{-\infty}^{+\infty}\frac{\cos2x}{x^2+4}dx=$$
$$=2\int\limits_{0}^{+\infty}\frac{\cos2x}{x^2+4}dx=\frac{\pi}{2e^4},$$
where the last integral it's just the Laplace's integral. For $a>0$ and $b>0$ we have:
$$\int\limits_0^{+\infty}\frac{\cos{bx}}{x^2+a^2}dx=\frac{\pi e^{-ab}}{2a}.$$

A: Suppose that your half-circle is in the lower half-plane. Then, if $|z|>1$, you have$$\left|\frac{e^{-2iz}}{z^2+1}\right|=\frac{e^{\operatorname{Re}(-2iz)}}{|1+z^2|}=\frac{e^{2\operatorname{Im}(z)}}{|z^2+1|}\leqslant\frac1{|z|^2-1}\to0\text,$$as $z$ goes to $+\infty$.


text:
Q: Wildcard Help for find and replace I have thousands of these records in a text file:
ROESImageCameraMake=�iP{��!-T�x0�
ROESImageCameraModel=��O�W�

ROESImageCameraMake=��%.Bph�����
ROESImageCameraModel=�d�

Notice that the value is different in every case (all 1000+ entries).  I need to do a find and replace in Notepad++ to give me this:
ROESImageCameraMake=Nikon
ROESImageCameraModel=D100

I am not familiar with Regex.

A: Find: ROESImageCameraMake=.*
Replace: ROESImageCameraMake=Nikon
Make sure to tick "Regular expression" at the bottom.
This is based on your comment that you want to replace random junk with always Nikon


text:
Q: Castle Windsor: How to release instance with PerThread lifestyle i'm using Castle Windsor with PerThread lifestyle in a windows service.
When a new thread worker is started, a new instance is created by windsor, but never disposed and stays in memory for the entire life-cycle of our win-service.
I've seen in the Windsor documentation that:

Releasing the component explicitly does nothing. Instances will be
  released when the container they're registered with is disposed

But in our case - i need to release a PerThread instance at the end of the thread work. Therefore we cannot dispose the entire container - which will dispose all the needed instances of other threads or any resolved instances at all.

A solution which will require disposing a child containers etc - seems to be too complex and not really effective for our per-thread need.
For now we really concern about the amount of instances that will be hold in the IOC container till the windows service will be stopped.
Questions:

1. Is there a way to achieve this action - to release the specific per-thread instance from the IOC container in order that it will be disposed by the GC?

2. Is there a preferred way to solve this issue by a custom lifestyle or something similar to this?

3. I've read about a way that may be right for our case - using "Scoped" lifestyle and calling "Container.BeginScope()" at the beginning of the thread worker, and dispose the scope at the end of the thread's work.
 But i'm not familiar with this lifestyle and if its thread-safe and won't cause any problems using this option in a thread context.
TNX.
Update 1:
Here's a basic example which reflects our case flow.
 // This is a thread worker logic.
// We need that IConfig will be the same instance for the entire thread's context.
public void ThreadWorker(object manager)
{
    // Init config object.
    var config = Container.Resolve<IConfig>();
    // Updating states in config
    config.init(manager);

    // working.
    doSomeLogics(manager.services);
}

private void doSomeLogics(List<IService> services)
{
    foreach (Iservice curService in services)
    {
        curService.Execute();
    }
}

// Each IService implementor comes from external dlls and cannot be changed since its decoupled from our main app.

public class Service1 : IService
{
    public void Execute()
    {
        // Use the IConfig instance which need to be the same instance per thread.
        IConfig curConfig = Container.Resolve<IConfig>();

        // using the curConfig properties to do a specific work...
    }
}

public class Service2 : IService
{
    public void Execute()
    {
        // Use the IConfig instance which need to be the same instance per thread.
        IConfig curConfig = Container.Resolve<IConfig>();

        // using the curConfig properties to do a specific work...
    }
}


text:
Q: Axiom of Choice (Naive Set Theory, Halmos) I'm currently reading Naive Set Theory by Paul Halmos and I'm not quite understanding what he means in sec. 15, The Axiom of Choice.

Suppose that $\mathscr{C}$ is a non-empty collection of non-empty sets. We may regard $\mathscr{C}$ as a family, or, to say it better, we can convert $\mathscr{C}$ into an indexed set, just by using the collection $\mathscr{C}$ itself in the role of the index set and using the identity mapping on $\mathscr{C}$ in the role of the indexing.

This much I understand, essentially $\mathscr{C}_{x}=x$ (correct me if I'm wrong).

The axiom of choice says that the Cartesian product of the sets of $\mathscr{C}$ has at least one element. An element of such a Cartesian product is, by definition, a function (family, indexed set) whose domain is the index set (in this case $\mathscr{C}$) and whose value at each index belongs to the set bearing that index. Conclusion: there exists a function $f$ with domain $\mathscr{C}$ such that if $A \in \mathscr{C}$, then $f(A) \in A$.

I'm a little confused by the manner in which we define the Cartesian product of a family of three sets or more. Do we define it as $A \times B \times C = \{(a,b,c) \; \; | \; \; a \in A , b \in B, c \in C\}$?
My understanding was that a function consists of only ordered pairs, am I missing something here? Any help would be appreciated, thanks!

A: The set theoretic definition of an ordered pair is not such that allow a nice generalization for ordered tuples. So in order to define $A\times B\times C$ we need to choose, $A\times(B\times C)$ or $(A\times B)\times C$. Truly it doesn't matter one bit, since there is a very natural bijection between the two sets.
But then we move to longer and longer and longer products. And finally to infinite products, which we cannot even represent as repeated Cartesian products.
Instead we define a notion of $I$-tuples, where $I$ is any index set: If $I$ is our index set, and for every $i\in I$ we match some $A_i$, then the product $\prod_{i\in I}A_i$ is all the functions whose domain is $I$ and $f(i)\in A_i$. Then we redefine the product as the set of $2$-tuples, and product of three sets as $3$-tuples and so on. In the case of $A\times B\times C$ we have $I=\{0,1,2\}$ and $A_0=A,A_1=B,A_2=C$.
This notion also generalizes to infinite index sets quite easily, so we can define $I$-tuples when $I$ is any set.
But note that if $I$ is given, and $A_i$ are given, and all are non-empty, then an $I$-tuple is really a choice function on the family $\{A_i\mid i\in I\}$. And the axiom of choice really just says that given any such family their product is non-empty, that is to say that there is some choice function on this family.
If the family is finite, then we can prove this without using the axiom of choice. It's quite easy. But if the family is infinite, then we can prove that we have to use the axiom of choice to prove that their product is non-empty.

A: Note that, for your example, one can define
$$A\times B\times C:=\left\{\;f:\{1,2,3\}\to A\cup B\cup C\;\;:\;\;f(1)\in A\;,\;f(2)\in B \;,\;f(3)\in C\;\right\}$$
The above, of course, is way more cumbersome than the usual definition you wrote since this is a finite, easy-to-grasp, example.
Thus, in your example, the element $\;(a,b,c)\;$ would be represented by the function
$$f:\{1,2,3\}\to A\cup B\cup C\;\;s.t.\;\;  f(1)=a\in A\;,\;\;f(2)=b\in B\;,\;\;f(3)=c\in C$$


text:
Q: How can I catch the Print option being selected in the File menu/tab in Word 2016 (backstage view)? The following code opens the screen I want to detect being opened:
Sub Test()
  Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")
End Sub

It does not seem to activate a CommandBarButton object I can create an event handler for. Any thoughts on how to do this without having to change the structure of the File Tab because this is only relevant for one document. The goal is to be able to set duplex printing before the document is printed while the standard File->Print option can still be used.

A: You can go old school. Before there were events to trap it was common to intercept commands simply by creating a routine with the same name.
For example:
Public Sub PrintPreviewAndPrint()
   MsgBox "Hello!"
End Sub

Alternatively, you can trap the DocumentBeforePrint event, though this will only fire after the dialog has been executed.

A: There is no way to repurpose backstage UI controls, but you can create your own UI instead. So, a better solution would be to consider hiding the built-in UI and rebuilding it fully with custom commands. The Introduction to the Office 2010 Backstage View for Developers article explains the basics of building a custom backstage UI.
The Application.DocumentBeforePrint event allows canceling the default action, so you can programmatically print the document in the way you want by using the PrintOut method.
Public WithEvents appWord as Word.Application

Private Sub appWord_DocumentBeforePrint _
 (ByVal Doc As Document, _
 Cancel As Boolean)

 Dim intResponse As Integer

 intResponse = MsgBox("Have you checked the " _
 & "printer for letterhead?", _
 vbYesNo)

 If intResponse = vbNo Then Cancel = True
End Sub


text:
Q: Retain cycles when using addObserverForName:object:queue:usingBlock: I am new to programming with block. I have following code (not using arc) in my Listener class:
- (void)someBlock:((void)^(NSDictionary *)myDictionary)myBlock
{
    __block Listener *weakSelf = self;
    weakSelf = [[NSNotificationCenter defaultCenter]
                   addObserverForName:@"MyNotification"
                               object:nil
                                queue:nil
                           usingBlock:^(NSNotification *note)
        {
            //--- Here have the retain cycles
            myBlock(note.userInfo);
            [[NSNotificationCenter defaultCenter] removeObserver:weakSelf
                                                            name:@"MyNotification"];
        }];
}

and in my DoMyStuff class:
... some code
Listener *myListener = [[[Listener alloc] init] autorelease];
[myListener someBlock:((void)^(NSDictionary *)myDictionary)myBlock{
    [self.someProperty doSomething:myDictionary];
}];

Can anyone tell me the right direction to solve the retain cycles?
I have checked these two questions

*

*"Correct management of addObserverForName:object:queue:usingBlock:"

*"Why doesn't Remove Observer from NSNotificationCenter:addObserverForName:usingBlock get called"
but they did not use block inside another block, so, the solutions there don't work for me.

A: The problem here is that you are using [self.someProperty doSomething:myDictionary]; inside block thus retaining self. Note that using ivars will lead to retain cycles as it's the same as self->ivar.
Usually it looks like this (__weak/__unsafe_unretained is for ARC, __block for MRR)
__weak ClassName *weakSelf = self;
[SomeClass someMethodWithBlock:^{
    // use weakSelf here; if you want to make sure that self is alive throughout whole block, do something like ClassName *strongSelf = weakSelf;
}];

There is nice library https://github.com/jspahrsummers/libextobjc which has @weakify/@strongify macroses for this(probably ARC only).
Also you should use ARC if possible(it is available from iOS 4, if I remember correctly and has __weak from iOS 5, which should be fine these days).


text:
Q: Trying to pass id variable from 'accounts' table to app.blade with undefined variable error I am trying to pass the id variable from the accounts table to the app.blade view to specify a custom URL for each user.  I am trying to store it in $account, but I am obviously not doing something right.
Error Message: Undefined variable: account (View: /home/vagrant/www/upsapp/resources/views/layouts/app.blade.php) (View: /home/vagrant/www/upsapp/resources/views/layouts/app.blade.php)
app.blade
<a class="navbar-brand" href=" {{ url('/account/'.$account->id).'/' }}">
   {{ $account->accountname}}
</a>

Original AccountController
<?php

namespace App\Http\Controllers;

use App\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;

class AccountController extends Controller
{
    public function __construct()
    {
    $this->middleware('auth');
    }

public function index()
    {
    $result = Auth::user()->account()->get();
    if(!$result->isEmpty()){
        return view('account.dashboard',['account'=>$result,'image'=>Auth::user()]);
    }
    else{
        return view('account.dashboard',['account'=>false,'image'=>Auth::user()]);
    }
}

Updated AccountController
public function index()
{
$result = Auth::user()->account()->get();
    if(!$result->isEmpty()){
        return view(layouts.app,['account'=>$result,'image'=>Auth::user()]);
    }
    else{
        return view(layouts.app,['account'=>false,'image'=>Auth::user()]);
    }
}

Account.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
protected $table = 'accounts';

protected $fillable = ['id', 'accountname',  'address1', 'address2', 'city', 'state', 'zip', 'accountalpha', 'accountnotes'];

public function account()
    {
    return $this->hasMany('App\User');
    }
}

Routes
Route::get('/', function () {
return redirect('/login');
});

Auth::routes();

Route::resource('account','AccountController');

Route::get('/home', 'HomeController@index');

'accounts' table
Schema::create('accounts', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('accountname');
        $table->string('accountalpha')->nullable();
        $table->string('address1');
        $table->string('address2');
        $table->string('city');
        $table->string('state');
        $table->integer('zip');
        $table->string('accountnotes')->nullable();
        $table->timestamps();
    });

'users' table
Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('email')->unique();
        $table->string('phonenumber');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
        $table->integer('account_id');

        $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');


text:
Q: Writing Queries in sqlite with vb.net & uwp I have searched most of SO, and spent countless hours googling, so I'm going to post in the hopes that someone can help or just tell me it can't be done!
I am trying to make my vb.net uwp application be able to query a local sqlite database with a test query, but I am at a complete loss trying to find an example or any sort of documentation that isn't in c# without a clear parallel to how to translate to vb.net.
I have a base test class that can successfully connect with my database file, but I can't find anywhere how to do a query - all the resources online just link me to either vb.net without uwp or c# with uwp! I'll paste my code, but links to any resources or any advice would be so so helpful :)
Public Class dtbTest
Private conn As SQLiteConnection
Private sqcommand As SQLiteCommand
Private query As String = "SELECT * FROM userdetails"
Private cnn As SQLiteConnection
Private DBConnection As String = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "test.s3db")
Private tableInfo As List(Of SQLiteConnection.ColumnInfo)

Public Sub New()
    Try

        conn = New SQLiteConnection(DBConnection)
        conn.BeginTransaction()
        tableInfo = conn.GetTableInfo("userdetails")
        sqcommand.CommandText = query
    Catch

    End Try
End Sub

End Class

A: In case people are interested, I got it working by trying the new Microsoft.Data.SQL package, so would recommend checking that if anyone is having similar problems!


text:
Q: Android : Read ChekboxPreference value from Service I have an Android Service which implements SensorEventListener for detecting motion. I've a CheckBoxPreference where user can choose to enable or disable motion detection. The problem I'm facing is that I'm not able to get the correct value in the service, namely in the OnSensorChanged method.
The service is started as soon as the application is launched. There is an activity which starts the service, and is binded with it.
Service where I detect the motion change:
    public class MotionService extends Service implements SensorEventListener{

     public static int SHAKE_THRESHOLD = 0;
    public static boolean SHAKE_ENABLE = false;
 @Override
    public void onCreate() {
        if (D) Log.d(TAG, "Creating service");
        super.onCreate();
 SHAKE_THRESHOLD = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("shake_threshold",60)*10;
        SHAKE_ENABLE = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("shake_enable",false);
}

    @Override
        public void onSensorChanged(SensorEvent event) {
            Sensor mySensor = event.sensor;

            if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                long curTime = System.currentTimeMillis();
                if ((curTime - lastUpdate) > 100) {
                    long diffTime = (curTime - lastUpdate);
                    lastUpdate = curTime;

                    float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000;

                    Log.d("Sensor Changed",SHAKE_THRESHOLD+"================="+SHAKE_ENABLE); //values here remain the same ones i assign on OnCreate, even though i change it in the settings. It should change when i change from settings. NOT HAPPENING!!

                        if (speed > SHAKE_THRESHOLD) {
                            //do sensor related stuffs here
                            if (SHAKE_ENABLE) { //the boolean value i get from the preferences

                                if ((x) > 8.0000) {
                                    Log.d("sensor", "=====LEFT====");

                                } else if ((x) < -8.0000) {
                                    Log.d("sensor", "=====RIGHT====");

                                } else if ((z) < -0.0) {
                                    Log.d("sensor", "=====UP====");

                                } else if ((y) < 1.0) {
                                    Log.d("sensor", "=====DOWN====");

                                }
                            }
                            last_x = x;
                            last_y = y;
                            last_z = z;
                        }
                }

            }

        }
    }

And this is my preference activity:
public class SettingsActivity extends PreferenceActivity {
@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Fade it in
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        addPreferencesFromResource(R.xml.settings);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("shake_enable");

        checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());
                if (newValue.toString().equals("true")){
                    MotionService.SHAKE_ENABLE=true;
                    Log.d("SHAKE_ENABLE",MotionService.SHAKE_ENABLE+"================="+MotionService.SHAKE_THRESHOLD);
                    MotionService.SHAKE_THRESHOLD = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("shake_threshold",60);
                }
                else{
                    MotionService.SHAKE_ENABLE=false;
                    Log.d("SHAKE_ENABLE",MotionService.SHAKE_ENABLE+"================="+MotionService.SHAKE_THRESHOLD);
                    MotionService.SHAKE_THRESHOLD = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt("shake_threshold",60);
                }
                    return true;
            }
        });
    }

So when I check and unchek, the logs from the SettingsActivity show that values of MotionService.SHAKE_ENABLE and MotionService.SHAKE_THRESHOLD are changed, but it is not reflected in the OnSensorChanged method of the MotionService.
Where am I going wrong? Help Appreciated!

A: Why you even bother checkbox? if this is your preference checkbox then each change is reflected in your app's preferences. So basically just read current state of your preference


text:
Q: Matrix powers sequence bounded Let $m\in\mathbb{N}^*$ and $A\in\mathcal{M}_m(\mathbb{C})$ such that the matrix sequence $(A^n)_{n\geq 0}$ is bounded. Is the sequence $(\|A\|^n)_{n \geq 0}$ bounded ?

A: It does not need to be. Take
$$
A = \begin{bmatrix} \alpha & 1 \\ 0 & \alpha\end{bmatrix}, \qquad 0<\alpha<1.
$$
Then $A^n\rightarrow 0$ as $n\rightarrow\infty$ and hence $(\|A^n\|_2)_{n\geq 0}$ is bounded, while $\|A\|_2>1$ and hence $\|A\|^n_2\rightarrow+\infty$.


text:
Q: jquery | To make show() and hide() using divs I had a html code which i have to make divs show() and hide() as a list. I know how to make show() and hide() but i'm not familiar with html structure.
This is the my html code.

FAQ

자주하는 질문?

자주하는 질문?
답변
답변
답변
답변
답변

자주하는 질문?

자주하는 질문?
답변
답변
답변
답변
답변

자주하는 질문?

자주하는 질문?
답변
답변
답변
답변
답변

자주하는 질문?

자주하는 질문?
답변
답변
답변
답변
답변

자주하는 질문?

자주하는 질문?
답변
답변
답변
답변
답변


text:
Q: Cannot find element for Selenium on a website on Chrome So I'm trying to create a Selenium automation in Python but I can't for the life of me figure out where the xpath/class/id/etc for the username or password fields are. I'm trying to work with this page here. It is the login page to redeem Marvel comic codes. Thanks so much for the help.

A: It is in iframe, so you would have to switch the driver focus to iframe first and then can interact with username and password field :
Code :
wait = WebDriverWait(driver, 10)
driver.get("https://www.marvel.com/signin?referer=http%3A%2F%2Fwww.marvel.com%2Fredeem")
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "disneyid-iframe")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='email']"))).send_keys('some username')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='password']"))).send_keys('some password')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[ng-click]"))).click()
driver.switch_to.default_content()

Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: searching for space separated words in Elasticsearch my data is,
POST index_name/_doc/1
{
          "created_date" : "2023-02-09T13:21:41.632492",
          "created_by" : "hats",
          "data" : [
                        {
              "name" : "west cost",
              "document_id" : "1"
            },
            {
              "name" : "mist cost",
              "document_id" : "2"
            },
            {
              "name" : "cost",
              "document_id" : "3"
            }
          ]
        }

i used query_String to search
GET index_name/_serach
{
    "query_string": {
       "default_field": "data.name",
        "query": "*t cost"
    }
}

expected result was:
west cost, mist cost
but the output was:
west cost, mist cost, cost
i have tried many search query but still couldn't find a solution
which search query is used to handle the space, i need to search for the similar patterned value in the field

A: elasticsearch will return you the documents that satisfy the query, and your document 1 does satisfy the query, i.e., there is at least one item in the data array that has a name ending by *t cost. If you want only the first two data items to be returned in your response, you need to index each item independently in a separated document


text:
Q: Is there any faster algorithm to find approx value of log(n) and what will be time complexity of that? Is there any faster algorithm to find approx value of log(n) and what will be time complexity of that ?
I just want approx integer value of log(n) and inbuilt function log(n) in java gives ans with  approximate accuracy in double which is useless for me and it take much time. since log and multiplication are is one of the primary function in my program and but log make my program too much slow.
here some benchmark

Multiply  took: 466 milliseconds
Logarithm took: 3245 milliseconds

it's approximate 10 time of multiplication.
(Note:-here i used benchmark to just show that it took too much time compare to other primary function of my program and i know it is not possible to compare two different type of function)
so i want to know is there any faster algorithm to find approx value of log(n) and what will be time complexity of that ?
(Note :- algorithm should work for log() with any base)

A: I have no idea if it will actually be faster, but assuming you have an integer x and you want its log in base k:
log_k(x) = log_2(x)/log_2(k)

Note that for any i, floor(log_2(i)) is the 'index' of the most significant none zero bit


text:
Q: Proof of frustum surface area I found a proof for surface area of a conical frustum and I do not understand the first proportion from which everything else is derived. Can anyone explain that?

A: Since the right triangle $VOB$ is similar to the right triangle $A'AB$ ($OB$ and $O'A'$ are coplanar and both perpendicular to $VO$), it follows that
$$\frac{L_1}{R}=\frac{|VB|}{|OB|}=\frac{|A'B|}{|AB|}=\frac{L}{R-r}.$$


text:
Q: Excel (Dependent) Data Validation Across three seperate fields I am looking to create a data validation formula which will allow me to check against multiple fields.
Amount Claimed, Amount Approved, Amount Paid.
The Amount Claimed is first entered. From there, the amount Approved is entered. This can be less than or equal to the claimed amount.
The amount paid is then entered. This again can be less than or equal to the amount Approved.
I noticed in my initial review of the sheet, I could have an amount claimed, and an amount paid input without the approved input. This caused a hiccup in my sheet.
I need a dependent data validation, right? I am not sure how to set it up that I can't have a Paid entry  without the Approved entry.
Hopefully this is clear enough. Thanks!

A: When you go to set up the data validation, you want to go to
Allow: whole number and
Data: less than or equal to.
Put the Maximum: as =A1 or whatever cell the first number is in.
The just do the same for the C1, but reference =B1 as the maximum


text:
Q: Reason why function P is a primitive function I am supposed to give reasons why function P is a primitive function. I have to explain it as a general method for determination of area or volume of geometric figures.
What I have so far:
Function f is nonnegative function, which is continous on interval [a,b]. For  every  $$  t \epsilon [a,b]$$ we label P(t) as area of figure given by these conditions:  $$ \left \{ [x, y]; a\leq x\leq t, 0\leq y\leq f(x)  \right \} $$
For h>0 we have: P(t+h)-P(t) is area of figure given by:  $$ \left \{ [x, y]; t\leq x\leq t+h, 0\leq y\leq f(x)  \right \} $$
And now I know that I have to use continuity of function together with  $$ \varepsilon ,\delta  $$ and make a conclusion.
This is the description with the picture. But I am not sure if I get it right, or I think that I understand the explanation of the picture, but I have a feeling that I do not understand the whole idea behind it.
Can anyone please describe it?


text:
Q: ¿Se puede cambiar los atributos src, width y height de una imagen que ya antes le asigné atributos diferentes? Intento setear nuevos valores a una imagen con JS, primero al crear el objeto sí se asignan pero al quererlos cambiar no se aplican, tengo duda en si es posible desde JS o tengo que usar CSS.
El src de la img es obtenido del valor del atributo de un Objeto, el constructor de la clase es: (id, name, position, level, imgFront, imgBack)
var $img1  = document.getElementById('img1')
var $img2  = document.getElementById('img2')
//a las imagenes se les asignará el valor de un objeto y atributos de dimensión
//en el HTML no tienen mas que el "id"

function setImgAttributes($element, attributes) {
    for(let attribute in attributes)
        $element.setAttribute(attribute, attributes[attribute])
}

function imgTurno1() {
    setImgAttributes($img1, {
        src: `${person1.imgBack}`,
        width: 150,
        height: 150,
    })
    setImgAttributes($img2, {
        src: `${person2.imgFront}`,
        width: 120,
        height: 120,
    })
}

function imgTurno2() {
    setImgAttributes($img1, {
        src: `${person1.imgFront}`,
        width: 120,
        height: 120,
    })
    setImgAttributes($img2, {
        src: `${person2.imgBack}`,
        width: 150,
        height: 150,
    })
}

//después de instanciar los objetos se asignan los primeros valores sin problema
imgTurno1()

//durante el proceso al interactuar se intenta setear nuevos valores a la imagen pero no se aplican
imgTurno2()

Si lo intento por separado en la consola del navegador si me aplica los cambios pero me arroja esta alerta:

"Uncaught TypeError: Assignment to constant variable. at <anonymous>"

$img2 = setImgAttributes($img2, {
        src: `${person2.imgBack}`,
        width: 150,
        height: 150,
    })

En un principio si tenia declaradas las imagenes en js como const, pero despues de intentar esto en la consola las cambie a var. Esta es mi primer pregunta. Gracias desde ya!

A: Comunidad, una disculpa realmente el fragmento de código que tengo esta correcto y se puede aplicar sin problemas.
El error lo tuve por estar buscando los resultados al probar el archivo equivocado en lugar del archivo local.(ya saben cosas de novatos)
No voy a borrar la pregunta por si en algún momento a alguien le sirve. A menos claro que algún moderador lo solicite.
function changePosition() {
    switch(turno) {
        case 1:
            imgTurno2()
            $img1.classList.toggle('rotar')
            $img2.classList.toggle('rotar')
            turno++
            break
        case 2:
            imgTurno1()
            $img1.classList.toggle('rotar')
            $img2.classList.toggle('rotar')
            turno--
            break
    }
}

En esa parte de la aplicación se iteran las imagenes llamando a esta función con el evento click a un botón.


text:
Q: ASP.NET - Overriding Javascript and Styleheets cached by browser I'm working on an asp.net website. I need to make sure my javascript and css updates will be immediately available for returning visitors, without them having to clear their cache to get the latest code. How can I force this when needed, and leave it alone on other occasions?
Thanks in advance.

A: Stackoverflow does this very elegantly IMO. You can see in there source there is a query-string variable passed.
<script type="text/javascript" src="http://sstatic.net/js/stub.js?v=778aaf5a38e2"></script>

This will force new load if that changes.

A: In order to reliably force a refresh of cached content on the browser you need to change the name / requested URL of the file somehow.
Often this is done by appending a query string to the URL (which is often ignored)
See When Does Browser Automatically Clear JavaScript Cache? for a more complete discussion.

A: You'll need to apply no-cache header to those resources, alternatively make the url dynamic somehow.
see - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html


text:
Q: Using the model hook to load data dependent on another API call In an app I'm currently developing, I need to load some data before deciding what data to load next and display. My initial approach was to define a route with a dynamic section like this:
this.route( "chart", { path: "/chart/:type" } );

The idea would be to use type to download some metadata and then request the actual chart data based on the metadata. This is a bit awkward in Ember, at least to the extent of my knowledge, as it would require doing an AJAX request in a controller without using ember-data to wrap it.
As the chart will be displayed using the same code independently of the metadata and there are some interface elements that will be rendered based on that metadata, I thought it would be a good idea to use Ember's router to handle the calls doing something like:
this.route( "chart", { path: "/chart/" }, function () {
  this.route( "display-chart", { path: "/score/" } );
  this.route( "display-chart", { path: "/ranking/" } );
  this.route( "display-chart", { path: "/matches/" } );
} );

There is only a limited number of values for the dynamic segment so for each segment I will create a route handled by the same handler. The chart template will load the metadata and render the common UI elements, leaving the actual chart to the display-chart handler.
I have two questions:

*

*Using the first approach, a route with a dynamic segment, is it possible to load the additional data (which depends on first downloading metadata) within the model hook? Something like RSVP but using previously downloaded data to download the next bit.

*The second approach, using nested routes, is this the right way to do it? Can you think of any issues with this approach?

A: You could chain promises in your model hook, i.e.
model() {
  return this.get('ajax').request(/*some url*/).then(data => {

    /* Now here you can use your requested data
       to decide what to load in the store
       and then just return that promise back, like this:  */

    return this.store.findAll('someModel');

    /* The result of the model hook
       will be the result of the findAll method */
  })
}


text:
Q: Hardcopy of CDN assests , security , Production I have dotnet core server and I want to get jQuery and bootstrap files.
My question is: on a Production grad software, can I use hard-copy  and the server will update the hard-copy of the files on a daily basis from Microsoft CDN or should i follow the warning and let the client get his copy direct form the CDN?
Is there a security issue when using this method?
https://learn.microsoft.com/en-us/aspnet/ajax/cdn/overview
Warning :
Production applications should not take a hard dependency on CDN assets. Applications should test for the CDN asset referenced, and use a fallback asset when the CDN is not available.

A: Using a CDN isn't a security risk but it does mean your application wont work properly if the CDN provider is down (shouldn't happen often but can happen).
For why you would or wouldn't want to use a CDN, I'll defer to more informed folks
If you decide you want to avoid using a CDN, simply go to the CDN link you have, copy the text, save it to a file, and include that file in your app. Point all your links to this file instead of the CDN.
This will not "autoupdate" the file as you've asked for, but IMHO auto-updating a dependency like jQuery is a decidedly bad idea as doing so daily will almost certainly break your application at some point. Other libraries you use depend on specific versions of things, changing a dependency like that should be done with caution and tested thoroughly before release, definitely not via an automated process.
FYI, the CDN files you speak of should NEVER change. That is https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js will never change. The file content from CDN files are meant to remain constant always. If the library is updated, an NEW CDN file with a new name (probably with an updated version number) will be created but the old file will still be there with the old name and the same content.
Regarding this bit:

Warning : Production applications should not take a hard dependency on CDN assets. Applications should test for the CDN asset referenced, and use a fallback asset when the CDN is not available.

Basically, this seems to be saying, "Don't design you application where it simply links to the CDN file and if the file is not present, your app fails. Instead, link to the CDN but your code should check that that CDN file was loaded and if not, try to load it from a different location.
Personally, I prefer a local copy of the needed file (preferably minified) in most cases and avoid CDNs, unless I'm building something that has a specific need to keep the total project size as small as possible.


text:
Q: Why is scala.xml.Atom type-parameterized? I noticed that scala.xml.Atom takes a type parameter A, even though all of its subclasses extend Atom[String], and the documentation says "The class Atom provides an XML node for text (PCDATA)."
Are there legitimate use cases for instantiating an Atom with a type parameter other than string?
More concretely, I'm interested in using Scala XML literal to define sort of a nice DSL for defining an in-memory tree-based document structure, where many of the nodes would be existing scala classes. It would be super nice to use <document>{new JButton("Hi")}</document> and access the non-text data in the Atom[JButton] without having to define an XML serialization scheme for every existing class.
Is that a legitimate use case, or am I abusing the current implementation of Scala's XML library?

A: if you take a look into the sources the reason is revealled. Atom is generic because it converts the passed object to a String. So you can pass a JButton to it but then it will just call its toString method. (line 48 is what matters)
I guess it is possible to get the data back out of the atom:
val doc = <document>{ 42 }</document>

doc.child.head match {
  case i: Atom[Int] => i.data / 7
  case _ => error("Unsupported type")
}

returns 6. So your plan would work. I still think a tree based on abstract classes and case classes would be a better choice because with your method all type safety is gone as you can pass in everything, so that type errors will not be discovered until runtime.

A: If you look at http://sites.google.com/site/burakemir/scalaxbook.docbk.html?attredirects=0, you will find that Atom was indeed intended "for nodes containing data of any type, e.g. int, Date".
As you observed, embedded expressions inside elements are turned into atoms if they aren't strings, for example
<foo>{42}</foo>

has as child an Atom[Int].
To add an atom into an attribute value, you have to write
<foo life={new Atom(42)}>

(In the "book", it was just Atom(42), but that was then--Atom is no longer a case class since case class inheritance has been deprecated.)
So, yes, what you want to do is perfectly within the spirit of the design.
But the design is several years old, and a good number of people are unhappy about some of the decisions. The XML support in Scala might be cleaned up in the future, and this rather obscure feature might not survive.


text:
Q: Proxy HTTPS never receives data from either client or server My proxy HTTPS, dealing with CONNECT HTTP requests from client, does the following steps:

*

*opens a socket to remote server;

*sets the socket to non blocking mode;

*attempts connect() checking for if ((connect_res == -1) && (errno != EINPROGRESS));

*loops with select() checking if server socket is ready to send or receive data;

*sets socket back to blocking mode;

*sends "HTTP/1.1 200 Connection established\r\n\r\n"to the client after successfull connect();

*calls proxyHTTPS();
// if client sent a CONNECT request...
struct sockaddr_in remote_server, local_bind;
int conn_res, select_res;

memset(&remote_server, 0, sizeof(remote_server));
remote_server.sin_family = AF_INET;
remote_server.sin_addr.s_addr = rm.getServerAddr();
remote_server.sin_port = rm.getServerPort();

memset(&local_bind, 0, sizeof(local_bind));
local_bind.sin_family = AF_INET;
local_bind.sin_addr.s_addr = htonl(INADDR_ANY);
local_bind.sin_port = htons(0);

fd_set rdset, wrset;
struct timeval tv;

sockfd_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd_server < 0) {
    perror("socket: ");
}

// make socket not blocking
if(!setNonBlocking(sockfd_server))
    perror("fcntl");
debug_green("CONNECT set socket to non-blocking mode\n");

bind(sockfd_server, (struct sockaddr*) &local_bind, sizeof(local_bind));

conn_res = connect(sockfd_server, (struct sockaddr *)&remote_server, sizeof(struct sockaddr_in));
// The socket is nonblocking and the connection cannot be completed immediately
// check for EINPROGRESS
if ((conn_res == -1) && (errno != EINPROGRESS)) {
    debug_yellow("CONNECT attempting select()\n");
    do {
        FD_ZERO(&rdset);
        FD_SET(sockfd_server, &rdset);
        wrset = rdset;
        tv.tv_sec = 0;
        tv.tv_usec = 0;
        select_res = select(sockfd_server+1, &rdset, &wrset, NULL, &tv);
    } while ((select_res == -1) && (errno == EINTR));

    if ((!FD_ISSET(sockfd_server, &rdset)) && ((!FD_ISSET(sockfd_server, &wrset)))) {
        debug_red("SELECT sockfd non risponde\n");
        close(sockfd_server);
        sockfd_server = -1;
        return false;
    }

    /* repeat not blocking connect() to check if it gives error saying connection already happened (from my teacher's slides) */
    conn_res = connect(sockfd_server, (struct sockaddr *)&remote_server, sizeof(struct sockaddr_in));
    if (conn_res == -1)  {
        if(errno == EISCONN)
            printf ("connect(): connection already existing, OK\n");
        else  {
            printf("connect(): connection failed\n");
            close(sockfd_server);
            sockfd_server = -1;
            return false;
        }
    }
    printf("connection OK\n");
} else {
    debug_green("connected immediately\n");
}
if (!setBlocking(sockfd_server)) {
    perror("FCNTL:");
}
debug_green("CONNECT set socket back to blocking mode\n");fflush(stdout);
// #define CONNECT_200_OK HTTP/1.1 200 Connection established\r\n\r\n
std::string connect_200_to_client(CONNECT_200_OK);
int connect_200_to_client_send = send(new_sockfd_client, connect_200_to_client.c_str(), sizeof(connect_200_to_client), 0);
if (connect_200_to_client_send <= 0) {
    perror("CONNECT send() 200 OK to client failed");
    close(sockfd_server);
    sockfd_server = -1;
    return false;
}
// finally calling proxyHTTPS
hm.proxyHTTPS(new_sockfd_client, sockfd_server);

Now I should be ready to forward data from client to server and from server to client when data are available from one of the two sides of connection, but it never succeeds.
Here's the code that should forward data from both sides of connection:
void proxyHTTPS(int new_sockfd_client, int sockfd_server) {

printf("starting proxyHTTPS\n");
fd_set fdset;
int maxp1 = sockfd_server > new_sockfd_client ? sockfd_server+1 : new_sockfd_client+1;
int r;
int read_from_client = 0;
int read_from_server = 0;
int send_to_client = 0;
int send_to_server = 0;
struct timeval timeout;
char https_buf[4096];
int https_buf_size = sizeof(https_buf);
memset(https_buf, 0, https_buf_size);
// tried 0, 5, 10, 20, 30, 60 seconds timeout,
// still got this problem
timeout.tv_sec = 10;
timeout.tv_usec = 0;

while (true) {
    FD_ZERO(&fdset);
    FD_SET(new_sockfd_client, &fdset);
    FD_SET(sockfd_server, &fdset);
    timeout.tv_sec = 10;
    timeout.tv_usec = 0;

    r = select(maxp1, &fdset, NULL, NULL, &timeout);

    if (r < 0) {
        perror("select()");
        break;
    }

    if (r == 0) { // select timed out
        debug_yellow("proxyHTTPS: select() request timeout 408\n");
        break;
    }

    if ((!FD_ISSET(new_sockfd_client, &fdset)) && ((!FD_ISSET(sockfd_server, &fdset)))) {
        debug_red("proxyHTTPS: SELECT sockfds not responding\n");
        break;
    }

    else if (FD_ISSET(new_sockfd_client, &fdset)) {
        debug_green("proxyHTTPS: reading from client and sending to server\n");
        read_from_client = recv(new_sockfd_client, https_buf, https_buf_size, 0);
        if (read_from_client < 0) {
            debug_red("proxyHTTPS recv() from client " << strerror(errno) << '\n');
            break;
        }
        else if (read_from_client == 0) {
            debug_yellow("proxyHTTPS client closed conn\n");
            break;
        }
        else { // read_from_client > 0
            send_to_server = send(sockfd_server, https_buf, read_from_client, 0);
            if (send_to_server > 0) {
                debug_green("proxyHTTPS: sent to server " << std::to_string(send_to_server) << " bytes \n");
            }
            else if (send_to_server == 0) {
                debug_yellow("proxyHTTPS: sent to server 0 bytes...\n");
                break;
            }
            else {
                debug_red("proxyHTTPS send() to server " << strerror(errno) << '\n');
                break;
            }
        }
    }
    else if (FD_ISSET(sockfd_server, &fdset)) {
        debug_green("proxyHTTPS: reading from server and sending to client\n");
        read_from_server = recv(sockfd_server, https_buf, https_buf_size, 0);
        if (read_from_server < 0) {
            debug_red("proxyHTTPS recv() from server " << strerror(errno) << '\n');
            break;
        }
        else if (read_from_server == 0) {
            debug_yellow("proxyHTTPS server closed conn\n");
            break;
        }
        else { // read_from_server > 0
            send_to_client = send(new_sockfd_client, https_buf, read_from_server, 0);
            if (send_to_client > 0) {
                debug_green("proxyHTTPS: sent to client " << std::to_string(send_to_client) << " bytes\n");
            }
            else if (send_to_client == 0) {
                debug_yellow("proxyHTTPS: sent 0 bytes to client, errno: " << errno << '\n');
                break;
            }
            else {
                debug_red("proxyHTTPS send() to client " << strerror(errno) << '\n');
                break;
            }
        }
    }
}
debug_yellow("proxyHTTPS: quitting\n");
}

This is, e.g., a CONNECT request the proxy gets from client:
CONNECT www.youtube.com:443 HTTP/1.1
Host: www.youtube.com:443
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36
/r/n

If client sends CONNECT www.netflix.com:443 HTTP/1.1, my proxy fails and on terminal prints:
setting non block socket
connected immediately
setting block socket
54.228.227.144:443 OK
CONNECT: send to client HTTP/1.1 200 Connection established
starting proxyHTTPS
proxyHTTPS: reading from server and sending to client
proxyHTTPS read from server: Connection refused
quitting proxyHTTPS

If clients sends CONNECT www.youtube.com:443 HTTP/1.1, my proxy fails again and shows:
setting non block socket
connected immediately
setting block socket
216.58.201.238:443 OK
CONNECT: send to client HTTP/1.1 200 Connection established
starting proxyHTTPS
select(): Operation now in progress
proxyHTTPS: select() request timeout 408
quitting proxyHTTPS

I think I did all the steps I was told to do in order to establish a tunnel between client and server, connect() is always ok, so mistakes must be in my proxyHTTPS. I have no clue!
EDIT 1: removed perror() when select() returns 0, since errno is not raised; improved error checking in select() loop, distinguishing returned values > or == zero.
Despite that, still got the same problem: in a way or another, can't read any data from client or server.
EDIT 2: updated code about connecting to remote server.
I'm starting to think that since the select() loop seems correct, the problem may be caused by something else...
Debug functions used above are defined below:
#define DEFAULTCOLOR    "\033[0m"
#define RED             "\033[22;31m"
#define YELLOW          "\033[1;33m"
#define GREEN           "\033[0;0;32m"

#define debug_red(...) std::cout << RED << __VA_ARGS__ << DEFAULTCOLOR; fflush(stdout);
#define debug_yellow(...) std::cout << YELLOW << __VA_ARGS__ << DEFAULTCOLOR; fflush(stdout);
#define debug_green(...) std::cout << GREEN << __VA_ARGS__ << DEFAULTCOLOR; fflush(stdout);