Resizing HBITMAP while keeping transparent background

Question: I have an application that loads an image with a transparent background, then I use StretchBlt to resize it to the desired size, with HALFTONE set using SetStretchBltMode (I tried using other modes that, while keeping the transparency intact, also made the resized image look 'ugly').
However, StretchBlt replaces the transparent background with a color (black) that doesn't fit the background of the window that the image will be displayed on.
So I have two options:
1) Replace the transparent background of the image with the background color of the window, then resize it using StretchBlt
2) Resize it while keeping the background transparency (preferred option)
I tried looking for WinAPI function that would provide either functionality, but I found none.
How do I do any of those options (replace the transparency or resize it while keeping it) using plain WinAPI?
Comment: "transparent background" is very unspecific - please tell us the exact image format, e. g. "32 bpp ARGB with premultiplied alpha". Also, showing your current code would be helpful.
Comment: It is a GDI function, GDI is stuck at 24bpp and does not support 32bpp image formats.  Consider GDI+, gdiplus.h header file.
Comment: Have a look at the [WIC API](https://msdn.microsoft.com/en-us/library/windows/desktop/ee719655(v=vs.85).aspx). GDI is not up to much these days (and GDI+ is rather slow).
Comment: One way to make your image transparent is to get the individual pixels using *GetDIBits* and then merge them with the window background color (pixel by pixel).
Answer: First, BitBlt, StretchBlt and TransparentBlt do NOT support the alpha channel..
TransparentBlt works by making whatever specified colour you want, transparent.
If you want Alpha channel and blending support, you need: AlphaBlend.
You can do the following:
BLENDFUNCTION fnc;
fnc.BlendOp = AC_SRC_OVER;
fnc.BlendFlags = 0;
fnc.SourceConstantAlpha = 0xFF;
fnc.AlphaFormat = AC_SRC_ALPHA;

//You need to create a memDC.. and an HBITMAP..

//Select the hBitmap into the memDC.
HGDIOBJ obj = SelectObject(memDC, hBmp);

//Render with alpha blending..
AlphaBlend(DC, rect.X, rect.Y, rect.Width, rect.Height, memDC, 0, 0, Width, Height, fnc);

//Restore the memDC to original state..
SelectObject(memDC, obj);

OR do your own pre-multiplied alpha rendering by calculating the channel colours yourself..
Alternatively, you can try GDI+ and see how that works out:
ULONG_PTR GdiImage::GDIToken = 0;
Gdiplus::GdiplusStartupInput GdiImage::GDIStartInput = NULL;
Gdiplus::GdiplusStartup(&GdiImage::GDIToken, &GdiImage::GDIStartInput, NULL);

Gdiplus::Image* Img = Gdiplus::Image::FromFile(L"PathToImage.ext"); //where ext can be png, bmp, etc..

Gdiplus::Graphics graphics(DC);
//graphics.SetSmoothingMode(SmoothingModeHighSpeed);
graphics.SetInterpolationMode(Gdiplus:: InterpolationModeBilinear); //InterpolationModeNearestNeighbor
//graphics.SetPixelOffsetMode(Gdiplus::PixelOffsetModeHalf);
graphics.DrawImage(Img, x, y, w, h);

delete Img;
Gdiplus::GdiplusShutdown(GdiImage::GDIToken);
GdiImage::GDIStartInput = NULL;
GdiImage::GDIToken = 0;

Comment: This works, but the resulting image is ugly just like with `StretchBlt` without using `HALFTONE`, as described in my question.
Comment: Well I'm not sure what you mean by "looks ugly". You don't want to use `HALFTONE`,  but you want to up-scale.. Do you have before and after images? (before scaling, scaling with half-tone, scaling without half-tone).
Comment: @あぶらだこ; I added `GDIPlus` just in case you want to try that.. `GDIPlus` can support Transparent bitmaps, png, etc.. it also has interpolation, smoothing, half-tone and other effects and transformations..
Answer:
I tried looking for WinAPI function that would provide either
  functionality, but I found none.

Although others already gave a few suggestions, to my knowledge none of the currently (12/2017) available native OS APIs provide high-quality image resampling.
There are many third-party libraries available for resampling. Many (most?) of them are quite complicated and propably overkill if image processing is not the main job of your application.
In the following example I am using the public-domain, single-header file, no-external-dependencies "stb_image_resize.h" library. Just #include it in your project and be done with it. The library is not the fastest, but I wouldn't call it particularly slow. Where it shines is ease-of-use and versatility. It is also easy to extend, if you'd like to have additional filters like Lanczos (for which I can provide code if there is interest). Though the built-in filters are already much better than the ones of the OS APIs.
The following sample program expects to find a 32 bpp bitmap with an alpha-channel (non-premultiplied) in the file "flower.bmp" of the current directory.
The image is loaded using the OS API LoadImageW(), resampled to one third of the original dimensions using stbir_resize_uint8() and stored as "flower_resized.bmp" in the current directory using GDI+.
#include <Windows.h>
#include <iostream>
#include <gdiplus.h>
#pragma comment( lib, "gdiplus" )
namespace gp = Gdiplus;

#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "stb_image_resize.h"

int main()
{
    // Using LR_CREATEDIBSECTION flag to get direct access to the bitmap's pixel data.
    HBITMAP hBmpIn = reinterpret_cast<HBITMAP>(
        LoadImageW( NULL, L"flower.bmp", IMAGE_BITMAP, 0, 0,
                    LR_LOADFROMFILE | LR_CREATEDIBSECTION ) );
    if( !hBmpIn )
    {
        std::cout << "Failed to load bitmap.\n";
        return 1;
    }

    // Getting bitmap information including a pointer to the bitmap's pixel data
    // in infoIn.dsBm.bmBits.
    // This will fail if hBmpIn is not a DIB. In this case you may call GetDIBits()
    // to get a copy of the bitmap's pixel data instead.
    DIBSECTION infoIn{};
    if( !GetObject( hBmpIn, sizeof( infoIn ), &infoIn ) )
    {
        std::cout << "Bitmap is not a DIB.\n";
        return 1;
    }

    // Some sanity checks of the input image.
    if( infoIn.dsBm.bmBitsPixel != 32 || infoIn.dsBm.bmPlanes != 1 ||
        infoIn.dsBmih.biCompression != BI_RGB )
    {
        std::cout << "Bitmap is not 32 bpp uncompressed.\n";
        return 1;
    }

    // Create a DIB for the output. We receive a HBITMAP aswell as a writable
    // pointer to the bitmap pixel data.
    int out_w = infoIn.dsBm.bmWidth / 3, out_h = infoIn.dsBm.bmHeight / 3;
    BITMAPINFO infoOut{};
    auto& hdr = infoOut.bmiHeader;
    hdr.biSize = sizeof(hdr);
    hdr.biBitCount = 32;
    hdr.biCompression = BI_RGB;
    hdr.biWidth = out_w;
    hdr.biHeight = out_h;  // negate the value to create top-down bitmap
    hdr.biPlanes = 1;
    unsigned char* pOutPixels = nullptr;
    HBITMAP hBmpOut = CreateDIBSection( NULL, &infoOut, DIB_RGB_COLORS,
        reinterpret_cast<void**>( &pOutPixels ), NULL, 0 );
    if( !hBmpOut )
    {
        std::cout << "Could not create output bitmap.\n";
        return 1;
    }

    // Resample the input bitmap using the simplest API.
    // These functions use a "default" resampling filter defined at compile time
    // (currently "Mitchell" for downsampling and "Catmull-Rom" for upsampling).
    // To change the filter, you can change the compile-time defaults
    // by #defining STBIR_DEFAULT_FILTER_UPSAMPLE and STBIR_DEFAULT_FILTER_DOWNSAMPLE,
    // or you can use the medium-complexity API.
    // Consult "stb_image_resize.h" which contains the documentation.

    stbir_resize_uint8(
        reinterpret_cast< unsigned char const* >( infoIn.dsBm.bmBits ),
        infoIn.dsBm.bmWidth,
        infoIn.dsBm.bmHeight,
        0,  // input_stride_in_bytes, 0 = packed continously in memory
        pOutPixels,
        out_w,
        out_h,
        0,  // output_stride_in_bytes, 0 = packed continously in memory
        4   // num_channels
    );

    // Use GDI+ for saving the resized image to disk.

    gp::GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR gdipToken = 0;
    gp::GdiplusStartup( &gdipToken, &gdiplusStartupInput, nullptr );

    {
        gp::Bitmap bmpOut( hBmpOut, nullptr );
        // I'm taking a shortcut here by hardcoding the encoder CLSID. Check MSDN to do it by-the-book:
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms533843(v=vs.85).aspx
        class __declspec(uuid("{557cf400-1a04-11d3-9a73-0000f81ef32e}")) BmpEncoderId;
        bmpOut.Save( L"flower_resized.bmp", &__uuidof(BmpEncoderId) );
    }

    // Cleanup
    gp::GdiplusShutdown( gdipToken );
    DeleteObject( hBmpIn );
    DeleteObject( hBmpOut );

    std::cout << "All done.\n";

    return 0;
}

Notes:
When resampling transparent images, it is generally advisable to use a premultiplied alpha channel. Otherwise the resampled image can have artifacts, generally noticable along the edges of shapes. STBIR will use "alpha-weighted resampling" (effectively premultiplying, resampling, then unpremultiplying) unless you specify the STBIR_FLAG_ALPHA_PREMULTIPLIED flag. So you will gain performance benefits when manually premultiplying once after loading an image. Most Windows APIs (like AlphaBlend) that can show transparent images, expect the alpha channel to be premultiplied anyway.


Is this answer wrong? Shouldn't it be $+8x$ in numerator? (it's in my textbook)

Question: I did it with log and quotient rule and got $+8x$ in numerator both times.
Am I making a mistake or is the answer is wrong?
Comment: Yes it should be +8x.
Comment: Welcome to MSE. It is in your best interest that you type your questions (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.
Comment: Thanks @AnkitKumar
Comment: @JoséCarlosSantos Thanks for the suggestion. I'm trying to learn MathJax.
Comment: Hmm,   sure seems wrong to  me.  Let's see. If $x > 2$ then if we compare $y(x)$ to $y(x + h); h> 0$ we know $$y(x+h) > y(x) \iff \frac {(x+h)^2 - 4}{(x+h)^2 + 4} > \frac {x^2 -4}{x^2 + 4} \iff ((x+h)^2 -4)(x^2+4) > (x^2 -4)((x+h)^2 +4) \iff -4x^2 + 4(x+h)^2 > -4(x^2 +h)^2 + 4x \iff 8(x+h)^2 > 8x^2\iff x+h > x$$ which of course it is.  So at $x> 2$, $y$ is increasing so $y'$ is positive.  Which is not what the book gets.  So the book is wrong.
Answer: On the third to last line the book calculates $(x^3 + 4x) - (x^3 - 4x) = -8x$.
Well.... obviously that is a careless error. (One that we've all made and will all make again sometime).
So you are right and the book is wrong.
This may be overkill but $x > 2$ then book's derivative is negative and ours is positive.  So for $2 < x < x'$ we can check to see if $y$ increases or decreases.
I claim for positive $b > a > c$ that $\frac {b-c}{b+c} > \frac {a-c}{a+c} \iff (b-c)(a+c) > (b+c)(a-c) \iff bc - ac > ac - bc $ which is clearly true as $bc - ac > 0 > ac - bc$.
So $\sqrt{\frac {x'^2 -4}{x'^2 + 4}} > \sqrt{\frac {x^2 -4}{x^2 +4}}$ and $y$ is increasing which confirms our suspicions and refutes the book's result.


How to convert an object to a set?

Question: so I have a set named "all" that contains objects Doc. Then I have another set called "partDocs" that contains other sets that contains Doc. Let's say that "all" contains = [Doc1, Doc2, Doc3]. I want partDocs to contain those sets like: [[Doc1], [Doc2], [Doc3]]. How can I do that?
I tried
Set<Doc> all = new HashSet<Doc>(); // contains [Doc1, Doc2, Doc3]
Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> set2 = new HashSet<Doc>();

for (i = 0; i < all.size(); i++) {
   set2.clear();
   set2.add(all.stream().toList().get(i)); // adds the i.th element of the all set
   partDocs.add(set2);
}

However when I do this, partDocs only has the last element of the all set, because set2 is always changing, and its last value is [Doc3]
I also tried doing below, but its syntax is wrong
for (i = 0; i < all.size(); i++) {
   partDocs.add(Set<allDocuments.stream().toList().get(i)>);
}

Does anyone have any idea about how to implement this?
Comment: This is extremely confusing. Maybe you should start by reading the javadoc for the Set interface carefully first. And a good tutorial about java collections. See, your code to add the elements of `all` to set2 is super overkill. You could just do: `set2.clear(); set2.addAll(all)`. Thing is: I really do not understand what you want to do. So really carefully list the **objects** you have in your INPUT sets, and describe EXACTLY how your OUTPUT sets should look like.
Comment: What is the difference between all and set2?
Comment: Also,  `sat2` looks like a typo .
Comment: What I'm trying to do is turn [doc1, doc2, doc3] into 3 different sets, which will be contained by partDocs like this [[doc1],[doc2],[doc3]]. I didnt explain why I want to use this in my program because it would have been a very long post
Comment: all = [doc1, doc2, doc3]
set2 is empty at the start, but during the loop it takes the value of the i.th element at "all", so when i = 0, set2 = [doc1], and then when i=1, set2.clear() happens, set becomes empty and then set2 = [doc2]
Answer: I don't know if you actually want to do this. It seems like very confusing code but try the following:
Set<Set<Doc>> partDocs = new HashSet<Set<Doc>>();
Set<Doc> all = new HashSet<>();

for(Doc doc : all) {
    partDocs.add(Set.of(doc));
}

And now you have a set (partDocs) that contains sets which contain docs
Comment: If this worked for you please check it as accepted answer.
Answer: The invalidation of set2 is flawed.
Instead of
set2.clear();

it should be
set2 = new HashSet<Doc>();

This particular bug may be easier to understand if we use a list for partDocs
List<Set<Doc>> partDocs = new ArrayList<Set<Doc>>();

which results in
[[Doc3], [Doc3], [Doc3]]

Essentially, we are adding the same Set to the List and since we are using the same reference, consecutive calls to set2.clear() and set2.add() will affect both the local variable and the Set in the List.
Going back to partDocs being a Set, it will end up with only one entry, because a Set guarantees to not contain duplicate values and three identical instances are  of course duplicates.

So, to fix this bug, we must ensure that the three objects added to partDocs are truly distinct, which is accomplished (partly) by the new invalidation routine
set2 = new HashSet<Doc>();

and otherwise by the fact that we add a different element to it each time.
Comment: Thanks for letting me know! I didn't know about this

How to convert an object to a set?


Proving that $\sin(x+y)$ is uniformly continuous

Question: How may I prove that both are uniformly continuous?:

$f(x,y)=\sin(x+y)$
for 1, I said, let $\epsilon > 0$ if $d((x,y),(u,v))<\lambda$:

$|f(x,y)-f(u,v)|<|f(x,y)|+|f(u,v)|=|\sin(x+y)|+|\sin(u,v)|<|x+y|+|u+v|$
But how may I continue from here?
Comment: Your line beginning with 1. is incomprehensible.
Answer: Note that\begin{align}|\sin(x+y)-\sin(u+v)|&\leqslant|\sin(x+y)-\sin(x+v)|+|\sin(x+v)-\sin(u+v)|\\&\leqslant|y-v|+|x-u|.\end{align}Can you take it from here?
Comment: Why $sin(+)−sin(+) < |y-v|$ we know that $|sin|(x)<|x|$
Comment: $|\sin(x+y)-\sin(x+v)|\leqslant|(x+y)-(x+v)|=|y-v|$
Comment: Edit: I can't continue from here. How this: ((,),(,))<  => $(x-u)^2+(y-v)^2<^2$ may be helpful in your case?
Comment: Now you use the fact that$$|x-u|+|y-v|\leqslant\sqrt2\lVert(x,y)-(u,v)\rVert.$$So, given $\varepsilon>0$, you can take $\delta=\frac\varepsilon{\sqrt2}$.


How to build remote Webdriver for Chrome

Question: I am trying to run my Selenium tests against Chrome. When I initialize driver locally:
@driver = Selenium::WebDriver.for( :chrome )

Everything works fine (I already put Chrome binary on my PATH)
But when I try to launch it remotely:
@driver = Selenium::WebDriver.for(:remote, :url => 'http://' + SELENIUM_HOST + port + webdriver_hub, :desired_capabilities => :chrome)

I get the following error

Selenium::WebDriver::Error::UnhandledError: The path to the
  chromedriver executable must be set by the webdriver.chrome.driver
  system property; for more information, see
  http://code.google.com/p/selenium/wiki/ChromeDriver. The latest
  version can be downloaded from
  http://code.google.com/p/chromium/downloads/list
  (java.lang.IllegalStateException)

I am a bit confused there - how exactly should I set this system property? I found this code written in Java:
DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setJavascriptEnabled(true);
caps.setCapability("chrome.binary", "/path/to/where/chrome/is/installed/chrome.exe");
System.setProperty("webdriver.chrome.driver","/path/to/where/you/ve/put/chromedriver.exe");
ChromeDriver driver = new ChromeDriver(caps);

but my tests are written in Ruby. RubyBindings don't talk about this issue  http://code.google.com/p/selenium/wiki/RubyBindings
Answer: Actually the error message is slightly wrong. You don't have to set the system property, but the chromedriver executable needs to be available in the PATH on the remote machine (where the server is running).
If you want to specify the path as a property, you can do that when you launch the server, e.g.:
java -Dwebdriver.chrome.driver=/path/to/driver -jar selenium-server-standalone.jar

Answer: Okay, guys. With the help I could find the answer. Check it out.
That is how you set up the driver on your local machine:
    @driver = Selenium::WebDriver.for(:remote, :chrome :url => 'http://' + SELENIUM_HOST + port + webdriver_hub, :desired_capabilities => browser)

where
browser = ':chrome'
port = ':4444'
webdriver_hub = '/wd/hub'

On the remote machine running the server would be something like this
    java -jar selenium-server-standalone-2.2.0.jar -Dwebdriver.chrome.driver="path/to/where/you/put/chromedriver.exe"

After run your tests from the local machine.
Best of luck!
Answer: You have to set path to your cromedriver.exe inside the code of the test. Its something like
System.setproperty();

in Java
I am also using Java based tests, so I cannot give you exact example for Ruby. But basically you have to tell your Ruby program where is the path to chromedriver.exe
Comment: Thanks for the tips, Pavel. But it is exactly what I am looking for - how to set up this property in Ruby.
Comment: I am not Ruby expert, so I dont have clue... But after some searching I found this question: http://stackoverflow.com/questions/2348621/ruby-setting-property-values-when-initializing-object Is that helpful? If not, maybe consider asking Ruby specific question
Answer: I found the selected answer to be very misleading. It took me about an hour to release the mistake in it. The node is the one that should have the webdriver.chrome.driver property set, not the hub.
Therefore the selected answer's command should instead be:
java -Dwebdriver.chrome.driver=/path/to/driver -jar selenium-server-standalone.jar -role node


Good and reliable practice to get a Node.js client to connect to a gremlin-server (all running on the same server) for CRUD operations

Question: [On Ubuntu 18.04]
I have (and am constrained to use) janusgraph to create a persona repository. I will be using a graphDB, largely because persona relationships are as important as persona attributes and the structure needs to be fluid. I need to create a Node.js application (+ pug & stylus eventually) to do CRUD operations on the data in the graphDB but I don't understand how to connect the client to the server. (Research has shown solutions for this problem but only with different components in place - Neo4j, OrientDB, etc)
I can start gremlin-server successfully and then I have tried creating a gremlin-console connection such as the following
/opt/janusgraph-0.2.2-hadoop2/bin/gremlin.sh /opt/janusgraph-0.2.2-hadoop2/conf/gremlin-server/gremlin-server.yaml
where the yaml looks like this:
(As well as localhost, I also tried the host's specific IP address, and both options with and without the square brackets, but with similar results)
host: [localhost]
port: 8182
scriptEvaluationTimeout: 30000
channelizer: org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer
graphs: {
  graph: conf/gremlin-server/janusgraph-cql-es-server.properties
}
plugins:
  - janusgraph.imports
scriptEngines: {
  gremlin-groovy: {
    imports: [java.lang.Math],
    staticImports: [java.lang.Math.PI],
    scripts: [scripts/empty-sample.groovy]}}
serializers:
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoLiteMessageSerializerV1d0, config: {ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { serializeResultToString: true }}
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistryV1d0] }}
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerGremlinV2d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry] }}
  - { className: org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV1d0, config: { ioRegistries: [org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistryV1d0] }}
processors:
  - { className: org.apache.tinkerpop.gremlin.server.op.session.SessionOpProcessor, config: { sessionTimeout: 28800000 }}
  - { className: org.apache.tinkerpop.gremlin.server.op.traversal.TraversalOpProcessor, config: { cacheExpirationTime: 600000, cacheMaxSize: 1000 }}
metrics: {
  consoleReporter: {enabled: true, interval: 180000},
  csvReporter: {enabled: true, interval: 180000, fileName: /tmp/gremlin-server-metrics.csv},
  jmxReporter: {enabled: true},
  slf4jReporter: {enabled: true, interval: 180000},
  gangliaReporter: {enabled: false, interval: 180000, addressingMode: MULTICAST},
  graphiteReporter: {enabled: false, interval: 180000}}
maxInitialLineLength: 4096
maxHeaderSize: 8192
maxChunkSize: 8192
maxContentLength: 65536
maxAccumulationBufferComponents: 1024
resultIterationBatchSize: 64
writeBufferLowWaterMark: 32768
writeBufferHighWaterMark: 65536

The stdout looks like this:
         (o o)
-----oOOo-(3)-oOOo-----
plugin activated: janusgraph.imports
plugin activated: tinkerpop.server
plugin activated: tinkerpop.utilities
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/opt/janusgraph-0.2.2-hadoop2/lib/slf4j-log4j12-1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/opt/janusgraph-0.2.2-hadoop2/lib/logback-classic-1.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
16:19:01 WARN  org.apache.hadoop.util.NativeCodeLoader  - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
plugin activated: tinkerpop.hadoop
plugin activated: tinkerpop.spark
plugin activated: tinkerpop.tinkergraph
Error in /opt/janusgraph-0.2.2-hadoop2/conf/gremlin-server/gremlin-server.yaml at [1: host: [localhost]] - No such property: localhost for class: groovysh_evaluate

Clearly, I've assumed or configured something(s) incorrectly, even in the console to server yaml and I don't know if the same yaml file would work for a Node.js client to connect.
I think I want the console connection so I can import the starter data from a graphml file and thereafter create new entries, query them, update them & delete them from the front end Node.js application.
What do I need to do to ?
Answer: The following doesn't create any connections from Gremlin Console to Gremlin Server:
/opt/janusgraph-0.2.2-hadoop2/bin/gremlin.sh /opt/janusgraph-0.2.2-hadoop2/conf/gremlin-server/gremlin-server.yaml

gremlin.sh does not take a Gremlin Server yaml file as an argument. Simply start bin/gremlin.sh and then write connect commands:
gremlin> :remote connect tinkerpop.server conf/remote.yaml

where remote.yaml points at Gremlin Server. You can read more about this in detail in a variety of places but I'll just point you to the TinkerPop reference documentation here.
Comment: Thank you. That got me over the issue.


accessing doc.id in .onWrite firebase cloud function

Question: I'm triggering a cloud function with onWrite. Within the onWrite function, I want to do something with the ref ID of the document that was written. How can I grab this? My current code looks something like this, but I don't know how to fill eventID.
exports.syncEvents = functions.firestore
    .document('events/{eventID}')
    .onWrite((change, context) => {

admin.firestore().collection('users').doc(host).collection('events').doc(eventID).set({
            active: true
          })
        });

Answer: change.after is a DocumentSnapshot of the document that changed, after it was written.  DocumentSnapshot has a property called id that contains the id of the document.  So change.after.id is the document id.
Comment: Great, thanks Doug. I had been trying to use change.after.data().id
Answer: The context object contains the params of the query.
In your example, the context object will look like this:
{
 ...
 params: {
   eventID: "whatever-eventId-is"
 }
 ...
}

So you just call get it from the context:
const eventId = context.params.eventId;

Here is more about context:
https://firebase.google.com/docs/reference/functions/cloud_functions.eventcontext


IIS - Running Codeigniter does not execute PHP scripts

Question: I just installed a Codeigniter application on Windows 7 IIS in my local computer.
The routes are ok and the controllers seem to be loading the views, but the PHP scripts on them do not show the passed variables and are interpreted as HTML.
PHP scripts run ok without Codeigniter.
Any clues?
Comment: Nope... the values are passed OK. I thik I got it! The PHP version that comes with ISS requires the load->view() are not accessible? If so can you post me the code of how you are passing the value?
Answer: The PHP version that comes with ISS requires the PHP sentence to be declared.
<?php

The new opening by itself won't work.
<?


Micronaut/Kotlin - AWS: One of the required keys was not given a value

Question: So I have a rest controller and I'm sending a request with body expecting to store that body on a dynamodb table, but I'm getting the error on the title, here is my code:
Controller:
@Patch("/activity/{activity-id}/")
    fun createNoteRecord(@PathVariable("activity-id") activity: String,
                         @PathVariable("enrollment-id") enrollment: String,
                         @PathVariable("student-id") student: String,
                         @Body eNote: ENote
    ): Mono<HttpResponse<ENote>> {
        logger.info("{activity-id: $activity - enrollment-id: $enrollment - student-id: $student - eNote: $eNote}")
        return service.save(eNote)
            .map { HttpResponse.ok(it) }
    }

Model:
@Introspected
@DynamoDbBean
data class ENote(
    @get:DynamoDbPartitionKey
    @get:DynamoDbAttribute(value = "student_id")
    var studentId: String? = null,

    @get:DynamoDbAttribute(value = "note_key")
    val noteKey: String? = null,

    @get:DynamoDbAttribute(value = "enrollment_id")
    val enrollmentId: String? = null,

    @get:DynamoDbAttribute(value = "course_id")
    val courseId: String? = null,

    @get:DynamoDbAttribute(value = "activity_id")
    val activityId: String? = null,

    @get:DynamoDbAttribute(value = "note_entries")
    val noteEntries: List<String> = emptyList(),

    @get:DynamoDbAttribute(value = "audit")
    val audit: Audit = Audit(),
)

Repository:
private val tableSchema = TableSchema.fromBean(ENote::class.java)
    private val eNoteMapTable = dynamoDbEnhancedAsyncClient.table(eNoteTableMapName, tableSchema)

    fun save(eNote: ENote): Mono<ENote>{
        return eNoteMapTable.putItem(eNote)
            .thenApply { eNote }
            .toMono()
    }

Postman body:
{
    "studentId": "ce63fa97-9f26-4ae2-869e-529904f41e91",
    "noteKey": "ENROLLMENT:f84d89b6-0b21-4461-9fc0-43a7f0ab6b9f#ACTIVITY:7b763b3c-1faa-41f0-b6be-1664034acd88",
    "enrollmentId": "f84d89b6-0b21-4461-9fc0-43a7f0ab6b9f",
    "courseId": "1bebf49b-cc49-4aa9-a0b6-c0ac6ad62b14",
    "activityId": "7b763b3c-1faa-41f0-b6be-1664034acd88",
    "noteEntries": [
        "Nota 1",
        "Nota 2",
        "Nota 3"
    ],
    "audit": {
        "createdBy":"ce63fa97-9f26-4ae2-869e-529904f41e91",
        "updatedBy":"ce63fa97-9f26-4ae2-869e-529904f41e91",
        "createdAt":"2022-02-18T19:51:35.605706Z",
        "updatedAt":"2022-02-18T19:51:35.605711Z"
    }
}

Object log output:
eNote: ENote(studentId=ce63fa97-9f26-4ae2-869e-529904f41e91, noteKey=ENROLLMENT:f84d89b6-0b21-4461-9fc0-43a7f0ab6b9f#ACTIVITY:7b763b3c-1faa-41f0-b6be-1664034acd88, enrollmentId=f84d89b6-0b21-4461-9fc0-43a7f0ab6b9f, courseId=1bebf49b-cc49-4aa9-a0b6-c0ac6ad62b14, activityId=7b763b3c-1faa-41f0-b6be-1664034acd88, noteEntries=[Nota 1, Nota 2, Nota 3], audit=Audit(createdBy=ce63fa97-9f26-4ae2-869e-529904f41e91, createdAt=2022-02-18T19:51:35.605706Z, updatedBy=ce63fa97-9f26-4ae2-869e-529904f41e91, updatedAt=2022-02-18T19:51:35.605711Z))}","logger_name":"com.il.cw.enote.controller.ENotesController","thread_name":"default-nioEventLoopGroup-1-3","level":"INFO","level_value":20000}

As you can see, when sending the request the object is actually received in the cotroller, so maybe I'm missing something somewhere else? I already verify that the database actually exist, and here is the schema:
{   "AttributeDefinitions": [
    {
      "AttributeName": "student_id",
      "AttributeType": "S"
    },
    {
      "AttributeName": "note_key",
      "AttributeType": "S"
    }   ],   "TableName": "namespace-cwng-local-enote",   "KeySchema": [
    {
      "AttributeName": "student_id",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "note_key",
      "KeyType": "RANGE"
    }   ],   "TableStatus": "ACTIVE",   "CreationDateTime": "2022-10-10T18:15:04.722Z",   "ProvisionedThroughput": {
    "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z",
    "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z",
    "NumberOfDecreasesToday": 0,
    "ReadCapacityUnits": 10,
    "WriteCapacityUnits": 5   },   "TableSizeBytes": 519,   "ItemCount": 1,   "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/namespace-cwng-local-enote" }

Am I doing something wrong?
Answer: In your DynamoDB table you have set a PK = student_id and an SK = note_key
When you declare your class you only state PK and there is no declaration for SK.
Try adding the range key annotation for your sort key.
Also just after seeing the postman data does not have the same naming convention for variables as your tables. You need to check that also.
Comment: Yep, that worked, but now is storing only undefined values, the names of the variables on kotlin and table should be mapped by the DynamoDbAttribute annotation, but it seems not working, however the problem on the question is solved, thanks


Rpart regression tree using aggregate data instead of record level data – The results are not the same

Question: I have a large dataset (over 6 million records) and I have aggregated the dataset (dplyer package) and tested rpart() on the two datasets. However the results of the two trees are not the same.  I wanted to use aggregated data to speed up the calculations – Is this approach incorrect?
Tree: Data no aggregated - no weights
rpart.fraud <- rpart(PERCENTAGE_FRAUD ~ VERTICALNAME + ROUNDED_AMOUNT_TRANSACTIONS_EUR,
                     data = fraud_data)

The tree has 1 node unless I used  control = rpart.control(cp=0.001) and then I have some nodes: 14 nodes
fraud_data_sum <- select(fraud_data,VERTICALNAME,ROUNDED_AMOUNT_TRANSACTIONS_EUR,NUMBER_TRXS_PAID, NUMBER_TRXS_PAID_CBFRAUD) %>%
            group_by(VERTICALNAME,ROUNDED_AMOUNT_TRANSACTIONS_EUR) %>%
            summarise(NUMBER_TRXS_PAID=sum(NUMBER_TRXS_PAID),
                      NUMBER_TRXS_PAID_CBFRAUD = sum(NUMBER_TRXS_PAID_CBFRAUD),
                      PERCENTAGE_FRAUD = sum(NUMBER_TRXS_PAID_CBFRAUD)/sum(NUMBER_TRXS_PAID))

Tree: Data aggregated - using weights argument
rpart.fraud <- rpart(PERCENTAGE_FRAUD ~ VERTICALNAME + ROUNDED_AMOUNT_TRANSACTIONS_EUR,
                     data = fraud_data_sum, weights = NUMBER_TRXS_PAID)

the tree (using aggregate data and weights) has 30 nodes (using the default control cp).
Answer: I did try out both above mentioned methods once in the past. Both methods are correct. However, you will get different trees because the minsplit and minbucket criteria doesn't take weights of the records into consideration. minsplit and minbucket is checked on the number of records.
Hope that answers your question.


Does "ZF + no amorphous sets" implies some form of choice?

Question: If we forbid existence of amorphous sets, then does that prove axiom of choice? Or some form of choice?
Where by a "form of choice" I mean something along those lines.
Comment: Unless you define exactly what "weak form of choice" means, one standard interpretation is "somewhere between ZF and ZFC", in which case it is a weak form of choice.
Comment: What kind of answer are you looking for? Clearly it is consistent that there are no amorphous sets, but other Dedekind finite sets exist. So clearly not countable choice or anything that implies it...
Comment: so it doesn't enforce any known form of choice, I mean weak forms?
Comment: Again, what kind of "weak forms"? Sure, it implies that every infinite set can be split into two infinite sets. Great. But that's not really an interesting answer to your question, is it?
Comment: @AsafKaragila, this is not a known weak form of choice. I mean of the known ones. Apparently the answer is No.
Comment: @AsafKaragila, well I meant a form of choice along the known lines that are either sequence based or cardinality based. I'll search in one of my old questions where you actually answered.
Answer: No, not at all.
The Cohen model, for example, does not have any amorphous sets. The second Cohen model does not have any either, although the proof is slightly more involved.
In either case, countable choice fails, and there are Dedekind-finite sets. In the latter case, countable choice from families of pairs fails as well.


Reverse node reference

Question: I have 2 content types:

vehicles
engines

Several engine nodes are referenced to the single vehicle.
Is there any way I can load all engines referenced to the single vehicle node if I have that vehicle node object (thus the nid as well)?
I use Node reference module.
If you need any more info, please ask.
Thanks in advance!
Comment: If you switch to Entity reference my earlier response today might be helpfulhttp://drupal.stackexchange.com/questions/124893/what-is-the-difference-between-referenced-entity-and-referencing-entity-in-views
Comment: Using [Reverse Node Reference](https://www.drupal.org/project/reverse_node_reference) maybe? Have you searched before you asked? If so, why this module does not help?
Comment: @Mołot of course I've searched before I asked. This module doesn't help because it is for Drupal 6 solely. I know I can do a reverse reference from Views, so I suppose there is a way to do it programmatically.
Answer: I found a solution to this issue by performing a query on 'field_data_field_vehicle_reference' table.
For my case, the solution can be something like this:
<code>function engines_of_vehicle($vehicle) {
  $nid = $vehicle->nid;

  // get all engine nids referenced to this vehicle
  $engine_nids = db_query('SELECT ref.entity_id FROM {field_data_field_vehicle_reference} ref WHERE ref.field_vehicle_reference_nid  =:nid AND ref.bundle =:bundle', array(':nid' => $nid, ':bundle' => 'engine'))->fetchCol();

  //load all engines referenced to this nid
  $engines = node_load_multiple($engine_nids);

  return $engines;
}
</code>

Reverse node reference


Truncating data reduces correlation?

Question: Here is an argument I came across: by limiting your sample by some range of one of the variables the (Pearson) correlation coefficient between the two variables is likely to be reduced.
I can't see the logic. I would think it could both increase or reduce, depending on whether the linear relationship is stronger or not for that interval at hand.
Any clues?
Comment: "Limiting your sample" sounds like *truncation.*  Censoring means that values in the sample are *replaced* by censoring limits.  The effect on the nominal correlation coefficient (as incorrectly calculated by replacing each censored value by its censoring limit) is profoundly different from removing such values altogether (truncation).  Which one do you really mean?
Comment: This phenomenon is illustrated in my answer at http://stats.stackexchange.com/a/13317/919, which slices one variable into quantiles and quotes the $R^2$ (squared correlation coefficient) for the data within each slice.
Comment: However, *"is likely to"* does not imply "*will always*."
Comment: I mean "removing such values altogether (truncation)". Thanks, I will change the title.
Comment: Of course! But it implies more likely than not, which I have hard time accepting.
Answer: There's a number of ways to look at it, but this is a pretty straightforward one:
Imagine for a moment we're looking at a regression problem. The squared correlation between the two variables ($r^2$) is $R^2$, the coefficient of determination, which is $1-\frac{s^2_\epsilon}{\text{Var}(y)}$. When you restrict the range of $x$, you also reduce the range of $y$, so $\text{Var}(y)$ goes down with it, while $s^2_\epsilon$ (the noise about the line) should hardly change, since it still has an expected value of $\sigma^2_\epsilon$. Here's an example of that:

Since the denominator of the fraction decreases while the numerator hardly changes, the fraction gets larger, so $R^2$ gets smaller, so $r^2(x,y)$ and hence $|r|$ will be smaller. So we really should expect that the size of the correlation decreases.
Answer: Thinking of a 2D plot of one variable plotted against the other, limiting the range for one variable means only looking at a vertical or horizontal "slice".
So my intuition is that the overall shape of the "cloud" of points will be more vertical or more horizontal, instead of "diagonal". A vertical or horizontal-looking cloud of points has zero correlation. So to me there is indeed an intuition that correlation is likely to decrease.
As a toy example, if your data points are (1,1), (1,20), and (20,20), you have 0.5 correlation, but if you limit the range of the first variable to [0,10] you are left with two points (1,1) and (1,20), and correlation =0. If you limit the second variable to [10,30] then you get two points aligned vertically, and again correlation =0.

Truncating data reduces correlation?


FlatMapLatest with Replay

Question: I have a situation where I have three observables that map to a result stream.
The first observable tells me which of two other observables I should take values from. On every emission of the first observable, the result stream switches to emitting the flatmap of the appropriate observable.
This is a situation that normally can be accomplished via flatMapLatest.
However, on every switch of the flatMap, I also happen to want to replay the latest stale value. This is an issue, because flatMapLatest does not provide for an ability for a replay on old values of existing observables.
See below for an RxMarbles of what I want to accomplish:

I tried using shareReplay(N), as in the code below, but that does not seem to solve the issue.
    let Observable1Replay = Observable1.share(replay: 1, scope: .forever)

    let Observable2Replay = Observable2.share(replay: 1, scope: .forever)

    let resultObservable = Observable3
        .flatMapLatest { boolValue in
            if boolValue == true {
               return Observable1Replay
            } else {
               return Observable2Replay
            }
        }

Comment: Are `observable1` and `observable2` cold or hot?
Answer: When you are stuck, you can always roll your own and come back to it later:
func example(source: Observable<String>, obs1: Observable<String>, obs2: Observable<String>) -> Observable<String> {
    return Observable.create { observer in
        let lock = NSRecursiveLock()
        var last1 = ""
        var last2 = ""
        var isFirst = false
        var completeCount = 3
        let srcSub = source.subscribe { event in
            lock.lock(); defer { lock.unlock() }
            switch event {
            case .next:
                isFirst = !isFirst
                if isFirst && !last1.isEmpty {
                    observer.onNext(last1)
                }
                else if !isFirst && !last2.isEmpty {
                    observer.onNext(last2)
                }
            case .error(let error):
                observer.onError(error)
            case .completed:
                completeCount -= 1
                if completeCount == 0 {
                    observer.onCompleted()
                }
            }
        }
        let obs1Sub = obs1.subscribe { event in
            lock.lock(); defer { lock.unlock() }
            switch event {
            case .next(let element):
                if isFirst {
                    observer.onNext(element)
                }
                last1 = element
            case .error(let error):
                observer.onError(error)
            case .completed:
                completeCount -= 1
                if completeCount == 0 {
                    observer.onCompleted()
                }
            }
        }
        let obs2Sub = obs2.subscribe { event in
            lock.lock(); defer { lock.unlock() }
            switch event {
            case .next(let element):
                if !isFirst {
                    observer.onNext(element)
                }
                last2 = element
            case .error(let error):
                observer.onError(error)
            case .completed:
                completeCount -= 1
                if completeCount == 0 {
                    observer.onCompleted()
                }
            }
        }
        return CompositeDisposable(srcSub, obs1Sub, obs2Sub)
    }
}

FlatMapLatest with Replay


Any build-in JSON.parse in MongoDB?

Question: Is there any Mongo (command line) function that I can turn a string into object? e.g. JSON.parse or something like that?
db.sessions.update({}, {'$set':{ 'extra':JSON.parse(stringData)   }});

my solution:
function my_extra() {
  db.tempData.find().forEach( function(obj) {
                       obj.extra = db.eval(obj.myString);
                       db.tempData.save(obj);
                     } );
};

my_extra();

However, I try this: db.tempData.update({}, {'$set':{ 'extra':db.eval(myString)   }});
but it doesn't work.. saying myString is not defined.
so i use this.myString but doesn't work neither.  that's why I have to use the function.
is there a way to reference myString in the second parameter?
Comment: What I want to do is.. the current data I have contains stringified JSON object.  e.g. stringData:"{\"key\":12345}"

I want to parse it and assign back to the record under a new variable.  :)
Comment: I know I can use node.js or others to extract the data, json parse, and save it back.  but I have close to 1M records.  I think doing it in mongo will be faster.
Comment: What is it exactly that you're trying to do? If you want to import a bunch of data there is a command-line import tool http://www.mongodb.org/display/DOCS/Import+Export+Tools
Answer: The version 2.1+ Mongo shell includes a JSON utility object:

From object to JSON: JSON.serialize(object)
From JSON to object: JSON.parse(string)

http://api.mongodb.org/java/2.6/com/mongodb/util/JSON.html
Note: In version 2.4+ Mongo shell, use JSON.stringify() instead of JSON.serialize()
http://docs.mongodb.org/manual/release-notes/2.4-javascript/
Answer: You can try eval function:
obj = eval("(function() { return {\"key\": \"value\"} })()")

But note it's unsafe because it can execute arbitrary Javascript code including db.dropDatabase().
Comment: thanks. that's not a worry for me coz the data is generated internally. :D  thanks.
Comment: Thanks.. Here it is:

function my_extra() {
  db.tempData.find().forEach( function(obj) {
                       obj.extra = db.eval(obj.string);
                       db.tempData.save(obj);
                     } );
}

my_extra();
Comment: @murvinlai `db.eval` is not really the same as `eval`, it executes DB command `$eval` (means roundtrip to the server) while `eval` is executed inside shell. Glad it helped anyway, feel free to mark the answer ;)

Any build-in JSON.parse in MongoDB?


Personalizar barra de volume player html5

Question: Amigos, tenho um player html5 com os controllers tudo padrão. Gostaria de fazer um controlador de volume nesse mesmo estilo:

Meu código até agora

<audio id="demo" src="http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"></audio>

    <button onclick="document.getElementById('demo').play()">Reproduzir o áudio</button>
    <button onclick="document.getElementById('demo').pause()">Pausar o áudio</button>
    <button onclick="document.getElementById('demo').volume+=0.1">Aumentar o volume</button>
    <button onclick="document.getElementById('demo').volume-=0.1">Diminuir o volume</button>

e gostaria que no lugar desses botões que aparecem para aumentar e diminuir o volume fosse uma barra no mesmo estilo da que postei acima. Se alguém puder me ajudar agradeço.
Grato desde já.
Answer: Podes usar o "novo" input type=range com min=0, max=1 e step=0.1, quando acontecer o onchange ele faz o assign do volume para this.value:

    <audio id="demo" src="http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"></audio>

    <button onclick="document.getElementById('demo').play()">Reproduzir o áudio</button>
    <button onclick="document.getElementById('demo').pause()">Pausar o áudio</button>

<input type="range" id="weight" min="0" value="0.5" max="1" step="0.1" onchange="document.getElementById('demo').volume=this.value">
Comment: Obrigado! Era exatamente isso que procurava.


Prove for all all $x\in\mathbb{R}: \exp(x-1) \geq x$

Question: i just tried to solve this question, which is a small part of a bigger one.
Prove for all all $x \in \mathbb{R}: \exp(x-1) \geq x$
My first attempt was to simplify:
$$ e^{x-1} \geq x $$ $$ \Leftrightarrow \ln(e^{x-1}) \geq \ln(x) $$ $$ \Leftrightarrow x-1 \geq \ln(x) $$ $$ \Leftrightarrow x \geq \ln(x)+1 $$ $$ \Leftrightarrow e^x \geq e^{\ln(x)}+e^1 $$ $$ \Leftrightarrow e^x \geq x+e $$
My idea is that $e$ power $x$ is of course greater equal $x+e$. Is this correct  and if yes is it enough?
Comment: Also notice that $e^{\ln(x)+1}=e^{\ln x}\cdot e=x\cdot e\neq x+e$.
Comment: You made a mistake at the point where you asserted the "equivalent" inequality $e^x\le e^{\ln x}+e^1$.  That inequality is not true.  For example, if $x=1$, then $e^{\ln 1}=e^0=1$ so we have $e^1\lt1+e^1$, not $\ge$.
Comment: Careful: when you try to run this backwards you have $\ln x$ which only makes sense for positive $x$s, and you may want this for all $x$s.
Comment: ok yes. you got a point :-/ you have an idea how to solve?
Comment: To further emphasize the two previous comments, note that $e^x\geq x+e$ implies $1\geq e$ which is pretty unlikely.
Comment: ok this was a huge mistake i do understand now :) - i have really some maths issues
Comment: Also: https://math.stackexchange.com/questions/630481/prove-expx-geq-1x-forall-x-in-mathbbr (and probably some more).
Answer: Let $f(x)=e^{x-1}-x.$
Thus, $f'(x)=e^{x-1}-1$, which says that $x_{\min}=1$.
Id est, $$f(x)\geq f(1)=0$$ and we are done!
Comment: ok this was fast ^^ So my idea was totally wrong :-( but thank you :-)
Comment: @hukachaka You are welcome!
Answer: the answer Michael gave is a good answer but if you want different way,
$$e^{x-1}=x\implies x=1$$ now because both $x$ and $e^{x-1}$ are continuous you just need to check one value of $x$ that is above $1$ and one that is less. for example:$$\text{for $x<1,\,x=0$},\,e^{0-1}={1\over e}\gt0\\\text{for $x>1,\,x=2$},\,e^{2-1}=e\gt2$$
therefore $$e^{x-1}\ge1$$
Comment: So you have $e^{x-1}=x \Longrightarrow x-1 = \ln x \Longrightarrow e^x = ex$. Where to you *prove* that this implies $x=1$?
Comment: thank you very much. I think i will try to understang both answers first :-)
Comment: @hukachaka sure, if there is anything you want further explanation just ask
Comment: thank you very much :)))
Comment: Why does $e^{x-1}=x$ imply $x=1$?
Comment: @MartinR $e^{x-1}=x\implies x-1=\ln x\implies x=1$
Comment: Why does the last implication hold?


Como executar java no prompt pelo Eclipse

Question: Eu fiz um código em java e nele eu uso "\r" que só funciona no prompt e gostaria de saber como executar esse código no prompt pelo próprio eclipse.
Answer: Directamente, através do Eclipse, não é possível.
Terá de exportar a aplicação como "Runnable JAR file" e executá-la numa janela de comando:
Clique com o botão do lado direito do rato sobre o seu projecto:
Escolha Runnable JAR file e clique em Next.

Seleccione a Launche configuration e indique o local onde gravar o jar.

Clique em Finish.
Para executar abra uma janela de comando onde guardou o jar e execute o seguinte comando:
<code>java -jar nomePrograma.jar
</code>


Elements of $\mathbb{Z}/(n)$

Question: Let $(n) = \{ \lambda n | \lambda \in \mathbb{Z} \}$. In my book it has shown that every element in  $\mathbb{Z}/(n)$ can be expressed uniquely in the form $r + (n)$ where $0 \leq r \leq n-1$ now I look at a practical application of this, say:
$\mathbb{Z}/6 = \{ 0,1,2,3,4,5 \}$ and when computing elements in this set we just do it in modulo $6$, so everytime I see a $6$ I write $0$, so for $\mathbb{Z}/(n)$ everytime I see $n$ I write $0$. However, I don't see how this leads on from the theorem I stated above, i.e. if we know that every element in  $\mathbb{Z}/(n)$ can be represented in the form $r + (n)$ with $ 0 \leq r \leq n-1$ why does that mean, when I see $n$ I write $0$? I'm just not comfortable with $r + (n)$ I mean, what is the $(n)$ doing there?
Answer: Remember that $r + (n)$ in this context is a coset, it itself is not a single number but an infinite collection of integers (namely those elements $k \in \mathbb{Z}$ such that $r-k$ is a multiple of $n$.  You should think of the coset $r+(n)$ as the set of elements that are $n$-translates of $r$.  In your example above you had $\mathbb{Z}/(6)$ so the coset corresponding to $r=5$ is
$$
5 + (6) \; \; = \;\; \{\ldots, -7, -1, 5, 11, 17, 23, \ldots \}.
$$
So the $6$-translates of $6$ would be the coset
$$
6 + (6) \;\; =\;\; \{\ldots, -18, -12, -6, 0, 6, 12, 18, \ldots\}
$$
We see that $0 \in [6 + (6)]$ so if we want to represent the coset uniquely in terms of nonnegative integers less than $6$ we can use $0$ to represent the coset containing $6$.
Answer: Notice that $r$ is the remainder of the division of any integer number by $n$. And as $0 \leq r < n$ then you may choose a class representant to the residue class $[r]$ then
$$[r] = r + (n) = \{r + x ; x \in (n)\}$$
You may also notice that
$$a \equiv b\mod (n) \iff b-a \in (n)$$
Answer: The problem is that $\mathbb Z/(6)$ is not the set $\{0,1,2,3,4,5\}$. Instead, $\mathbb Z/(6)$ is the set of equivalence classes of $\mathbb Z$ under the equivalence relation $x\sim y:\Leftrightarrow x-y\in(6)$. These equivalece classes are not single numbres, but are sets of numbers, for example
$$\{\ldots,-24,-18,-12,-6,0,6,12,18,24,\ldots\} $$
and
$$\{\ldots,-23,-17,-11,-5,1,7,13,19,25,\ldots\} $$
are two of these equivalence classes.
The first is just $(6)$ (cf. the definition of $(n)$). Since $0$ "does nothing" we can also write it as $0+(6)$. The second equivalence class is the set $(6)$ with $1$ added to each element, which is suggestively written as $1+(6)$. There is nothing special about the $1$ for we might with the same justification cwrite this set as $-5+(6)$ or $6667+(6)$ or many other ways of the form $r+(6)$. But the theorem you quote says that we can pick $r$ such that $0\le r\le 5$ (which we actually did in our first attempt, with $r=1$).
So more precisely
$$\mathbb Z/(6)=\{(6),1+(6),2+(6),3+(6),4+(6),5+(6)\} $$
Remark: You may sometimes find the notation $6\mathbb Z$ instead of $(6)$, so with that convention $\mathbb Z/6\mathbb Z=\{6\mathbb Z,1+6\mathbb Z,2+6\mathbb Z,3+6\mathbb Z,4+6\mathbb Z,5+6\mathbb Z\}$

Elements of $\mathbb{Z}/(n)$


osx, making tableview reloadable

Question: I have another simple question I can not solve by myself. I have two xibs. main.xib for the user input and result.xib for the results. Xib2 starts when a button is pushed on input-xib.
The button action (in AppDelegate.m):
- (IBAction)pushRun:(id)sender {

    if (!rwc)
    {
        rwc = [[ResultWindowController alloc] init];
    }
    [rwc setValueArray:[toDoItemArrayController arrangedObjects]];
    [rwc setNumberOfCalculations:[NSNumber numberWithInt:[_inputNumberOfCalculations intValue]]];
    [rwc calculateResults]; //starts method in 2nd-window controller for result calculation

    [rwc showWindow:self];
}

rwc is a WindowController doing the calculation and showing the result.xib (ResultWindow):
ResultWindowController.h:
#import <Cocoa/Cocoa.h>

@interface ResultWindowController : NSWindowController{

    NSArray *valueArray;
    NSMutableArray *resultArray;
    NSNumber *numberOfCalculations;
}

@property (nonatomic, retain, readwrite) NSArray *valueArray;
@property (retain) NSNumber *numberOfCalculations;
@property (nonatomic, retain, readwrite) NSMutableArray *resultArray;

-(void)calculateResults;

@end

ResultWindowController.m:
#import "ResultWindowController.h"
#import "ResultItem.h" //my result model

@implementation ResultWindowController
@synthesize valueArray, resultArray, numberOfCalculations;

- (id)init
{
    if(![super initWithWindowNibName:@"ResultWindow"])
    return nil;
    return self;
}

-(void)awakeFromNib
{

}

- (void)windowDidLoad
{
    [super windowDidLoad];
}

- (void)calculateResults
{
    //a lot of calculation code ...

    ResultItem *newResult = [[ResultItem alloc]init];

    [newResult setValue:[nameArray objectAtIndex:i] forKey:@"name"];
    [newResult setValue:[NSNumber numberWithDouble:avg] forKey:@"averageValue"];
    [newResult setValue:[NSNumber numberWithDouble:min] forKey:@"minValue"];
    [newResult setValue:[NSNumber numberWithDouble:max] forKey:@"maxValue"];
    [newResult setValue:dimensionRandomArray forKey:@"randomArray"];

    [resultArray addObject:newResult];

}

The results are put in an model-object and collected in the resultArray.
Now it's going to get interesting (at least for me):

the resultArray is bound as content to a NSArrayController via BindingInspector
the NSArrayController is part of the result.xib
the result.xib has a tableview (without own class or viewcontroller)
the tableview columns are bound to the NSArrayController via keyvalues used in the  resultArray

Everything works really fine when the result.xib window starts. The tableview shows the content as expected. BUT! When I make changes at the input.xib and push the action button again the tableview at the result.xib is not updating.
I checked the resultArray content (via NSLog) and it gets all the new values, so works fine.
WHERE IS MY PROBLEM?
I read a lot of [tableView reloadData] but I don't know how to actuallay set up the code and the necessary bindings for it.
Answer: Instead of adding the object to your array, make an IBOutlet to your array controller, and use the method addObject: to add object's to your table view.
Comment: Hello TheAmateurProgrammer, do you mean I need to change `[resultArray addObject:newResult];` in `[resultArrayController addObject:newResult];` and create an outlet in `ResultWindowController`?

osx, making tableview reloadable


Exact expected value of a random walk?

Question: I was reading Noga Alon's book. I found that there was a Putnam competition question asking to prove that the expected value of a random walk is
$$\mathbb{E}[|S_n|]=n2^{1-n}\binom{n-1}{\lfloor(n-1)/2\rfloor}.$$
Here, $S_{n} = X_{1} + X_{2} + \cdots X_{n}$, where $X_{i}$ are independent uniform random numbers in $\left\{-1,+1\right\}$. Can someone provide a proof for that?
Comment: Can you define the random walk to make the question self-contained and use math delimiters instead of an image?
Comment: Please edit the question accordingly; people shouldn't have to read through the comments to undertsand the question.
Comment: @Aravind Sn=X1+X2+...Xn Which Xi are independent uniform random in {-1,+1}
Answer: Hint:
Consider a walker moving on an infinite one-dimensional uniform lattice (i.e. a line split into discrete points). Suppose the walker starts at the origin ($x=0$) and then moves a short distance $\delta$ either left or right in a short time $\Delta t$. The motion is assumed to be completely random, so the probabilities of moving both left and right are $\frac12.$ After one time step, the walker can either be at a distance $\delta$ to the left or right of the origin, with probability $\frac12$ each After the next time step, the walker will either be at a distance $2\delta$ to the left or right of the origin (with probability $\frac14$ each) or will have returned to the origin (with probability $\frac12$). Note that, after an even (odd) number of steps, the walker can only be at an even (odd) distance away from the origin. Continuing in this way, the probability that a walker will be at a distance $m\delta$ to the right of the origin after $n$ time steps  is given by
$${{\left( \frac{1}{2} \right)}^{n}}\left( \begin{matrix}
   n  \\
   \lfloor \frac{n-m}{2} \rfloor  \\
\end{matrix} \right)
$$
Comment: It was Trivial... So What?
Comment: Why ???????????
Comment: what is relation between expectation and probability of random variable?

Exact expected value of a random walk?


Issue running 4.0 c# application on XP .NET 4.0

Question: I am trying to run a c# application using WPF that runs in version 4.0, on an XP machine that has .NET 4.0 framework installed on it. It starts up, but then errors out afterwards during the InitliaizeComponent() method in the form load. Windows then displays the "Would you like to send an error report?".
How can I see or figure out what is exactly happening, so I can fix the issue? I tried looking at the error report, but it is mainly just win bin code, and means nothing in terms of the error to me.
EDIT:
Thanks for the advice to log it. I did so, and this is the error I am getting on the XP machine when running the deployed version.

'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '5' and line position '57'.
Comment: Why the down vote? Seriously? I am stating to get annoyed of "snooty" stack overflow users. Yes, we are all NOT guru's of the precise way of stack's social acceptance, and am really thinking about just dropping out of stack. It has become a competition of who is smarter and "politically correct" in their usage, rather then helping for some. Thanks to those who helped guide me on this one. Writing the error log was a good way to see the error.
Comment: Add logging and catch exceptions for the log. The stack trace should at least help. Is there anything unusual in `InitializeComponent`?
Comment: Check for an UnhandledException event (or something similar) on the AppDomain.  Handle it, log it.  If I guessed, this old XP box has a punk vidya card that isn't compatible with WPF.  But that's a guess.
Comment: Not that I can see off hand, but I am still learning. Always am. I have never realy used the logging before, so I wil give that a try. I do have try catches around the area failing, but it does not show up on the deployed version. I am not debugging on the XP machine, it is the deployed version that is failing on XP.
Comment: You might check [this answer](http://stackoverflow.com/questions/450563/running-a-wpf-application-on-windows-xp)
Comment: Yea, this company has so much legacy crap, they brought me in to upgrade to latest and best, but won't upgrade all their production machines. At the end of a development project, I was notified it had to also run on XP machines.  WTH? Know what I mean...
Comment: Try to check the windows errors within the event viewer of the machine, you might find some clues of what's happening deep inside `InitializeComponent()`
Comment: Thanks to that error, I think I will try this answer out found here http://stackoverflow.com/questions/12833294/provide-value-on-system-windows-baml2006-typeconvertermarkupextension-threw-a
Answer: The issue was that I was using a .ico for the in the WPF title field. When I changed it to use a .png image, it then did not crash. Maybe it is an issue regarding video, or a bug. The answer from another question I posted in a prior comment resolved my issue. Now, I would like to test more, and see why it corrected the problem.


VBScript Array Help for Select Statement

Question: I'm using a select statement to show all services on a system currently set to Auto (automatic). The trouble is the list of service I do not want to see is growing. While still not larger than the list of services I do not want to see. I'm hoping that I can put all the services I do not want to see in an array and then check against the array during the select query (or afterwards if I have to) but so far I can't find an example where something similar is done and or I have PowerShell in my head and I can't think of how to do it vbscript
<code>'Current Attempt
GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_Service where StartMode='Auto' and DisplayName<>'Performance Logs and Alerts' and DisplayName<>'SBSD Security Center Service' and DisplayName<>'TPM Base Services'")
</code>
Answer: Doing this in a select query isn't really the best option, as there is no "IN" operator in WQL. The only way to do it, would be to build your select query dynamically, based on the array of excluded services.
I'd recommend doing it the latter way, by building an array of service names, retrieving ALL services with your select query, and then iterating over them. During the iteration, you'd have to check them against the array of excluded services.
Cheers,
Trevor Sullivan
<code>=========================================================================

Excluded = Array("ccmexec", "wuauserv", "wudfsvc")

set svcs = GetObject("winmgmts:root\cimv2").ExecQuery("select * from win32_service where startmode = 'auto'")

for each svc in svcs
   skip = false
   for i = 0 to uBound(Excluded)
     if Excluded(i) =  svc.Name then skip = true
   next

   if skip = true then
      'msgbox svc.Name
   else
      ' Service was not skipped. Do stuff here.
   end if
next
</code>
Comment: Without actaully plugging User's code into something, this looks pretty good.  +1 to User-Who-Needs-A-Better-Name
Comment: *nod* Similar to how I was thinking I'd do it if I had to redo it in powershell. Thank you.


can we have two elements with the same name under the same complex type

Question: Please tell if this xsd declaration is syntactically correct or not. This is a 'native xsd' portion. Functionally it is working fine, i want to know if there is any syntax violation etc in it according to general schema rules.
Note that i have two elements with the same name 'data'.
<code>   <xsd:complexType name="rowType">
        <xsd:sequence>
          <xsd:element name="data" type="xsd:string" maxOccurs="3" nxsd:style="terminated" nxsd:terminatedBy="," />
          <xsd:element name="data" type="xsd:string" nxsd:style="terminated" nxsd:terminatedBy="${eol}" />
        </xsd:sequence>
      </xsd:complexType>
</code>
Answer: It violates the Unique Particle Attribution constraint, because when you get the second "data" element in the instance, it is not known whether to match it against the first "data" particle or the second.
Comment: Thanks Michael, still got a query though, I am using nxsd instead of xsd here. I guess the ambiguity in matching the elements will be handled by 'nxsd:style' and 'nxsd:terminatedBy' here. Will it be okay to assume it?
Comment: I haven't the faintest idea what nxsd is.


Understanding the Evidence Lower Bound (ELBO)

Question: I am reading this tutorial about Variational Inference, which includes the following depiction of ELBO as the lower bound on log-likelihood on the third page. In the tutorial, $x_i$ is the observed data and $z_i$ is the latent variable.

Let me first ask a quick clarification question. ELBO is defined in equation (4) as $\mathscr{L}(q, \theta) := -\operatorname*{KL}(q(z_i)||\mathbb{P}(x_i, z_i|\theta)).$ Since the KL divergence is non-negative, the ELBO must be non-positive. Am I right? The illustration seems to indicate that ELBO can be positive, so I am a little confused.
Now the main question: I understand ELBO is a lower bound of the log-likelihood so we want to make it as large as possible. However, why can we ignore the other term, $\operatorname*{KL}(q(z_i)||\mathbb{P}(z_i | x_i, \theta))$? In other words, how do we ensure increasing ELBO doesn't accidentally decrease $\operatorname*{KL}(q(z_i)||\mathbb{P}(z_i | x_i, \theta))$, given that they share the same $\theta$?
Answer: For the first question:
You are correct.  The log likelihood is always nonpositive, and the ELBO is a lower bound on it, so is also certainly always nonpositive. That picture (and similar the one in Bishop 2006, §9.4, Figure 9.11) is rather misleading in my opinion, since it seems too imply that both of these quantities are positive.  That cannot be.  The bottom line in the picture is not labeled, and cannot be zero (in fact that bottom line and the indicated distances from it to the other lines doesn't represent anything meaningful as far as I can tell, which is why I think this picture is quite misleading).
To clarify, we have the following inequalities:

First note that $\log \mathbb{P}(x\mid\theta) \le 0$ (the log likelihood is the log of a probability so it nonpositive by definition)

Also, $\operatorname{KL}(\,q(z)\,\|\,\mathbb{P}(z\mid x,\theta)\,)\ge 0$ (since KL is always nonnegative)

So,
$$ \begin{aligned} \mathcal{L}(q,\theta)
:=&~ \int\,q(z)\,\log\frac{\mathbb{P}(x,z\mid\theta)}{q(z)}\mathrm{d}z \\
=&~ \underbrace{\log \mathbb{P}(x\mid\theta)}_{\le 0}
    - \underbrace{\operatorname{KL}(\,q(z)\,\|\,\mathbb{P}(z\mid x,\theta)\,)}_{\ge 0}
    \le 0
\end{aligned} $$
since subtracting the KL from the log likelihood can only make the result more negative.

IMO, a less confusing version of the picture you shared would be something like the following:

In this picture, the horizontal lines represent real values. The dashed line is zero, the likelihood $\log \mathbb{P}(x\mid\theta)$ is some negative real value, and the ELBO $\mathcal{L}(\theta,q)$ is below that (more negative).  The (positive) difference between these two lines is the $\operatorname{KL}(\,q(z)\,\|\,\mathbb{P}(z\mid x,\theta)\,)$.
I hope that clarifies somewhat.

For your second question as asking "how do we ensure increasing ELBO doesn't accidentally decrease the KL?": Look at the following equation:
$$
\operatorname{KL}(\,q(z)\,\|\,\mathbb{P}(z\mid x,\theta)\,)
=
\log \mathbb{P}(x\mid\theta)-\mathcal{L}(q,\theta)
$$
Looking at it this way, the KL is broken down into two pieces, the likelihood and the ELBO.  If you are looking to find the $q$ which maximizes this lowerbound for a fixed $\theta$, maximizing the ELBO by finding the optimal $q$ will necessarily only make the KL term smaller (making it vanish to zero, in the best case).
In a setting where you're doing a two step EM algorithm to get a maximum likelihood estimate, this maximization with respect to $q$ (while fixing $\theta$) is the E step.  Then, in the subsequent M step, the distribution $q$ is held constant, and you optimize the ELBO with respect to $\theta$.  Any increase in the ELBO that results will necessarily also increase the log likelihood term.  Say you were at the optimal situation after the E step, and the KL term was zero. Since $q$ is held fixed during the M step that you just carried out, you will also have increased the KL to some nonzero positive number.  That implies that the increase in the ELBO was smaller than increase the log likelihood.
See Bishop (2006 CH9) for further discussion of this EM algorithm.
I'd also highly recommend the discussion of this math in D. Kingma's thesis (2017 see section 2.3).
Answer: Don't forget that log probabilities are non-positive, too. They're the logs of values that cannot exceed 1.
With that in mind, the ELBO can be a meaningful lower bound on the log-likelihood: both are negative, but ELBO is lower. How much lower? The KL divergence from the conditional distribution.
I don't see where you think the figure is indicating that it should be positive. The bottom of the diagram isn't 0.

As for the second half of your question, see here: Should the likelihood function be increasing in every step of the EM algorithm?.
Answer: Regular expectation maximization works because the lower bound on the log likelihood is tight, so the M step will push up on the log-likelihood itself.
In the case of variational EM/inference, it is not the case that the lower bound is tight. Therefore, maximizing the lower bound can actually lead to a decrease in the actual log likelihood.
In terms of your question, you misread the equations. The definition of ELBO in the source you reference (eq 4) is
$$
\begin{aligned}
\mathcal{L}(\theta,q)
:=&~-\operatorname{KL}(q(z)\|\mathbb P(z, x|\theta))\\
=&~\log \mathbb P(x|\theta)-\operatorname{KL}(q(z)\|\mathbb P(z|x,\theta))
\end{aligned}
$$
In the M step we maximize the left two expressions with respect to $\theta$. The rightmost expression containing the expression in your question is automatically maximized by maximizing the overall expression, so it is not being "ignored." Nonetheless, be careful that variational EM is not a tight lower bound so can lead to not finding the local, let alone global, maximum.


how to define ECK form url

Question: I am using ECK
I create one form through  entity->bundle->feedbackform->managedfield
my form is created, but how to get form path,
current path is of my feedback form is:-
admin/structure/entity-type/feedbackform/feedbackform/add
but this path is not for anonymous user. i want to show my form to anonymous user with some simple path
Answer: Assuming you have a module called 'helloworld', and entity type called 'vechile' and a bundle called 'car'.Here is some code that should do the trick.
/**
 * Implements hook_menu().
 */
function helloworld_menu(){
$items['feedbackform'] = array(
'page callback' => 'example_my_eck_form_page',
'access arguments' => array('Access feedback form'),// permission
'type' => MENU_CALLBACK,
);
return $items;
}

function example_my_eck_form_page(){
   module_load_include('inc', 'eck', 'eck.entity');
   $bundle_name='car';
   return eck__entity__add('vechile', $bundle_name);
}

function helloworld_permission() {
   return array(
    'Access feedback form' => array(
      'title' => t('Access feedback form'),
    )
  );
}

Access feedback form is a custom permission so you still would have to give that permission to the  users from admin to be able to access the path.
Answer: I haven't tried this with ECK, but I believe that the behaviour should be the same as with any other form. You would simply need to:

Register a menu callback in a custom module for the "simple path", accessible to anonymous user role (see hook_menu())
The 'page callback' can either be

a custom function 'example_my_eck_form_page', where you return drupal_get_form('eck_name_of_your_form');
or 'drupal_get_form' and pass the form name in 'page arguments' array.
Answer: There is a module for that: https://www.drupal.org/project/eck_pm
Alternatively you could use hook_entity_info_alter like so:
function MYMODULE_entity_info_alter(&$info) {
  if (isset($info['ENTITY']['bundles']['BUNDLE'])) {
    $info['ENTITY']['bundles']['BUNDLE']['crud']['add']['path'] = 'my/public/path';
  }
}

how to define ECK form url


Brezis Exercise 3.12: Passing Conjugate into Inequalities

Question: This is Exercise 3.12 from Brezis:

Let $E$ be a Banach space and let $x_0 \in E$. Let $\varphi: E \to (-\infty, +\infty]$ be a convex l.s.c. function with $\varphi \not\equiv +\infty$.

Show that the following properties are equivalent:\begin{align*}\text{(A)} & \text{ There exist }R, \,M < +\infty \text{ such that }\varphi(x) \le M \text{ for all }x \in E \text{ with }\|x - x_0\| \le R. \\ \text{(B)}& \text{ }\lim_{f \in E^*, \| f \| \to \infty} \{\varphi^*(f) - \langle f,\,x_0\rangle\} = \infty.\end{align*}

Assuming (A) or (B) prove that$$\inf_{f \in E^*} \{\varphi^*(f) - \langle f,\,x_0\rangle\} \text{ is achieved.}$$What is the value of this inf?

After a bit of work, I was able to show now (A) $\implies$ (B). Now I got really stuck on the converse. I tried to follow the solution given in the book, but I do not understand how the solution works:
In particular, why would showing there exists constant $k > 0$ and $C$ such that S1 hold would help us to prove (A)? It does not make sense to me what Brezis meant when he said passing conjugate into S1. I am not sure how conjugate would be "passed" into inequalities?
Moreover, why can we assume after translation that $\psi(0) < \infty$? What if $\psi(0) = \infty$? How can we reduce back to the case when $\psi(0) < \infty$?
Answer: So… I can't completely answer this question, I don't have time to work out all the details. But … hopefully this is helpful.
To answer your last question first, proposition 1.10 of Brezis says that if $\phi$ is not identically equal to $\infty$ then also $\phi^*$ is not identically equal to $\infty$. I.e. there is some $f \in E^*$ such that $\phi^*(f) < \infty$. Thus, wlog we may assume that $f = 0$ by translating the domain of $\phi$.
To see why the inquality S1 implies the question statement will almost certainly use the fact that the Legendre transform is order reversing. I.e. if $$ \phi \leq \psi $$ then $$ \phi^* \geq \psi^*.$$ Using this fact, S1 becomes something like $$ \psi^* \leq (k \| \cdot \| - C)^* .$$
Finally, you will probably want to use the fact  that $\phi^{**} = \phi$ if $\phi$ is convex.
Comment: Why would the translation of domain preserve the result the we proved?


General solution to a non-homogeneous Cauchy-Euler differential equation

Question: Here is the problem:
Solve $ t^2x'' + x = \sin(\ln t)$ for $t>0$
I first find the fundamental set of solutions to the corresponding homogeneous equation $$ t^2x'' + x = 0$$
Let
$$\ x(t)=t^r , x''(t) = r(r-1)t^{r-2} $$
Then
$$ \ r(r-1)t^r + t^r = 0$$
$$ r^2 - r +1 = 0 \Rightarrow r = \frac{1\pm\sqrt{3}i}{2} $$
$$ \Rightarrow t^{\frac{1}{2}(1+\sqrt{3}i)} = e^{\frac{1}{2}\ln{t}}[\cos(\frac{\sqrt{3}}{2}\ln{t})+i \sin(\frac{\sqrt{3}}{2}\ln{t})]$$
$$ \Rightarrow x_1(t) = e^{\frac{1}{2}\ln{t}}\cos(\frac{\sqrt{3}}{2}\ln{t}) ;\ x_2(t)=e^{\frac{1}{2}\ln{t}}\sin(\frac{\sqrt{3}}{2}\ln{t})$$
(1) Is it necessary to check that the Wronskian for $x_1(t)\ \text{and}\ x_2(t)$ is non-zero?
(2) How do I proceed with finding the particular solution for the non-homogeneous case? What should my ansatz be?
Thank you!
Comment: You could use variation of parameters to find the particular solution.
Answer: (1) It is blatantly obvious that $x_1$ and $x_2$ are linearly independent; I don't know why anybody would insist on checking a Wronskian in a case such as this.
Hint for (2): try for a particular solution of the form $x = a \sin(\ln(t)) + b \cos(\ln(t))$.
BTW: you might note that $e^{\frac{1}{2} \ln t} = t^{1/2}$.
Answer: Question 2:
$$t^2x'' + x = \sin(\ln t)$$
Substitute $u= \ln t$
$$t^2\left(\dfrac {1}{t^2}x''_u-\dfrac 1{t^2}x'_u \right)+x=\sin u$$
$$x''-x'+x =\sin u$$
Try for the particular solution:
$$x_p=A\cos u$$


...Does the new data indicate a departure from previous admission rates?

Question:
Previous enrollment records at a large university indicate that of the
  total number of persons who apply for admission, 60% are admitted
  unconditionally, 5% are conditionally admitted,and the remainder are
  refused admission. Of 500 applicants to date for next year, 329 were
  admitted unconditionally, 43 were conditionally admitted, and the
  remainder were not admitted. Do the data indicate a departure from
  previous admission rates? Test using $\alpha=0.05$

I'm guessing we're supposed to use a Pearson chi square test for independence.
Skipping the hypothesis statements, and straight to the calculaton for the value of $\chi^2$ I tried:$\newcommand{\obs}{\operatorname{obs}}$
$$\chi^2=\sum\limits^3_{i=1}\frac{(\obs_i-\hat{E}(\obs_i))^2}{\hat{E}(\obs_i)} \\= \frac{(329-329(0.6))^2}{329(0.6)}+\frac{(43-43(0.05))^2}{43(0.05)}+\frac{(128-128(0.35))^2}{128(0.35)} = 1018.4$$
$\obs$ = observed value.
The test statistic seems too large to be correct. So what did I do wrong?
Comment: I think you just made an error regarding your $E_{i}$ values.
Answer: Just a quick look. Your statistic is:
$$\chi^{2}=\sum_{i=1}^{3}\frac{(O_{i}-E_{i})^{2}}{E_{i}}$$
For $i=\{1,2,3\}$, your values should be:
$$O_{i}=\{329,43,128\}$$
and
$$E_{i}=\{0.6\times 500,0.05\times 500,0.35\times 500\}=\{300,25,175\}$$
Your resulting statistic should be:
$$\chi^{2}=26.8520$$
Essentially, your expected number $E_{i}$ should be:
$$E_{i}=p_{i}N$$
where $N$ is your sample size.


Stack underflow problem using PIC assembly on a PIC16F84A

Question: I have a small project for a course I am doing that requires us to produce a PWM signal using PIC assembly language. To try and simplify things I have set the high time to 5ms and the low time to 15ms so I can call the same delay sub routine multiple times. Calling this delay multiple times seems to be causing the problem with the stack underflow.
I am not really sure what I can try to resolve this as I am very fresh to programming. I have tried searching on this site as well as generally but haven't been able to find a solution. I am using MPLab 9.82 as well.
The code is as follows:
list        p=16F84A
#include    <p16F84A.inc>

    __CONFIG _CP_OFF & _XT_OSC & _PWRTE_ON & _WDT_OFF ;turn off watchdog timer

org 0x00 ; program starts at 0x00

counter equ 4Fh ; create a counter at position 4Fh in RAM

    BSF STATUS, RP0 ; select bank 1
    BCF TRISB, D'1' ; set port B pin 1 to output
    BCF STATUS, RP0 ; select bank 0

    goto main

main

    BSF PORTB,1 ; turn port B pin 1 on
    call delay_5ms ; calls sub routine for 5ms delay
    BCF PORTB,1 ; turn port B pin 1 off
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay

delay_5ms

    movlw D'200' ; put decimal number 200 into working register
    movwf counter ; move 200 from working register into counter

lp  nop ; no operation. just take 1 instruction
    nop  ; 1 instruction
    decfsz counter ; 1 instruction and decreases counter by 1
    goto lp ; 2 instructions (goto takes 2 instructions)
    return

end

mplab 9.82 Simulator code
Comment: You'll have to do something meaningful at the end of main, so that the processor doesn't blunder into the delay_5ms routine and dies on its return opcode.  Perhaps `goto main`.
Comment: Thank you! that seems to have fixed the problem
Comment: A bare metal main() should not return anything neither in C nor in assembler.
Answer: Every embedded system need an infinite loop. The infinite loop is necessary because the embedded software's job is never done. It is intended to be run until either the world comes to an end or the board is reset, whichever happens first. In addition, most embedded systems have just one piece of software running on them.
In an non-embedded systems, when main() finishes it returns to the operating system and the program is removed from memory. In embedded systems there's no operating system to return to, and the program can't be removed from memory.
In assembler the structure could look like:
reset:
 ; do init part

main:
  ; do the job in infinite loop
goto main

or in C
void main ()
{
    init();
    while(1)
    {
        do_job();
    }
}

Comment: Or in a toy program for playing around, you can simulate "exiting" by just spinning in an empty infinite loop, like `do_job();  while(1){}`.  If there's a power-save instruction like x86 `hlt` (sleep until next interrupt), put it inside that loop.
Answer: As Hans Passant pointed out, main needs to have some way to prevent fallthrough. For a detailed explanation of what's going on here, let's look at a C function:
void doNothing()
{
    asm("nop");
}

Not the best example, but I needed something that didn't have a return statement. At least, in C there is no return statement, but in assembly this function (assuming it doesn't get inlined) would look like this:
doNothing:
nop
return

A function written in C will always compile to an assembly function with a return instruction (unless the compiler inlines the function), even if your function doesn't have a C return statement.
Why is this necessary? Because ASM labels don't exist.
A labeled line of code in an assembly source file is just a reference to a specific memory address. When I have the following code:
main:
   nop
   nop
   nop
   goto main

The goto main is just a hardware abstraction which means "goto whatever memory address main happens to be. Whether the branch is relative or absolute, it matters not-- the assembler does the math for you and replaces the main in goto main with the required offset to make the branch take you where you want. However, when your executable is created, the main: (note the colon after, I'm talking about the label itself) is gone. This leads to a few quirks with assembly that don't happen in other languages:

First, I can have multiple labels that point to the same instruction, and doing so does not increase the file size of the executable.

foo:
bar:
baz:
nop

Second, and most importantly, there is nothing stopping execution from falling through a lable. The CPU sees
main

    BSF PORTB,1 ; turn port B pin 1 on
    call delay_5ms ; calls sub routine for 5ms delay
    BCF PORTB,1 ; turn port B pin 1 off
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay

delay_5ms
    movlw D'200' ; put decimal number 200 into working register

exactly the same as
main

    BSF PORTB,1 ; turn port B pin 1 on
    call delay_5ms ; calls sub routine for 5ms delay
    BCF PORTB,1 ; turn port B pin 1 off
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay
    call delay_5ms ; calls sub routine for 5ms delay
    movlw D'200' ; put decimal number 200 into working register

That being said, you can use fallthrough to your advantage, if for example you want to execute some function a fixed number of times, without the overhead of a loop.
foo:
;execute "bar" four times

call bar
call bar
call bar

bar:
   nop
   return


Heteroscedasticity in Linear Regression

Question: I implemented a linear regression model on some dataset. When I plotted the scatter plot of residual v/s predicted y (i.e., yhat), I observed heteroscedasticity in the plot. What can I do about it?
x-axis -> yhat
y-axis -> Residual
Comment: Without some context, not much useful can be said. What are your variables measuring? how many predictors? But the symmetric look is intriguing, and the fact that variance is largest around predicted values of zero is also interesting! But: The obvious **overplotting** in the plot hides information, maybe, so: How many observations in total?  Maybe make a plot with smaller plotting symbols, lower alpha to get transparency, ...
Comment: It clearly looks that as the yhat goes away from zero, the variance reduces. I can't think of a proper function between variance and yhat which I can use for variance stabilization method
Comment: Does a similar plot of residual error vs. actual y have a similar appearance?
Comment: Would you please post a link to the data?
Comment: I am sorry. I can't
Comment: That looks like a straight line. Here is the link
https://drive.google.com/file/d/1ag-l1UBnoXm51PNZKrX_atr41GaGiYqy/view?usp=sharing
Comment: I will add the plot. By the way there are roughly 400k points in this plot
Comment: Would you mind adding a scatter plot of a random subsample of 500 points, say? There is a lot of overplotting with 400k points.
Comment: Won't subsampling just 500 points out of 400k points lack the representation of the actual distribution of data
Answer: Before doing anything about heteroscedasticity, first you must establish whether it even exists.
The scatterplot in the question is not evidence of heteroscedasticity.
"Heteroscedasticity" refers to any important variation in the dispersion of one variable (here plotted on the vertical axis) when another variable (here plotted on the horizontal axis) is varied.
The problem with this plot is that it does not enable us to make accurate estimates of the dispersion.  The reason why not is that because there are so many points, essentially all we can see are the ranges of the vertical variable, but the range is both a highly unstable estimate of dispersion as well as dependent on the amount of data.  As you scan left to right across this plot, it is possible for there to be much, much more data in the middle compared to the ends.  That can give rise to a false impression of greater dispersion of $y$ for middling $x$-values.
To illustrate this problem, I generated 400,000 $(x,y)$ values where the coordinates are independent--and therefore $y$ is as homoscedastic (non-heteroscedastic) as possible.
n <- 4e5
x <- pmax(-8, pmin(8, abs(rnorm(n, sd=7/6))^1.25 * sample(c(-1,1), n, replace=TRUE)))
y <- sample(c(-1,1), n, replace=TRUE) * rgamma(n, 1/3, 1/20)

Whether or not you are familiar with R (the language used for this simulation), it should be apparent that the x values and y values have been separately generated.  But here's their scatterplot, shown using the overplotting method of the question:

It sure looks like the y-values are spread out less near the extremes than in the middle, doesn't it?  This mistaken impression is the cause of many related questions (and incorrect answers) on this site.
A better way to look at heteroscedasticity is to split the $x$ values into groups and robustly estimate the dispersion of each group.  There are many ways to do this.  John Tukey observed that generally there's not a whole lot going on in the middle of a batch of data: the interesting changes tend to occur out in the extremes.  In his "wandering schematic plot" he proposed splitting the $x$ data (essentially) into the most extreme halves, quarters, eighths, and so on, and plotting some of the extremes of the $y$ values found within each such group.  This leads to a quick, simple plot.

The vertical bars in this figure demark the boundaries between the groups of $x$ values used to estimate the dispersion of the corresponding $y$ values.  Thus, the middle half of all points falls within the two vertical strips surrounding $x=0.$ (Each of those strips contains about 100,000 points.)  Thereafter, as you move away from $0,$ each vertical strip includes one-half as many points as previously.  Ultimately the outer strips (roughly from $x=-8$ to $-5.4$ and $x=5.4$ to $8$) contain only $200$ points each.
The horizontal black graphs trace out the 1%, 5%, 25%, 50%, 75%, 95%, and 99% quantiles of the corresponding $y$ values.  We can't distinguish the middle quantiles because they are so close, but it's nevertheless clear that these "wandering traces" are essentially horizontal.  This shows, contrary to what the original figure suggested, that the dispersion of $y$ does not appreciably vary with $x.$  Indeed, it shows that the entire (conditional) distribution of $y$ appears to be independent of $x.$  That's what you're looking for when you assess the relationship between regression residuals and predicted values.
What does heteroscedasticity look like?  Here's an example.  The preceding $y$ values were divided by the larger of $1$ and $x^2,$ thereby reducing their dispersion (greatly) near the extremes of $x.$  The schematic traces are no longer horizontal: they contract towards the left and right to reflect the decreasing dispersion with large values of $x.$

(This time I plotted only a random sample of 10,000 points, because plotting all 400,000 requires a wait.   But the traces are based on all 400,000 points.)
Finally, I suspect you might be correct that there is heteroscedasticity: but before we can say anything about what to do, it still needs to be represented clearly, quantified, and accurately characterized.  Creating a wandering schematic plot or one of its newer variants (such as quantile regression) would be a good first step.

References
For an example of the wandering schematic plot used to diagnose heteroscedasticity, see https://stats.stackexchange.com/a/166267/919.  Other examples of this plot can be found at https://stats.stackexchange.com/a/106083/919 (with working R code) and Measures of residuals heteroscedasticity (also with code).
Tukey describes this method in his book Exploratory Data Analysis (Addison-Wesley 1977).  He provides many more ways to depict and diagnose heteroscedasticity, as well as methods to "cure" it, such as Box-Cox transformations.
Comment: The idea of that plot actually helped. Here is the plot of 20 box-plots. I divided the yhat(i.e. x-axis in the plot in the question) into 20 slices and made a box plot of data for each of the slices
Comment: Thanks. Actually I thought of the somewhat same idea before I looked at your answer. I was thinking about slicing the x's into vertical boxes and then in each box find the variance of y. But I think instead of variance if we plot the box plots for each slice i.e. wandering schematic plot, it will provide more insights
Comment: On a side note, I think box-cox transformation is only valid when the target variable is positive because in box-cox we apply transformation f(y) = (y^lambda - 1)/lambda where lambda is any real number. So what shall be done for the case when the target variable can be both negative and positive
Comment: The target variable is the *original response* in the regression, not the residual.  Also, as illustrated at https://stats.stackexchange.com/a/35717/919 (*inter alia*), there are principled ways to shift variables to make them positive and apply a Box-Cox transformation. There are also many nonlinear transformations available for variables generally (see https://stats.stackexchange.com/questions/251449 for a general analysis); my reference to the Box-Cox family was only an example, not a recommendation.
Comment: https://drive.google.com/file/d/1_DOZh4SJiU1snpaAHybD-BB7qb0kW0_h/view?usp=sharing

This looks like a straight line i.e. residual is directly proportional to yhat. which means that, the regression hasn't happened at all. And that is my the R^2 value is comint as 0.029
Comment: Due to the lack of axis labels and other markings, it's unclear what you are plotting.  It doesn't appear to be related to the graphic in your question.  Judging from the numbers on the vertical axis, it looks like you might have split the residuals according to some value very closely correlated with the residuals, such as the residuals themselves.
Answer: The existence of heteroscedasticity gives rise to certain problems in the regression analysis as the assumption says that error terms are uncorrelated and, hence, the variance is constant. The presence of heteroscedasticity can often be seen in the form of a cone-like scatter plot for residual vs fitted values.
One of the basic assumptions of linear regression is that heteroscedasticity is not present in the data. Due to violation of the assumptions, the Ordinary Least Squares (OLS) estimators are not the Best Linear Unbiased Estimators (BLUE). Hence, they do not give the least variance than other Linear Unbiased Estimators (LUEs).
There is no fixed procedure to overcome heteroscedasticity. However, there are some ways that may lead to the reduction of heteroscedasticity. They are —
Logarithmising the data: A series that is increasing exponentially often results in increased variability. This can be overcome using the log transformation.
Using weighted linear regression: Here, the OLS method is applied to the weighted values of X and Y. One way is to attach weights directly related to the magnitude of the dependent variable.
Comment: Your first paragraph reads a bit like saying that heteroscedasticity implies the errors are correlated.

Heteroscedasticity in Linear Regression


How can I use field_attach_load()

Question:
Possible Duplicate:
Listing entity fields

I want list fields of my content type(example: blog), so as described at Drupal API reference, I should pass $entity_type and $entities to this function.
I know $entity_type is 'node', but how can I fill $entities?
I should fill $entities with bundle of "blog" so I should know the bundle ID.
How can I know bundle ID for blog?
Answer: If you want the list of fields per content type (now bundles in Drupal 7), you should use field_info_instances().
//List all fields of bundle "your_content_type" using devel module
dsm(field_info_instances('node', 'your_content_type'));

How can I use field_attach_load()


Decide if $\mathbb Z[i]/\langle i\rangle$ and $\mathbb Z$ are isomorphic, if $\mathbb Z[i]/\langle i+1\rangle$ and $\mathbb Z_2$ are isomorphic

Question:
Decide if $\mathbb Z[i]/\langle i\rangle$ and $\mathbb Z$ are isomorphic, if $\mathbb Z[i]/\langle i+1\rangle$ and $\mathbb Z_2$ are isomorphic

I know that in the first case if there exist such homomorphism then $f(i)=0$   (and in the second case $f(i+1)=0$), but I don't know exactly how to prove it.
Comment: yes , sorry i didn't know how to write it
Comment: @Did Is it a ring homomorphism?
Comment: Is $Z2$ the set $\mathbb{Z}_2$, the integers modulo $2$?
Comment: @egreg Right. Thanks for the correction.
Answer: It seems you are in the context of rings.
Note that $i$ is invertible in $\mathbb{Z}[i]$, so the ideal it generates is the whole ring. Hence the quotient $\mathbb{Z}[i]/\langle i\rangle$ is the trivial ring.
For the second part, consider $a+bi=a-b+b(1+i)$ and the ring homomorphism
$$
\varphi\colon\mathbb{Z}[i]\to\mathbb{Z}/2\mathbb{Z}
$$
defined by $\varphi(a+bi)=[a-b]$ where $[x]$ denotes the residue class of $x$ modulo $2$ (prove it is a ring homomorphism and that its kernel is $\langle 1+i\rangle$).
Answer: To show the first isomorphism you can use one of the isomorphism theorems:
$$(A+I)/I \cong A/(A\cap I) $$
In this case $A=\mathbb{Z}\subseteq \mathbb{Z}[i]$ and $I=(i)$.
In the second case, note that $(i+1)^{2}=(2)$, so we have $\mathbb{Z}\cap (i+1)^{2}=(2)$. Then apply again the same theorem.
Answer: Here is an answer for the second question:
Since $2=(1+i)(1-i)$, we have $2 \in (1+i)$.
Thus, $a+bi \equiv (a\bmod 2)+(b\bmod 2)\,i \equiv (1+i)$.
Therefore, the classes of $\mathbb Z[i]$ mod $(1+i)$ are reduced to the classes of $0,1,i,1+i$.
Now $0 \equiv 1+i$ and $1 \equiv i$ and so $\mathbb Z[i]$ mod $(1+i)$ has only two classes and must be $\mathbb Z_2$.


A closed formula for the measure of the union of $n$ sets

Question: Suppose $\mu$ is a finite measure on $(X,\mathscr{A})$ and {${A_n}$}$_{i=1}^n$ is an arbitrary sequence of $\mathscr{A}$-measurable sets. I conjecture that
$$
\mu\left(\bigcup_{i=1}^n{A_n}\right) = \sum_{i=1}^n{\mu({A_n})} -\sum_{i\neq{j}}\mu\left(A_i\cap A_j\right)+\ldots+ (-1)^{n+1}\mu\left(\bigcap_{i=1}^n{A_n}\right).
$$
For the cases $n=2$ and $n=3$ it is quite easy to verify it, but I don't know how to verify it for the general case.
Comment: @Did the usual reason is that it is an exercise in a chapter preceding the definition of the integral.
Comment: This really is just [inclusion-exclusion](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle#In_probability).
Comment: Asked ten times on the site: integrate the identity $$\mathbf 1_{\bigcup\limits_i A_i}=1-\mathbf 1_{\bigcap\limits_i A_i^c}=1-\prod_i(1-\mathbf 1_{A_i})=\sum_k(-1)^{k-1}\sum_{|J|=k}\prod_{i\in J}\mathbf 1_{A_i}=\ldots$$
Comment: @Did can you prove it without using integrals?
Comment: It seems like a generalization of inclusion-exclusion principle. You can prove yours by mimicking a proof of inclusion-exclusion principle.
Comment: try a recursive proof
Comment: @Milad What for? This is by far the simplest and most powerful approach.
Comment: @Did My measure theory book has stated measures before introducing integrals.
Comment: @UmbertoP. How sad, if this is indeed the case.
Comment: @Milad -- what is your measure-theory textbook?
Comment: Measure theory by Cohn @uniquesolution
Comment: I just did not want to open my combinatorics book, but I think now I have to @Chappers
Comment: @Milad Thanks. I never looked at this book, but apparently is is quite popular. It is very natural, and hardly sad, to start from measures and only then arrive at integrals, the reason being, that integrals are of measurable functions against measures.
Comment: @uniquesolution you are welcome
Answer: Hint: The base $n=2$ step is easy to verify, as you've said. For the induction step, suppose that it holds for any $n$ sets, and observe that $$\bigcup_{k=1}^{n+1}A_k=\left(\bigcup_{k=1}^nA_k\right)\cup A_{n+1}$$ and $$\bigcup_{k=1}^n\left(A_k\cap A_{n+1}\right)=\left(\bigcup_{k=1}^nA_k\right)\cap A_{n+1}.$$ Now, apply the base result and the induction hypothesis.
Comment: I did not realize induction would help. thanks