Google Play - File an exception and roll out a submission

Question: I have released a version of an application that collects background information and I received a notice from google play that it is rejected. Google has outlined next steps as either submitting a compliant update by Jan 1 2021 or requesting an exception. I am a bit confused about exactly what to do though as I don't understand what they mean by 'submit' app. Do I need to make another release once I either declare an exception or submit the declaration form filled out?
Option 1: File an exception and roll out a submission (without making changes)
During the extended timeline for compliance, you will be allowed to roll out your latest submission without making any changes by requesting a Location exception. Here's how:

Sign in to your Play Console
Select your app.
Navigate to the Permissions Declaration Form.
To file an exception in the form, go to the question "Does your app meet the Location permissions policy?" and select "No, this app does not meet the Location permissions policy."
Selecting this option will allow you to access location in the background in your latest submission, in any updates to your app, or when submitting a new app, until the dates mentioned above. For more information, please visit our Help Center.
Submit your app.

Option 2: Submit a compliant update
Once you're ready to submit a compliant version of your app:

Make the necessary updates to address the issue(s) identified above.
If your app is not eligible to access location in the background or does not meet requirements for accessing location in the background, please remove the permission from your manifest and in-app functionality.
Double check that your app is compliant with all other Developer Program Policies.
Sign in to your Play Console and submit the update to your app.
Answer: Here is the solution
remove permission

and go to google play console

select app
select App content
select Sensitive app permissions
select manage
select No, this app does not meet the location permissions policy
Comment: Has anyone been able to do this in the new Google Play Console? I can't find the 'App content' button anywhere.
Comment: @Michiel check on your left side (navigation menu), under Policy, there is the App Content.


MVC model with a property for related models

Question: Imagine there is a model defined as:
public class Book
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Guid> RelatedBooks { get; set; } // List<Book> would be more ideal.
}

I'm trying to add a field in both the Create and Edit views whereby a user will be able to search for related items, in this example by name, and then add them to the new/current item as a related item.
I think this might be possible with a partial view + jQuery, where the partial view acts a search box and returns a list of items. Then with some buttons and jQuery magic these could be added to the current model upon submission of the parent form.
I'm not against using jQuery if it's the only option, but I was wondering if there were any alternatives?
If this is too vague I'm happy to add some more specific details, I've tried search for similar questions but I'm either using the wrong search terms or there aren't any.
Any help would be really appreciated - I'd rather not go down the jQuery + partial view route if there is a cleaner alternative.
Answer: First off, you need to create a view-model for what you're trying to achieve that will hold both the list of related books, but also a list of all books we can select.
public class CreateBookViewModel {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Guid> RelatedBooks { get; set; }

    public List<Book> AllBooks { get; set; }
}

Populate AllBooks in the Controller and return the view model. Then you could create some magic, maybe with jQuery, to have a select list with all books, that when selected are added to the list of related books by Id. At least you wouldn't need partial views, if you don't want any more functionality than just selecting one or more books.
Comment: Ah yeah, the model in question was hypothetical (I do use view models in my actual implementation) - I have considered the above, but it prevents the user from being able to search through all of the books, and also means loading every single book every time they may want to create or edit one which eventually (with _lots_ of books) will not be good for performance.
Thanks for the input though, really appreciate it, and if I can't find an alternative, a proof of concept like the above will be a good starting point.
Comment: @Callum Will edit my answer when I have time then, because then I definitely think you should use jQuery (or any other Javascript framework for that matter) to have an autocomplete searchbox on the create/edit page, which requests book from an AJAX endpoint on some controller based on the search condition.


PDF reader not working

Question:     import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.Writer;
    import java.nio.file.Files;

    import com.itextpdf.text.pdf.PdfReader;
    import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
    import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
    import com.itextpdf.text.pdf.parser.TextExtractionStrategy;
`
public class Test{

    public static void main(String []args) throws IOException
    {

        String  pdf= "c:\\sample.pdf";

         PdfReader reader = new PdfReader(pdf);

    }

}

it not working
like it should i am running windows
need help please help i tried a lot of things but still getting the same message
here is the error message
this is the output i get when i tried ur code
File Exists: true
Exception in thread "main" java.lang.NoClassDefFoundError:
org/bouncycastle/asn1/ASN1Encodable
at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:1024)
at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1430)
at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:732)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:181)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:219)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:207)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:197)
at pdfconverter.Test.main(Test.java:37)
Caused by: java.lang.ClassNotFoundException:
org.bouncycastle.asn1.ASN1Encodable
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 9 more

Comment: What error message are you getting?  Please use the [edit] link under the question and include this information.  Also detail what you have tried.
Answer: The code looks good to me. Perhaps more information on the error you are having? For instance, it could be a classpath error - something like the itextpdf classes not being located...
In case it helps as a baseline - the following code works for me. I removed the extraneous includes, though they won't hurt to leave them in.
import java.io.File;
import com.itextpdf.text.pdf.PdfReader;

public class Test {

    public static void main(String[] args) {

        String  pdf= "C:\\Java-Design-Patterns.pdf";

        try {
            System.out.println("File Exists: "+new File(pdf).exists());
            PdfReader reader = new PdfReader(pdf);
            int count = reader.getNumberOfPages();
            System.out.println("PDF has "+count+" pages.");
         } catch (Exception e) {
            System.out.println("Failed to open PDF ["+pdf+"]: "+e);
            e.printStackTrace();
         }

    }
}

The output is:
File Exists: true
PDF has 183 pages.

The itext jar I used is: itextpdf-5.5.12.jar (included via maven).
The pdf I used (courtesy of google: java design patterns pdf) is here: http://enos.itcollege.ee/~jpoial/java/naited/Java-Design-Patterns.pdf
I haven't read it yet, but the first page looks good ;)
That said, itextpdf is quite awesome.
Answer: java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1Encodable

clearly indicates the issue: Bouncy Castle is missing! (Or at least the required version is missing.)
Bouncy Castle is a library used by iText for encryption, decryption, signing, and signature verification, here their web representation.
Thus, add the Bouncy Castle libraries to your class path. Please be aware, though, that the BC version required depends on the iText version in question. The maven link you provided for your itext7 version indicates that BC 1.49 is required.

PDF reader not working


JS acting differently when logged in

Question: I am trying to remove a class from inside my navigation menu.
When not logged in, the class is removed. However, when logged in as an authenticated user or administrator, the behavior changes and the class is not removed.
All my other jQuery code works, but not when trying to remove this class. I have been working all day at this trying all kinds of different approaches to target the class I want to remove with no luck.
The class I'm trying to remove is .visually-hidden.
HTML:

Link 1-A

        Link 2-A

                Link 3-A

                Link 3-B

        Link 2-B

JS:
(function ($) {
  'use strict';

  Drupal.behaviors.themeJS = {
    attach: function (context, settings) {
      var isActive = $('.is-active');
      isActive.parentsUntil('level-1').removeClass('hide-menu');
      isActive.closest('li').children('ul').removeClass('hide-menu');
    }
  };
  $.noConflict();
})(jQuery);

The scripts when not logged in:

The scripts when logged in:

Comment: It might be a cache issue. Try clearing your cache. Reasons: if you check `/admin/config/development/performance`, you might see the 'Cache pages for anonymous users' checked. If that's true, your code could only possibly work in that cache.
Comment: Yes, the difference is, that logged out `active-link.js` is not used, for anonymous the class is set in Drupal\Core\EventSubscriber\ActiveLinkResponseFilter
Comment: Yes, I've thought of this and I've cleared the cache many times.
Comment: I've also cleared the cache on the browser (chrome) as I've seen this clear up javascript issues in the past.
Comment: Thank you! That worked. My js file is now loaded after `active-link.js` and everything is working regardless of logged in status. Thank you so much! Add this as the answer, and I'll mark it.
Answer: The problem is that the active-link.js is loaded after your theme.js file when you are logged in as @4k4 mentioned. This means that the .is-active class does not exist until after your code is run.
Two ways come to mind:

Add a higher weight to theme.js so that it'll be run after active-link.js. See the "Weighted JavaScript" Section.
Run your code after everything is loaded. E.g. window.onload
Comment: I had a similar issue and `window.onload`solved it.

JS acting differently when logged in


Jersey 2.4 on Glassfish 4.0.1: How to inject context HttpServletRequest into ContainerRequestFilter?

Question: Jersey 2.4 is able to inject HttpServletRequest: https://java.net/jira/browse/JERSEY-1960
Glassfish 4.0.1 is bundled with Jersey 2.4: http://dlc.sun.com.edgesuite.net/glassfish/4.0.1/nightly/latest-glassfish.zip
Opened bug at Glassfish:
https://java.net/jira/browse/GLASSFISH-20885
<code>@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthRequestFilter implements ContainerRequestFilter {
    @Context
    HttpServletRequest webRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        HttpSession session = webRequest.getSession();
        String user = (String)session.getAttribute("USER_ID");
    }
}
</code>
Glassfish 4.0.1 can not deploy this filter with the following exception:
<code>    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:284)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:302)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
java.lang.IllegalArgumentException: While attempting to create a Proxy for javax.servlet.http.HttpServletRequest in proxiable scope org.glassfish.jersey.process.internal.RequestScoped an error occured while creating the proxy
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2309)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
    at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:104)
    at org.jvnet.hk2.internal.Utilities.justInject(Utilities.java:803)
    at org.jvnet.hk2.internal.ServiceLocatorImpl.inject(ServiceLocatorImpl.java:832)
    at org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider$CdiFactory$2.getInstance(CdiComponentProvider.java:203)
    at org.glassfish.jersey.gf.cdi.internal.CdiComponentProvider$CdiFactory.provide(CdiComponentProvider.java:149)
    at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
    at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
    at org.jvnet.hk2.internal.PerLookupContext.findOrCreate(PerLookupContext.java:69)
    at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2350)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
    at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
    at org.glassfish.jersey.internal.inject.Providers.getAllRankedProviders(Providers.java:235)
    at org.glassfish.jersey.server.ApplicationHandler.getProcessingProviders(ApplicationHandler.java:617)
    at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:410)
    at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:162)
    at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:287)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:284)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:302)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:284)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:302)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5946)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    Startup of context  failed due to previous errors]]

[glassfish 4.0] [SEVERE] [AS-WEB-CORE-00108] [javax.enterprise.web.core] [tid: _ThreadID=50 _ThreadName=admin-listener(4)] [timeMillis: 1383814486801] [levelValue: 1000] [[
  ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: interface org.glassfish.hk2.api.ProxyCtl is not visible from class loader
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5954)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:691)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:1041)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:1024)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:747)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2286)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1932)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:139)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
    at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
    at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:284)
    at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:302)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:167)
    at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:349)
    at javax.servlet.GenericServlet.init(GenericServlet.java:244)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1583)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1382)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5704)
    ... 50 more
    ]]
</code>
Comment: I've recently thrown out Glassfish and migrated to Wildfly. Now I'm happy that everything works stable.
Answer: This is fixed in the nightly version of 4.0.1 Glassfish on 12/25/2013.  I added a comment to the referenced Glassfish ticket, but will look forward to this fix being pushed to any release.
Comment: Yes. It was fixed and works with the latest nightly build: http://dlc.sun.com.edgesuite.net/glassfish/4.0.1/nightly/glassfish-4.0.1-b04-02_13_2014-ml.zip


Running different PHP CLI version depending on working path

Question: I set up PHP-FPM to have different versions of PHP for different folders. This was necessary due to legacy code and was achieved using the apache's .htaccess.
My question is: does anyone have a simple elegant way to do this in CLI? I was thinking maybe have a file in the folder indicating the desired version of PHP to run, but unsure of how to go about it.
My expected result is that when I run php ... in folder A, it runs with PHP 7.4 and when I do the same php ... in folder B, it runs with PHP 8.1
Thank you.
Answer: Assuming your PHP versions are installed in different paths, e.g.:

php 7.4 is in /usr/local/php74/bin
php 8.1 is in /usr/local/php81/bin
etc

Create a script php that looks for a .phppath file in each directory that describes which php binary to use. Something like:
#!/bin/sh

# This sets the default if not otherwise specified
phppath=/usr/local/php81/bin/php

if [ -f .phppath ]; then
  phppath=$(cat .phppath)
fi

exec $phppath "$@"

Put this in your $PATH somewhere and you should be all set. In directories where you want, say, PHP 7.4, create an appropriate .phppath file:
echo /usr/local/php74/bin/php > .phppath

Note that as written, this only finds .phppath in the current directory. It won't find it if you're working in a subdirectory. That's a solvable problem, but it's left as an exercise to the reader.
Comment: wonderful! actually it is exactly what I need, the extra exercise wasn't necessary. I think the path should be written into `> .phpversion` instead of `> .phppath`. Thank you!
Comment: i think there is still a bug in your script, checking for `.phppath`, but reading from `.phpversion`. I would have different names for variable and filename for clarity especially for new folks trying to learn. Thank you.
Comment: Yes, good catch. Updating.


How to show describe a bijection between 2 infinite intervals?

Question: I am attempting to find a bijection between $(0,1/2)$ and $(2,\infty)$ in a addition to $(0,\infty)$ and $(2,\infty)$. I understand how to solve this when all of the ranges and bounded by integers, its pretty easy to find a linear map, but how are you supposed to solve it when infinity is involved?
Answer: I find the function $x \to \frac{1}{x}$ most easy to manipulate for this kind of intervals. Draw a graph and move the hyperbola around to fit into the intervals.
Define $f:(0,\frac{1}{2}) \to (2,\infty)$ by $f(x)=-\frac{1}{x-\frac{1}{2}}$
Define $g:(0,\infty) \to (2,\infty)$ by $g(x)=\frac{1}{x}+2$
Answer: For the first one, consider $x\to\frac{1}{x}$. For the second one consider $x\to x+2$.
Comment: I mean, sure you've given an answer, but I think what he wants is more of an intuitive understanding.


ASP.NET auto submits form with only one textbox

Question:
<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <input type="text" />
    </form>
</body>
</html>
</code>
When I hit the enter key, when the input box has focus - the form submits.
If I add another input box it doesn't submit. How can I avoid the auto submit when there's only one input box?
Comment: possible duplicate of [ENTER key on a FORM with a single Input Field, will automatically  SUBMIT with GET ](http://stackoverflow.com/questions/1370021/enter-key-on-a-form-with-a-single-input-field-will-automatically-submit-with-ge)
Answer: Look here for the answer SO post
HTH


Should the average prediction for a given attribute value equal the rate for that value?

Question: Let's say I'm predicting the likelihood that someone will buy a widget, using their age, eye color, and gender as input attributes.
I split my data into a training set and a test set, and train up my predictive model using the (large) training set.
Let's say that 15% of people in the test set with blue eyes buy the widget, should I expect the average predicted buy probability of people with blue eyes would be around 0.15 also (assuming a good predictive model)?
Intuitively it seems like it should, but I don't want to assume that it's true.
Answer: If the phrase

Let's say that 15% of people in the test set with blue eyes buy the widget

means "15% of those having blue eyes in the test sample", then the answer is "yes", this is the magnitude to which your model should compare.
Let's abstract from the existence of the other explanatory variables. In the very general terms you put it, you have a model to predict a conditional probability
$$\hat P(W =1 \mid X_1) = g(X_1)$$
and you wonder whether
$$\hat P_\text{model}(W =1 \mid X_1 = B)=g(X_1=B)\; ?\approx?\;\frac {n_\text{test}\{W=1,X_1=B\}}{n_\text{test}\{X_1=B\}} \tag{1}$$
I believe it is obvious how notation maps to the description you gave of your case.
Denote $N_\text{test}$ the test sample size. Then the right-hand-side of $(1)$ can be identically written
$$\frac {n_\text{test}\{W=1,X_1=B\} / N_\text{test}}{n_\text{test}\{X_1=B\}/N_\text{test}}$$
The numerator is the relative empirical frequency of the joint event "have blue eyes and bought the widget", while the denominator is the relative empirical frequency of blue-eyed people in the test sample. Under various assumptions, we usually accept this as estimates of the corresponding probabilities. In other words,
$$\frac {n_\text{test}\{W=1,X_1=B\} / N_\text{test}}{n_\text{test}\{X_1=B\}/N_\text{test}} = \frac {\hat P_\text{test}(W=1,X_1=B)}{\hat P_\text{test}(X_1=B)} = \hat P_\text{test}(W =1 \mid X_1 = B)$$
the last equality from the theoretical relationship between joint, marginal and conditional probabilities.
So you want to compare
$$g(X_1=B) = \hat P_\text{model}(W =1 \mid X_1 = B) =\;\;?\approx ? \;\;\frac {\hat P_\text{test}(W=1,X_1=B)}{\hat P_\text{test}(X_1=B)}$$
$$\Rightarrow \hat P_\text{model}(W =1 \mid X_1 = B) \;\;?\approx?\;\; \hat P_\text{test}(W =1 \mid X_1 = B)$$
which is indeed what your model should tend to satisfy


jqgrid editGridRow selection list for each cell

Question: In my case, I want the user to pickup the values by clicking on a ">" type image at the end of the cell and a modal window is opened. Within the modal window a dynamic way to pass the value selected back to the cell.
Comment: Explain your requirements clearly, please
Comment: Within the modal window a dynamic way to pass the value selected back to the cell. this line is not clear
Comment: It seems he wants the user to be able to click on a `>`  image link, open a dialog, pick a value, and then dynamically pass that value back to the table cell.
Comment: Yes. Justin is correct. That is what I am looking for.
Comment: okay but dont post your question again and again please. I'm going to look for a solution for you.
Comment: i m sorry. when i found my question was not answered. i thought i should reframe my question because i did not think users would be reading comments on this post. i will delete the other question..
Answer: You should look into this answer..instead of having custom button you can have an image button with each cell, in this answer he's adding a custom button in pager, but you can have a custom button with each cell like this.
Now after adding a image button, on click function you can get the value of the column using getCol and open a dialog using jQuery like this and then you can use setCol property of jqGrid to set the value of column.
Now try to write code using this approach. If you get any difficulty let us know.


Multivariate and integral representations explanation

Question: I would to understand more on the multivariate and integral representations. I am fascinated by the possibility of a multivariate distribution like this one:
$$\mathbb{P}(X_1 \le Z + a, X_2 \le Z + a, ..., X_n \le Z + a),$$
to be transformed into:
$$\int \limits_{- \infty} ^{+ \infty} {\Phi(z+a)^n \phi(z)dz}.$$
and vice-versa. Here $\Phi(z)$ and $\phi(z)$ are, respectively, the cdf and the pdf. Everything started reading about this: Integrating pdf times cdf squared.
How is that a random vector is transformed into a scalar? is this some sort of projection? is there an analog transformation between a euclidean vector and a scalar?
Answer: Lets assume $Z$ is a random variable defined over a support of $\mathbb{R}$ and $X_1,...,X_n$ are i.i.d and have cdf $\Phi$, in which case
\begin{align}
\text{Prob}(a)
&\equiv \mathbb{P}(X_1 \le Z + a, X_2 \le Z + a, ..., X_n \le Z + a) \\[18pt]
&= \mathbb{E}_Z[\mathbb{P}(X_1 \le Z + a, X_2 \le Z+ a, ..., X_n \le Z + a | Z = z)] \\[12pt]
&= \int \limits_{-\infty}^{\infty} \mathbb{P}(X_1 \le Z + a, X_2 \le Z+ a, ..., X_n \le Z + a | Z = z) \phi(z) \,dz \\[6pt]
&= \int \limits_{-\infty}^{\infty}\mathbb{P}(X_1 \le z + a, X_2 \le z + a, ..., X_n \le z + a) \phi(z) \,dz \\[6pt]
&= \int \limits_{-\infty}^{\infty}\mathbb{P}(X_1 \le z + a) \cdot \mathbb{P}(X_2 \le z + a) \cdots \mathbb{P}(X_n \le z + a) \phi(z) \,dz \\[6pt]
&= \int \limits_{-\infty}^{\infty}\Phi(z + a)^n \phi(z) \,dz. \\[6pt]
\end{align}
Intuitively, $z$ (the variable of integration) is a scalar as opposed to a vector because it is the same variable that all $X_1,...,X_n$ are being compared with, and it allows us to compute the total probability utilizing the conditional probability given $Z=z$, which is much easier probability to compute. This alternative, easier formulation is allowed as per the law of total probability.
Observe that the integration variable would instead be the vector $(z_1,...,z_n$) if we were instead computing $\mathbb{P}(X_1 \le Z_1 + a, X_2 \le Z_2 + a, ..., X_n \le Z_n + a.)$


How to use the completeness here

Question: Suppose that $G\subset \mathbb{C}$ is an open subset and that $X$ is a Banach space. Fix $z_0 \in G$ and let $V:=\{(h,k) \in \mathbb{C}^*\times\mathbb{C}^* : z_0+h \in G\ ; z_0 + k \in G\}$. Let $f: G \to X$ be a function such that
$$
\sup_{(h,k) \in V} \frac{1}{|h-k|}\left\| \frac{f(z_0+h)-f(z_0)}{h}-\frac{f(z_0+k)-f(z_0)}{k}\right\| < \infty
$$
I have just read that the above implies, by the completeness of $X$ that the limit
$$
\lim_{h \to 0} \frac{f(z_0+h)-f(z_0)}{h}
$$
exist in X.
At first sight I thought this could be something like the Cauchy criterion, but I can´t see how. I feel it must be a triviality, can anyone here see further than I?
Thanks in advance !
Answer: Let $(h_n)$ a sequence in $V$ converging in $\mathbb{C}$.
Let $u_n = \frac{f(z_0+h_n)-f(z_0)}{h_n}$
The bounded $\sup$ condition implies $||u_p - u_q|| \leq M |h_p-h_q|$
Hence $(u_n)$ is a Cauchy sequence in $X$ so it converges in $X$ by completeness.
Therefore $\lim \frac{f(z_0+h_n)-f(z_0)}{h_n}$ exists in X.
Comment: Many thanks, I tried to do something similar by changing $h$ and $k$ for $1/n$ and $1/m$ but I dropped very soon.

How to use the completeness here


What is the distribution of a Poisson variable, where the Poisson rate is Normal (or Binomial)?

Question: What is the distribution of $X$ if
$$ X \sim \text{Poisson}(\lambda), \quad  \text{where }\lambda \sim N(\mu,\sigma^2)$$
or
$$ X \sim \text{Poisson} (\lambda),  \quad  \text{where }\lambda \sim Bin(n,p) $$
where $n$ is very large.
Detail and motivation
In biology, next-generation sequencing is often used to quantify the level of RNA in a cell. The experiment goes like this:
Imagine that a cell (or a extract made from many cells), is a mixed bag of 200,000 RNAs molecules from 20,000 classes. We wish to estimate the proportions of the various classes.
For each replicate of an experiment we sample, with replacement, RNA "reads" from the bag.
For a class of RNA we get a count of "reads".
Each replicate of an experiment is performed with RNA from a different cell (or an extract from a different group of many cells), drawn from the same underlying population of cells.
If X is the count of "reads" from a particular replicate of the experiment, in practice we often model X as being negatively binomial as when we look at it, it looks like an overdispersed poisson.
There has been some discussion recently if their is any theoretical basis behind using the negative bionomial other than "it seems to fit". One obvious answer is that the negative binomial is the result of a poisson distribution where the poisson rate follows a gamma distribution. One interpretation is that our measurement error is poisson (counts from a sample), and the underlying variance between biological samples is gamma. But why gamma: it does not seem like an obvious answer as to the distribution to use.
A model that we are more used to might be that the amount of RNA in a sample is normally distributed (or equivalently binomially distributed with large n).
Previous attempts
I'm sure I've seen this written down somewhere before, using PGFs to figure out the result.
$$\Pi_x(s) = \sum_x{P(X=x)s^x}$$
$$P(X=x) = \int_r{P(X=x|\lambda=r)P(\lambda=r)}$$
but writing this down has only resulted in an intergral I don't know how to solve!
Comment: 1. The Poission $\lambda$ parameter is required to be positive, so some care is needed if you want to assume that $\lambda$ is Normal, to ensure the Normail tails do not practically become negative. _______ 2. One can solve the parameter-mix distribution for your desired Poisson-Normal as a closed form, but it is a bit messy with Hypergeometric1F1 functions. ___3. What is the meaning of your title: TL:DR?
Comment: You write "A model that we are more used to might be [...] binomially distributed with large n)": And that is Poisson. Citing from Wikipedia for simplicity: "The Poisson distribution can be derived as a limiting case to the binomial distribution as the number of trials goes to infinity and the expected number of successes remains fixed" or https://en.wikipedia.org/wiki/Poisson_distribution#law_of_rare_events . Binomial and Poisson are always positive.
Comment: A Poisson parameter $\lambda$ cannot be negative hence cannot be Normal.
Comment: Regarding the negbin: On the one hand, I personally am good with "because it works". On the other hand, Hilbe's *Negative Binomial Regression* lists many, many motivations and constructions that all lead to the negbin. (But that doesn't have much to do with your original question, which I find interesting and wait for an answer on.)
Comment: @wolfies it stands for "too long; didn't read."
Comment: @Bernhard: Interesting, I hadn't thought of that. I was think of the fact that large n Binomial is approximately Gaussian. Under what circumstances do we think of large n Binomial as normal, and what circumstances Poisson? Poisson X with Poisson lambda is still Poisson right? Interestingly this doesn't fit the data.
Comment: "But why gamma": the gamma is positive, so it's a parameterization of $\lambda$ that makes more sense than a normal distribution. And of course another rationale for the gamma is that the resulting negative binomial is at least somewhat tractable.
Comment: The claim doing the rounds is that using the NB for counts (or equivalently Gamma for the distribution of concentrations) is an empirical decision without a mechanistic model to justify it.
Comment: @Ian Sudbery  - Poisson X with Poisson lambda is still Poisson right? - wrong. For Poisson, lambda has to be a constant, cannot have any distribution.
Answer: So you assume a continuous mixture of Poisson distributions, say
$$ X \mid \Lambda=\lambda \sim \mathcal{Pois}(\lambda),$$
where $\Lambda$ then has some distribution on the positive line.
If we assume that $\Lambda$ has a gamma distribution, results that $X$ has a marginal negative binomial distribution. You asks what happens if $\Lambda$ has a normal distribution. That doesn't seem like a natural model since a normal distribution can take negative values, which does not make sense here. Also, the proposal of a binomial mixture distribution seems strange, since why restrict $\lambda$ to integers? Here is a review paper on continuous Poisson mixtures you could have a look at it and try some of the more prominent examples. Table 1 page 50 in the cited paper is a list of examples, many of them difficult to use due to numerical issues.
An interesting idea would be to estimate the mixing density $g$ on $(0,\infty)$ nonparametrically.  There are many possible methods and many papers.
Answer:
Normal approximation
One approach is to use a normal approximation by matching the moments.
The compound Poisson distribution is a mixture distribution of Poisson distributions with weights distributed according to a binomial distribution $w_i = P_{binom}(i\vert n,p)$
$$P(x) = \sum_{i=0}^n w_iP_{Poisson}(x\vert \lambda = i )$$

The mean of the distribution will be equal to
$$E[X] = \sum_{i=0}^n w_i E[X\vert i] = \sum w_i i = np$$
the mean of the binomial distribution.
The variance will be
$$\begin{array}{}
   E[(X-\mu_X)^2] &=& \sum_{i=0}^n w_i (\sigma_i^2 + \mu_i^2 - \mu^2) \\& = &\sum_{i=0}^n w_i (i + i^2 - (np)^2) \\&=& \sum_{i=0}^n w_i (i + i^2) - \sum_{i=0}^n   (np)^2\\ &=&  np(1-p) + (np)
   \end{array}$$
the variance plus the mean of the binomial distribution

Negative binomial approximation
We can do the same sort of approximation (matching the moments) with a negative binomial distribution.
In the examples below, we have plotted this approximation as well. The curve resembles more closely the histogram than the normal approximation, but it is still not exactly the same.
Computational
The example below is computed with $n=40$ and $p=0.5$ giving $\mu_X = 20$ and $\sigma_X^2 = 30$

<code>## parameters
set.seed(1)
ns <- 10^5
nbinom <- 40
pbinom <- 0.5

### generate sample
Y <- rbinom(ns, nbinom, pbinom)
X <- rpois(ns, Y)

### plot histogram
h <- hist(X, breaks = seq(0,max(X)+1)-0.5, freq = 0)

### add curve
xs <- seq(0,max(X))
#lines(xs,dpois(xs,nbinom*pbinom)*ns, col = 2)
lines(xs,dnorm(xs+0.5, mean = nbinom*pbinom,
                     sd = sqrt(nbinom*pbinom*(2-pbinom))), col = 2)

### binomial approximation
mu = nbinom*pbinom
vr = (nbinom*pbinom*(2-pbinom))
p = 1-mu/vr
r = mu*(1-p)/p
lines(xs,dnbinom(xs, size = r, p= 1-p ), col = 3)

legend(max(X),max(h$density), c("normal approximation", "negative binomial approximation"),
       cex= 0.7, col = c(2,3),lty = 1, xjust = 1)
</code>
The problem with the normal approximation is that it does not work so well when $\sigma_X$ is not a lot smaller than $\mu_X$. This occurs when $\mu_X = np$ is small.
See for instance the plot below with $n=4000$ and $p=0.0005$ giving $\mu_X = 2$ and $\sigma_X^2 = 1.99975$


bash: Dynamic cross-script variable's value update

Question: I have 2 scripts: S1.sh and S2.sh.
S1.sh can run independently, and can receive positional value from "$1" as an optional parameter. This "$1" value is dynamic, and may be any number between 0 and 9.
VAL=$1

S2.sh is designed for remote triggering of S1.sh, and it uses its own "$1" (string value) for a different purposes.
I'm looking for a way to assign "$2" provided to S2.sh  to $VAL of S1.sh.
Answer: When S2.sh calls S1.sh, use
S1.sh "$2"

The value of S2's second parameter is passed as the first argument to S1.


Integral of a gradient over a plane area

Question: Let $A$ be a plane area bounded by a curve $\partial A$. Then, is
$$ \iint_A \nabla f\, \textrm{d}x \textrm{d}y = \oint_{\partial A} f\ \hat{\mathbf{n}}\ dl $$
where $f=f(x,y)$ and $\mathbf{\hat n}$ is the outward unit normal?
Comment: Bye_World  - thanks
Comment: @user89699 What is to be done here ?
Answer: Under the assumptions for the Divergence Theorem to apply, we have
$$\iint_A \nabla \cdot \vec F\,dx\,dy=\oint_{\partial A} \vec F\cdot \hat n\, d\ell$$
Now, let $\vec F=\hat x_i f$.  Then, we have
$$\iint_A \frac{\partial f}{\partial x_i}\,dx\,dy=\oint_{\partial A}f\,(\hat x_i\cdot \hat n)\,d\ell \tag 1$$
Multiplying $(1)$ by $\hat x_i$ and summing over $i$ from $i=1$ to $i=2$ yields

$$\iint_A \nabla f\,dA=\oint_{\partial A} f\,\hat n\,d\ell$$

as was to be shown!
Comment: I dont think this is right - If $\vec F=\hat x_i f $, then
Comment: $$ \nabla \cdot \vec F = 2f + \vec x \cdot \nabla f $$
Comment: @user89699 $\hat x_i$ denotes a unit vector, not a coordinate variable.  So, the answer is correct.  Anf $f$ is a scalar, not a vector.
Comment: +1. This identity is useful to derive Archimedes Principle ( Eureka !!! ).
Comment: @FelixMarin Thank you Felix!
Comment: Dr.MV - this is still  not correct. If $ \hat x_i $ are unit vectors, then $$ \nabla \cdot \vec F =  \frac{\partial f}{\partial x_1}\ + \frac{\partial f}{\partial x_2}\ $$ From there, I do not see how you can get to the final result.
Comment: @user89699 No, it is correct.  $\hat x_i$ is a Cartesian Unit vector and does not depend on the coordinate variables.  So, $$\nabla \cdot (\hat x_i f)=f\,\,\overbrace{\nabla \cdot (\hat x_i)}^{=0}+\overbrace{(\hat x_i \cdot \nabla )}^{=\frac{\partial }{\partial x_i}}f=\frac{\partial f}{\partial x_i}$$


Unable to run includes() method on string returned by fs.readFileSync()

Question: having a bit of trouble:
let data = fs.readFileSync(pathToCsv, "utf8");
the value of data comes out to be:
clan,mem1,mem2,mem3,mem4,language,managerID,serverJoinedDate
pm,
pm

(through console.log())
but still data.toString().includes("pm") is false.
Here is my full code:
const filter = (m) => m.author.bot === false;
      await ogMessage.author.dmChannel
        .awaitMessages(filter, {
          max: 1,
          time: 60000,
        })
        .then((collected) => {
          if (clans[parseInt(collected.toJSON()[0].content) - 1]) {
            let clan = clans[parseInt(collected.toJSON()[0].content) - 1];
            let data = fs.readFileSync(pathToCsv, "utf8");
            console.log(typeof clan);
            // let reg = new RegExp(clan, "g");
            // let count = (data.match(reg) || []).length;
            if (data.split(",").includes(clan)) {
              ogMessage.author.send(
                "People from this clan are already registered!\nPlease contact the hosts for help!"
              );
              return;
            } else {
              teamCheck = true;
            }
          } else {
            ogMessage.author.send("Invalid Clan! Please try again!");
            return;
          }
        })
        .catch((collected) => {
          try {
            console.log("Error" + collected);
          } catch (e) {
            console.log(e);
          }
        });
      if (teamCheck === false) {
        return;
      }

I have tried splitting the data, using regular expressions but nothing seems to work on the string returned by
readFileSync()
PS. I am making a discord bot.
Comment: In the data example you provided, there is a space in front of `pm`.
Comment: The space before pm is actually supposed to be a new line, I'll update it in the question
Comment: Try `data.split(",").map(it => it.trim()).includes(clan)`
Comment: It doesn't work :( there is a newline before pm as i previously mentioned
Comment: Can you post the output of `console.log(data)` and `console.log(clan)` ?
Comment: `console.log(data)`:

`clan,mem1,mem2,mem3,mem4,language,managerID,serverJoinedDate`
`\npm,`
`\npm`
("\n" is not visible in console, I am just adding to help you ubnderstand that there is a newline before both the "pm"s)
and `console.log(clan)` gives `pm`
Comment: Possibilities I could ever think of: 1. `String.prototpye.includes` get override somewhere  2. There are invisible characters between `p` and `m`. Maybe try `fs.readFileSync(pathToCsv, "hex");` to inspect the raw bytes.
Comment: I logged my clans array and got this `[
  'pm\r',
  'ar\r',
  'lz\r',
  'gm\r',
  'kr\r',
  'dp-divinity parcel\r',
  'abx'
]` Maybe the `\r` is causing something since I am reading this info from another txt file and then splitting to  form an array
Comment: I tried logging the bytes and this is what I get:
`636c616e2c6d656d312c6d656d322c6d656d332c6d656d342c6c616e67756167652c6d616e6167657249442c7365727665724a6f696e6564446174650d0a706d2c0d0a706d2c` I don't know what to make of it
Answer: In the source string you have pm with a space before it. That's why after calling split("," you end up with the element " pm" in the result array and "pm" is not equal to it.
You just need to trim spaces in all elements before searching some string in it
Comment: Actually it is supposed to be a new line before `pm` for some reason it doesn't show up correctly in the question but even if I do a simple `data.includes("pm")`, it still doesn't work but pm is there in the string right?
Comment: `var a = 'clan,mem1,mem2,mem3,mem4,language,managerID,serverJoinedDate pm, pm'` and `a.toString().includes('pm')` returns `true`
Comment: Yes but it returns false in my case
Answer: The problem was in the clans array.
I was defining it as such:
var clans = fs.readFileSync(pathToData, "utf8").split("\n");
but the problem was that the readFileSync() method added an "\r" after every string of the array. That is why it was not able to match the clan string to the data
So what worked was var clans = fs.readFileSync(pathToData, "utf8").split("\r\n");
Now, the array includes only the string, and the includes() method can find a match!


D3 TypeError: link.exit is not a function link.exit().remove(); What am I doing wrong?

Question: I'm making a D3 tree layout. I've looked all over and it seems like this error shows up when you don't have data tied to the DOM and you try to remove it. I've ensured not only that there is data there, but I've also made sure the data changes by doing a count on the links array before and after I modify it.
Here is the problem code from my update function.
    link = linkElements.selectAll("path.link") //link elements is dom object that holds my links
    .data(links).enter().append("path")
    .attr("class", "link")
    .attr("d", diagonal);

    link.exit().remove();

It's practically the same as many examples, but I keep seeing this:
TypeError: link.exit is not a function

link.exit().remove();

What is going on? I do something similar with the nodes. I can't get anything to delete from the tree.
Answer: Notice what link is getting assigned to:
link = linkElements.selectAll("path.link")
  .data(links)
.enter() // <----- THIS
  .append("path")
  .attr("class", "link")
  .attr("d", diagonal);

So link is a selection containing newly appended nodes resulting from the enter() sub-selection, so it doesn't have an exit() sub-selection by definition.
What you need (and probably meant) to do is assign link to the entire data-bound selection, and then work on the sub-selections:
link = linkElements.selectAll("path.link")
  .data(links);// link assigned
link.enter() // <----- THIS
  .append("path")
  .attr("class", "link")
  .attr("d", diagonal);
link.exit().remove(); // no more errors!


FASM - Criar e executar arquivo em lote

Question: Em Assembly(usando montador FASM), gostaria de criar um arquivo .bat e, em seguida, executa-lo.
Consigo criar o arquivo normalmente usando as funções contidas em msvcrt.dll.
Eu fecho o arquivo e tento executar usando system, mas nada ocorre(nem mesmo uma mensagem de erro)
O arquivo é criado corretamente.
Seção de código do programa:
main:
push mode ; w
push fileN ; run.bat
call [fopen]

pop [fileP] ; pego o endereço do stream do arquivo e jogo em fileP

push [fileP] ; coloco novamente o valor na pilha, para o fwrite
push eax
mov eax, 85 ; número de valores para escrever
push eax
mov eax, 1 ; tamanho em bytes de cada valor
push eax
push dataB ; conteúdo do arquivo batch
call [fwrite] ; -> até aqui tudo ok

push [fileP] ; endereço stream do arquivo
call [fclose] ; Creio que funcione corretamente

push pExec ; string contento os comandos pada executar
call [system] ; executado corretamente, mas não executa o .bat
call [exit]

Presumi que poderia não estar fechando o arquivo corretamente, ou que no tempo de execução o arquivo ainda não estaria fechado(por delay do sistema)
Tentei ao usar system utilizar o timeout, de qualquer forma nada ocorreu.(exceto a execução do timeout)
Pensei em usar sleep, mas não sei como usar em ASM. (Também já tentei fazer delay com um loop, mesmo resultado.)
Alguém saberia dizer o erro?
Mais alguns detalhes:
Estou montando para 32bits, o S.O. é o Windows 7 64 bits.
Answer: Acabei descobrindo o erro.(isto que dá ser teimoso e não usar a macro cinvoke >.<)
Na verdade a função retorna valores em eax, e estava pegando o valor da pilha. Escrevia corretamente pois estava dando push eax(jogando o endereço do stream de forma correta para o fwrite)
Me confundi na hora de escrever isso, e por isso acabou dando este resultado.
No fim das contas, o erro estava mesmo ao fechar o arquivo.
O código correto:
main:
push mode ; w
push fileN ; run.bat
call [fopen]

mov [fileP], eax ; pego o endereço do stream do arquivo e jogo em fileP
push eax ; jogo na pilha para o fwrite
mov eax, 85 ; número de valores para escrever
push eax
mov eax, 1 ; tamanho em bytes de cada valor
push eax
push dataB ; conteúdo do arquivo batch
call [fwrite]

push [fileP] ; endereço stream do arquivo
call [fclose]

push pExec ; string contento os comandos para executar
call [system]
call [exit]

FASM - Criar e executar arquivo em lote


Passing environment arguments to npm commands in package.json

Question: I have a script section in my package.json file as shown below
<code>"scripts": {
    "start": "node_modules/.bin/grunt transpile && node dist/src/app.js",
}
</code>
when I run "npm start" from command shell it works fine. Now I have the requirement to introduce two environment variables which my js code is accessing as below
<code>if (process.env.APP_DATA_MODE === "complete") {
    // perform some actions here
} else {
    // perform some actions here
}

if (process.env.HOST_NAME === "dev") {
    // do some dev env related code here
} else {
    // do prod related code here
}
</code>
What I want to know is how should I introduce these two environment variables in the "start" command above OR at the very least how I can run the npm start command and also specify arguments for the two environment variables listed above
Already tried stack overflow article which does look like a close match but having no luck there as the environment variable keep coming as blank during code execution
Answer: This should work
<code>"start": "node_modules/.bin/grunt transpile && APP_DATA_MODE=complete HOST_NAME=dev node dist/src/app.js"
</code>
Assuming you need pass them to your app.js
Okay so I guess I wasn't convincing enough so let me provide a simple proof
Let's write a simple script
<code>#!/bin/bash

echo "VAR1 = $VAR1"
echo "VAR2 = $VAR2"
</code>
Here's the output
Comment: That returns with error with module not found saying

my-app\APP_DATA_MODE=complete cannot be resolved

If I run it with

node  dist/src/app.js APP_DATA_MODE=complete HOST_NAME=dev
it runs fine but it doesn't set the environment variables
Comment: Sorry 'node' call was in the wrong place. Have updated the answer
Comment: Yeah I figured. Even after putting the node call first and then adding arguments after like below

node dist/src/app.js APP_DATA_MODE=complete HOST_NAME=dev

Command runs fine but it doesn't set the environment variables
Comment: You've missed the point env vars should be at the beginning before node


Javascript static variables and using in different pages

Question: I have a jQuery plugin in my layout page header:

and my layout.js:
    (function ($) {
    var Layout = function (node, options) {
        this.node = node;
        this.options = $.extend({
            url: ""
        }, options);
        $(this.node).find('.HButton').bind('click', $.proxy(this.HButtonClicked, this));
    };

    Layout.prototype = {
        constructor: Layout,
        _loadBackground: function () {
            debugger;
            //load second now 'Common.currentTarget' have been lost
            $(Common.currentTarget).removeClass();
            $(Common.currentTarget).addClass(".HButton_Selected");
        },

        HButtonClicked: function (e) {
            debugger;
            //load first
            Common.currentTarget = e.currentTarget;
        }
    }

    $.fn.Layout = function (options) {
        return this.each(function () {
            $(this).data('Layout', new Layout(this, options));
        });
    };

}(jQuery));

in the other side I have a share repository javascript object like this :
function common() {

}

common.currentTarget = null;

var Common = new common();

then in the other page I've triggered an event like following :

when the HButton element click happened at the first I'm writing the object inside the "Common.currentTarget" and it saved successfully when I've watched variable but when another page loads completely and then trigger the event "_loadBackground" the value of "Common.currentTarget" have been lost, my question is how I can define a static variable like this to be permanent in whole of my pages?
Comment: You want a variable to stay populated after changing page? If so you'll have to put it into some kind of storage.
Answer: You can set a cookie from javascript to store the data, and then access the cookie from another page. Cookies can persist just during the browser session, or you can give them an expiration. For HTML5, there is local storage.
Comment: @kamiar3001 It is widely used and supported. See http://www.quirksmode.org/html5/ for the compatibility matrix. Some browsers may be configured to ask the user if it's ok for the page to store some local data. Session storage is probably sufficient for your case, rather than persistent local storage.
Comment: Are there any side effects if I use localstorage I think it is solution (but only for HTML5)?
Comment: Session storage store only text but how about Jquery object??
Comment: @kamiar3001 You will have to convert it to a json string. jquery probably has support or plug-ins to support it -- google it.
Comment: JSON.stringify(e.currentTarget) => it gets me like this : "{\"jQuery19106981751315333444\":15}"
Comment: There are some jquery plugins to directly support local storage described here: http://plugins.jquery.com/tag/localstorage/
Comment: I think I need implementation or sample using localstorage which store object and then get and change it.
Answer: All JavaScript data is unloaded when the page is changed or refreshed.  There is no way around this in JavaScript itself.  You will have to send data to the server instead.  Probably the easiest way to do this is to store your data in a hidden field:
<input type="hidden" id="storable" />
....
document.getElementById("storable").value = // whatever value you want to store

Then on the server side you can transfer that data to the new page.
If you are redirecting client side, use a query parameter instead.
Comment: But how about OOP javascript like define a static variable in namespace? is that possible I like to implement this as kind of the design pattern.
Comment: @kamiar3001 No, if you're interested head on over to Mozilla's Firefox source code and you can see that the whole DOM is unloaded every time the page changes.  There's just no way to do it.  What you could do is host everything on one page, although that's a serious thing to do and I don't recommend it.  You'd still lose your state on a refresh anyway.


compound index syntax in mongodb

Question: a quick question regarding how to define a compound index
as per the definition I can create a compound index as below and it would create a compound index for student_id and class_id.
db.students.createIndex({"student_id":1,"class_id":1});

however what will happen if I give something like this
db.students.createIndex({"student_id,class_id":1})

the syntax is valid and it accepts the index, but I am not sure how the index would be created.
any thoughts ?
Comment: Nice question but have never seen someone creating a compound index that way.
Answer: Well if you do that and then just run db.students.getIndexes() you will see that the index is created for a field called student_id,class_id - which is exactly what you asked for, i.e. not a compound index but an index on a field with a comma in its name.
{
    "v" : 1,
    "key" : {
        "student_id,class_id" : 1.0
    },
    "name" : "student_id,class_id_1",
    "ns" : "tmp.students"
}

Comment: shouldnt mongodb throw an exception there since there does not exists a field by that name?
Comment: mongoDB is not a SQL database with strict schemas. There are even features which are directly targeting the fact that there may be documents without the indexed field and therefore don't create index entries for them - see https://docs.mongodb.com/manual/core/index-sparse/

compound index syntax in mongodb


How to add a space before and after certain characters using sed or awk?

Question: I know that I can add space after or before a character using
sed -i 's/char/char /g' fname.txt

However, I need help adding space before and after these characters ```[]<>'''
for example,
nie[breath]hi
hi </langenglish>'tjie

would turn into
nie [breath] hi
hi </langenglish> 'tjie

NOTE: that i want a single space after <>[] because using the first code, I would essentially get two spaces.
Please let me know how I could accomplish this task.
Answer: From your example it seems like you're mis-specifying your problem and you actually want a space before and after every [...] or <...> string rather than before and after every [, ], <, or > character. If that's correct then using any sed that allows \n to represent a newline in the regexp and replacement text (e.g. GNU sed):
$ sed 's/ /\n/g; s/\[[^]]*]/ & /g; s/<[^>]*>/ & /g; s/ *\n */ /g' file
nie [breath] hi
hi </langenglish> 'tjie

or with any awk:
$ awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1' file
nie [breath] hi
hi </langenglish> 'tjie

You should add some non-sunny-day test cases to your example to make sure you get what you really need, e.g.:
$ echo 'head[foo<bar]tail' | awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1'
head [foo<bar] tail

$ echo 'head<foo<bar>tail' | awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1'
head <foo<bar> tail

$ echo 'head<foo[bar>tail' | awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1'
head <foo[bar> tail

$ echo 'head<foo]bar>tail' | awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1'
head <foo]bar> tail

$ echo 'head<foo[bar]tail' | awk '{gsub(/ /,"\n"); gsub(/\[[^]]*]/," & "); gsub(/<[^>]*>/," & "); gsub(/ *\n */," ")} 1'
head<foo [bar] tail

Answer: Could you please try following. Written as per shown samples only. This will add spaces before [ and < then it will add spaces after > and ]. As per shown samples.
awk '{gsub(/\[|</," &");gsub(/\]|>/,"& ")} 1' Input_file

Explanation: simply globally substituting [ and > with spaces before their values in first gsub. Then performing second global substitution to add spaces after > and ].
Answer: You can use sed like
sed 's/[[:space:]]*\([]>]\)[[:space:]]*/\1 /g;s/[[:space:]]*\([[<]\)[[:space:]]*/ \1/g' file > newfile

See an online demo:
s="nie[breath]hi
hi </langenglish>'tjie"
sed 's/[[:space:]]*\([]>]\)[[:space:]]*/\1 /g;s/[[:space:]]*\([[<]\)[[:space:]]*/ \1/g' <<< "$s"

Output:
nie [breath] hi
hi </langenglish> 'tjie

Details:

s/[[:space:]]*\([]>]\)[[:space:]]*/\1 /g  - "normalizes" whitespace before ] and > chars by removing all whitespace before and keeping one after
s/[[:space:]]*\([[<]\)[[:space:]]*/ \1/g  - "normalizes" whitespace before [ and < chars by removing all whitespace after and keeping one before


Refresh ListView in fragment TabHost

Question: I have MainActivity, which holds fragment. One of my fragments (Participants) checks if there's anything in database. If no, shows fragment(EmptyParticipantsList) with message to add data. If yes, it shows fragment with TabHost with 2 tabs, one of them holds fragment (ParticipantsList) with ListView with database entries. There's a FAB button to add more records. How can I refresh ListView after adding another record? I'm not sure since TabHost is not working with FragmentManager which I'm using in app.
//TODO refresh ListView is the place where I need to put my code.
EDIT 6.5.2017
I modify the code and add 'myCursorAdapter.notifyDataSetChanged();' after adding/editting items in SQLite but List still not refresh it self. Any help?
Participants.java
  myDB =  new DBAdapter(getActivity());
    myDB.open();
    Class S;
    if (myDB.isEmptyParticipants()) {
        S = EmptyParticipantsList.class;
    } else {
        S = ParticipantsList.class;
    }
    myDB.close();

    mTabHost = (FragmentTabHost) root.findViewById(R.id.tabHost);
    mTabHost.setup(getContext(), getChildFragmentManager(), android.R.id.tabcontent);
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("List of participants"),
    S, bundle1);
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Event information"),
            EventInfo.class, bundle1);

ParticipantsList.java
 public class ParticipantsList extends DialogFragment {

DBAdapter myDB;
ListView participantList;
long id_eventu;
EditText participantName;
EditText participantSurname;
SimpleCursorAdapter myCursorAdapter;

public ParticipantsList() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View root = inflater.inflate(R.layout.fragment_participants_list, container, false);
    myDB =  new DBAdapter(getContext());
    participantList = (ListView) root.findViewById(R.id.list_participants);
    myDB.open();
    FloatingActionButton fab1 = (FloatingActionButton) root.findViewById(R.id.fab_participant);
    Bundle bundle = getArguments();
    if (bundle != null) {
        id_eventu = bundle.getLong("key");
    }
    myDB.open();
    Cursor cursor = myDB.getAllRowsParticipant(id_eventu);
    String[] fromParticipantNames = new String[] {DBAdapter.PARTICIPANTS_NAME, DBAdapter.PARTICIPANTS_SURNAME};
    int[] toViewIDs = new int[] {R.id.name_of_participant, R.id.surname_of_participant};
    myCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.row_participant, cursor, fromParticipantNames, toViewIDs,0 );
    participantList.setAdapter(myCursorAdapter);
    myCursorAdapter.notifyDataSetChanged();
    myDB.close();

    registerForContextMenu(participantList);

    fab1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final AlertDialog.Builder addParticipantDialog = new AlertDialog.Builder(getContext());
            addParticipantDialog.setTitle("Add new Participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addParticipantDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            addParticipantDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String name = participantName.getText().toString();
                    String surname = participantSurname.getText().toString();
                    myDB.open();
                    myDB.insertRowParticipant(name,surname, id_eventu);
                    Toast.makeText(getActivity(),"Participant added", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();

                }
            });
            addParticipantDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addParticipantDialog.show();
        }
    });

    return root;
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getActivity().getMenuInflater();
    inflater.inflate(R.menu.event_popup, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    final long id = info.id;
    switch(item.getItemId()) {
        case R.id.edit_event_popup:
            final android.app.AlertDialog.Builder addEventDialog = new android.app.AlertDialog.Builder(getContext());
            addEventDialog.setTitle("Edit participant");
            final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
            addEventDialog.setView(viewInflated);
            participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
            participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
            myDB.open();
            Cursor c = myDB.db.rawQuery("SELECT * FROM participants WHERE _id=="+id, null);
            c.close();
            c.moveToFirst();
            String name_par = c.getString(c.getColumnIndex("name"));
            String surname_par = c.getString(c.getColumnIndex("surname"));
            participantName.setText(name_par); //tady se musí načíst data z db
            participantSurname.setText(surname_par);
            addEventDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //TODO zde se načtou data z polí a uloží do databáze
                    String str = participantName.getText().toString();
                    String str1 = participantSurname.getText().toString();
                    ContentValues cv = new ContentValues();
                    cv.put("name",str);
                    cv.put("surname",str1);
                    myDB.db.update("participants", cv, "_id="+id, null);
                    Toast.makeText(getActivity(),"participant changed", Toast.LENGTH_LONG).show();
                    myDB.close();
                    myCursorAdapter.notifyDataSetChanged();
                    //TODO refresh listview
                }
            });
            addEventDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            addEventDialog.show();
            return true;
        case R.id.delete_event_popup:
            myDB.open();
            myDB.deleteRowParticipant(id);
            Toast.makeText(getActivity(),"participant deleted", Toast.LENGTH_LONG).show();
            myCursorAdapter.notifyDataSetChanged();
            //TODO když je to poslední záznam, tak nahodit empty frag
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

}
Answer: You should call notifyDataSetChanged after setAdapter

Notifies the attached observers that the underlying data has been
  changed and any View reflecting the data set should refresh itself.

participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged(); // this
myDB.close();

Comment: Thanks, after i add populateListView(); where is my comment //TODO refresh ListView it is working.
Comment: @Raddino Happy to hear . #Abid Thanks
Comment: I was trying to reuse code in different places in app and it's not working. I read a few articles and I'm sure calling populateListView(); after adding/editing item to refresh ListView is bad idea, correct is to use notifyDataSetChanged but not sure where to use it properly.

Refresh ListView in fragment TabHost


Django ORM - LEFT JOIN Table2 ON Table2.Column = 123

Question: What i whant to achieve:
http://sqlfiddle.com/#!5/dccc4/5
DB Scheme:

CREATE TABLE Table1
(
 idTable1 integer primary key
);

CREATE TABLE Table2
(
  idTable1 integer,
  user_id integer,
  num integer
);

INSERT INTO Table1 (idTable1) VALUES (1);
INSERT INTO Table1 (idTable1) VALUES (2);
INSERT INTO Table2 (idTable1, user_id, num) VALUES (1, 11, 111);
INSERT INTO Table2 (idTable1, user_id, num) VALUES (1, 22, 222);

Raw SQL query:
SELECT    T1.idTable1,
          IFNULL(T2.num, 0) num
FROM      Table1 T1
LEFT JOIN Table2 T2
ON        T1.idTable1 = T2.idTable1
AND       T2.user_id  = 11
WHERE     T1.idTable1 = 1

Resulting QuerySet:
| idTable1 | num |
|----------|-----|
|        1 | 111 |

Is it possible to code using Django ORM?
UPDATE
Models are:

class Table1(models.Model):
    # ...

class Table2(models.Model):
    user = models.ForeignKey(User)
    table1 = models.ForeignKey(Table1)

    num = models.IntegerField(null=True)

Answer: Something like this:
from django.db.models import Q, Value as V
from django.db.models.functions import Coalesce

objects = Table1.objects.filter(
              Q(table2__isnull=True) | Q(table2__user=11),
              id=1
          ).annotate(
              num=Coalesce('table2__num', V(0))
          ).values('id', 'num')

It is LEFT JOIN, but I don't know if Django can construct AND part in queries like ... LEFT JOIN ... ON ... AND ... WHERE. In this case, end result is the same (I hope).
Comment: That gives me INNER JOIN instead of LEFT JOIN:

SELECT "myApp_Table1"."idTable1", COALESCE("myApp_Table2"."number", 0) AS "number" FROM "myApp_Table1" INNER JOIN "myApp_Table2" ON ( myApp_Table1"."idTable1" = "myApp_Table2"."idTable1" ) WHERE ( "myApp_Table2"."user_id" = 11 AND "myApp_Table1"."idTable1" = 1 )
Comment: Excellent! Thank you very much!


Exclude nodes present in panel from view pane

Question: I have a panel page where a user selects nodes (using IPE) to be displayed, the page also contains a view pane, which must not contain those same nodes.
How do I get the view to exclude the nodes present in the panel?
Answer: We had the same issue on a page with a lots of news and user customizable Top News - we used the module views_exclude_previous module and it worked fine for this case.
Comment: I've added the views_exclude_previous filter to the view-pane which is added to the panel page. It seems to work well!


Is www-data considered a non-privileged user on Apache?

Question: Great Apache Hardening post that recommends "Run Apache from non-privileged account" because "Default apache configuration is to run as nobody or daemon."
Is www-data:www-data considered a non-privileged account by default?
Or is it better to change to something like apache2:apache2?
In either case, is it best to change the Apache files from root ownership to that user?
sudo chown -R www-data:www-data /etc/apache2

OR
sudo chown -R apache2:apache2 /etc/apache2

Answer: It makes no difference at all if the Apache user is called www-data, apache2 or dumbo (www-data is the default on Debian derivatives, and apache2 on RedHat). Both are non-privileged (e.g. non-root) on their respective platforms, because that is what's important: The user needs to have as few permissions as possible in the rest of the system. The default installation/configuration on nearly all distributions for Apache automatically take care of this.
Furthermore, you should restrict the data files as much as possible, but that is often limited by other concerns like allowing users to edit the files.
Comment: I can't tell. It's your system and you have to know who needs access to it. In many cases, I only allow read-only access for only the web server user but your requirement might differ.
Comment: Thanks.  So it is best to sudo chown -R www-data:www-data /etc/apache2 on Debian systems?  I assume you want to deny access to all except root and www-data anyway.  Is there a user I am forgetting that would need write access?


How do I define RowVersion in a C# class when using SQL Server and Entity Framework

Question: I have created a SQL table and an EF Fluent mapping as follows:
CREATE TABLE [dbo].[Application] (
    [ApplicationId]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (50) Not NULL,
    [DataVersion] ROWVERSION,
    CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);

My EF Fluent API looks like this:
public class ApplicationConfiguration : EntityTypeConfiguration<Application>
    {
        public ApplicationConfiguration()
        {
            Property(a => a.Name)
                .IsRequired()
                .HasMaxLength(35);

            Property(p => p.RowVersion).IsRowVersion();

        }
    }

My Class looks like this:
public class Application
{
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
    xxxxxxx
}

Can someone tell me how I can define the RowVersion in my class?
Comment: What version of EF are you using?
Answer: This works for me - I'm using EF4:
public class Application
{
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }

    public virtual byte[] RowVersion { get; set; }
}

Mapping:
public class ApplicationConfiguration : EntityTypeConfiguration<Application>
{
    public ApplicationConfiguration()
    {
        Property(a => a.Name)
            .IsRequired()
            .HasMaxLength(35);

        Property(p => p.RowVersion).HasColumnName("DataVersion").IsRowVersion();
    }
}

PS: The datatype of my database colum is timestamp (I'm using SQL Server 2005)
Answer: I think it's
public class Application
{
    public int ApplicationId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TestAccount> TestAccounts { get; set; }
    public virtual byte[] DataVersion { get; set; }
}


Confused on two parts of Proof in C* algebras by Murphy

Question: I'm working through the proof of the following theorem from C* algebra by Murphy.  For context, $T_{\varphi}: H^2(T) \longrightarrow H^2(T)$ is given by $T_{\varphi}(f) = p(\varphi f)$ for $p: L^2(T) \longrightarrow H^2(T)$ the orthogonal projection of $L^2(T)$ onto $H^2(T)$.

I don't understand how the collection $(\epsilon_n f)_{n \in \mathbb{Z}}$ is $L^2$ norm dense in $L^2(T)$ for seemingly every $f \in H^2(T)$.  What if $f=0$?

While I understand that $||M_{\varphi}(g)||^2 = \langle M_{\varphi}^{*}M_{\varphi}(g),g\rangle \geq \langle g,g\rangle/M^2$ which implies $||M_{\varphi}^{*}M_{\varphi}(g)|| \geq ||g||/M$, so $M_{\varphi}^{*}M_{\varphi} \geq I/M^2 > 0$, and thus by applying the Gelfand representation  theorem to $C^{*}(M^{*}_{\varphi}M_{\varphi})$ (using normality of $M_{\varphi}$ to conclude this algebra is abelian), we conclude that $M_{\varphi}^{*}M_{\varphi} \in \text{Inv}(B(L^2(T)))$, why does this imply $M_{\varphi}$ is also invertible?  I don't see why normality implies this.
Comment: If $M_\varphi^* M_\varphi$ is invertible then $M_\varphi$ admits a left inverse.  If $M_\varphi M_\varphi ^*$ is invertible then $M_\varphi$ admits a right inverse.  So it is invertible.
Comment: I think Murphy means that $\{\varepsilon_nf:n\in\mathbb{Z}\wedge f\in H^2\}$ is dense in $L^2$. This is all you need, because the goal is to show that $\|M_\varphi(g)\|\ge \|g\|/M$ for all $g\in L^2(\mathbb{T})$.
Answer: I think Murphy means that $\{\varepsilon_nf:n\in\mathbb{Z}\wedge f\in H^2\}$ is dense in $L^2$. This is all you need, because the goal is to show that $\|M_\varphi(g)\|\ge \|g\|/M$ for all $g\in L^2(\mathbb{T})$.
For 2, use the spectral theorem: if $A$ is a unital $C^*$-algebra and $a\in A$ is normal, then $\sigma(f(a))=f(\sigma(a))$ for any $f\in C(\sigma(a))$. So $\sigma(aa^*)=\{|\lambda|^2:\lambda\in\sigma(a)\}$. If $aa^*$ is invertible, then $0\not\in \sigma(aa^*)$, and the previous set equality implies that $0\not\in \sigma(a)$. This means that $a$ is invertible.


Analisar emails com R

Question: Gostaria de saber por favor se há algum pacote no R que faça text mining para emails do outlook, para que possa filtrar emails por palavras chave, ou por algum tipo de argumento, extraindo informações relevantes e ignorando os demais emails.
Answer: O R tem pacotes que lhe permitem analisar documentos de texto para a realização de processamento dos documentos, como filtragem e extração de informações. Entretanto, as APIs, não soh de R, como Python, Java, etc, são bem "baixo nível".
Posso estar errado, mas observando a sua pergunta acredito que vc seja iniciante na questão de text mining. Enfim, existe o processo de KDD que orienta o pesquisador em como analisar documentos.
No caso, acredito que vc vá precisar extrair os emails do Outlook para documentos de texto. Fazer a limpagem e processamento dos dados.
Aplicar técnicas básicas de text mining, como remoção de stop word, TF-IDF, etc.
Após criar um dicionário de palavras, e aplicar uim regex em todos os documentos, para localizar as palavras. Quando vc escreve "extraindo informações relevantes" pode significar muitas coisas.
Como a pergunta não tem nenhum código e ainda sugere que vc eh muito iniciante, recomendo fazer algum curso na área, como o Datacamp que é super prático.

Analisar emails com R


Mismatch of CPU Architecture for the Crosswalk using Cordova

Question: I have integrate crosswalk plugin in my Cordova application. When I publish this app to google play. I'm not able to open in my Asus gen phone 2 it throws following error
Error message:Mismatch of CPU Architecture for the Crosswalk

Cordova version - 6.0.0
Crosswalk Version - latest

Can any one help me for resolving this problem?
Answer: The Asus phones tend to use an Intel x86 chipset. When doing anything with native code, you need to account for the various chipsets used by devices. Crosswalk is built with native code. It sounds like you did not include builds for both the ARM and x86 chipsets to Google play.
The Cordava Crosswalk plugin out-of-the-box will give you 2 chipset builds, 1 for ARM and 1 for x86 CPU architectures. You should be uploading both APK output files to Google Play.
NOTE: Since Google play changed the max APK size from 50mb to 100mb, you now have the option of package both chipsets together. However, you may still want to consider having a separate build for each and uploading them separately.
Comment: If someone doesn't know how to upload multiple apk to store, here is the official manual:
https://developer.android.com/google/play/publishing/multiple-apks.html


android emulator ==> change heapSize?

Question: I am trying to change the heap size of the emulator, to make sure that my app doesn't run out of memory with 16 mb available? How can i change the heap size on the emulator?
I run the emulator through Eclipe.
Answer: When creating an emulator u can set the properties, and there is a heap size, which u can change.

android emulator ==> change heapSize?


Printing smallest and largest number.Output is not what i wanted

Question: Write a method named smallestLargest that asks the user to enter numbers, then prints the smallest and largest of all the numbers typed in by the user. You may assume the user enters a valid number greater than 0 for the number of numbers to read. Here is an example dialogue:
How many numbers do you want to enter? 4
Number 1: 5
Number 2: 11
Number 3: -2
Number 4: 3
Smallest = -2
Largest = 11

This is what i have done but i am unable to get the smallest and largest output.
import java.util.*;
public class smallestLargest{
    public static void main(String[] args){

        System.out.print("How many numbers do you want to enter? ");
        Scanner sc=new Scanner(System.in);
        int count=sc.nextInt();

        int smallest=Integer.MAX_VALUE;
        int largest=Integer.MIN_VALUE;

        for(int i=1;i<=count;i++){
            System.out.println("Number" + i + ": ");
            int nextNumber=sc.nextInt();
            if(nextNumber<smallest){
                smallest+=nextNumber;
            }
            else if(nextNumber<largest){
                largest+=nextNumber;
            }

        }
        System.out.println("Smallest= "+ smallest);
        System.out.println("Largest= "+ largest);

    }
}

Answer: This is the problem:
if(nextNumber<smallest){
    smallest+=nextNumber;
}
else if(nextNumber<largest){
    largest+=nextNumber;
}

That doesn't do what you want at all.
I'm not going to give you the solution, but think about it - just do one of them at a time. Let's start with "smallest".

If our current smallest number is 5, and someone enters 2, what should the new smallest number be? Why?
If our current smallest number is 5, and someone enters 10, what should the new smallest number be? Why?

Work that out, then apply the same thought process to "largest number".
Comment: Got my solution!Thank you so much!
Comment: @user2098510: In the lines that Jon quoted, just FYI, there are *three* separate issues, so do follow the thought process through carefully. It would be easy to catch only one or two of them.
Answer: Don't use "else if", because on the first loop, the number will pass both tests - i.e. it will be the smallest AND the largest, also don't use "+=", just "=" and change the "largest". So something like:
if(nextNumber<smallest)
    smallest=nextNumber;

if(nextNumber>largest)
    largest=nextNumber;

Comment: Well, it's perfectly fine that the first number is the smallest and largest. Look at it this way: If there is only one number, is it the smallest or the largest? In my world, both.
Answer: Little bit 'I am lazy' solution:
        Scanner sc = new Scanner(System.in);
        List<Integer> numbers = new ArrayList<Integer>();
        while (sc.hasNextInt())
        {
            numbers.add(sc.nextInt());
        }
        System.out.println("Smallest= " + Collections.min(numbers));
        System.out.println("Largest= " + Collections.max(numbers));


what do you mean with the "common practice period?"

Question: Does anybody know a German equivalent term?
Now I have read some articles but nowhere found an answer (translation) in German.
Looking up "Klassische Musik" - whereby I know this term is used for the Classic period - and also for all tonal so called "serious music" but in this Wiki link in German there was not clear when the common practice period began.
The English version of this Wiki page says:
Classical music is art music produced or rooted in the traditions of Western culture, *including both liturgical (religious) and secular music. While a more precise term is also used to refer to the period from 1750 to 1820 (the Classical period), this article is about the broad span of time from before the 6th century AD to the present day, which includes the Classical period and various other periods. The central norms of this tradition became codified between 1550 and 1900, which is known as the common-practice period.
https://en.wikipedia.org/wiki/Classical_music
Would  you say the term common practice period is identical as the term "classical music" in the extended sense (not the classical period).
Am I right the central norms are the tonal system, harmony, the melodic- harmonic and rhythmic language as  figured bass and counterpoint, e.g. the  subjects that composers of this era had been taught and used?
With other words: the theory and practice of  traditional western european music?
So I wonder where does this term come from? I couldn't find a name mentioned ... is it a British term or American? as I've never heard an equivalent German term ...
Comment: All of your questions are answered by consensus in the Wikipedia article that you included a link to in your question. Classical music before 1550 is called "medieval music" and later "renaissance music". Classical music after the common practice period is called "Romantic", "Modern/Modernist", "Contemporary", "Post-Modern", and/or "Post-Post-Modern", depending. Music as a whole is not an "objective science", but as this site clearly shows, **there are many questions related to music that do have objective answers**. Subjective questions are off-topic.
Comment: Did you notice the separate Wikipedia page "Common practice period"? https://en.wikipedia.org/wiki/Common_practice_period
Comment: Note that there are so many kinds of music made since 1900 that would not even remotely be called "pop". In terms of the phrase "classical music", I think many people use that term broader than the common practice period. There is a lot of 20th century music that most people would call "classical", in the larger sense, including serialism, Penderecki, Ligeti, and many film scores.
Comment: I love (sarcasm) how that Wikipedia date range would lump together Palestrina with Erik Satie as sharing a common _practice_. That's absurd! Yes, I know about Satie's interest in the Medieval (not Palestrina) but that was _appropriation_, not a shared practice in my view.
Comment: yes, I remember this one too, I've even downloaded this Pdf:
Konečni, Vladimir J. (2009). "Mode and Tempo in Western Classical Music of the Common-Practice Era" - But the I was focussing the question how this is named in German and I was still interested how other users would explain their concept without looking up Wikipedia.
Comment: Based on your comment, it sounds like you're looking for various people's personal views on the term, and you're looking for a translation to German. Neither of those two things are on-topic here. Did I misunderstand your comment?
Comment: Todd, I still am convinced that each one has his own concept of any of all this musical terms as tonality, harmony, function. As long as you believe that music is an  objective science and not subjective can vote for all my questions as off-topic and opinion based. I understand that your first comment means that "classical music" would not mean common practice. And yes I for got to ask where this term comes from.
Comment: I agree with you. I've also found this page:
https://study.com/academy/lesson/common-practice-style-developing-tonal-harmony.html
So the answer would be concerning the era: Barock, Klassik, Romantik?

I'm still asking as it is not clear what people understand under classical music.
Comment: I'm voting to close this question as off-topic because it should be migrated to English Learners or English Language, maybe even German if that exists. Translation's not on-topic here.
Comment: We should probably start using a [common-practice] tag with a good tag description. There are over 800 posts here which contain the phrase "common practice", and half of them seem to be about the "common practice period" and assume that the reader knows what this means, and the other half just use the everyday meaning of "common practice". Adding the tag could clear up some of the confusion.
Comment: Thank you, uncle Bob. That's in a few words what I mean.
Comment: @Albrecht - please remember to **only ask one question** in a post!
Comment: And as Todd said, all the answerable (ie not opinion-based) answers to your questions are in the wikipedia page you linked to!
Comment: I have asked in the English-German SE before. I am convinced that all terms as *common, use, ordinary,  natural, normal* should be questioning more often.
Answer: You could write a very long description of what 'common practice' means re. the common practice period.
But my feeling is the longer the description becomes - when attempting to cover the extreme ends of the 17th and 19th century - the less meaningful the description will be.
So, IMO, I think two of the most important ideas of 'common practice' are: the voicing leading norms exemplified in Fux and other similar teaching, and the 'rule of the octave' from figured bass harmony.
My understanding is both of those are very important aspects of music teaching from the common practice era. Literally the musicians shared a common practice through application of what was taught to them.
So things like...

resolving a dissonant 4th to a 3rd
harmonizing the mediant in the bass with I6 not iii
raise the leading tone in minor for cadences, etc.

...can be accounted for simply from counterpoint rules and the rule of the octave.
To me, adhering to those fundamentals is 'common practice' in a nutshell.
Comment: @AlbrechtHugli, The introduction to my Piston's Harmony, 1st edition, 1941, uses "common practice" several time, although not "common practice period."
Comment: thank you. Michel, and do you know where the term comes from? It seems to be a newer  one as I can't find it in all my books before 2000.
Comment: I don't know the origin, but I'm sure I remember it from college, which for me is way before 2000. :-)
Comment: Walter Piston! That's what I've found out too. Sometimes it is not so easy as someone with a foreigner language to understand. I would have wished to receive more help from my american musician friends, somehow like you. It would have been so easy to tell me: common practice is what ordinary people understand as "normal music" ... Thank you, Michael, you have to know that to Swiss people also German is a foreign language and also the translation of "common practice" has a quite different meaning.


Porque a somas esta retornando 0 e só funciona quando coloco as variáveis como locais?

Question: quando coloco a var n1,n2 e a s dentro da function somar, só ai que o resultado aparece certo!porque?  Sou iniciante.
/*variaveis dos elelentos html*/
var dr1= document.querySelector('input#txtn1')
var dr2= document.querySelector('input#txtn2')
var botao = document.querySelector('button.so')
var r = document.querySelector('div.res')

/*recebe os valores digitados no input*/
var n1= Number(dr1.value)
var n2 = Number(dr2.value)
/*realizar a soma dos valores do input*/
var s = n1 + n2
/*cria um evento para ser chamado*/
botao.addEventListener("click",somar)

function somar(){

    r.innerHTML = s
    r.style.color = 'red'
}

Comment: é simples, quando executa o código guarda os valores da variáveis, e se mudar não são atualizadas. Se quer pegar os valores atualizados tem que colocar o código na função soma como o @AugustoVasques comentou. Faça um debug e vais perceber isso facil ;)
Comment: Do comentário `/*recebe os valores digitados no input*/` até o comentário `/*cria um evento para ser chamado*/` mova para primeira linha da função `soma()`.
Comment: Vlw, então é recomendado colocar as variáveis de conversão  e de operação dentro da função como variáveis locais? e quando devo ou não usar como variável global teria um exemplo ou alguma referencia bibliografia sobre isso?
Comment: *"é recomendado colocar as variáveis de conversão e de operação dentro da função como variáveis locais"* não tem a ver com ser recomendado, só que **é preciso que seja local** pq precisa pegar o valor atualizado, mas uma ideia mais ampla é sempre usar variável local, a global é excessão, só use se **realmente precisar**
Comment: O vlw, agradeço de verdade, abraço.
Answer: Você esta executando a soma antes mesmo do evento ser disparado, a soma esta sendo executada quando a página carrega, e neste momento provavelmente os inputs estão vazios
Quando você usa o click a soma JÁ FOI EXECUTADA, então basta mover tudo pra dentro da função:

/*variaveis dos elelentos html*/
var dr1= document.querySelector('input#txtn1')
var dr2= document.querySelector('input#txtn2')
var botao = document.querySelector('button.so')
var r = document.querySelector('div.res')

botao.addEventListener("click",somar)

function somar(){

    /*recebe os valores digitados no input*/
    var n1= Number(dr1.value)
    var n2 = Number(dr2.value)
    /*realizar a soma dos valores do input*/
    var s = n1 + n2
    /*cria um evento para ser chamado*/

    r.innerHTML = s
    r.style.color = 'red'
}
<input id="txtn1"> + <input id="txtn2"> =

<button type="button" class="so">Somar</button>


Why is jQuery .focus not firing?

Question: In the code below, the first alert() fires, but the second one never fires when I click the textfield assigned with the 'clear' class.
Does anyone have a clue why this happens?
(function ($){

   alert('TEST 1');
   var clearMePrevious = '';

   // Clear input on focus.
   (function ($)('.clear').focus(function() {
     alert('TEST 2');
     /*
      if ($(this).val() == $(this).attr('title')) {
        clearMePrevious = $(this).val();
        $(this).val('');
      }
      */
    }(jQuery));

}(jQuery));

The problem is just in the inner code, as $document.ready() fires the TEST 1 alert.
I have tried different variations of (function ($){}); and function (jQuery){});.
Answer: Your formatting made me twitch, so I fixed it up for you.
Drupal JS Coding Standards
Also you weren't using a behavior, so I fixed that too:
Javascript in D7
(function ($) {
  Drupal.behaviors.textFieldClearer = {
    attach: function (context, settings) {
      var clearMePrevious = '';

      // clear input on focus
      $('.clear').focus(function() {
        if($(this).val() == $(this).attr('title')) {
          clearMePrevious = $(this).val();
          $(this).val('');
        }
      });

      // if field is empty afterward, add text again
      $('.clear').blur(function() {
        if($(this).val() == '') {
          $(this).val(clearMePrevious);
        }
      });
    }
  };
}(jQuery));

Answer: It turns out I misunderstood the documentation: $ is accessible inside a (function ($){} block. The trick is that you really need to add the $(document).ready() call to have the selectors accessible after the page loads.
(function ($) {
  $(document).ready(function() {
    var clearMePrevious = '';

    // clear input on focus
    $('.clear').focus(function()
    {
        if($(this).val()==$(this).attr('title'))
        {
            clearMePrevious = $(this).val();
            $(this).val('');
        }
    });
    // if field is empty afterward, add text again
    $('.clear').blur(function()
    {
        if($(this).val()=='')
        {
            $(this).val(clearMePrevious);
        }
    });
  });
})(jQuery);

Why is jQuery .focus not firing?


Adding time values together to form a Total

Question: I have the below code, and am expecting the total to be 12:37:47 but I'm getting a whole number of 12 instead.  These are the results:
Category 1 - 06:02:06
Category 2 - 06:35:41
Total - 12
How can I get a Total result of 12:37:47?
$sql    = "SELECT hesk_categories.name, COALESCE(NULLIF(SEC_TO_TIME(SUM(TIME_TO_SEC(TimeSpent))),0),'00:00:00') AS TimeSpent from hesk_categories left Join hesk_tickets on hesk_categories.id = hesk_tickets.category left join TimeSpent on hesk_tickets.id = TimeSpent.ID and (DateCreated between  DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() ) where hesk_categories.name <> 'Feature Request' group by hesk_categories.name";
$query  = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
    $TimeSpent = $row['TimeSpent'];
    $TimeSpent = $TimeSpent + $TimeSpent;

    $message.="
";
    $message.="" . $row['name'] . "	";
    $message.="" . $row['TimeSpent'] . "	";
    $message.="
";
}

$message.="
";
$message.="Total	";

    if ($TimeSpent >= '10:00:00')
    {
        $message.="" . $TimeSpent . " (Support Hours have exceeded 10 hours for the month.)	";
    }
    else
    {
        $message.="" . $TimeSpent . "	";
    }
$message.="
";
$message.="

";

Comment: Why are you doing `$TimeSpent = $row['TimeSpent'];    $TimeSpent = $TimeSpent + $TimeSpent;`? Do you want to add time or add total of hours, mins, secs?
Comment: Yes, total time including hours, mins, secs
Comment: You would be better off getting the time from the database in number of seconds and then formatting the display in PHP (or fetching both).  Your code is trying to add 2 formatted times together as numbers (and it doesn't accumulate the total either).
Comment: You can not can not calculate hour, minutes that way simply.
Comment: Doing `if ($TimeSpent >= '10:00:00')` is kinda bad style. I think it might work, but you're not comparing dates, but strings, and you never know how that will turn out.
Answer: I added this to the query:
SUM(TIME_TO_SEC(TimeSpent)) as TimeSpentSeconds

and this to the if statement:
if ($TimeSpentSeconds >= 36000)
{
    $TimeSpentSeconds = $TimeSpentSeconds / 3600;
    $message.="" . number_format((float)$TimeSpentSeconds, 2, '.', '') . " hrs (Support Hours have exceeded 10 hours for the month.)	";
}
else
{
    $TimeSpentSeconds = $TimeSpentSeconds / 3600;
    $message.="" . $number_format((float)$TimeSpentSeconds, 2, '.', '') . " hrs	";
}

Does the job.